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.

279394 lines
7.5MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /*** Start of inlined file: juce_TargetPlatform.h ***/
  30. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  31. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  32. /* This file figures out which platform is being built, and defines some macros
  33. that the rest of the code can use for OS-specific compilation.
  34. Macros that will be set here are:
  35. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  36. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  37. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  38. - Either JUCE_INTEL or JUCE_PPC
  39. - Either JUCE_GCC or JUCE_MSVC
  40. */
  41. #if (defined (_WIN32) || defined (_WIN64))
  42. #define JUCE_WIN32 1
  43. #define JUCE_WINDOWS 1
  44. #elif defined (LINUX) || defined (__linux__)
  45. #define JUCE_LINUX 1
  46. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  47. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  48. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  49. #define JUCE_IPHONE 1
  50. #define JUCE_IOS 1
  51. #else
  52. #define JUCE_MAC 1
  53. #endif
  54. #else
  55. #error "Unknown platform!"
  56. #endif
  57. #if JUCE_WINDOWS
  58. #ifdef _MSC_VER
  59. #ifdef _WIN64
  60. #define JUCE_64BIT 1
  61. #else
  62. #define JUCE_32BIT 1
  63. #endif
  64. #endif
  65. #ifdef _DEBUG
  66. #define JUCE_DEBUG 1
  67. #endif
  68. #ifdef __MINGW32__
  69. #define JUCE_MINGW 1
  70. #endif
  71. /** If defined, this indicates that the processor is little-endian. */
  72. #define JUCE_LITTLE_ENDIAN 1
  73. #define JUCE_INTEL 1
  74. #endif
  75. #if JUCE_MAC
  76. #ifndef NDEBUG
  77. #define JUCE_DEBUG 1
  78. #endif
  79. #ifdef __LITTLE_ENDIAN__
  80. #define JUCE_LITTLE_ENDIAN 1
  81. #else
  82. #define JUCE_BIG_ENDIAN 1
  83. #endif
  84. #if defined (__ppc__) || defined (__ppc64__)
  85. #define JUCE_PPC 1
  86. #else
  87. #define JUCE_INTEL 1
  88. #endif
  89. #ifdef __LP64__
  90. #define JUCE_64BIT 1
  91. #else
  92. #define JUCE_32BIT 1
  93. #endif
  94. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  95. #error "Building for OSX 10.3 is no longer supported!"
  96. #endif
  97. #ifndef MAC_OS_X_VERSION_10_5
  98. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  99. #endif
  100. #endif
  101. #if JUCE_IOS
  102. #ifndef NDEBUG
  103. #define JUCE_DEBUG 1
  104. #endif
  105. #ifdef __LITTLE_ENDIAN__
  106. #define JUCE_LITTLE_ENDIAN 1
  107. #else
  108. #define JUCE_BIG_ENDIAN 1
  109. #endif
  110. #endif
  111. #if JUCE_LINUX
  112. #ifdef _DEBUG
  113. #define JUCE_DEBUG 1
  114. #endif
  115. // Allow override for big-endian Linux platforms
  116. #ifndef JUCE_BIG_ENDIAN
  117. #define JUCE_LITTLE_ENDIAN 1
  118. #endif
  119. #if defined (__LP64__) || defined (_LP64)
  120. #define JUCE_64BIT 1
  121. #else
  122. #define JUCE_32BIT 1
  123. #endif
  124. #define JUCE_INTEL 1
  125. #endif
  126. // Compiler type macros.
  127. #ifdef __GNUC__
  128. #define JUCE_GCC 1
  129. #elif defined (_MSC_VER)
  130. #define JUCE_MSVC 1
  131. #if _MSC_VER >= 1400
  132. #define JUCE_USE_INTRINSICS 1
  133. #endif
  134. #else
  135. #error unknown compiler
  136. #endif
  137. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  138. /*** End of inlined file: juce_TargetPlatform.h ***/
  139. // FORCE_AMALGAMATOR_INCLUDE
  140. /*** Start of inlined file: juce_Config.h ***/
  141. #ifndef __JUCE_CONFIG_JUCEHEADER__
  142. #define __JUCE_CONFIG_JUCEHEADER__
  143. /*
  144. This file contains macros that enable/disable various JUCE features.
  145. */
  146. /** The name of the namespace that all Juce classes and functions will be
  147. put inside. If this is not defined, no namespace will be used.
  148. */
  149. #ifndef JUCE_NAMESPACE
  150. #define JUCE_NAMESPACE juce
  151. #endif
  152. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  153. project settings, but if you define this value, you can override this to force
  154. it to be true or false.
  155. */
  156. #ifndef JUCE_FORCE_DEBUG
  157. //#define JUCE_FORCE_DEBUG 0
  158. #endif
  159. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  160. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  161. Enabling it will also leave this turned on in release builds. When it's disabled,
  162. however, the jassert and jassertfalse macros will not be compiled in a
  163. release build.
  164. @see jassert, jassertfalse, Logger
  165. */
  166. #ifndef JUCE_LOG_ASSERTIONS
  167. #define JUCE_LOG_ASSERTIONS 0
  168. #endif
  169. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  170. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  171. on your Windows build machine.
  172. See the comments in the ASIOAudioIODevice class's header file for more
  173. info about this.
  174. */
  175. #ifndef JUCE_ASIO
  176. #define JUCE_ASIO 0
  177. #endif
  178. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  179. */
  180. #ifndef JUCE_WASAPI
  181. #define JUCE_WASAPI 0
  182. #endif
  183. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  184. */
  185. #ifndef JUCE_DIRECTSOUND
  186. #define JUCE_DIRECTSOUND 1
  187. #endif
  188. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  189. #ifndef JUCE_ALSA
  190. #define JUCE_ALSA 1
  191. #endif
  192. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  193. #ifndef JUCE_JACK
  194. #define JUCE_JACK 0
  195. #endif
  196. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  197. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  198. installed, and its header files will need to be on your include path.
  199. */
  200. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || (JUCE_WINDOWS && ! JUCE_MSVC))
  201. #define JUCE_QUICKTIME 0
  202. #endif
  203. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  204. #undef JUCE_QUICKTIME
  205. #endif
  206. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  207. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  208. */
  209. #ifndef JUCE_OPENGL
  210. #define JUCE_OPENGL 1
  211. #endif
  212. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  213. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  214. */
  215. #ifndef JUCE_DIRECT2D
  216. #define JUCE_DIRECT2D 0
  217. #endif
  218. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  219. If your app doesn't need to read FLAC files, you might want to disable this to
  220. reduce the size of your codebase and build time.
  221. */
  222. #ifndef JUCE_USE_FLAC
  223. #define JUCE_USE_FLAC 1
  224. #endif
  225. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  226. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  227. reduce the size of your codebase and build time.
  228. */
  229. #ifndef JUCE_USE_OGGVORBIS
  230. #define JUCE_USE_OGGVORBIS 1
  231. #endif
  232. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  233. Unless you're using CD-burning, you should probably turn this flag off to
  234. reduce code size.
  235. */
  236. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  237. #define JUCE_USE_CDBURNER 1
  238. #endif
  239. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  240. Unless you're using CD-reading, you should probably turn this flag off to
  241. reduce code size.
  242. */
  243. #ifndef JUCE_USE_CDREADER
  244. #define JUCE_USE_CDREADER 1
  245. #endif
  246. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  247. */
  248. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  249. #define JUCE_USE_CAMERA 0
  250. #endif
  251. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  252. gets repainted will flash in a random colour, so that you can check exactly how much and how
  253. often your components are being drawn.
  254. */
  255. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  256. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  257. #endif
  258. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  259. Unless you specifically want to disable this, it's best to leave this option turned on.
  260. */
  261. #ifndef JUCE_USE_XINERAMA
  262. #define JUCE_USE_XINERAMA 1
  263. #endif
  264. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  265. turned on unless you have a good reason to disable it.
  266. */
  267. #ifndef JUCE_USE_XSHM
  268. #define JUCE_USE_XSHM 1
  269. #endif
  270. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  271. */
  272. #ifndef JUCE_USE_XRENDER
  273. #define JUCE_USE_XRENDER 0
  274. #endif
  275. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  276. unless you have a good reason to disable it.
  277. */
  278. #ifndef JUCE_USE_XCURSOR
  279. #define JUCE_USE_XCURSOR 1
  280. #endif
  281. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  282. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  283. you're building a plugin hosting app.
  284. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  285. */
  286. #ifndef JUCE_PLUGINHOST_VST
  287. #define JUCE_PLUGINHOST_VST 0
  288. #endif
  289. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  290. of course, and should only be enabled if you're building a plugin hosting app.
  291. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  292. */
  293. #ifndef JUCE_PLUGINHOST_AU
  294. #define JUCE_PLUGINHOST_AU 0
  295. #endif
  296. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  297. This should be enabled if you're writing a console application.
  298. */
  299. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  300. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  301. #endif
  302. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  303. If you're not using any embedded web-pages, turning this off may reduce your code size.
  304. */
  305. #ifndef JUCE_WEB_BROWSER
  306. #define JUCE_WEB_BROWSER 1
  307. #endif
  308. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  309. Carbon isn't required for a normal app, but may be needed by specialised classes like
  310. plugin-hosts, which support older APIs.
  311. */
  312. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  313. #define JUCE_SUPPORT_CARBON 1
  314. #endif
  315. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  316. You might need to tweak this if you're linking to an external zlib library in your app,
  317. but for normal apps, this option should be left alone.
  318. */
  319. #ifndef JUCE_INCLUDE_ZLIB_CODE
  320. #define JUCE_INCLUDE_ZLIB_CODE 1
  321. #endif
  322. #ifndef JUCE_INCLUDE_FLAC_CODE
  323. #define JUCE_INCLUDE_FLAC_CODE 1
  324. #endif
  325. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  326. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  327. #endif
  328. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  329. #define JUCE_INCLUDE_PNGLIB_CODE 1
  330. #endif
  331. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  332. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  333. #endif
  334. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  335. (Currently, this only affects Windows builds in debug mode).
  336. */
  337. #ifndef JUCE_CHECK_MEMORY_LEAKS
  338. #define JUCE_CHECK_MEMORY_LEAKS 1
  339. #endif
  340. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  341. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  342. are passed to the JUCEApplication::unhandledException() callback for logging.
  343. */
  344. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  345. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  346. #endif
  347. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  348. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  349. #undef JUCE_QUICKTIME
  350. #define JUCE_QUICKTIME 0
  351. #undef JUCE_OPENGL
  352. #define JUCE_OPENGL 0
  353. #undef JUCE_USE_CDBURNER
  354. #define JUCE_USE_CDBURNER 0
  355. #undef JUCE_USE_CDREADER
  356. #define JUCE_USE_CDREADER 0
  357. #undef JUCE_WEB_BROWSER
  358. #define JUCE_WEB_BROWSER 0
  359. #undef JUCE_PLUGINHOST_AU
  360. #define JUCE_PLUGINHOST_AU 0
  361. #undef JUCE_PLUGINHOST_VST
  362. #define JUCE_PLUGINHOST_VST 0
  363. #endif
  364. #endif
  365. /*** End of inlined file: juce_Config.h ***/
  366. // FORCE_AMALGAMATOR_INCLUDE
  367. #ifndef JUCE_BUILD_CORE
  368. #define JUCE_BUILD_CORE 1
  369. #endif
  370. #ifndef JUCE_BUILD_MISC
  371. #define JUCE_BUILD_MISC 1
  372. #endif
  373. #ifndef JUCE_BUILD_GUI
  374. #define JUCE_BUILD_GUI 1
  375. #endif
  376. #ifndef JUCE_BUILD_NATIVE
  377. #define JUCE_BUILD_NATIVE 1
  378. #endif
  379. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  380. #undef JUCE_BUILD_MISC
  381. #undef JUCE_BUILD_GUI
  382. #endif
  383. //==============================================================================
  384. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  385. #if JUCE_WINDOWS
  386. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  387. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  388. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  389. #ifndef STRICT
  390. #define STRICT 1
  391. #endif
  392. #undef WIN32_LEAN_AND_MEAN
  393. #define WIN32_LEAN_AND_MEAN 1
  394. #if JUCE_MSVC
  395. #pragma warning (push)
  396. #pragma warning (disable : 4100 4201 4514 4312 4995)
  397. #endif
  398. #define _WIN32_WINNT 0x0500
  399. #define _UNICODE 1
  400. #define UNICODE 1
  401. #ifndef _WIN32_IE
  402. #define _WIN32_IE 0x0400
  403. #endif
  404. #include <windows.h>
  405. #include <windowsx.h>
  406. #include <commdlg.h>
  407. #include <shellapi.h>
  408. #include <mmsystem.h>
  409. #include <vfw.h>
  410. #include <tchar.h>
  411. #include <stddef.h>
  412. #include <ctime>
  413. #include <wininet.h>
  414. #include <nb30.h>
  415. #include <iphlpapi.h>
  416. #include <mapi.h>
  417. #include <float.h>
  418. #include <process.h>
  419. #include <Exdisp.h>
  420. #include <exdispid.h>
  421. #include <shlobj.h>
  422. #if ! JUCE_MINGW
  423. #include <crtdbg.h>
  424. #include <comutil.h>
  425. #endif
  426. #if JUCE_OPENGL
  427. #include <gl/gl.h>
  428. #endif
  429. #undef PACKED
  430. #if JUCE_ASIO
  431. /*
  432. This is very frustrating - we only need to use a handful of definitions from
  433. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  434. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  435. implementation...
  436. ..unfortunately that would break Steinberg's license agreement for use of
  437. their SDK, so I'm not allowed to do this.
  438. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  439. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  440. (see www.steinberg.net/Steinberg/Developers.asp).
  441. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  442. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  443. if you prefer). Make sure that your header search path will find the
  444. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  445. files are actually needed - so to simplify things, you could just copy
  446. these into your JUCE directory).
  447. If you're compiling and you get an error here because you don't have the
  448. ASIO SDK installed, you can disable ASIO support by commenting-out the
  449. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  450. */
  451. #include "iasiodrv.h"
  452. #endif
  453. #if JUCE_USE_CDBURNER
  454. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  455. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  456. flag in juce_Config.h to avoid these includes.
  457. */
  458. #include <imapi.h>
  459. #include <imapierror.h>
  460. #endif
  461. #if JUCE_USE_CAMERA
  462. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  463. These files are provided in the normal Windows SDK, but some Microsoft plonker
  464. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  465. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  466. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  467. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  468. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  469. The dummy file just needs to contain the following content:
  470. #define __IDxtCompositor_INTERFACE_DEFINED__
  471. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  472. #define __IDxtJpeg_INTERFACE_DEFINED__
  473. #define __IDxtKey_INTERFACE_DEFINED__
  474. ..and that should be enough to convince qedit.h that you have the SDK!
  475. */
  476. #include <dshow.h>
  477. #include <qedit.h>
  478. #include <dshowasf.h>
  479. #endif
  480. #if JUCE_WASAPI
  481. #include <MMReg.h>
  482. #include <mmdeviceapi.h>
  483. #include <Audioclient.h>
  484. #include <Avrt.h>
  485. #include <functiondiscoverykeys.h>
  486. #endif
  487. #if JUCE_QUICKTIME
  488. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  489. add its header directory to your include path.
  490. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  491. flag in juce_Config.h
  492. */
  493. #include <Movies.h>
  494. #include <QTML.h>
  495. #include <QuickTimeComponents.h>
  496. #include <MediaHandlers.h>
  497. #include <ImageCodec.h>
  498. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  499. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  500. your include search path to make these import statements work.
  501. */
  502. #import <QTOLibrary.dll>
  503. #import <QTOControl.dll>
  504. #endif
  505. #if JUCE_MSVC
  506. #pragma warning (pop)
  507. #endif
  508. #if JUCE_DIRECT2D
  509. #include <d2d1.h>
  510. #include <dwrite.h>
  511. #endif
  512. /** A simple COM smart pointer.
  513. Avoids having to include ATL just to get one of these.
  514. */
  515. template <class ComClass>
  516. class ComSmartPtr
  517. {
  518. public:
  519. ComSmartPtr() throw() : p (0) {}
  520. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  521. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  522. ~ComSmartPtr() { release(); }
  523. operator ComClass*() const throw() { return p; }
  524. ComClass& operator*() const throw() { return *p; }
  525. ComClass* operator->() const throw() { return p; }
  526. ComSmartPtr& operator= (ComClass* const newP)
  527. {
  528. if (newP != 0) newP->AddRef();
  529. release();
  530. p = newP;
  531. return *this;
  532. }
  533. ComSmartPtr& operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  534. // Releases and nullifies this pointer and returns its address
  535. ComClass** resetAndGetPointerAddress()
  536. {
  537. release();
  538. p = 0;
  539. return &p;
  540. }
  541. HRESULT CoCreateInstance (REFCLSID classUUID, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  542. {
  543. #ifndef __MINGW32__
  544. return ::CoCreateInstance (classUUID, 0, dwClsContext, __uuidof (ComClass), (void**) resetAndGetPointerAddress());
  545. #else
  546. return E_NOTIMPL;
  547. #endif
  548. }
  549. template <class OtherComClass>
  550. HRESULT QueryInterface (REFCLSID classUUID, ComSmartPtr<OtherComClass>& destObject) const
  551. {
  552. if (p == 0)
  553. return E_POINTER;
  554. return p->QueryInterface (classUUID, (void**) destObject.resetAndGetPointerAddress());
  555. }
  556. private:
  557. ComClass* p;
  558. void release() { if (p != 0) p->Release(); }
  559. ComClass** operator&() throw(); // private to avoid it being used accidentally
  560. };
  561. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  562. */
  563. template <class ComClass>
  564. class ComBaseClassHelper : public ComClass
  565. {
  566. public:
  567. ComBaseClassHelper() : refCount (1) {}
  568. virtual ~ComBaseClassHelper() {}
  569. HRESULT __stdcall QueryInterface (REFIID refId, void __RPC_FAR* __RPC_FAR* result)
  570. {
  571. #ifndef __MINGW32__
  572. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  573. #endif
  574. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  575. *result = 0;
  576. return E_NOINTERFACE;
  577. }
  578. ULONG __stdcall AddRef() { return ++refCount; }
  579. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  580. protected:
  581. int refCount;
  582. };
  583. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  584. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  585. #elif JUCE_LINUX
  586. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  587. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  588. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  589. /*
  590. This file wraps together all the linux-specific headers, so
  591. that we can include them all just once, and compile all our
  592. platform-specific stuff in one big lump, keeping it out of the
  593. way of the rest of the codebase.
  594. */
  595. #include <sched.h>
  596. #include <pthread.h>
  597. #include <sys/time.h>
  598. #include <errno.h>
  599. #include <sys/stat.h>
  600. #include <sys/dir.h>
  601. #include <sys/ptrace.h>
  602. #include <sys/vfs.h>
  603. #include <sys/wait.h>
  604. #include <fnmatch.h>
  605. #include <utime.h>
  606. #include <pwd.h>
  607. #include <fcntl.h>
  608. #include <dlfcn.h>
  609. #include <netdb.h>
  610. #include <arpa/inet.h>
  611. #include <netinet/in.h>
  612. #include <sys/types.h>
  613. #include <sys/ioctl.h>
  614. #include <sys/socket.h>
  615. #include <net/if.h>
  616. #include <sys/sysinfo.h>
  617. #include <sys/file.h>
  618. #include <signal.h>
  619. /* Got a build error here? You'll need to install the freetype library...
  620. The name of the package to install is "libfreetype6-dev".
  621. */
  622. #include <ft2build.h>
  623. #include FT_FREETYPE_H
  624. #include <X11/Xlib.h>
  625. #include <X11/Xatom.h>
  626. #include <X11/Xresource.h>
  627. #include <X11/Xutil.h>
  628. #include <X11/Xmd.h>
  629. #include <X11/keysym.h>
  630. #include <X11/cursorfont.h>
  631. #if JUCE_USE_XINERAMA
  632. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  633. #include <X11/extensions/Xinerama.h>
  634. #endif
  635. #if JUCE_USE_XSHM
  636. #include <X11/extensions/XShm.h>
  637. #include <sys/shm.h>
  638. #include <sys/ipc.h>
  639. #endif
  640. #if JUCE_USE_XRENDER
  641. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  642. #include <X11/extensions/Xrender.h>
  643. #include <X11/extensions/Xcomposite.h>
  644. #endif
  645. #if JUCE_USE_XCURSOR
  646. // If you're missing this header, try installing the libxcursor-dev package
  647. #include <X11/Xcursor/Xcursor.h>
  648. #endif
  649. #if JUCE_OPENGL
  650. /* Got an include error here?
  651. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  652. and "freeglut3-dev".
  653. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  654. want to disable it.
  655. */
  656. #include <GL/glx.h>
  657. #endif
  658. #undef KeyPress
  659. #if JUCE_ALSA
  660. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  661. not got your paths set up correctly to find its header files.
  662. The package you need to install to get ASLA support is "libasound2-dev".
  663. If you don't have the ALSA library and don't want to build Juce with audio support,
  664. just disable the JUCE_ALSA flag in juce_Config.h
  665. */
  666. #include <alsa/asoundlib.h>
  667. #endif
  668. #if JUCE_JACK
  669. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  670. installed, or you've not got your paths set up correctly to find its header files.
  671. The package you need to install to get JACK support is "libjack-dev".
  672. If you don't have the jack-audio-connection-kit library and don't want to build
  673. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  674. */
  675. #include <jack/jack.h>
  676. //#include <jack/transport.h>
  677. #endif
  678. #undef SIZEOF
  679. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  680. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  681. #elif JUCE_MAC || JUCE_IPHONE
  682. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  683. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  684. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  685. /*
  686. This file wraps together all the mac-specific code, so that
  687. we can include all the native headers just once, and compile all our
  688. platform-specific stuff in one big lump, keeping it out of the way of
  689. the rest of the codebase.
  690. */
  691. #define USE_COREGRAPHICS_RENDERING 1
  692. #if JUCE_IOS
  693. #import <Foundation/Foundation.h>
  694. #import <UIKit/UIKit.h>
  695. #import <AudioToolbox/AudioToolbox.h>
  696. #import <AVFoundation/AVFoundation.h>
  697. #import <CoreData/CoreData.h>
  698. #import <MobileCoreServices/MobileCoreServices.h>
  699. #import <QuartzCore/QuartzCore.h>
  700. #include <sys/fcntl.h>
  701. #if JUCE_OPENGL
  702. #include <OpenGLES/ES1/gl.h>
  703. #include <OpenGLES/ES1/glext.h>
  704. #endif
  705. #else
  706. #import <Cocoa/Cocoa.h>
  707. #import <CoreAudio/HostTime.h>
  708. #import <CoreAudio/AudioHardware.h>
  709. #import <CoreMIDI/MIDIServices.h>
  710. #import <QTKit/QTKit.h>
  711. #import <WebKit/WebKit.h>
  712. #import <DiscRecording/DiscRecording.h>
  713. #import <IOKit/IOKitLib.h>
  714. #import <IOKit/IOCFPlugIn.h>
  715. #import <IOKit/hid/IOHIDLib.h>
  716. #import <IOKit/hid/IOHIDKeys.h>
  717. #import <IOKit/pwr_mgt/IOPMLib.h>
  718. #include <Carbon/Carbon.h>
  719. #include <sys/dir.h>
  720. #endif
  721. #include <sys/socket.h>
  722. #include <sys/sysctl.h>
  723. #include <sys/stat.h>
  724. #include <sys/param.h>
  725. #include <sys/mount.h>
  726. #include <fnmatch.h>
  727. #include <utime.h>
  728. #include <dlfcn.h>
  729. #include <ifaddrs.h>
  730. #include <net/if_dl.h>
  731. #include <mach/mach_time.h>
  732. #include <mach-o/dyld.h>
  733. #if MACOS_10_4_OR_EARLIER
  734. #include <GLUT/glut.h>
  735. #endif
  736. #if ! CGFLOAT_DEFINED
  737. #define CGFloat float
  738. #endif
  739. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  740. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  741. #else
  742. #error "Unknown platform!"
  743. #endif
  744. #endif
  745. //==============================================================================
  746. #define DONT_SET_USING_JUCE_NAMESPACE 1
  747. #undef max
  748. #undef min
  749. #define NO_DUMMY_DECL
  750. #if JUCE_BUILD_NATIVE
  751. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  752. #endif
  753. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  754. #pragma warning (disable: 4309 4305)
  755. #endif
  756. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  757. BEGIN_JUCE_NAMESPACE
  758. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  759. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  760. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  761. /**
  762. Creates a floating carbon window that can be used to hold a carbon UI.
  763. This is a handy class that's designed to be inlined where needed, e.g.
  764. in the audio plugin hosting code.
  765. */
  766. class CarbonViewWrapperComponent : public Component,
  767. public ComponentMovementWatcher,
  768. public Timer
  769. {
  770. public:
  771. CarbonViewWrapperComponent()
  772. : ComponentMovementWatcher (this),
  773. wrapperWindow (0),
  774. carbonWindow (0),
  775. embeddedView (0),
  776. recursiveResize (false)
  777. {
  778. }
  779. virtual ~CarbonViewWrapperComponent()
  780. {
  781. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  782. }
  783. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  784. virtual void removeView (HIViewRef embeddedView) = 0;
  785. virtual void mouseDown (int, int) {}
  786. virtual void paint() {}
  787. virtual bool getEmbeddedViewSize (int& w, int& h)
  788. {
  789. if (embeddedView == 0)
  790. return false;
  791. HIRect bounds;
  792. HIViewGetBounds (embeddedView, &bounds);
  793. w = jmax (1, roundToInt (bounds.size.width));
  794. h = jmax (1, roundToInt (bounds.size.height));
  795. return true;
  796. }
  797. void createWindow()
  798. {
  799. if (wrapperWindow == 0)
  800. {
  801. Rect r;
  802. r.left = getScreenX();
  803. r.top = getScreenY();
  804. r.right = r.left + getWidth();
  805. r.bottom = r.top + getHeight();
  806. CreateNewWindow (kDocumentWindowClass,
  807. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  808. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  809. &r, &wrapperWindow);
  810. jassert (wrapperWindow != 0);
  811. if (wrapperWindow == 0)
  812. return;
  813. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  814. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  815. [ownerWindow addChildWindow: carbonWindow
  816. ordered: NSWindowAbove];
  817. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  818. EventTypeSpec windowEventTypes[] =
  819. {
  820. { kEventClassWindow, kEventWindowGetClickActivation },
  821. { kEventClassWindow, kEventWindowHandleDeactivate },
  822. { kEventClassWindow, kEventWindowBoundsChanging },
  823. { kEventClassMouse, kEventMouseDown },
  824. { kEventClassMouse, kEventMouseMoved },
  825. { kEventClassMouse, kEventMouseDragged },
  826. { kEventClassMouse, kEventMouseUp},
  827. { kEventClassWindow, kEventWindowDrawContent },
  828. { kEventClassWindow, kEventWindowShown },
  829. { kEventClassWindow, kEventWindowHidden }
  830. };
  831. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  832. InstallWindowEventHandler (wrapperWindow, upp,
  833. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  834. windowEventTypes, this, &eventHandlerRef);
  835. setOurSizeToEmbeddedViewSize();
  836. setEmbeddedWindowToOurSize();
  837. creationTime = Time::getCurrentTime();
  838. }
  839. }
  840. void deleteWindow()
  841. {
  842. removeView (embeddedView);
  843. embeddedView = 0;
  844. if (wrapperWindow != 0)
  845. {
  846. RemoveEventHandler (eventHandlerRef);
  847. DisposeWindow (wrapperWindow);
  848. wrapperWindow = 0;
  849. }
  850. }
  851. void setOurSizeToEmbeddedViewSize()
  852. {
  853. int w, h;
  854. if (getEmbeddedViewSize (w, h))
  855. {
  856. if (w != getWidth() || h != getHeight())
  857. {
  858. startTimer (50);
  859. setSize (w, h);
  860. if (getParentComponent() != 0)
  861. getParentComponent()->setSize (w, h);
  862. }
  863. else
  864. {
  865. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  866. }
  867. }
  868. else
  869. {
  870. stopTimer();
  871. }
  872. }
  873. void setEmbeddedWindowToOurSize()
  874. {
  875. if (! recursiveResize)
  876. {
  877. recursiveResize = true;
  878. if (embeddedView != 0)
  879. {
  880. HIRect r;
  881. r.origin.x = 0;
  882. r.origin.y = 0;
  883. r.size.width = (float) getWidth();
  884. r.size.height = (float) getHeight();
  885. HIViewSetFrame (embeddedView, &r);
  886. }
  887. if (wrapperWindow != 0)
  888. {
  889. Rect wr;
  890. wr.left = getScreenX();
  891. wr.top = getScreenY();
  892. wr.right = wr.left + getWidth();
  893. wr.bottom = wr.top + getHeight();
  894. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  895. ShowWindow (wrapperWindow);
  896. }
  897. recursiveResize = false;
  898. }
  899. }
  900. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  901. {
  902. setEmbeddedWindowToOurSize();
  903. }
  904. void componentPeerChanged()
  905. {
  906. deleteWindow();
  907. createWindow();
  908. }
  909. void componentVisibilityChanged (Component&)
  910. {
  911. if (isShowing())
  912. createWindow();
  913. else
  914. deleteWindow();
  915. setEmbeddedWindowToOurSize();
  916. }
  917. static void recursiveHIViewRepaint (HIViewRef view)
  918. {
  919. HIViewSetNeedsDisplay (view, true);
  920. HIViewRef child = HIViewGetFirstSubview (view);
  921. while (child != 0)
  922. {
  923. recursiveHIViewRepaint (child);
  924. child = HIViewGetNextView (child);
  925. }
  926. }
  927. void timerCallback()
  928. {
  929. setOurSizeToEmbeddedViewSize();
  930. // To avoid strange overpainting problems when the UI is first opened, we'll
  931. // repaint it a few times during the first second that it's on-screen..
  932. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  933. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  934. }
  935. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  936. {
  937. switch (GetEventKind (event))
  938. {
  939. case kEventWindowHandleDeactivate:
  940. ActivateWindow (wrapperWindow, TRUE);
  941. return noErr;
  942. case kEventWindowGetClickActivation:
  943. {
  944. getTopLevelComponent()->toFront (false);
  945. [carbonWindow makeKeyAndOrderFront: nil];
  946. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  947. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  948. sizeof (ClickActivationResult), &howToHandleClick);
  949. HIViewSetNeedsDisplay (embeddedView, true);
  950. return noErr;
  951. }
  952. }
  953. return eventNotHandledErr;
  954. }
  955. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  956. {
  957. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  958. }
  959. protected:
  960. WindowRef wrapperWindow;
  961. NSWindow* carbonWindow;
  962. HIViewRef embeddedView;
  963. bool recursiveResize;
  964. Time creationTime;
  965. EventHandlerRef eventHandlerRef;
  966. };
  967. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  968. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  969. END_JUCE_NAMESPACE
  970. #endif
  971. #define JUCE_AMALGAMATED_TEMPLATE 1
  972. //==============================================================================
  973. #if JUCE_BUILD_CORE
  974. /*** Start of inlined file: juce_FileLogger.cpp ***/
  975. BEGIN_JUCE_NAMESPACE
  976. FileLogger::FileLogger (const File& logFile_,
  977. const String& welcomeMessage,
  978. const int maxInitialFileSizeBytes)
  979. : logFile (logFile_)
  980. {
  981. if (maxInitialFileSizeBytes >= 0)
  982. trimFileSize (maxInitialFileSizeBytes);
  983. if (! logFile_.exists())
  984. {
  985. // do this so that the parent directories get created..
  986. logFile_.create();
  987. }
  988. String welcome;
  989. welcome << "\r\n**********************************************************\r\n"
  990. << welcomeMessage
  991. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  992. << "\r\n";
  993. logMessage (welcome);
  994. }
  995. FileLogger::~FileLogger()
  996. {
  997. }
  998. void FileLogger::logMessage (const String& message)
  999. {
  1000. DBG (message);
  1001. const ScopedLock sl (logLock);
  1002. FileOutputStream out (logFile, 256);
  1003. out << message << "\r\n";
  1004. }
  1005. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  1006. {
  1007. if (maxFileSizeBytes <= 0)
  1008. {
  1009. logFile.deleteFile();
  1010. }
  1011. else
  1012. {
  1013. const int64 fileSize = logFile.getSize();
  1014. if (fileSize > maxFileSizeBytes)
  1015. {
  1016. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1017. jassert (in != 0);
  1018. if (in != 0)
  1019. {
  1020. in->setPosition (fileSize - maxFileSizeBytes);
  1021. String content;
  1022. {
  1023. MemoryBlock contentToSave;
  1024. contentToSave.setSize (maxFileSizeBytes + 4);
  1025. contentToSave.fillWith (0);
  1026. in->read (contentToSave.getData(), maxFileSizeBytes);
  1027. in = 0;
  1028. content = contentToSave.toString();
  1029. }
  1030. int newStart = 0;
  1031. while (newStart < fileSize
  1032. && content[newStart] != '\n'
  1033. && content[newStart] != '\r')
  1034. ++newStart;
  1035. logFile.deleteFile();
  1036. logFile.appendText (content.substring (newStart), false, false);
  1037. }
  1038. }
  1039. }
  1040. }
  1041. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1042. const String& logFileName,
  1043. const String& welcomeMessage,
  1044. const int maxInitialFileSizeBytes)
  1045. {
  1046. #if JUCE_MAC
  1047. File logFile ("~/Library/Logs");
  1048. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1049. .getChildFile (logFileName);
  1050. #else
  1051. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1052. if (logFile.isDirectory())
  1053. {
  1054. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1055. .getChildFile (logFileName);
  1056. }
  1057. #endif
  1058. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1059. }
  1060. END_JUCE_NAMESPACE
  1061. /*** End of inlined file: juce_FileLogger.cpp ***/
  1062. /*** Start of inlined file: juce_Logger.cpp ***/
  1063. BEGIN_JUCE_NAMESPACE
  1064. Logger::Logger()
  1065. {
  1066. }
  1067. Logger::~Logger()
  1068. {
  1069. }
  1070. Logger* Logger::currentLogger = 0;
  1071. void Logger::setCurrentLogger (Logger* const newLogger,
  1072. const bool deleteOldLogger)
  1073. {
  1074. Logger* const oldLogger = currentLogger;
  1075. currentLogger = newLogger;
  1076. if (deleteOldLogger)
  1077. delete oldLogger;
  1078. }
  1079. void Logger::writeToLog (const String& message)
  1080. {
  1081. if (currentLogger != 0)
  1082. currentLogger->logMessage (message);
  1083. else
  1084. outputDebugString (message);
  1085. }
  1086. #if JUCE_LOG_ASSERTIONS
  1087. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1088. {
  1089. String m ("JUCE Assertion failure in ");
  1090. m << filename << ", line " << lineNum;
  1091. Logger::writeToLog (m);
  1092. }
  1093. #endif
  1094. END_JUCE_NAMESPACE
  1095. /*** End of inlined file: juce_Logger.cpp ***/
  1096. /*** Start of inlined file: juce_Random.cpp ***/
  1097. BEGIN_JUCE_NAMESPACE
  1098. Random::Random (const int64 seedValue) throw()
  1099. : seed (seedValue)
  1100. {
  1101. }
  1102. Random::~Random() throw()
  1103. {
  1104. }
  1105. void Random::setSeed (const int64 newSeed) throw()
  1106. {
  1107. seed = newSeed;
  1108. }
  1109. void Random::combineSeed (const int64 seedValue) throw()
  1110. {
  1111. seed ^= nextInt64() ^ seedValue;
  1112. }
  1113. void Random::setSeedRandomly()
  1114. {
  1115. combineSeed ((int64) (pointer_sized_int) this);
  1116. combineSeed (Time::getMillisecondCounter());
  1117. combineSeed (Time::getHighResolutionTicks());
  1118. combineSeed (Time::getHighResolutionTicksPerSecond());
  1119. combineSeed (Time::currentTimeMillis());
  1120. }
  1121. int Random::nextInt() throw()
  1122. {
  1123. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1124. return (int) (seed >> 16);
  1125. }
  1126. int Random::nextInt (const int maxValue) throw()
  1127. {
  1128. jassert (maxValue > 0);
  1129. return (nextInt() & 0x7fffffff) % maxValue;
  1130. }
  1131. int64 Random::nextInt64() throw()
  1132. {
  1133. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1134. }
  1135. bool Random::nextBool() throw()
  1136. {
  1137. return (nextInt() & 0x80000000) != 0;
  1138. }
  1139. float Random::nextFloat() throw()
  1140. {
  1141. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1142. }
  1143. double Random::nextDouble() throw()
  1144. {
  1145. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1146. }
  1147. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1148. {
  1149. BigInteger n;
  1150. do
  1151. {
  1152. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1153. }
  1154. while (n >= maximumValue);
  1155. return n;
  1156. }
  1157. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1158. {
  1159. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1160. while ((startBit & 31) != 0 && numBits > 0)
  1161. {
  1162. arrayToChange.setBit (startBit++, nextBool());
  1163. --numBits;
  1164. }
  1165. while (numBits >= 32)
  1166. {
  1167. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1168. startBit += 32;
  1169. numBits -= 32;
  1170. }
  1171. while (--numBits >= 0)
  1172. arrayToChange.setBit (startBit + numBits, nextBool());
  1173. }
  1174. Random& Random::getSystemRandom() throw()
  1175. {
  1176. static Random sysRand (1);
  1177. return sysRand;
  1178. }
  1179. END_JUCE_NAMESPACE
  1180. /*** End of inlined file: juce_Random.cpp ***/
  1181. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1182. BEGIN_JUCE_NAMESPACE
  1183. RelativeTime::RelativeTime (const double seconds_) throw()
  1184. : seconds (seconds_)
  1185. {
  1186. }
  1187. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1188. : seconds (other.seconds)
  1189. {
  1190. }
  1191. RelativeTime::~RelativeTime() throw()
  1192. {
  1193. }
  1194. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1195. {
  1196. return RelativeTime (milliseconds * 0.001);
  1197. }
  1198. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1199. {
  1200. return RelativeTime (milliseconds * 0.001);
  1201. }
  1202. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1203. {
  1204. return RelativeTime (numberOfMinutes * 60.0);
  1205. }
  1206. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1207. {
  1208. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1209. }
  1210. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1211. {
  1212. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1213. }
  1214. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1215. {
  1216. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1217. }
  1218. int64 RelativeTime::inMilliseconds() const throw()
  1219. {
  1220. return (int64) (seconds * 1000.0);
  1221. }
  1222. double RelativeTime::inMinutes() const throw()
  1223. {
  1224. return seconds / 60.0;
  1225. }
  1226. double RelativeTime::inHours() const throw()
  1227. {
  1228. return seconds / (60.0 * 60.0);
  1229. }
  1230. double RelativeTime::inDays() const throw()
  1231. {
  1232. return seconds / (60.0 * 60.0 * 24.0);
  1233. }
  1234. double RelativeTime::inWeeks() const throw()
  1235. {
  1236. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1237. }
  1238. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1239. {
  1240. if (seconds < 0.001 && seconds > -0.001)
  1241. return returnValueForZeroTime;
  1242. String result;
  1243. if (seconds < 0)
  1244. result = "-";
  1245. int fieldsShown = 0;
  1246. int n = abs ((int) inWeeks());
  1247. if (n > 0)
  1248. {
  1249. result << n << ((n == 1) ? TRANS(" week ")
  1250. : TRANS(" weeks "));
  1251. ++fieldsShown;
  1252. }
  1253. n = abs ((int) inDays()) % 7;
  1254. if (n > 0)
  1255. {
  1256. result << n << ((n == 1) ? TRANS(" day ")
  1257. : TRANS(" days "));
  1258. ++fieldsShown;
  1259. }
  1260. if (fieldsShown < 2)
  1261. {
  1262. n = abs ((int) inHours()) % 24;
  1263. if (n > 0)
  1264. {
  1265. result << n << ((n == 1) ? TRANS(" hr ")
  1266. : TRANS(" hrs "));
  1267. ++fieldsShown;
  1268. }
  1269. if (fieldsShown < 2)
  1270. {
  1271. n = abs ((int) inMinutes()) % 60;
  1272. if (n > 0)
  1273. {
  1274. result << n << ((n == 1) ? TRANS(" min ")
  1275. : TRANS(" mins "));
  1276. ++fieldsShown;
  1277. }
  1278. if (fieldsShown < 2)
  1279. {
  1280. n = abs ((int) inSeconds()) % 60;
  1281. if (n > 0)
  1282. {
  1283. result << n << ((n == 1) ? TRANS(" sec ")
  1284. : TRANS(" secs "));
  1285. ++fieldsShown;
  1286. }
  1287. if (fieldsShown < 1)
  1288. {
  1289. n = abs ((int) inMilliseconds()) % 1000;
  1290. if (n > 0)
  1291. {
  1292. result << n << TRANS(" ms");
  1293. ++fieldsShown;
  1294. }
  1295. }
  1296. }
  1297. }
  1298. }
  1299. return result.trimEnd();
  1300. }
  1301. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1302. {
  1303. seconds = other.seconds;
  1304. return *this;
  1305. }
  1306. bool RelativeTime::operator== (const RelativeTime& other) const throw() { return seconds == other.seconds; }
  1307. bool RelativeTime::operator!= (const RelativeTime& other) const throw() { return seconds != other.seconds; }
  1308. bool RelativeTime::operator> (const RelativeTime& other) const throw() { return seconds > other.seconds; }
  1309. bool RelativeTime::operator< (const RelativeTime& other) const throw() { return seconds < other.seconds; }
  1310. bool RelativeTime::operator>= (const RelativeTime& other) const throw() { return seconds >= other.seconds; }
  1311. bool RelativeTime::operator<= (const RelativeTime& other) const throw() { return seconds <= other.seconds; }
  1312. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1313. {
  1314. return RelativeTime (seconds + timeToAdd.seconds);
  1315. }
  1316. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1317. {
  1318. return RelativeTime (seconds - timeToSubtract.seconds);
  1319. }
  1320. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1321. {
  1322. return RelativeTime (seconds + secondsToAdd);
  1323. }
  1324. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1325. {
  1326. return RelativeTime (seconds - secondsToSubtract);
  1327. }
  1328. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1329. {
  1330. seconds += timeToAdd.seconds;
  1331. return *this;
  1332. }
  1333. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1334. {
  1335. seconds -= timeToSubtract.seconds;
  1336. return *this;
  1337. }
  1338. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1339. {
  1340. seconds += secondsToAdd;
  1341. return *this;
  1342. }
  1343. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1344. {
  1345. seconds -= secondsToSubtract;
  1346. return *this;
  1347. }
  1348. END_JUCE_NAMESPACE
  1349. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1350. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1351. BEGIN_JUCE_NAMESPACE
  1352. SystemStats::CPUFlags SystemStats::cpuFlags;
  1353. const String SystemStats::getJUCEVersion()
  1354. {
  1355. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1356. + "." + String (JUCE_MINOR_VERSION)
  1357. + "." + String (JUCE_BUILDNUMBER);
  1358. }
  1359. const StringArray SystemStats::getMACAddressStrings()
  1360. {
  1361. int64 macAddresses [16];
  1362. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1363. StringArray s;
  1364. for (int i = 0; i < numAddresses; ++i)
  1365. {
  1366. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1367. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1368. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1369. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1370. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1371. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1372. }
  1373. return s;
  1374. }
  1375. #ifdef JUCE_DLL
  1376. void* juce_Malloc (const int size)
  1377. {
  1378. return malloc (size);
  1379. }
  1380. void* juce_Calloc (const int size)
  1381. {
  1382. return calloc (1, size);
  1383. }
  1384. void* juce_Realloc (void* const block, const int size)
  1385. {
  1386. return realloc (block, size);
  1387. }
  1388. void juce_Free (void* const block)
  1389. {
  1390. free (block);
  1391. }
  1392. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1393. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1394. {
  1395. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1396. }
  1397. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1398. {
  1399. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1400. }
  1401. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1402. {
  1403. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1404. }
  1405. void juce_DebugFree (void* const block)
  1406. {
  1407. _free_dbg (block, _NORMAL_BLOCK);
  1408. }
  1409. #endif
  1410. #endif
  1411. END_JUCE_NAMESPACE
  1412. /*** End of inlined file: juce_SystemStats.cpp ***/
  1413. /*** Start of inlined file: juce_Time.cpp ***/
  1414. #if JUCE_MSVC
  1415. #pragma warning (push)
  1416. #pragma warning (disable: 4514)
  1417. #endif
  1418. #ifndef JUCE_WINDOWS
  1419. #include <sys/time.h>
  1420. #else
  1421. #include <ctime>
  1422. #endif
  1423. #include <sys/timeb.h>
  1424. #if JUCE_MSVC
  1425. #pragma warning (pop)
  1426. #ifdef _INC_TIME_INL
  1427. #define USE_NEW_SECURE_TIME_FNS
  1428. #endif
  1429. #endif
  1430. BEGIN_JUCE_NAMESPACE
  1431. namespace TimeHelpers
  1432. {
  1433. static struct tm millisToLocal (const int64 millis) throw()
  1434. {
  1435. struct tm result;
  1436. const int64 seconds = millis / 1000;
  1437. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1438. {
  1439. // use extended maths for dates beyond 1970 to 2037..
  1440. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1441. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1442. const int days = (int) (jdm / literal64bit (86400));
  1443. const int a = 32044 + days;
  1444. const int b = (4 * a + 3) / 146097;
  1445. const int c = a - (b * 146097) / 4;
  1446. const int d = (4 * c + 3) / 1461;
  1447. const int e = c - (d * 1461) / 4;
  1448. const int m = (5 * e + 2) / 153;
  1449. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1450. result.tm_mon = m + 2 - 12 * (m / 10);
  1451. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1452. result.tm_wday = (days + 1) % 7;
  1453. result.tm_yday = -1;
  1454. int t = (int) (jdm % literal64bit (86400));
  1455. result.tm_hour = t / 3600;
  1456. t %= 3600;
  1457. result.tm_min = t / 60;
  1458. result.tm_sec = t % 60;
  1459. result.tm_isdst = -1;
  1460. }
  1461. else
  1462. {
  1463. time_t now = static_cast <time_t> (seconds);
  1464. #if JUCE_WINDOWS
  1465. #ifdef USE_NEW_SECURE_TIME_FNS
  1466. if (now >= 0 && now <= 0x793406fff)
  1467. localtime_s (&result, &now);
  1468. else
  1469. zeromem (&result, sizeof (result));
  1470. #else
  1471. result = *localtime (&now);
  1472. #endif
  1473. #else
  1474. // more thread-safe
  1475. localtime_r (&now, &result);
  1476. #endif
  1477. }
  1478. return result;
  1479. }
  1480. static int extendedModulo (const int64 value, const int modulo) throw()
  1481. {
  1482. return (int) (value >= 0 ? (value % modulo)
  1483. : (value - ((value / modulo) + 1) * modulo));
  1484. }
  1485. static uint32 lastMSCounterValue = 0;
  1486. }
  1487. Time::Time() throw()
  1488. : millisSinceEpoch (0)
  1489. {
  1490. }
  1491. Time::Time (const Time& other) throw()
  1492. : millisSinceEpoch (other.millisSinceEpoch)
  1493. {
  1494. }
  1495. Time::Time (const int64 ms) throw()
  1496. : millisSinceEpoch (ms)
  1497. {
  1498. }
  1499. Time::Time (const int year,
  1500. const int month,
  1501. const int day,
  1502. const int hours,
  1503. const int minutes,
  1504. const int seconds,
  1505. const int milliseconds,
  1506. const bool useLocalTime) throw()
  1507. {
  1508. jassert (year > 100); // year must be a 4-digit version
  1509. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1510. {
  1511. // use extended maths for dates beyond 1970 to 2037..
  1512. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1513. : 0;
  1514. const int a = (13 - month) / 12;
  1515. const int y = year + 4800 - a;
  1516. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1517. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1518. - 32045;
  1519. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1520. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1521. + milliseconds;
  1522. }
  1523. else
  1524. {
  1525. struct tm t;
  1526. t.tm_year = year - 1900;
  1527. t.tm_mon = month;
  1528. t.tm_mday = day;
  1529. t.tm_hour = hours;
  1530. t.tm_min = minutes;
  1531. t.tm_sec = seconds;
  1532. t.tm_isdst = -1;
  1533. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1534. if (millisSinceEpoch < 0)
  1535. millisSinceEpoch = 0;
  1536. else
  1537. millisSinceEpoch += milliseconds;
  1538. }
  1539. }
  1540. Time::~Time() throw()
  1541. {
  1542. }
  1543. Time& Time::operator= (const Time& other) throw()
  1544. {
  1545. millisSinceEpoch = other.millisSinceEpoch;
  1546. return *this;
  1547. }
  1548. int64 Time::currentTimeMillis() throw()
  1549. {
  1550. static uint32 lastCounterResult = 0xffffffff;
  1551. static int64 correction = 0;
  1552. const uint32 now = getMillisecondCounter();
  1553. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1554. if (now < lastCounterResult)
  1555. {
  1556. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1557. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1558. {
  1559. // get the time once using normal library calls, and store the difference needed to
  1560. // turn the millisecond counter into a real time.
  1561. #if JUCE_WINDOWS
  1562. struct _timeb t;
  1563. #ifdef USE_NEW_SECURE_TIME_FNS
  1564. _ftime_s (&t);
  1565. #else
  1566. _ftime (&t);
  1567. #endif
  1568. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1569. #else
  1570. struct timeval tv;
  1571. struct timezone tz;
  1572. gettimeofday (&tv, &tz);
  1573. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1574. #endif
  1575. }
  1576. }
  1577. lastCounterResult = now;
  1578. return correction + now;
  1579. }
  1580. uint32 juce_millisecondsSinceStartup() throw();
  1581. uint32 Time::getMillisecondCounter() throw()
  1582. {
  1583. const uint32 now = juce_millisecondsSinceStartup();
  1584. if (now < TimeHelpers::lastMSCounterValue)
  1585. {
  1586. // in multi-threaded apps this might be called concurrently, so
  1587. // make sure that our last counter value only increases and doesn't
  1588. // go backwards..
  1589. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1590. TimeHelpers::lastMSCounterValue = now;
  1591. }
  1592. else
  1593. {
  1594. TimeHelpers::lastMSCounterValue = now;
  1595. }
  1596. return now;
  1597. }
  1598. uint32 Time::getApproximateMillisecondCounter() throw()
  1599. {
  1600. jassert (TimeHelpers::lastMSCounterValue != 0);
  1601. return TimeHelpers::lastMSCounterValue;
  1602. }
  1603. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1604. {
  1605. for (;;)
  1606. {
  1607. const uint32 now = getMillisecondCounter();
  1608. if (now >= targetTime)
  1609. break;
  1610. const int toWait = targetTime - now;
  1611. if (toWait > 2)
  1612. {
  1613. Thread::sleep (jmin (20, toWait >> 1));
  1614. }
  1615. else
  1616. {
  1617. // xxx should consider using mutex_pause on the mac as it apparently
  1618. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1619. for (int i = 10; --i >= 0;)
  1620. Thread::yield();
  1621. }
  1622. }
  1623. }
  1624. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1625. {
  1626. return ticks / (double) getHighResolutionTicksPerSecond();
  1627. }
  1628. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1629. {
  1630. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1631. }
  1632. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1633. {
  1634. return Time (currentTimeMillis());
  1635. }
  1636. const String Time::toString (const bool includeDate,
  1637. const bool includeTime,
  1638. const bool includeSeconds,
  1639. const bool use24HourClock) const throw()
  1640. {
  1641. String result;
  1642. if (includeDate)
  1643. {
  1644. result << getDayOfMonth() << ' '
  1645. << getMonthName (true) << ' '
  1646. << getYear();
  1647. if (includeTime)
  1648. result << ' ';
  1649. }
  1650. if (includeTime)
  1651. {
  1652. const int mins = getMinutes();
  1653. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1654. << (mins < 10 ? ":0" : ":") << mins;
  1655. if (includeSeconds)
  1656. {
  1657. const int secs = getSeconds();
  1658. result << (secs < 10 ? ":0" : ":") << secs;
  1659. }
  1660. if (! use24HourClock)
  1661. result << (isAfternoon() ? "pm" : "am");
  1662. }
  1663. return result.trimEnd();
  1664. }
  1665. const String Time::formatted (const String& format) const
  1666. {
  1667. String buffer;
  1668. int bufferSize = 128;
  1669. buffer.preallocateStorage (bufferSize);
  1670. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1671. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1672. {
  1673. bufferSize += 128;
  1674. buffer.preallocateStorage (bufferSize);
  1675. }
  1676. return buffer;
  1677. }
  1678. int Time::getYear() const throw()
  1679. {
  1680. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1681. }
  1682. int Time::getMonth() const throw()
  1683. {
  1684. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1685. }
  1686. int Time::getDayOfMonth() const throw()
  1687. {
  1688. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1689. }
  1690. int Time::getDayOfWeek() const throw()
  1691. {
  1692. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1693. }
  1694. int Time::getHours() const throw()
  1695. {
  1696. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1697. }
  1698. int Time::getHoursInAmPmFormat() const throw()
  1699. {
  1700. const int hours = getHours();
  1701. if (hours == 0)
  1702. return 12;
  1703. else if (hours <= 12)
  1704. return hours;
  1705. else
  1706. return hours - 12;
  1707. }
  1708. bool Time::isAfternoon() const throw()
  1709. {
  1710. return getHours() >= 12;
  1711. }
  1712. int Time::getMinutes() const throw()
  1713. {
  1714. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1715. }
  1716. int Time::getSeconds() const throw()
  1717. {
  1718. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1719. }
  1720. int Time::getMilliseconds() const throw()
  1721. {
  1722. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1723. }
  1724. bool Time::isDaylightSavingTime() const throw()
  1725. {
  1726. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1727. }
  1728. const String Time::getTimeZone() const throw()
  1729. {
  1730. String zone[2];
  1731. #if JUCE_WINDOWS
  1732. _tzset();
  1733. #ifdef USE_NEW_SECURE_TIME_FNS
  1734. {
  1735. char name [128];
  1736. size_t length;
  1737. for (int i = 0; i < 2; ++i)
  1738. {
  1739. zeromem (name, sizeof (name));
  1740. _get_tzname (&length, name, 127, i);
  1741. zone[i] = name;
  1742. }
  1743. }
  1744. #else
  1745. const char** const zonePtr = (const char**) _tzname;
  1746. zone[0] = zonePtr[0];
  1747. zone[1] = zonePtr[1];
  1748. #endif
  1749. #else
  1750. tzset();
  1751. const char** const zonePtr = (const char**) tzname;
  1752. zone[0] = zonePtr[0];
  1753. zone[1] = zonePtr[1];
  1754. #endif
  1755. if (isDaylightSavingTime())
  1756. {
  1757. zone[0] = zone[1];
  1758. if (zone[0].length() > 3
  1759. && zone[0].containsIgnoreCase ("daylight")
  1760. && zone[0].contains ("GMT"))
  1761. zone[0] = "BST";
  1762. }
  1763. return zone[0].substring (0, 3);
  1764. }
  1765. const String Time::getMonthName (const bool threeLetterVersion) const
  1766. {
  1767. return getMonthName (getMonth(), threeLetterVersion);
  1768. }
  1769. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1770. {
  1771. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1772. }
  1773. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1774. {
  1775. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1776. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1777. monthNumber %= 12;
  1778. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1779. : longMonthNames [monthNumber]);
  1780. }
  1781. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1782. {
  1783. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1784. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1785. day %= 7;
  1786. return TRANS (threeLetterVersion ? shortDayNames [day]
  1787. : longDayNames [day]);
  1788. }
  1789. END_JUCE_NAMESPACE
  1790. /*** End of inlined file: juce_Time.cpp ***/
  1791. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1792. BEGIN_JUCE_NAMESPACE
  1793. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1794. #endif
  1795. #if JUCE_WINDOWS
  1796. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1797. #endif
  1798. #if JUCE_DEBUG
  1799. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1800. #endif
  1801. static bool juceInitialisedNonGUI = false;
  1802. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1803. {
  1804. if (! juceInitialisedNonGUI)
  1805. {
  1806. juceInitialisedNonGUI = true;
  1807. JUCE_AUTORELEASEPOOL
  1808. DBG (SystemStats::getJUCEVersion());
  1809. SystemStats::initialiseStats();
  1810. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1811. }
  1812. // Some basic tests, to keep an eye on things and make sure these types work ok
  1813. // on all platforms. Let me know if any of these assertions fail on your system!
  1814. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1815. static_jassert (sizeof (int8) == 1);
  1816. static_jassert (sizeof (uint8) == 1);
  1817. static_jassert (sizeof (int16) == 2);
  1818. static_jassert (sizeof (uint16) == 2);
  1819. static_jassert (sizeof (int32) == 4);
  1820. static_jassert (sizeof (uint32) == 4);
  1821. static_jassert (sizeof (int64) == 8);
  1822. static_jassert (sizeof (uint64) == 8);
  1823. }
  1824. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1825. {
  1826. if (juceInitialisedNonGUI)
  1827. {
  1828. juceInitialisedNonGUI = false;
  1829. JUCE_AUTORELEASEPOOL
  1830. LocalisedStrings::setCurrentMappings (0);
  1831. Thread::stopAllThreads (3000);
  1832. #if JUCE_WINDOWS
  1833. juce_shutdownWin32Sockets();
  1834. #endif
  1835. #if JUCE_DEBUG
  1836. juce_CheckForDanglingStreams();
  1837. #endif
  1838. }
  1839. }
  1840. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1841. void juce_setCurrentThreadName (const String& name);
  1842. static bool juceInitialisedGUI = false;
  1843. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  1844. {
  1845. if (! juceInitialisedGUI)
  1846. {
  1847. juceInitialisedGUI = true;
  1848. JUCE_AUTORELEASEPOOL
  1849. initialiseJuce_NonGUI();
  1850. MessageManager::getInstance();
  1851. LookAndFeel::setDefaultLookAndFeel (0);
  1852. juce_setCurrentThreadName ("Juce Message Thread");
  1853. #if JUCE_DEBUG
  1854. // This section is just for catching people who mess up their project settings and
  1855. // turn RTTI off..
  1856. try
  1857. {
  1858. TextButton tb (String::empty);
  1859. Component* c = &tb;
  1860. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1861. c = dynamic_cast <Button*> (c);
  1862. }
  1863. catch (...)
  1864. {
  1865. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1866. jassertfalse;
  1867. }
  1868. #endif
  1869. }
  1870. }
  1871. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  1872. {
  1873. if (juceInitialisedGUI)
  1874. {
  1875. juceInitialisedGUI = false;
  1876. JUCE_AUTORELEASEPOOL
  1877. DeletedAtShutdown::deleteAll();
  1878. LookAndFeel::clearDefaultLookAndFeel();
  1879. delete MessageManager::getInstance();
  1880. shutdownJuce_NonGUI();
  1881. }
  1882. }
  1883. #endif
  1884. #if JUCE_UNIT_TESTS
  1885. class AtomicTests : public UnitTest
  1886. {
  1887. public:
  1888. AtomicTests() : UnitTest ("Atomics") {}
  1889. void runTest()
  1890. {
  1891. beginTest ("Misc");
  1892. char a1[7];
  1893. expect (numElementsInArray(a1) == 7);
  1894. int a2[3];
  1895. expect (numElementsInArray(a2) == 3);
  1896. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1897. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1898. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1899. beginTest ("Atomic types");
  1900. AtomicTester <int>::testInteger (*this);
  1901. AtomicTester <unsigned int>::testInteger (*this);
  1902. AtomicTester <int32>::testInteger (*this);
  1903. AtomicTester <uint32>::testInteger (*this);
  1904. AtomicTester <long>::testInteger (*this);
  1905. AtomicTester <void*>::testInteger (*this);
  1906. AtomicTester <int*>::testInteger (*this);
  1907. AtomicTester <float>::testFloat (*this);
  1908. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1909. AtomicTester <int64>::testInteger (*this);
  1910. AtomicTester <uint64>::testInteger (*this);
  1911. AtomicTester <double>::testFloat (*this);
  1912. #endif
  1913. }
  1914. template <typename Type>
  1915. class AtomicTester
  1916. {
  1917. public:
  1918. AtomicTester() {}
  1919. static void testInteger (UnitTest& test)
  1920. {
  1921. Atomic<Type> a, b;
  1922. a.set ((Type) 10);
  1923. a += (Type) 15;
  1924. a.memoryBarrier();
  1925. a -= (Type) 5;
  1926. ++a; ++a; --a;
  1927. a.memoryBarrier();
  1928. testFloat (test);
  1929. }
  1930. static void testFloat (UnitTest& test)
  1931. {
  1932. Atomic<Type> a, b;
  1933. a = (Type) 21;
  1934. a.memoryBarrier();
  1935. /* These are some simple test cases to check the atomics - let me know
  1936. if any of these assertions fail on your system!
  1937. */
  1938. test.expect (a.get() == (Type) 21);
  1939. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1940. test.expect (a.get() == (Type) 21);
  1941. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1942. test.expect (a.get() == (Type) 101);
  1943. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1944. test.expect (a.get() == (Type) 101);
  1945. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1946. test.expect (a.get() == (Type) 200);
  1947. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1948. test.expect (a.get() == (Type) 300);
  1949. b = a;
  1950. test.expect (b.get() == a.get());
  1951. }
  1952. };
  1953. };
  1954. static AtomicTests atomicUnitTests;
  1955. #endif
  1956. END_JUCE_NAMESPACE
  1957. /*** End of inlined file: juce_Initialisation.cpp ***/
  1958. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1959. BEGIN_JUCE_NAMESPACE
  1960. AbstractFifo::AbstractFifo (const int capacity) throw()
  1961. : bufferSize (capacity)
  1962. {
  1963. jassert (bufferSize > 0);
  1964. }
  1965. AbstractFifo::~AbstractFifo() {}
  1966. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1967. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1968. int AbstractFifo::getNumReady() const throw() { return validEnd.get() - validStart.get(); }
  1969. void AbstractFifo::reset() throw()
  1970. {
  1971. validEnd = 0;
  1972. validStart = 0;
  1973. }
  1974. void AbstractFifo::setTotalSize (int newSize) throw()
  1975. {
  1976. jassert (newSize > 0);
  1977. reset();
  1978. bufferSize = newSize;
  1979. }
  1980. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1981. {
  1982. const int vs = validStart.get();
  1983. const int ve = validEnd.get();
  1984. const int freeSpace = bufferSize - (ve - vs);
  1985. numToWrite = jmin (numToWrite, freeSpace);
  1986. if (numToWrite <= 0)
  1987. {
  1988. startIndex1 = 0;
  1989. startIndex2 = 0;
  1990. blockSize1 = 0;
  1991. blockSize2 = 0;
  1992. }
  1993. else
  1994. {
  1995. startIndex1 = (int) (ve % bufferSize);
  1996. startIndex2 = 0;
  1997. blockSize1 = jmin (bufferSize - startIndex1, numToWrite);
  1998. numToWrite -= blockSize1;
  1999. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, (int) (vs % bufferSize));
  2000. }
  2001. }
  2002. void AbstractFifo::finishedWrite (int numWritten) throw()
  2003. {
  2004. jassert (numWritten >= 0 && numWritten < bufferSize);
  2005. validEnd += numWritten;
  2006. }
  2007. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  2008. {
  2009. const int vs = validStart.get();
  2010. const int ve = validEnd.get();
  2011. const int numReady = ve - vs;
  2012. numWanted = jmin (numWanted, numReady);
  2013. if (numWanted <= 0)
  2014. {
  2015. startIndex1 = 0;
  2016. startIndex2 = 0;
  2017. blockSize1 = 0;
  2018. blockSize2 = 0;
  2019. }
  2020. else
  2021. {
  2022. startIndex1 = (int) (vs % bufferSize);
  2023. startIndex2 = 0;
  2024. blockSize1 = jmin (bufferSize - startIndex1, numWanted);
  2025. numWanted -= blockSize1;
  2026. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, (int) (ve % bufferSize));
  2027. }
  2028. }
  2029. void AbstractFifo::finishedRead (int numRead) throw()
  2030. {
  2031. jassert (numRead >= 0 && numRead < bufferSize);
  2032. validStart += numRead;
  2033. }
  2034. END_JUCE_NAMESPACE
  2035. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  2036. /*** Start of inlined file: juce_BigInteger.cpp ***/
  2037. BEGIN_JUCE_NAMESPACE
  2038. BigInteger::BigInteger()
  2039. : numValues (4),
  2040. highestBit (-1),
  2041. negative (false)
  2042. {
  2043. values.calloc (numValues + 1);
  2044. }
  2045. BigInteger::BigInteger (const int value)
  2046. : numValues (4),
  2047. highestBit (31),
  2048. negative (value < 0)
  2049. {
  2050. values.calloc (numValues + 1);
  2051. values[0] = abs (value);
  2052. highestBit = getHighestBit();
  2053. }
  2054. BigInteger::BigInteger (int64 value)
  2055. : numValues (4),
  2056. highestBit (63),
  2057. negative (value < 0)
  2058. {
  2059. values.calloc (numValues + 1);
  2060. if (value < 0)
  2061. value = -value;
  2062. values[0] = (unsigned int) value;
  2063. values[1] = (unsigned int) (value >> 32);
  2064. highestBit = getHighestBit();
  2065. }
  2066. BigInteger::BigInteger (const unsigned int value)
  2067. : numValues (4),
  2068. highestBit (31),
  2069. negative (false)
  2070. {
  2071. values.calloc (numValues + 1);
  2072. values[0] = value;
  2073. highestBit = getHighestBit();
  2074. }
  2075. BigInteger::BigInteger (const BigInteger& other)
  2076. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  2077. highestBit (other.getHighestBit()),
  2078. negative (other.negative)
  2079. {
  2080. values.malloc (numValues + 1);
  2081. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2082. }
  2083. BigInteger::~BigInteger()
  2084. {
  2085. }
  2086. void BigInteger::swapWith (BigInteger& other) throw()
  2087. {
  2088. values.swapWith (other.values);
  2089. swapVariables (numValues, other.numValues);
  2090. swapVariables (highestBit, other.highestBit);
  2091. swapVariables (negative, other.negative);
  2092. }
  2093. BigInteger& BigInteger::operator= (const BigInteger& other)
  2094. {
  2095. if (this != &other)
  2096. {
  2097. highestBit = other.getHighestBit();
  2098. numValues = jmax (4, (highestBit >> 5) + 1);
  2099. negative = other.negative;
  2100. values.malloc (numValues + 1);
  2101. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2102. }
  2103. return *this;
  2104. }
  2105. void BigInteger::ensureSize (const int numVals)
  2106. {
  2107. if (numVals + 2 >= numValues)
  2108. {
  2109. int oldSize = numValues;
  2110. numValues = ((numVals + 2) * 3) / 2;
  2111. values.realloc (numValues + 1);
  2112. while (oldSize < numValues)
  2113. values [oldSize++] = 0;
  2114. }
  2115. }
  2116. bool BigInteger::operator[] (const int bit) const throw()
  2117. {
  2118. return bit <= highestBit && bit >= 0
  2119. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  2120. }
  2121. int BigInteger::toInteger() const throw()
  2122. {
  2123. const int n = (int) (values[0] & 0x7fffffff);
  2124. return negative ? -n : n;
  2125. }
  2126. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2127. {
  2128. BigInteger r;
  2129. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2130. r.ensureSize (numBits >> 5);
  2131. r.highestBit = numBits;
  2132. int i = 0;
  2133. while (numBits > 0)
  2134. {
  2135. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2136. numBits -= 32;
  2137. startBit += 32;
  2138. }
  2139. r.highestBit = r.getHighestBit();
  2140. return r;
  2141. }
  2142. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2143. {
  2144. if (numBits > 32)
  2145. {
  2146. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2147. numBits = 32;
  2148. }
  2149. numBits = jmin (numBits, highestBit + 1 - startBit);
  2150. if (numBits <= 0)
  2151. return 0;
  2152. const int pos = startBit >> 5;
  2153. const int offset = startBit & 31;
  2154. const int endSpace = 32 - numBits;
  2155. uint32 n = ((uint32) values [pos]) >> offset;
  2156. if (offset > endSpace)
  2157. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2158. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2159. }
  2160. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2161. {
  2162. if (numBits > 32)
  2163. {
  2164. jassertfalse;
  2165. numBits = 32;
  2166. }
  2167. for (int i = 0; i < numBits; ++i)
  2168. {
  2169. setBit (startBit + i, (valueToSet & 1) != 0);
  2170. valueToSet >>= 1;
  2171. }
  2172. }
  2173. void BigInteger::clear()
  2174. {
  2175. if (numValues > 16)
  2176. {
  2177. numValues = 4;
  2178. values.calloc (numValues + 1);
  2179. }
  2180. else
  2181. {
  2182. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2183. }
  2184. highestBit = -1;
  2185. negative = false;
  2186. }
  2187. void BigInteger::setBit (const int bit)
  2188. {
  2189. if (bit >= 0)
  2190. {
  2191. if (bit > highestBit)
  2192. {
  2193. ensureSize (bit >> 5);
  2194. highestBit = bit;
  2195. }
  2196. values [bit >> 5] |= (1 << (bit & 31));
  2197. }
  2198. }
  2199. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2200. {
  2201. if (shouldBeSet)
  2202. setBit (bit);
  2203. else
  2204. clearBit (bit);
  2205. }
  2206. void BigInteger::clearBit (const int bit) throw()
  2207. {
  2208. if (bit >= 0 && bit <= highestBit)
  2209. values [bit >> 5] &= ~(1 << (bit & 31));
  2210. }
  2211. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2212. {
  2213. while (--numBits >= 0)
  2214. setBit (startBit++, shouldBeSet);
  2215. }
  2216. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2217. {
  2218. if (bit >= 0)
  2219. shiftBits (1, bit);
  2220. setBit (bit, shouldBeSet);
  2221. }
  2222. bool BigInteger::isZero() const throw()
  2223. {
  2224. return getHighestBit() < 0;
  2225. }
  2226. bool BigInteger::isOne() const throw()
  2227. {
  2228. return getHighestBit() == 0 && ! negative;
  2229. }
  2230. bool BigInteger::isNegative() const throw()
  2231. {
  2232. return negative && ! isZero();
  2233. }
  2234. void BigInteger::setNegative (const bool neg) throw()
  2235. {
  2236. negative = neg;
  2237. }
  2238. void BigInteger::negate() throw()
  2239. {
  2240. negative = (! negative) && ! isZero();
  2241. }
  2242. int BigInteger::countNumberOfSetBits() const throw()
  2243. {
  2244. int total = 0;
  2245. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2246. {
  2247. unsigned int n = values[i];
  2248. if (n == 0xffffffff)
  2249. {
  2250. total += 32;
  2251. }
  2252. else
  2253. {
  2254. while (n != 0)
  2255. {
  2256. total += (n & 1);
  2257. n >>= 1;
  2258. }
  2259. }
  2260. }
  2261. return total;
  2262. }
  2263. int BigInteger::getHighestBit() const throw()
  2264. {
  2265. for (int i = highestBit + 1; --i >= 0;)
  2266. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2267. return i;
  2268. return -1;
  2269. }
  2270. int BigInteger::findNextSetBit (int i) const throw()
  2271. {
  2272. for (; i <= highestBit; ++i)
  2273. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2274. return i;
  2275. return -1;
  2276. }
  2277. int BigInteger::findNextClearBit (int i) const throw()
  2278. {
  2279. for (; i <= highestBit; ++i)
  2280. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2281. break;
  2282. return i;
  2283. }
  2284. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2285. {
  2286. if (other.isNegative())
  2287. return operator-= (-other);
  2288. if (isNegative())
  2289. {
  2290. if (compareAbsolute (other) < 0)
  2291. {
  2292. BigInteger temp (*this);
  2293. temp.negate();
  2294. *this = other;
  2295. operator-= (temp);
  2296. }
  2297. else
  2298. {
  2299. negate();
  2300. operator-= (other);
  2301. negate();
  2302. }
  2303. }
  2304. else
  2305. {
  2306. if (other.highestBit > highestBit)
  2307. highestBit = other.highestBit;
  2308. ++highestBit;
  2309. const int numInts = (highestBit >> 5) + 1;
  2310. ensureSize (numInts);
  2311. int64 remainder = 0;
  2312. for (int i = 0; i <= numInts; ++i)
  2313. {
  2314. if (i < numValues)
  2315. remainder += values[i];
  2316. if (i < other.numValues)
  2317. remainder += other.values[i];
  2318. values[i] = (unsigned int) remainder;
  2319. remainder >>= 32;
  2320. }
  2321. jassert (remainder == 0);
  2322. highestBit = getHighestBit();
  2323. }
  2324. return *this;
  2325. }
  2326. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2327. {
  2328. if (other.isNegative())
  2329. return operator+= (-other);
  2330. if (! isNegative())
  2331. {
  2332. if (compareAbsolute (other) < 0)
  2333. {
  2334. BigInteger temp (other);
  2335. swapWith (temp);
  2336. operator-= (temp);
  2337. negate();
  2338. return *this;
  2339. }
  2340. }
  2341. else
  2342. {
  2343. negate();
  2344. operator+= (other);
  2345. negate();
  2346. return *this;
  2347. }
  2348. const int numInts = (highestBit >> 5) + 1;
  2349. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2350. int64 amountToSubtract = 0;
  2351. for (int i = 0; i <= numInts; ++i)
  2352. {
  2353. if (i <= maxOtherInts)
  2354. amountToSubtract += (int64) other.values[i];
  2355. if (values[i] >= amountToSubtract)
  2356. {
  2357. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2358. amountToSubtract = 0;
  2359. }
  2360. else
  2361. {
  2362. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2363. values[i] = (unsigned int) n;
  2364. amountToSubtract = 1;
  2365. }
  2366. }
  2367. return *this;
  2368. }
  2369. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2370. {
  2371. BigInteger total;
  2372. highestBit = getHighestBit();
  2373. const bool wasNegative = isNegative();
  2374. setNegative (false);
  2375. for (int i = 0; i <= highestBit; ++i)
  2376. {
  2377. if (operator[](i))
  2378. {
  2379. BigInteger n (other);
  2380. n.setNegative (false);
  2381. n <<= i;
  2382. total += n;
  2383. }
  2384. }
  2385. total.setNegative (wasNegative ^ other.isNegative());
  2386. swapWith (total);
  2387. return *this;
  2388. }
  2389. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2390. {
  2391. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2392. const int divHB = divisor.getHighestBit();
  2393. const int ourHB = getHighestBit();
  2394. if (divHB < 0 || ourHB < 0)
  2395. {
  2396. // division by zero
  2397. remainder.clear();
  2398. clear();
  2399. }
  2400. else
  2401. {
  2402. const bool wasNegative = isNegative();
  2403. swapWith (remainder);
  2404. remainder.setNegative (false);
  2405. clear();
  2406. BigInteger temp (divisor);
  2407. temp.setNegative (false);
  2408. int leftShift = ourHB - divHB;
  2409. temp <<= leftShift;
  2410. while (leftShift >= 0)
  2411. {
  2412. if (remainder.compareAbsolute (temp) >= 0)
  2413. {
  2414. remainder -= temp;
  2415. setBit (leftShift);
  2416. }
  2417. if (--leftShift >= 0)
  2418. temp >>= 1;
  2419. }
  2420. negative = wasNegative ^ divisor.isNegative();
  2421. remainder.setNegative (wasNegative);
  2422. }
  2423. }
  2424. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2425. {
  2426. BigInteger remainder;
  2427. divideBy (other, remainder);
  2428. return *this;
  2429. }
  2430. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2431. {
  2432. // this operation doesn't take into account negative values..
  2433. jassert (isNegative() == other.isNegative());
  2434. if (other.highestBit >= 0)
  2435. {
  2436. ensureSize (other.highestBit >> 5);
  2437. int n = (other.highestBit >> 5) + 1;
  2438. while (--n >= 0)
  2439. values[n] |= other.values[n];
  2440. if (other.highestBit > highestBit)
  2441. highestBit = other.highestBit;
  2442. highestBit = getHighestBit();
  2443. }
  2444. return *this;
  2445. }
  2446. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2447. {
  2448. // this operation doesn't take into account negative values..
  2449. jassert (isNegative() == other.isNegative());
  2450. int n = numValues;
  2451. while (n > other.numValues)
  2452. values[--n] = 0;
  2453. while (--n >= 0)
  2454. values[n] &= other.values[n];
  2455. if (other.highestBit < highestBit)
  2456. highestBit = other.highestBit;
  2457. highestBit = getHighestBit();
  2458. return *this;
  2459. }
  2460. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2461. {
  2462. // this operation will only work with the absolute values
  2463. jassert (isNegative() == other.isNegative());
  2464. if (other.highestBit >= 0)
  2465. {
  2466. ensureSize (other.highestBit >> 5);
  2467. int n = (other.highestBit >> 5) + 1;
  2468. while (--n >= 0)
  2469. values[n] ^= other.values[n];
  2470. if (other.highestBit > highestBit)
  2471. highestBit = other.highestBit;
  2472. highestBit = getHighestBit();
  2473. }
  2474. return *this;
  2475. }
  2476. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2477. {
  2478. BigInteger remainder;
  2479. divideBy (divisor, remainder);
  2480. swapWith (remainder);
  2481. return *this;
  2482. }
  2483. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2484. {
  2485. shiftBits (numBitsToShift, 0);
  2486. return *this;
  2487. }
  2488. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2489. {
  2490. return operator<<= (-numBitsToShift);
  2491. }
  2492. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2493. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2494. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2495. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2496. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2497. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2498. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2499. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2500. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2501. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2502. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2503. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2504. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2505. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2506. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2507. int BigInteger::compare (const BigInteger& other) const throw()
  2508. {
  2509. if (isNegative() == other.isNegative())
  2510. {
  2511. const int absComp = compareAbsolute (other);
  2512. return isNegative() ? -absComp : absComp;
  2513. }
  2514. else
  2515. {
  2516. return isNegative() ? -1 : 1;
  2517. }
  2518. }
  2519. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2520. {
  2521. const int h1 = getHighestBit();
  2522. const int h2 = other.getHighestBit();
  2523. if (h1 > h2)
  2524. return 1;
  2525. else if (h1 < h2)
  2526. return -1;
  2527. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2528. if (values[i] != other.values[i])
  2529. return (values[i] > other.values[i]) ? 1 : -1;
  2530. return 0;
  2531. }
  2532. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2533. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2534. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2535. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2536. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2537. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2538. void BigInteger::shiftBits (int bits, const int startBit)
  2539. {
  2540. if (highestBit < 0)
  2541. return;
  2542. if (startBit > 0)
  2543. {
  2544. if (bits < 0)
  2545. {
  2546. // right shift
  2547. for (int i = startBit; i <= highestBit; ++i)
  2548. setBit (i, operator[] (i - bits));
  2549. highestBit = getHighestBit();
  2550. }
  2551. else if (bits > 0)
  2552. {
  2553. // left shift
  2554. for (int i = highestBit + 1; --i >= startBit;)
  2555. setBit (i + bits, operator[] (i));
  2556. while (--bits >= 0)
  2557. clearBit (bits + startBit);
  2558. }
  2559. }
  2560. else
  2561. {
  2562. if (bits < 0)
  2563. {
  2564. // right shift
  2565. bits = -bits;
  2566. if (bits > highestBit)
  2567. {
  2568. clear();
  2569. }
  2570. else
  2571. {
  2572. const int wordsToMove = bits >> 5;
  2573. int top = 1 + (highestBit >> 5) - wordsToMove;
  2574. highestBit -= bits;
  2575. if (wordsToMove > 0)
  2576. {
  2577. int i;
  2578. for (i = 0; i < top; ++i)
  2579. values [i] = values [i + wordsToMove];
  2580. for (i = 0; i < wordsToMove; ++i)
  2581. values [top + i] = 0;
  2582. bits &= 31;
  2583. }
  2584. if (bits != 0)
  2585. {
  2586. const int invBits = 32 - bits;
  2587. --top;
  2588. for (int i = 0; i < top; ++i)
  2589. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2590. values[top] = (values[top] >> bits);
  2591. }
  2592. highestBit = getHighestBit();
  2593. }
  2594. }
  2595. else if (bits > 0)
  2596. {
  2597. // left shift
  2598. ensureSize (((highestBit + bits) >> 5) + 1);
  2599. const int wordsToMove = bits >> 5;
  2600. int top = 1 + (highestBit >> 5);
  2601. highestBit += bits;
  2602. if (wordsToMove > 0)
  2603. {
  2604. int i;
  2605. for (i = top; --i >= 0;)
  2606. values [i + wordsToMove] = values [i];
  2607. for (i = 0; i < wordsToMove; ++i)
  2608. values [i] = 0;
  2609. bits &= 31;
  2610. }
  2611. if (bits != 0)
  2612. {
  2613. const int invBits = 32 - bits;
  2614. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2615. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2616. values [wordsToMove] = values [wordsToMove] << bits;
  2617. }
  2618. highestBit = getHighestBit();
  2619. }
  2620. }
  2621. }
  2622. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2623. {
  2624. while (! m->isZero())
  2625. {
  2626. if (n->compareAbsolute (*m) > 0)
  2627. swapVariables (m, n);
  2628. *m -= *n;
  2629. }
  2630. return *n;
  2631. }
  2632. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2633. {
  2634. BigInteger m (*this);
  2635. while (! n.isZero())
  2636. {
  2637. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2638. return simpleGCD (&m, &n);
  2639. BigInteger temp1 (m), temp2;
  2640. temp1.divideBy (n, temp2);
  2641. m = n;
  2642. n = temp2;
  2643. }
  2644. return m;
  2645. }
  2646. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2647. {
  2648. BigInteger exp (exponent);
  2649. exp %= modulus;
  2650. BigInteger value (1);
  2651. swapWith (value);
  2652. value %= modulus;
  2653. while (! exp.isZero())
  2654. {
  2655. if (exp [0])
  2656. {
  2657. operator*= (value);
  2658. operator%= (modulus);
  2659. }
  2660. value *= value;
  2661. value %= modulus;
  2662. exp >>= 1;
  2663. }
  2664. }
  2665. void BigInteger::inverseModulo (const BigInteger& modulus)
  2666. {
  2667. if (modulus.isOne() || modulus.isNegative())
  2668. {
  2669. clear();
  2670. return;
  2671. }
  2672. if (isNegative() || compareAbsolute (modulus) >= 0)
  2673. operator%= (modulus);
  2674. if (isOne())
  2675. return;
  2676. if (! (*this)[0])
  2677. {
  2678. // not invertible
  2679. clear();
  2680. return;
  2681. }
  2682. BigInteger a1 (modulus);
  2683. BigInteger a2 (*this);
  2684. BigInteger b1 (modulus);
  2685. BigInteger b2 (1);
  2686. while (! a2.isOne())
  2687. {
  2688. BigInteger temp1, temp2, multiplier (a1);
  2689. multiplier.divideBy (a2, temp1);
  2690. temp1 = a2;
  2691. temp1 *= multiplier;
  2692. temp2 = a1;
  2693. temp2 -= temp1;
  2694. a1 = a2;
  2695. a2 = temp2;
  2696. temp1 = b2;
  2697. temp1 *= multiplier;
  2698. temp2 = b1;
  2699. temp2 -= temp1;
  2700. b1 = b2;
  2701. b2 = temp2;
  2702. }
  2703. while (b2.isNegative())
  2704. b2 += modulus;
  2705. b2 %= modulus;
  2706. swapWith (b2);
  2707. }
  2708. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2709. {
  2710. return stream << value.toString (10);
  2711. }
  2712. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2713. {
  2714. String s;
  2715. BigInteger v (*this);
  2716. if (base == 2 || base == 8 || base == 16)
  2717. {
  2718. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2719. static const char* const hexDigits = "0123456789abcdef";
  2720. for (;;)
  2721. {
  2722. const int remainder = v.getBitRangeAsInt (0, bits);
  2723. v >>= bits;
  2724. if (remainder == 0 && v.isZero())
  2725. break;
  2726. s = String::charToString (hexDigits [remainder]) + s;
  2727. }
  2728. }
  2729. else if (base == 10)
  2730. {
  2731. const BigInteger ten (10);
  2732. BigInteger remainder;
  2733. for (;;)
  2734. {
  2735. v.divideBy (ten, remainder);
  2736. if (remainder.isZero() && v.isZero())
  2737. break;
  2738. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2739. }
  2740. }
  2741. else
  2742. {
  2743. jassertfalse; // can't do the specified base!
  2744. return String::empty;
  2745. }
  2746. s = s.paddedLeft ('0', minimumNumCharacters);
  2747. return isNegative() ? "-" + s : s;
  2748. }
  2749. void BigInteger::parseString (const String& text, const int base)
  2750. {
  2751. clear();
  2752. const juce_wchar* t = text;
  2753. if (base == 2 || base == 8 || base == 16)
  2754. {
  2755. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2756. for (;;)
  2757. {
  2758. const juce_wchar c = *t++;
  2759. const int digit = CharacterFunctions::getHexDigitValue (c);
  2760. if (((unsigned int) digit) < (unsigned int) base)
  2761. {
  2762. operator<<= (bits);
  2763. operator+= (digit);
  2764. }
  2765. else if (c == 0)
  2766. {
  2767. break;
  2768. }
  2769. }
  2770. }
  2771. else if (base == 10)
  2772. {
  2773. const BigInteger ten ((unsigned int) 10);
  2774. for (;;)
  2775. {
  2776. const juce_wchar c = *t++;
  2777. if (c >= '0' && c <= '9')
  2778. {
  2779. operator*= (ten);
  2780. operator+= ((int) (c - '0'));
  2781. }
  2782. else if (c == 0)
  2783. {
  2784. break;
  2785. }
  2786. }
  2787. }
  2788. setNegative (text.trimStart().startsWithChar ('-'));
  2789. }
  2790. const MemoryBlock BigInteger::toMemoryBlock() const
  2791. {
  2792. const int numBytes = (getHighestBit() + 8) >> 3;
  2793. MemoryBlock mb ((size_t) numBytes);
  2794. for (int i = 0; i < numBytes; ++i)
  2795. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2796. return mb;
  2797. }
  2798. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2799. {
  2800. clear();
  2801. for (int i = (int) data.getSize(); --i >= 0;)
  2802. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2803. }
  2804. END_JUCE_NAMESPACE
  2805. /*** End of inlined file: juce_BigInteger.cpp ***/
  2806. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2807. BEGIN_JUCE_NAMESPACE
  2808. MemoryBlock::MemoryBlock() throw()
  2809. : size (0)
  2810. {
  2811. }
  2812. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2813. {
  2814. if (initialSize > 0)
  2815. {
  2816. size = initialSize;
  2817. data.allocate (initialSize, initialiseToZero);
  2818. }
  2819. else
  2820. {
  2821. size = 0;
  2822. }
  2823. }
  2824. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2825. : size (other.size)
  2826. {
  2827. if (size > 0)
  2828. {
  2829. jassert (other.data != 0);
  2830. data.malloc (size);
  2831. memcpy (data, other.data, size);
  2832. }
  2833. }
  2834. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2835. : size (jmax ((size_t) 0, sizeInBytes))
  2836. {
  2837. jassert (sizeInBytes >= 0);
  2838. if (size > 0)
  2839. {
  2840. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2841. data.malloc (size);
  2842. if (dataToInitialiseFrom != 0)
  2843. memcpy (data, dataToInitialiseFrom, size);
  2844. }
  2845. }
  2846. MemoryBlock::~MemoryBlock() throw()
  2847. {
  2848. jassert (size >= 0); // should never happen
  2849. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2850. }
  2851. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2852. {
  2853. if (this != &other)
  2854. {
  2855. setSize (other.size, false);
  2856. memcpy (data, other.data, size);
  2857. }
  2858. return *this;
  2859. }
  2860. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2861. {
  2862. return matches (other.data, other.size);
  2863. }
  2864. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2865. {
  2866. return ! operator== (other);
  2867. }
  2868. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2869. {
  2870. return size == dataSize
  2871. && memcmp (data, dataToCompare, size) == 0;
  2872. }
  2873. // this will resize the block to this size
  2874. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2875. {
  2876. if (size != newSize)
  2877. {
  2878. if (newSize <= 0)
  2879. {
  2880. data.free();
  2881. size = 0;
  2882. }
  2883. else
  2884. {
  2885. if (data != 0)
  2886. {
  2887. data.realloc (newSize);
  2888. if (initialiseToZero && (newSize > size))
  2889. zeromem (data + size, newSize - size);
  2890. }
  2891. else
  2892. {
  2893. data.allocate (newSize, initialiseToZero);
  2894. }
  2895. size = newSize;
  2896. }
  2897. }
  2898. }
  2899. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2900. {
  2901. if (size < minimumSize)
  2902. setSize (minimumSize, initialiseToZero);
  2903. }
  2904. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2905. {
  2906. swapVariables (size, other.size);
  2907. data.swapWith (other.data);
  2908. }
  2909. void MemoryBlock::fillWith (const uint8 value) throw()
  2910. {
  2911. memset (data, (int) value, size);
  2912. }
  2913. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2914. {
  2915. if (numBytes > 0)
  2916. {
  2917. const size_t oldSize = size;
  2918. setSize (size + numBytes);
  2919. memcpy (data + oldSize, srcData, numBytes);
  2920. }
  2921. }
  2922. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2923. {
  2924. const char* d = static_cast<const char*> (src);
  2925. if (offset < 0)
  2926. {
  2927. d -= offset;
  2928. num -= offset;
  2929. offset = 0;
  2930. }
  2931. if (offset + num > size)
  2932. num = size - offset;
  2933. if (num > 0)
  2934. memcpy (data + offset, d, num);
  2935. }
  2936. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2937. {
  2938. char* d = static_cast<char*> (dst);
  2939. if (offset < 0)
  2940. {
  2941. zeromem (d, -offset);
  2942. d -= offset;
  2943. num += offset;
  2944. offset = 0;
  2945. }
  2946. if (offset + num > size)
  2947. {
  2948. const size_t newNum = size - offset;
  2949. zeromem (d + newNum, num - newNum);
  2950. num = newNum;
  2951. }
  2952. if (num > 0)
  2953. memcpy (d, data + offset, num);
  2954. }
  2955. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2956. {
  2957. if (startByte < 0)
  2958. {
  2959. numBytesToRemove += startByte;
  2960. startByte = 0;
  2961. }
  2962. if (startByte + numBytesToRemove >= size)
  2963. {
  2964. setSize (startByte);
  2965. }
  2966. else if (numBytesToRemove > 0)
  2967. {
  2968. memmove (data + startByte,
  2969. data + startByte + numBytesToRemove,
  2970. size - (startByte + numBytesToRemove));
  2971. setSize (size - numBytesToRemove);
  2972. }
  2973. }
  2974. const String MemoryBlock::toString() const
  2975. {
  2976. return String (static_cast <const char*> (getData()), size);
  2977. }
  2978. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2979. {
  2980. int res = 0;
  2981. size_t byte = bitRangeStart >> 3;
  2982. int offsetInByte = (int) bitRangeStart & 7;
  2983. size_t bitsSoFar = 0;
  2984. while (numBits > 0 && (size_t) byte < size)
  2985. {
  2986. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2987. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2988. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2989. bitsSoFar += bitsThisTime;
  2990. numBits -= bitsThisTime;
  2991. ++byte;
  2992. offsetInByte = 0;
  2993. }
  2994. return res;
  2995. }
  2996. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2997. {
  2998. size_t byte = bitRangeStart >> 3;
  2999. int offsetInByte = (int) bitRangeStart & 7;
  3000. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  3001. while (numBits > 0 && (size_t) byte < size)
  3002. {
  3003. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3004. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  3005. const unsigned int tempBits = bitsToSet << offsetInByte;
  3006. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  3007. ++byte;
  3008. numBits -= bitsThisTime;
  3009. bitsToSet >>= bitsThisTime;
  3010. mask >>= bitsThisTime;
  3011. offsetInByte = 0;
  3012. }
  3013. }
  3014. void MemoryBlock::loadFromHexString (const String& hex)
  3015. {
  3016. ensureSize (hex.length() >> 1);
  3017. char* dest = data;
  3018. int i = 0;
  3019. for (;;)
  3020. {
  3021. int byte = 0;
  3022. for (int loop = 2; --loop >= 0;)
  3023. {
  3024. byte <<= 4;
  3025. for (;;)
  3026. {
  3027. const juce_wchar c = hex [i++];
  3028. if (c >= '0' && c <= '9')
  3029. {
  3030. byte |= c - '0';
  3031. break;
  3032. }
  3033. else if (c >= 'a' && c <= 'z')
  3034. {
  3035. byte |= c - ('a' - 10);
  3036. break;
  3037. }
  3038. else if (c >= 'A' && c <= 'Z')
  3039. {
  3040. byte |= c - ('A' - 10);
  3041. break;
  3042. }
  3043. else if (c == 0)
  3044. {
  3045. setSize (static_cast <size_t> (dest - data));
  3046. return;
  3047. }
  3048. }
  3049. }
  3050. *dest++ = (char) byte;
  3051. }
  3052. }
  3053. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3054. const String MemoryBlock::toBase64Encoding() const
  3055. {
  3056. const size_t numChars = ((size << 3) + 5) / 6;
  3057. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3058. const int initialLen = destString.length();
  3059. destString.preallocateStorage (initialLen + 2 + numChars);
  3060. juce_wchar* d = destString;
  3061. d += initialLen;
  3062. *d++ = '.';
  3063. for (size_t i = 0; i < numChars; ++i)
  3064. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3065. *d++ = 0;
  3066. return destString;
  3067. }
  3068. bool MemoryBlock::fromBase64Encoding (const String& s)
  3069. {
  3070. const int startPos = s.indexOfChar ('.') + 1;
  3071. if (startPos <= 0)
  3072. return false;
  3073. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3074. setSize (numBytesNeeded, true);
  3075. const int numChars = s.length() - startPos;
  3076. const juce_wchar* srcChars = s;
  3077. srcChars += startPos;
  3078. int pos = 0;
  3079. for (int i = 0; i < numChars; ++i)
  3080. {
  3081. const char c = (char) srcChars[i];
  3082. for (int j = 0; j < 64; ++j)
  3083. {
  3084. if (encodingTable[j] == c)
  3085. {
  3086. setBitRange (pos, 6, j);
  3087. pos += 6;
  3088. break;
  3089. }
  3090. }
  3091. }
  3092. return true;
  3093. }
  3094. END_JUCE_NAMESPACE
  3095. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3096. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3097. BEGIN_JUCE_NAMESPACE
  3098. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3099. : properties (ignoreCaseOfKeyNames),
  3100. fallbackProperties (0),
  3101. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3102. {
  3103. }
  3104. PropertySet::PropertySet (const PropertySet& other)
  3105. : properties (other.properties),
  3106. fallbackProperties (other.fallbackProperties),
  3107. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3108. {
  3109. }
  3110. PropertySet& PropertySet::operator= (const PropertySet& other)
  3111. {
  3112. properties = other.properties;
  3113. fallbackProperties = other.fallbackProperties;
  3114. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3115. propertyChanged();
  3116. return *this;
  3117. }
  3118. PropertySet::~PropertySet()
  3119. {
  3120. }
  3121. void PropertySet::clear()
  3122. {
  3123. const ScopedLock sl (lock);
  3124. if (properties.size() > 0)
  3125. {
  3126. properties.clear();
  3127. propertyChanged();
  3128. }
  3129. }
  3130. const String PropertySet::getValue (const String& keyName,
  3131. const String& defaultValue) const throw()
  3132. {
  3133. const ScopedLock sl (lock);
  3134. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3135. if (index >= 0)
  3136. return properties.getAllValues() [index];
  3137. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3138. : defaultValue;
  3139. }
  3140. int PropertySet::getIntValue (const String& keyName,
  3141. const int defaultValue) const throw()
  3142. {
  3143. const ScopedLock sl (lock);
  3144. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3145. if (index >= 0)
  3146. return properties.getAllValues() [index].getIntValue();
  3147. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3148. : defaultValue;
  3149. }
  3150. double PropertySet::getDoubleValue (const String& keyName,
  3151. const double defaultValue) const throw()
  3152. {
  3153. const ScopedLock sl (lock);
  3154. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3155. if (index >= 0)
  3156. return properties.getAllValues()[index].getDoubleValue();
  3157. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3158. : defaultValue;
  3159. }
  3160. bool PropertySet::getBoolValue (const String& keyName,
  3161. const bool defaultValue) const throw()
  3162. {
  3163. const ScopedLock sl (lock);
  3164. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3165. if (index >= 0)
  3166. return properties.getAllValues() [index].getIntValue() != 0;
  3167. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3168. : defaultValue;
  3169. }
  3170. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3171. {
  3172. XmlDocument doc (getValue (keyName));
  3173. return doc.getDocumentElement();
  3174. }
  3175. void PropertySet::setValue (const String& keyName, const var& v)
  3176. {
  3177. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3178. if (keyName.isNotEmpty())
  3179. {
  3180. const String value (v.toString());
  3181. const ScopedLock sl (lock);
  3182. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3183. if (index < 0 || properties.getAllValues() [index] != value)
  3184. {
  3185. properties.set (keyName, value);
  3186. propertyChanged();
  3187. }
  3188. }
  3189. }
  3190. void PropertySet::removeValue (const String& keyName)
  3191. {
  3192. if (keyName.isNotEmpty())
  3193. {
  3194. const ScopedLock sl (lock);
  3195. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3196. if (index >= 0)
  3197. {
  3198. properties.remove (keyName);
  3199. propertyChanged();
  3200. }
  3201. }
  3202. }
  3203. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3204. {
  3205. setValue (keyName, xml == 0 ? var::null
  3206. : var (xml->createDocument (String::empty, true)));
  3207. }
  3208. bool PropertySet::containsKey (const String& keyName) const throw()
  3209. {
  3210. const ScopedLock sl (lock);
  3211. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3212. }
  3213. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3214. {
  3215. const ScopedLock sl (lock);
  3216. fallbackProperties = fallbackProperties_;
  3217. }
  3218. XmlElement* PropertySet::createXml (const String& nodeName) const
  3219. {
  3220. const ScopedLock sl (lock);
  3221. XmlElement* const xml = new XmlElement (nodeName);
  3222. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3223. {
  3224. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3225. e->setAttribute ("name", properties.getAllKeys()[i]);
  3226. e->setAttribute ("val", properties.getAllValues()[i]);
  3227. }
  3228. return xml;
  3229. }
  3230. void PropertySet::restoreFromXml (const XmlElement& xml)
  3231. {
  3232. const ScopedLock sl (lock);
  3233. clear();
  3234. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3235. {
  3236. if (e->hasAttribute ("name")
  3237. && e->hasAttribute ("val"))
  3238. {
  3239. properties.set (e->getStringAttribute ("name"),
  3240. e->getStringAttribute ("val"));
  3241. }
  3242. }
  3243. if (properties.size() > 0)
  3244. propertyChanged();
  3245. }
  3246. void PropertySet::propertyChanged()
  3247. {
  3248. }
  3249. END_JUCE_NAMESPACE
  3250. /*** End of inlined file: juce_PropertySet.cpp ***/
  3251. /*** Start of inlined file: juce_Identifier.cpp ***/
  3252. BEGIN_JUCE_NAMESPACE
  3253. StringPool& Identifier::getPool()
  3254. {
  3255. static StringPool pool;
  3256. return pool;
  3257. }
  3258. Identifier::Identifier() throw()
  3259. : name (0)
  3260. {
  3261. }
  3262. Identifier::Identifier (const Identifier& other) throw()
  3263. : name (other.name)
  3264. {
  3265. }
  3266. Identifier& Identifier::operator= (const Identifier& other) throw()
  3267. {
  3268. name = other.name;
  3269. return *this;
  3270. }
  3271. Identifier::Identifier (const String& name_)
  3272. : name (Identifier::getPool().getPooledString (name_))
  3273. {
  3274. /* An Identifier string must be suitable for use as a script variable or XML
  3275. attribute, so it can only contain this limited set of characters.. */
  3276. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3277. }
  3278. Identifier::Identifier (const char* const name_)
  3279. : name (Identifier::getPool().getPooledString (name_))
  3280. {
  3281. /* An Identifier string must be suitable for use as a script variable or XML
  3282. attribute, so it can only contain this limited set of characters.. */
  3283. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3284. }
  3285. Identifier::~Identifier()
  3286. {
  3287. }
  3288. END_JUCE_NAMESPACE
  3289. /*** End of inlined file: juce_Identifier.cpp ***/
  3290. /*** Start of inlined file: juce_Variant.cpp ***/
  3291. BEGIN_JUCE_NAMESPACE
  3292. class var::VariantType
  3293. {
  3294. public:
  3295. VariantType() {}
  3296. virtual ~VariantType() {}
  3297. virtual int toInt (const ValueUnion&) const { return 0; }
  3298. virtual double toDouble (const ValueUnion&) const { return 0; }
  3299. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3300. virtual bool toBool (const ValueUnion&) const { return false; }
  3301. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3302. virtual bool isVoid() const throw() { return false; }
  3303. virtual bool isInt() const throw() { return false; }
  3304. virtual bool isBool() const throw() { return false; }
  3305. virtual bool isDouble() const throw() { return false; }
  3306. virtual bool isString() const throw() { return false; }
  3307. virtual bool isObject() const throw() { return false; }
  3308. virtual bool isMethod() const throw() { return false; }
  3309. virtual void cleanUp (ValueUnion&) const throw() {}
  3310. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3311. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3312. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3313. };
  3314. class var::VariantType_Void : public var::VariantType
  3315. {
  3316. public:
  3317. VariantType_Void() {}
  3318. static const VariantType_Void* getInstance() { static const VariantType_Void i; return &i; }
  3319. bool isVoid() const throw() { return true; }
  3320. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3321. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3322. };
  3323. class var::VariantType_Int : public var::VariantType
  3324. {
  3325. public:
  3326. VariantType_Int() {}
  3327. static const VariantType_Int* getInstance() { static const VariantType_Int i; return &i; }
  3328. int toInt (const ValueUnion& data) const { return data.intValue; };
  3329. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3330. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3331. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3332. bool isInt() const throw() { return true; }
  3333. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3334. {
  3335. return otherType.toInt (otherData) == data.intValue;
  3336. }
  3337. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3338. {
  3339. output.writeCompressedInt (5);
  3340. output.writeByte (1);
  3341. output.writeInt (data.intValue);
  3342. }
  3343. };
  3344. class var::VariantType_Double : public var::VariantType
  3345. {
  3346. public:
  3347. VariantType_Double() {}
  3348. static const VariantType_Double* getInstance() { static const VariantType_Double i; return &i; }
  3349. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3350. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3351. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3352. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3353. bool isDouble() const throw() { return true; }
  3354. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3355. {
  3356. return otherType.toDouble (otherData) == data.doubleValue;
  3357. }
  3358. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3359. {
  3360. output.writeCompressedInt (9);
  3361. output.writeByte (4);
  3362. output.writeDouble (data.doubleValue);
  3363. }
  3364. };
  3365. class var::VariantType_Bool : public var::VariantType
  3366. {
  3367. public:
  3368. VariantType_Bool() {}
  3369. static const VariantType_Bool* getInstance() { static const VariantType_Bool i; return &i; }
  3370. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3371. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3372. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3373. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3374. bool isBool() const throw() { return true; }
  3375. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3376. {
  3377. return otherType.toBool (otherData) == data.boolValue;
  3378. }
  3379. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3380. {
  3381. output.writeCompressedInt (1);
  3382. output.writeByte (data.boolValue ? 2 : 3);
  3383. }
  3384. };
  3385. class var::VariantType_String : public var::VariantType
  3386. {
  3387. public:
  3388. VariantType_String() {}
  3389. static const VariantType_String* getInstance() { static const VariantType_String i; return &i; }
  3390. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3391. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3392. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3393. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3394. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3395. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3396. || data.stringValue->trim().equalsIgnoreCase ("true")
  3397. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3398. bool isString() const throw() { return true; }
  3399. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3400. {
  3401. return otherType.toString (otherData) == *data.stringValue;
  3402. }
  3403. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3404. {
  3405. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3406. output.writeCompressedInt (len + 1);
  3407. output.writeByte (5);
  3408. HeapBlock<char> temp (len);
  3409. data.stringValue->copyToUTF8 (temp, len);
  3410. output.write (temp, len);
  3411. }
  3412. };
  3413. class var::VariantType_Object : public var::VariantType
  3414. {
  3415. public:
  3416. VariantType_Object() {}
  3417. static const VariantType_Object* getInstance() { static const VariantType_Object i; return &i; }
  3418. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3419. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3420. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3421. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3422. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3423. bool isObject() const throw() { return true; }
  3424. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3425. {
  3426. return otherType.toObject (otherData) == data.objectValue;
  3427. }
  3428. void writeToStream (const ValueUnion&, OutputStream& output) const
  3429. {
  3430. jassertfalse; // Can't write an object to a stream!
  3431. output.writeCompressedInt (0);
  3432. }
  3433. };
  3434. class var::VariantType_Method : public var::VariantType
  3435. {
  3436. public:
  3437. VariantType_Method() {}
  3438. static const VariantType_Method* getInstance() { static const VariantType_Method i; return &i; }
  3439. const String toString (const ValueUnion&) const { return "Method"; }
  3440. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3441. bool isMethod() const throw() { return true; }
  3442. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3443. {
  3444. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3445. }
  3446. void writeToStream (const ValueUnion&, OutputStream& output) const
  3447. {
  3448. jassertfalse; // Can't write a method to a stream!
  3449. output.writeCompressedInt (0);
  3450. }
  3451. };
  3452. var::var() throw()
  3453. : type (VariantType_Void::getInstance())
  3454. {
  3455. }
  3456. var::~var() throw()
  3457. {
  3458. type->cleanUp (value);
  3459. }
  3460. const var var::null;
  3461. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3462. {
  3463. type->createCopy (value, valueToCopy.value);
  3464. }
  3465. var::var (const int value_) throw() : type (VariantType_Int::getInstance())
  3466. {
  3467. value.intValue = value_;
  3468. }
  3469. var::var (const bool value_) throw() : type (VariantType_Bool::getInstance())
  3470. {
  3471. value.boolValue = value_;
  3472. }
  3473. var::var (const double value_) throw() : type (VariantType_Double::getInstance())
  3474. {
  3475. value.doubleValue = value_;
  3476. }
  3477. var::var (const String& value_) : type (VariantType_String::getInstance())
  3478. {
  3479. value.stringValue = new String (value_);
  3480. }
  3481. var::var (const char* const value_) : type (VariantType_String::getInstance())
  3482. {
  3483. value.stringValue = new String (value_);
  3484. }
  3485. var::var (const juce_wchar* const value_) : type (VariantType_String::getInstance())
  3486. {
  3487. value.stringValue = new String (value_);
  3488. }
  3489. var::var (DynamicObject* const object) : type (VariantType_Object::getInstance())
  3490. {
  3491. value.objectValue = object;
  3492. if (object != 0)
  3493. object->incReferenceCount();
  3494. }
  3495. var::var (MethodFunction method_) throw() : type (VariantType_Method::getInstance())
  3496. {
  3497. value.methodValue = method_;
  3498. }
  3499. bool var::isVoid() const throw() { return type->isVoid(); }
  3500. bool var::isInt() const throw() { return type->isInt(); }
  3501. bool var::isBool() const throw() { return type->isBool(); }
  3502. bool var::isDouble() const throw() { return type->isDouble(); }
  3503. bool var::isString() const throw() { return type->isString(); }
  3504. bool var::isObject() const throw() { return type->isObject(); }
  3505. bool var::isMethod() const throw() { return type->isMethod(); }
  3506. var::operator int() const { return type->toInt (value); }
  3507. var::operator bool() const { return type->toBool (value); }
  3508. var::operator float() const { return (float) type->toDouble (value); }
  3509. var::operator double() const { return type->toDouble (value); }
  3510. const String var::toString() const { return type->toString (value); }
  3511. var::operator const String() const { return type->toString (value); }
  3512. DynamicObject* var::getObject() const { return type->toObject (value); }
  3513. void var::swapWith (var& other) throw()
  3514. {
  3515. swapVariables (type, other.type);
  3516. swapVariables (value, other.value);
  3517. }
  3518. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3519. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3520. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3521. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3522. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3523. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3524. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3525. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3526. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3527. bool var::equals (const var& other) const throw()
  3528. {
  3529. return type->equals (value, other.value, *other.type);
  3530. }
  3531. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3532. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3533. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3534. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3535. void var::writeToStream (OutputStream& output) const
  3536. {
  3537. type->writeToStream (value, output);
  3538. }
  3539. const var var::readFromStream (InputStream& input)
  3540. {
  3541. const int numBytes = input.readCompressedInt();
  3542. if (numBytes > 0)
  3543. {
  3544. switch (input.readByte())
  3545. {
  3546. case 1: return var (input.readInt());
  3547. case 2: return var (true);
  3548. case 3: return var (false);
  3549. case 4: return var (input.readDouble());
  3550. case 5:
  3551. {
  3552. MemoryOutputStream mo;
  3553. mo.writeFromInputStream (input, numBytes - 1);
  3554. return var (mo.toUTF8());
  3555. }
  3556. default: input.skipNextBytes (numBytes - 1); break;
  3557. }
  3558. }
  3559. return var::null;
  3560. }
  3561. const var var::operator[] (const Identifier& propertyName) const
  3562. {
  3563. DynamicObject* const o = getObject();
  3564. return o != 0 ? o->getProperty (propertyName) : var::null;
  3565. }
  3566. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3567. {
  3568. DynamicObject* const o = getObject();
  3569. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3570. }
  3571. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3572. {
  3573. if (isMethod())
  3574. {
  3575. DynamicObject* const target = targetObject.getObject();
  3576. if (target != 0)
  3577. return (target->*(value.methodValue)) (arguments, numArguments);
  3578. }
  3579. return var::null;
  3580. }
  3581. const var var::call (const Identifier& method) const
  3582. {
  3583. return invoke (method, 0, 0);
  3584. }
  3585. const var var::call (const Identifier& method, const var& arg1) const
  3586. {
  3587. return invoke (method, &arg1, 1);
  3588. }
  3589. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3590. {
  3591. var args[] = { arg1, arg2 };
  3592. return invoke (method, args, 2);
  3593. }
  3594. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3595. {
  3596. var args[] = { arg1, arg2, arg3 };
  3597. return invoke (method, args, 3);
  3598. }
  3599. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3600. {
  3601. var args[] = { arg1, arg2, arg3, arg4 };
  3602. return invoke (method, args, 4);
  3603. }
  3604. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3605. {
  3606. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3607. return invoke (method, args, 5);
  3608. }
  3609. END_JUCE_NAMESPACE
  3610. /*** End of inlined file: juce_Variant.cpp ***/
  3611. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3612. BEGIN_JUCE_NAMESPACE
  3613. NamedValueSet::NamedValue::NamedValue() throw()
  3614. {
  3615. }
  3616. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3617. : name (name_), value (value_)
  3618. {
  3619. }
  3620. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3621. {
  3622. return name == other.name && value == other.value;
  3623. }
  3624. NamedValueSet::NamedValueSet() throw()
  3625. {
  3626. }
  3627. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3628. : values (other.values)
  3629. {
  3630. }
  3631. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3632. {
  3633. values = other.values;
  3634. return *this;
  3635. }
  3636. NamedValueSet::~NamedValueSet()
  3637. {
  3638. }
  3639. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3640. {
  3641. return values == other.values;
  3642. }
  3643. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3644. {
  3645. return ! operator== (other);
  3646. }
  3647. int NamedValueSet::size() const throw()
  3648. {
  3649. return values.size();
  3650. }
  3651. const var& NamedValueSet::operator[] (const Identifier& name) const
  3652. {
  3653. for (int i = values.size(); --i >= 0;)
  3654. {
  3655. const NamedValue& v = values.getReference(i);
  3656. if (v.name == name)
  3657. return v.value;
  3658. }
  3659. return var::null;
  3660. }
  3661. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3662. {
  3663. const var* v = getItem (name);
  3664. return v != 0 ? *v : defaultReturnValue;
  3665. }
  3666. var* NamedValueSet::getItem (const Identifier& name) const
  3667. {
  3668. for (int i = values.size(); --i >= 0;)
  3669. {
  3670. NamedValue& v = values.getReference(i);
  3671. if (v.name == name)
  3672. return &(v.value);
  3673. }
  3674. return 0;
  3675. }
  3676. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3677. {
  3678. for (int i = values.size(); --i >= 0;)
  3679. {
  3680. NamedValue& v = values.getReference(i);
  3681. if (v.name == name)
  3682. {
  3683. if (v.value == newValue)
  3684. return false;
  3685. v.value = newValue;
  3686. return true;
  3687. }
  3688. }
  3689. values.add (NamedValue (name, newValue));
  3690. return true;
  3691. }
  3692. bool NamedValueSet::contains (const Identifier& name) const
  3693. {
  3694. return getItem (name) != 0;
  3695. }
  3696. bool NamedValueSet::remove (const Identifier& name)
  3697. {
  3698. for (int i = values.size(); --i >= 0;)
  3699. {
  3700. if (values.getReference(i).name == name)
  3701. {
  3702. values.remove (i);
  3703. return true;
  3704. }
  3705. }
  3706. return false;
  3707. }
  3708. const Identifier NamedValueSet::getName (const int index) const
  3709. {
  3710. jassert (((unsigned int) index) < (unsigned int) values.size());
  3711. return values [index].name;
  3712. }
  3713. const var NamedValueSet::getValueAt (const int index) const
  3714. {
  3715. jassert (((unsigned int) index) < (unsigned int) values.size());
  3716. return values [index].value;
  3717. }
  3718. void NamedValueSet::clear()
  3719. {
  3720. values.clear();
  3721. }
  3722. END_JUCE_NAMESPACE
  3723. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3724. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3725. BEGIN_JUCE_NAMESPACE
  3726. DynamicObject::DynamicObject()
  3727. {
  3728. }
  3729. DynamicObject::~DynamicObject()
  3730. {
  3731. }
  3732. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3733. {
  3734. var* const v = properties.getItem (propertyName);
  3735. return v != 0 && ! v->isMethod();
  3736. }
  3737. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3738. {
  3739. return properties [propertyName];
  3740. }
  3741. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3742. {
  3743. properties.set (propertyName, newValue);
  3744. }
  3745. void DynamicObject::removeProperty (const Identifier& propertyName)
  3746. {
  3747. properties.remove (propertyName);
  3748. }
  3749. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3750. {
  3751. return getProperty (methodName).isMethod();
  3752. }
  3753. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3754. const var* parameters,
  3755. int numParameters)
  3756. {
  3757. return properties [methodName].invoke (var (this), parameters, numParameters);
  3758. }
  3759. void DynamicObject::setMethod (const Identifier& name,
  3760. var::MethodFunction methodFunction)
  3761. {
  3762. properties.set (name, var (methodFunction));
  3763. }
  3764. void DynamicObject::clear()
  3765. {
  3766. properties.clear();
  3767. }
  3768. END_JUCE_NAMESPACE
  3769. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3770. /*** Start of inlined file: juce_Expression.cpp ***/
  3771. BEGIN_JUCE_NAMESPACE
  3772. class Expression::Helpers
  3773. {
  3774. public:
  3775. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3776. class Constant : public Term
  3777. {
  3778. public:
  3779. Constant (const double value_, bool isResolutionTarget_)
  3780. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3781. Type getType() const throw() { return constantType; }
  3782. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3783. double evaluate (const EvaluationContext&, int) const { return value; }
  3784. int getNumInputs() const { return 0; }
  3785. Term* getInput (int) const { return 0; }
  3786. const TermPtr negated()
  3787. {
  3788. return new Constant (-value, isResolutionTarget);
  3789. }
  3790. const String toString() const
  3791. {
  3792. if (isResolutionTarget)
  3793. return "@" + String (value);
  3794. return String (value);
  3795. }
  3796. double value;
  3797. bool isResolutionTarget;
  3798. };
  3799. class Symbol : public Term
  3800. {
  3801. public:
  3802. explicit Symbol (const String& symbol_)
  3803. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3804. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3805. {}
  3806. Symbol (const String& symbol_, const String& member_)
  3807. : mainSymbol (symbol_),
  3808. member (member_)
  3809. {}
  3810. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3811. {
  3812. if (++recursionDepth > 256)
  3813. throw EvaluationError ("Recursive symbol references");
  3814. try
  3815. {
  3816. return c.getSymbolValue (mainSymbol, member).term->evaluate (c, recursionDepth);
  3817. }
  3818. catch (...)
  3819. {}
  3820. return 0;
  3821. }
  3822. Type getType() const throw() { return symbolType; }
  3823. Term* clone() const { return new Symbol (mainSymbol, member); }
  3824. int getNumInputs() const { return 0; }
  3825. Term* getInput (int) const { return 0; }
  3826. const String getSymbolName() const { return toString(); }
  3827. const String toString() const
  3828. {
  3829. return member.isEmpty() ? mainSymbol
  3830. : mainSymbol + "." + member;
  3831. }
  3832. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3833. {
  3834. if (s == mainSymbol)
  3835. return true;
  3836. if (++recursionDepth > 256)
  3837. throw EvaluationError ("Recursive symbol references");
  3838. try
  3839. {
  3840. return c != 0 && c->getSymbolValue (mainSymbol, member).term->referencesSymbol (s, c, recursionDepth);
  3841. }
  3842. catch (EvaluationError&)
  3843. {
  3844. return false;
  3845. }
  3846. }
  3847. String mainSymbol, member;
  3848. };
  3849. class Function : public Term
  3850. {
  3851. public:
  3852. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3853. : functionName (functionName_), parameters (parameters_)
  3854. {}
  3855. Term* clone() const { return new Function (functionName, parameters); }
  3856. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3857. {
  3858. HeapBlock <double> params (parameters.size());
  3859. for (int i = 0; i < parameters.size(); ++i)
  3860. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3861. return c.evaluateFunction (functionName, params, parameters.size());
  3862. }
  3863. Type getType() const throw() { return functionType; }
  3864. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3865. int getNumInputs() const { return parameters.size(); }
  3866. Term* getInput (int i) const { return parameters [i]; }
  3867. const String getFunctionName() const { return functionName; }
  3868. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3869. {
  3870. for (int i = 0; i < parameters.size(); ++i)
  3871. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3872. return true;
  3873. return false;
  3874. }
  3875. const String toString() const
  3876. {
  3877. if (parameters.size() == 0)
  3878. return functionName + "()";
  3879. String s (functionName + " (");
  3880. for (int i = 0; i < parameters.size(); ++i)
  3881. {
  3882. s << parameters.getUnchecked(i)->toString();
  3883. if (i < parameters.size() - 1)
  3884. s << ", ";
  3885. }
  3886. s << ')';
  3887. return s;
  3888. }
  3889. const String functionName;
  3890. ReferenceCountedArray<Term> parameters;
  3891. };
  3892. class Negate : public Term
  3893. {
  3894. public:
  3895. Negate (const TermPtr& input_) : input (input_)
  3896. {
  3897. jassert (input_ != 0);
  3898. }
  3899. Type getType() const throw() { return operatorType; }
  3900. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3901. int getNumInputs() const { return 1; }
  3902. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3903. Term* clone() const { return new Negate (input->clone()); }
  3904. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3905. const String getFunctionName() const { return "-"; }
  3906. const TermPtr negated()
  3907. {
  3908. return input;
  3909. }
  3910. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3911. {
  3912. (void) input_;
  3913. jassert (input_ == input);
  3914. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3915. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3916. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3917. }
  3918. const String toString() const
  3919. {
  3920. if (input->getOperatorPrecedence() > 0)
  3921. return "-(" + input->toString() + ")";
  3922. else
  3923. return "-" + input->toString();
  3924. }
  3925. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3926. {
  3927. return input->referencesSymbol (s, c, recursionDepth);
  3928. }
  3929. private:
  3930. const TermPtr input;
  3931. };
  3932. class BinaryTerm : public Term
  3933. {
  3934. public:
  3935. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3936. {
  3937. jassert (left_ != 0 && right_ != 0);
  3938. }
  3939. int getInputIndexFor (const Term* possibleInput) const
  3940. {
  3941. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3942. }
  3943. Type getType() const throw() { return operatorType; }
  3944. int getNumInputs() const { return 2; }
  3945. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3946. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3947. {
  3948. return left->referencesSymbol (s, c, recursionDepth)
  3949. || right->referencesSymbol (s, c, recursionDepth);
  3950. }
  3951. const String toString() const
  3952. {
  3953. String s;
  3954. const int ourPrecendence = getOperatorPrecedence();
  3955. if (left->getOperatorPrecedence() > ourPrecendence)
  3956. s << '(' << left->toString() << ')';
  3957. else
  3958. s = left->toString();
  3959. s << ' ' << getFunctionName() << ' ';
  3960. if (right->getOperatorPrecedence() >= ourPrecendence)
  3961. s << '(' << right->toString() << ')';
  3962. else
  3963. s << right->toString();
  3964. return s;
  3965. }
  3966. protected:
  3967. const TermPtr left, right;
  3968. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3969. {
  3970. jassert (input == left || input == right);
  3971. if (input != left && input != right)
  3972. return 0;
  3973. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3974. if (dest == 0)
  3975. return new Constant (overallTarget, false);
  3976. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3977. }
  3978. };
  3979. class Add : public BinaryTerm
  3980. {
  3981. public:
  3982. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3983. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3984. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3985. int getOperatorPrecedence() const { return 2; }
  3986. const String getFunctionName() const { return "+"; }
  3987. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3988. {
  3989. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3990. if (newDest == 0)
  3991. return 0;
  3992. return new Subtract (newDest, (input == left ? right : left)->clone());
  3993. }
  3994. private:
  3995. Add (const Add&);
  3996. Add& operator= (const Add&);
  3997. };
  3998. class Subtract : public BinaryTerm
  3999. {
  4000. public:
  4001. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4002. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  4003. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  4004. int getOperatorPrecedence() const { return 2; }
  4005. const String getFunctionName() const { return "-"; }
  4006. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4007. {
  4008. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4009. if (newDest == 0)
  4010. return 0;
  4011. if (input == left)
  4012. return new Add (newDest, right->clone());
  4013. else
  4014. return new Subtract (left->clone(), newDest);
  4015. }
  4016. private:
  4017. Subtract (const Subtract&);
  4018. Subtract& operator= (const Subtract&);
  4019. };
  4020. class Multiply : public BinaryTerm
  4021. {
  4022. public:
  4023. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4024. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4025. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  4026. const String getFunctionName() const { return "*"; }
  4027. int getOperatorPrecedence() const { return 1; }
  4028. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4029. {
  4030. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4031. if (newDest == 0)
  4032. return 0;
  4033. return new Divide (newDest, (input == left ? right : left)->clone());
  4034. }
  4035. private:
  4036. Multiply (const Multiply&);
  4037. Multiply& operator= (const Multiply&);
  4038. };
  4039. class Divide : public BinaryTerm
  4040. {
  4041. public:
  4042. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4043. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4044. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  4045. const String getFunctionName() const { return "/"; }
  4046. int getOperatorPrecedence() const { return 1; }
  4047. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4048. {
  4049. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4050. if (newDest == 0)
  4051. return 0;
  4052. if (input == left)
  4053. return new Multiply (newDest, right->clone());
  4054. else
  4055. return new Divide (left->clone(), newDest);
  4056. }
  4057. private:
  4058. Divide (const Divide&);
  4059. Divide& operator= (const Divide&);
  4060. };
  4061. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4062. {
  4063. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4064. if (inputIndex >= 0)
  4065. return topLevel;
  4066. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4067. {
  4068. Term* t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4069. if (t != 0)
  4070. return t;
  4071. }
  4072. return 0;
  4073. }
  4074. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4075. {
  4076. Constant* c = dynamic_cast<Constant*> (term);
  4077. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4078. return c;
  4079. if (dynamic_cast<Function*> (term) != 0)
  4080. return 0;
  4081. int i;
  4082. const int numIns = term->getNumInputs();
  4083. for (i = 0; i < numIns; ++i)
  4084. {
  4085. Constant* c = dynamic_cast<Constant*> (term->getInput (i));
  4086. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4087. return c;
  4088. }
  4089. for (i = 0; i < numIns; ++i)
  4090. {
  4091. Constant* c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4092. if (c != 0)
  4093. return c;
  4094. }
  4095. return 0;
  4096. }
  4097. static bool containsAnySymbols (const Term* const t)
  4098. {
  4099. if (dynamic_cast <const Symbol*> (t) != 0)
  4100. return true;
  4101. for (int i = t->getNumInputs(); --i >= 0;)
  4102. if (containsAnySymbols (t->getInput (i)))
  4103. return true;
  4104. return false;
  4105. }
  4106. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4107. {
  4108. Symbol* const sym = dynamic_cast <Symbol*> (t);
  4109. if (sym != 0 && sym->mainSymbol == oldName)
  4110. {
  4111. sym->mainSymbol = newName;
  4112. return true;
  4113. }
  4114. bool anyChanged = false;
  4115. for (int i = t->getNumInputs(); --i >= 0;)
  4116. if (renameSymbol (t->getInput (i), oldName, newName))
  4117. anyChanged = true;
  4118. return anyChanged;
  4119. }
  4120. class Parser
  4121. {
  4122. public:
  4123. Parser (const String& stringToParse, int& textIndex_)
  4124. : textString (stringToParse), textIndex (textIndex_)
  4125. {
  4126. text = textString;
  4127. }
  4128. const TermPtr readExpression()
  4129. {
  4130. TermPtr lhs (readMultiplyOrDivideExpression());
  4131. char opType;
  4132. while (lhs != 0 && readOperator ("+-", &opType))
  4133. {
  4134. TermPtr rhs (readMultiplyOrDivideExpression());
  4135. if (rhs == 0)
  4136. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4137. if (opType == '+')
  4138. lhs = new Add (lhs, rhs);
  4139. else
  4140. lhs = new Subtract (lhs, rhs);
  4141. }
  4142. return lhs;
  4143. }
  4144. private:
  4145. const String textString;
  4146. const juce_wchar* text;
  4147. int& textIndex;
  4148. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4149. {
  4150. return c >= '0' && c <= '9';
  4151. }
  4152. void skipWhitespace (int& i)
  4153. {
  4154. while (CharacterFunctions::isWhitespace (text [i]))
  4155. ++i;
  4156. }
  4157. bool readChar (const juce_wchar required)
  4158. {
  4159. if (text[textIndex] == required)
  4160. {
  4161. ++textIndex;
  4162. return true;
  4163. }
  4164. return false;
  4165. }
  4166. bool readOperator (const char* ops, char* const opType = 0)
  4167. {
  4168. skipWhitespace (textIndex);
  4169. while (*ops != 0)
  4170. {
  4171. if (readChar (*ops))
  4172. {
  4173. if (opType != 0)
  4174. *opType = *ops;
  4175. return true;
  4176. }
  4177. ++ops;
  4178. }
  4179. return false;
  4180. }
  4181. bool readIdentifier (String& identifier)
  4182. {
  4183. skipWhitespace (textIndex);
  4184. int i = textIndex;
  4185. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4186. {
  4187. ++i;
  4188. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4189. ++i;
  4190. }
  4191. if (i > textIndex)
  4192. {
  4193. identifier = String (text + textIndex, i - textIndex);
  4194. textIndex = i;
  4195. return true;
  4196. }
  4197. return false;
  4198. }
  4199. Term* readNumber()
  4200. {
  4201. skipWhitespace (textIndex);
  4202. int i = textIndex;
  4203. const bool isResolutionTarget = (text[i] == '@');
  4204. if (isResolutionTarget)
  4205. {
  4206. ++i;
  4207. skipWhitespace (i);
  4208. textIndex = i;
  4209. }
  4210. if (text[i] == '-')
  4211. {
  4212. ++i;
  4213. skipWhitespace (i);
  4214. }
  4215. int numDigits = 0;
  4216. while (isDecimalDigit (text[i]))
  4217. {
  4218. ++i;
  4219. ++numDigits;
  4220. }
  4221. const bool hasPoint = (text[i] == '.');
  4222. if (hasPoint)
  4223. {
  4224. ++i;
  4225. while (isDecimalDigit (text[i]))
  4226. {
  4227. ++i;
  4228. ++numDigits;
  4229. }
  4230. }
  4231. if (numDigits == 0)
  4232. return 0;
  4233. juce_wchar c = text[i];
  4234. const bool hasExponent = (c == 'e' || c == 'E');
  4235. if (hasExponent)
  4236. {
  4237. ++i;
  4238. c = text[i];
  4239. if (c == '+' || c == '-')
  4240. ++i;
  4241. int numExpDigits = 0;
  4242. while (isDecimalDigit (text[i]))
  4243. {
  4244. ++i;
  4245. ++numExpDigits;
  4246. }
  4247. if (numExpDigits == 0)
  4248. return 0;
  4249. }
  4250. const int start = textIndex;
  4251. textIndex = i;
  4252. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4253. }
  4254. const TermPtr readMultiplyOrDivideExpression()
  4255. {
  4256. TermPtr lhs (readUnaryExpression());
  4257. char opType;
  4258. while (lhs != 0 && readOperator ("*/", &opType))
  4259. {
  4260. TermPtr rhs (readUnaryExpression());
  4261. if (rhs == 0)
  4262. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4263. if (opType == '*')
  4264. lhs = new Multiply (lhs, rhs);
  4265. else
  4266. lhs = new Divide (lhs, rhs);
  4267. }
  4268. return lhs;
  4269. }
  4270. const TermPtr readUnaryExpression()
  4271. {
  4272. char opType;
  4273. if (readOperator ("+-", &opType))
  4274. {
  4275. TermPtr term (readUnaryExpression());
  4276. if (term == 0)
  4277. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4278. if (opType == '-')
  4279. term = term->negated();
  4280. return term;
  4281. }
  4282. return readPrimaryExpression();
  4283. }
  4284. const TermPtr readPrimaryExpression()
  4285. {
  4286. TermPtr e (readParenthesisedExpression());
  4287. if (e != 0)
  4288. return e;
  4289. e = readNumber();
  4290. if (e != 0)
  4291. return e;
  4292. String identifier;
  4293. if (readIdentifier (identifier))
  4294. {
  4295. if (readOperator ("(")) // method call...
  4296. {
  4297. Function* f = new Function (identifier, ReferenceCountedArray<Term>());
  4298. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4299. TermPtr param (readExpression());
  4300. if (param == 0)
  4301. {
  4302. if (readOperator (")"))
  4303. return func.release();
  4304. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4305. }
  4306. f->parameters.add (param);
  4307. while (readOperator (","))
  4308. {
  4309. param = readExpression();
  4310. if (param == 0)
  4311. throw ParseError ("Expected expression after \",\"");
  4312. f->parameters.add (param);
  4313. }
  4314. if (readOperator (")"))
  4315. return func.release();
  4316. throw ParseError ("Expected \")\"");
  4317. }
  4318. else // just a symbol..
  4319. {
  4320. return new Symbol (identifier);
  4321. }
  4322. }
  4323. return 0;
  4324. }
  4325. const TermPtr readParenthesisedExpression()
  4326. {
  4327. if (! readOperator ("("))
  4328. return 0;
  4329. const TermPtr e (readExpression());
  4330. if (e == 0 || ! readOperator (")"))
  4331. return 0;
  4332. return e;
  4333. }
  4334. Parser (const Parser&);
  4335. Parser& operator= (const Parser&);
  4336. };
  4337. };
  4338. Expression::Expression()
  4339. : term (new Expression::Helpers::Constant (0, false))
  4340. {
  4341. }
  4342. Expression::~Expression()
  4343. {
  4344. }
  4345. Expression::Expression (Term* const term_)
  4346. : term (term_)
  4347. {
  4348. jassert (term != 0);
  4349. }
  4350. Expression::Expression (const double constant)
  4351. : term (new Expression::Helpers::Constant (constant, false))
  4352. {
  4353. }
  4354. Expression::Expression (const Expression& other)
  4355. : term (other.term)
  4356. {
  4357. }
  4358. Expression& Expression::operator= (const Expression& other)
  4359. {
  4360. term = other.term;
  4361. return *this;
  4362. }
  4363. Expression::Expression (const String& stringToParse)
  4364. {
  4365. int i = 0;
  4366. Helpers::Parser parser (stringToParse, i);
  4367. term = parser.readExpression();
  4368. if (term == 0)
  4369. term = new Helpers::Constant (0, false);
  4370. }
  4371. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4372. {
  4373. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4374. const Helpers::TermPtr term (parser.readExpression());
  4375. if (term != 0)
  4376. return Expression (term);
  4377. return Expression();
  4378. }
  4379. double Expression::evaluate() const
  4380. {
  4381. return evaluate (Expression::EvaluationContext());
  4382. }
  4383. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4384. {
  4385. return term->evaluate (context, 0);
  4386. }
  4387. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4388. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4389. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4390. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4391. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4392. const String Expression::toString() const
  4393. {
  4394. return term->toString();
  4395. }
  4396. const Expression Expression::symbol (const String& symbol)
  4397. {
  4398. return Expression (new Helpers::Symbol (symbol));
  4399. }
  4400. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4401. {
  4402. ReferenceCountedArray<Term> params;
  4403. for (int i = 0; i < parameters.size(); ++i)
  4404. params.add (parameters.getReference(i).term);
  4405. return Expression (new Helpers::Function (functionName, params));
  4406. }
  4407. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4408. const Expression::EvaluationContext& context) const
  4409. {
  4410. ScopedPointer<Term> newTerm (term->clone());
  4411. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4412. if (termToAdjust == 0)
  4413. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4414. if (termToAdjust == 0)
  4415. {
  4416. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4417. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4418. }
  4419. jassert (termToAdjust != 0);
  4420. const Term* parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4421. if (parent == 0)
  4422. {
  4423. termToAdjust->value = targetValue;
  4424. }
  4425. else
  4426. {
  4427. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4428. if (reverseTerm == 0)
  4429. return Expression (targetValue);
  4430. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4431. }
  4432. return Expression (newTerm.release());
  4433. }
  4434. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4435. {
  4436. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4437. Expression newExpression (term->clone());
  4438. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4439. return newExpression;
  4440. }
  4441. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext* context) const
  4442. {
  4443. return term->referencesSymbol (symbol, context, 0);
  4444. }
  4445. bool Expression::usesAnySymbols() const
  4446. {
  4447. return Helpers::containsAnySymbols (term);
  4448. }
  4449. Expression::Type Expression::getType() const throw()
  4450. {
  4451. return term->getType();
  4452. }
  4453. const String Expression::getSymbol() const
  4454. {
  4455. return term->getSymbolName();
  4456. }
  4457. const String Expression::getFunction() const
  4458. {
  4459. return term->getFunctionName();
  4460. }
  4461. const String Expression::getOperator() const
  4462. {
  4463. return term->getFunctionName();
  4464. }
  4465. int Expression::getNumInputs() const
  4466. {
  4467. return term->getNumInputs();
  4468. }
  4469. const Expression Expression::getInput (int index) const
  4470. {
  4471. return Expression (term->getInput (index));
  4472. }
  4473. int Expression::Term::getOperatorPrecedence() const
  4474. {
  4475. return 0;
  4476. }
  4477. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext*, int) const
  4478. {
  4479. return false;
  4480. }
  4481. int Expression::Term::getInputIndexFor (const Term*) const
  4482. {
  4483. return -1;
  4484. }
  4485. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4486. {
  4487. jassertfalse;
  4488. return 0;
  4489. }
  4490. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4491. {
  4492. return new Helpers::Negate (this);
  4493. }
  4494. const String Expression::Term::getSymbolName() const
  4495. {
  4496. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4497. return String::empty;
  4498. }
  4499. const String Expression::Term::getFunctionName() const
  4500. {
  4501. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4502. return String::empty;
  4503. }
  4504. Expression::ParseError::ParseError (const String& message)
  4505. : description (message)
  4506. {
  4507. DBG ("Expression::ParseError: " + message);
  4508. }
  4509. Expression::EvaluationError::EvaluationError (const String& message)
  4510. : description (message)
  4511. {
  4512. DBG ("Expression::EvaluationError: " + description);
  4513. }
  4514. Expression::EvaluationError::EvaluationError (const String& symbol, const String& member)
  4515. : description ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")))
  4516. {
  4517. DBG ("Expression::EvaluationError: " + description);
  4518. }
  4519. Expression::EvaluationContext::EvaluationContext() {}
  4520. Expression::EvaluationContext::~EvaluationContext() {}
  4521. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4522. {
  4523. throw EvaluationError (symbol, member);
  4524. }
  4525. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4526. {
  4527. if (numParams > 0)
  4528. {
  4529. if (functionName == "min")
  4530. {
  4531. double v = parameters[0];
  4532. for (int i = 1; i < numParams; ++i)
  4533. v = jmin (v, parameters[i]);
  4534. return v;
  4535. }
  4536. else if (functionName == "max")
  4537. {
  4538. double v = parameters[0];
  4539. for (int i = 1; i < numParams; ++i)
  4540. v = jmax (v, parameters[i]);
  4541. return v;
  4542. }
  4543. else if (numParams == 1)
  4544. {
  4545. if (functionName == "sin") return sin (parameters[0]);
  4546. else if (functionName == "cos") return cos (parameters[0]);
  4547. else if (functionName == "tan") return tan (parameters[0]);
  4548. else if (functionName == "abs") return std::abs (parameters[0]);
  4549. }
  4550. }
  4551. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4552. }
  4553. END_JUCE_NAMESPACE
  4554. /*** End of inlined file: juce_Expression.cpp ***/
  4555. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4556. BEGIN_JUCE_NAMESPACE
  4557. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4558. {
  4559. jassert (keyData != 0);
  4560. jassert (keyBytes > 0);
  4561. static const uint32 initialPValues [18] =
  4562. {
  4563. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4564. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4565. 0x9216d5d9, 0x8979fb1b
  4566. };
  4567. static const uint32 initialSValues [4 * 256] =
  4568. {
  4569. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4570. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4571. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4572. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4573. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4574. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4575. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4576. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4577. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4578. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4579. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4580. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4581. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4582. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4583. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4584. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4585. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4586. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4587. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4588. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4589. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4590. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4591. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4592. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4593. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4594. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4595. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4596. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4597. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4598. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4599. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4600. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4601. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4602. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4603. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4604. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4605. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4606. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4607. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4608. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4609. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4610. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4611. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4612. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4613. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4614. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4615. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4616. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4617. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4618. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4619. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4620. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4621. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4622. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4623. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4624. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4625. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4626. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4627. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4628. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4629. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4630. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4631. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4632. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4633. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4634. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4635. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4636. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4637. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4638. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4639. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4640. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4641. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4642. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4643. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4644. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4645. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4646. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4647. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4648. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4649. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4650. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4651. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4652. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4653. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4654. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4655. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4656. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4657. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4658. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4659. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4660. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4661. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4662. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4663. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4664. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4665. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4666. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4667. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4668. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4669. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4670. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4671. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4672. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4673. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4674. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4675. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4676. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4677. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4678. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4679. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4680. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4681. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4682. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4683. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4684. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4685. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4686. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4687. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4688. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4689. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4690. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4691. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4692. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4693. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4694. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4695. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4696. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4697. };
  4698. memcpy (p, initialPValues, sizeof (p));
  4699. int i, j = 0;
  4700. for (i = 4; --i >= 0;)
  4701. {
  4702. s[i].malloc (256);
  4703. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4704. }
  4705. for (i = 0; i < 18; ++i)
  4706. {
  4707. uint32 d = 0;
  4708. for (int k = 0; k < 4; ++k)
  4709. {
  4710. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4711. if (++j >= keyBytes)
  4712. j = 0;
  4713. }
  4714. p[i] = initialPValues[i] ^ d;
  4715. }
  4716. uint32 l = 0, r = 0;
  4717. for (i = 0; i < 18; i += 2)
  4718. {
  4719. encrypt (l, r);
  4720. p[i] = l;
  4721. p[i + 1] = r;
  4722. }
  4723. for (i = 0; i < 4; ++i)
  4724. {
  4725. for (j = 0; j < 256; j += 2)
  4726. {
  4727. encrypt (l, r);
  4728. s[i][j] = l;
  4729. s[i][j + 1] = r;
  4730. }
  4731. }
  4732. }
  4733. BlowFish::BlowFish (const BlowFish& other)
  4734. {
  4735. for (int i = 4; --i >= 0;)
  4736. s[i].malloc (256);
  4737. operator= (other);
  4738. }
  4739. BlowFish& BlowFish::operator= (const BlowFish& other)
  4740. {
  4741. memcpy (p, other.p, sizeof (p));
  4742. for (int i = 4; --i >= 0;)
  4743. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4744. return *this;
  4745. }
  4746. BlowFish::~BlowFish()
  4747. {
  4748. }
  4749. uint32 BlowFish::F (const uint32 x) const throw()
  4750. {
  4751. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4752. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4753. }
  4754. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4755. {
  4756. uint32 l = data1;
  4757. uint32 r = data2;
  4758. for (int i = 0; i < 16; ++i)
  4759. {
  4760. l ^= p[i];
  4761. r ^= F(l);
  4762. swapVariables (l, r);
  4763. }
  4764. data1 = r ^ p[17];
  4765. data2 = l ^ p[16];
  4766. }
  4767. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4768. {
  4769. uint32 l = data1;
  4770. uint32 r = data2;
  4771. for (int i = 17; i > 1; --i)
  4772. {
  4773. l ^= p[i];
  4774. r ^= F(l);
  4775. swapVariables (l, r);
  4776. }
  4777. data1 = r ^ p[0];
  4778. data2 = l ^ p[1];
  4779. }
  4780. END_JUCE_NAMESPACE
  4781. /*** End of inlined file: juce_BlowFish.cpp ***/
  4782. /*** Start of inlined file: juce_MD5.cpp ***/
  4783. BEGIN_JUCE_NAMESPACE
  4784. MD5::MD5()
  4785. {
  4786. zerostruct (result);
  4787. }
  4788. MD5::MD5 (const MD5& other)
  4789. {
  4790. memcpy (result, other.result, sizeof (result));
  4791. }
  4792. MD5& MD5::operator= (const MD5& other)
  4793. {
  4794. memcpy (result, other.result, sizeof (result));
  4795. return *this;
  4796. }
  4797. MD5::MD5 (const MemoryBlock& data)
  4798. {
  4799. ProcessContext context;
  4800. context.processBlock (data.getData(), data.getSize());
  4801. context.finish (result);
  4802. }
  4803. MD5::MD5 (const void* data, const size_t numBytes)
  4804. {
  4805. ProcessContext context;
  4806. context.processBlock (data, numBytes);
  4807. context.finish (result);
  4808. }
  4809. MD5::MD5 (const String& text)
  4810. {
  4811. ProcessContext context;
  4812. const int len = text.length();
  4813. const juce_wchar* const t = text;
  4814. for (int i = 0; i < len; ++i)
  4815. {
  4816. // force the string into integer-sized unicode characters, to try to make it
  4817. // get the same results on all platforms + compilers.
  4818. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4819. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4820. }
  4821. context.finish (result);
  4822. }
  4823. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4824. {
  4825. ProcessContext context;
  4826. if (numBytesToRead < 0)
  4827. numBytesToRead = std::numeric_limits<int64>::max();
  4828. while (numBytesToRead > 0)
  4829. {
  4830. uint8 tempBuffer [512];
  4831. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4832. if (bytesRead <= 0)
  4833. break;
  4834. numBytesToRead -= bytesRead;
  4835. context.processBlock (tempBuffer, bytesRead);
  4836. }
  4837. context.finish (result);
  4838. }
  4839. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4840. {
  4841. processStream (input, numBytesToRead);
  4842. }
  4843. MD5::MD5 (const File& file)
  4844. {
  4845. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4846. if (fin != 0)
  4847. processStream (*fin, -1);
  4848. else
  4849. zerostruct (result);
  4850. }
  4851. MD5::~MD5()
  4852. {
  4853. }
  4854. namespace MD5Functions
  4855. {
  4856. static void encode (void* const output, const void* const input, const int numBytes) throw()
  4857. {
  4858. for (int i = 0; i < (numBytes >> 2); ++i)
  4859. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4860. }
  4861. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4862. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4863. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4864. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4865. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4866. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4867. {
  4868. a += F (b, c, d) + x + ac;
  4869. a = rotateLeft (a, s) + b;
  4870. }
  4871. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4872. {
  4873. a += G (b, c, d) + x + ac;
  4874. a = rotateLeft (a, s) + b;
  4875. }
  4876. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4877. {
  4878. a += H (b, c, d) + x + ac;
  4879. a = rotateLeft (a, s) + b;
  4880. }
  4881. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4882. {
  4883. a += I (b, c, d) + x + ac;
  4884. a = rotateLeft (a, s) + b;
  4885. }
  4886. }
  4887. MD5::ProcessContext::ProcessContext()
  4888. {
  4889. state[0] = 0x67452301;
  4890. state[1] = 0xefcdab89;
  4891. state[2] = 0x98badcfe;
  4892. state[3] = 0x10325476;
  4893. count[0] = 0;
  4894. count[1] = 0;
  4895. }
  4896. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4897. {
  4898. int bufferPos = ((count[0] >> 3) & 0x3F);
  4899. count[0] += (uint32) (dataSize << 3);
  4900. if (count[0] < ((uint32) dataSize << 3))
  4901. count[1]++;
  4902. count[1] += (uint32) (dataSize >> 29);
  4903. const size_t spaceLeft = 64 - bufferPos;
  4904. size_t i = 0;
  4905. if (dataSize >= spaceLeft)
  4906. {
  4907. memcpy (buffer + bufferPos, data, spaceLeft);
  4908. transform (buffer);
  4909. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4910. transform (static_cast <const char*> (data) + i);
  4911. bufferPos = 0;
  4912. }
  4913. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4914. }
  4915. void MD5::ProcessContext::finish (void* const result)
  4916. {
  4917. unsigned char encodedLength[8];
  4918. MD5Functions::encode (encodedLength, count, 8);
  4919. // Pad out to 56 mod 64.
  4920. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4921. const int paddingLength = (index < 56) ? (56 - index)
  4922. : (120 - index);
  4923. uint8 paddingBuffer [64];
  4924. zeromem (paddingBuffer, paddingLength);
  4925. paddingBuffer [0] = 0x80;
  4926. processBlock (paddingBuffer, paddingLength);
  4927. processBlock (encodedLength, 8);
  4928. MD5Functions::encode (result, state, 16);
  4929. zerostruct (buffer);
  4930. }
  4931. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4932. {
  4933. using namespace MD5Functions;
  4934. uint32 a = state[0];
  4935. uint32 b = state[1];
  4936. uint32 c = state[2];
  4937. uint32 d = state[3];
  4938. uint32 x[16];
  4939. encode (x, bufferToTransform, 64);
  4940. enum Constants
  4941. {
  4942. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4943. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4944. };
  4945. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4946. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4947. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4948. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4949. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4950. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4951. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4952. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4953. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4954. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4955. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4956. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4957. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4958. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4959. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4960. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4961. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4962. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4963. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4964. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4965. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4966. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4967. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4968. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4969. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4970. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4971. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4972. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4973. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4974. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4975. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4976. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4977. state[0] += a;
  4978. state[1] += b;
  4979. state[2] += c;
  4980. state[3] += d;
  4981. zerostruct (x);
  4982. }
  4983. const MemoryBlock MD5::getRawChecksumData() const
  4984. {
  4985. return MemoryBlock (result, sizeof (result));
  4986. }
  4987. const String MD5::toHexString() const
  4988. {
  4989. return String::toHexString (result, sizeof (result), 0);
  4990. }
  4991. bool MD5::operator== (const MD5& other) const
  4992. {
  4993. return memcmp (result, other.result, sizeof (result)) == 0;
  4994. }
  4995. bool MD5::operator!= (const MD5& other) const
  4996. {
  4997. return ! operator== (other);
  4998. }
  4999. END_JUCE_NAMESPACE
  5000. /*** End of inlined file: juce_MD5.cpp ***/
  5001. /*** Start of inlined file: juce_Primes.cpp ***/
  5002. BEGIN_JUCE_NAMESPACE
  5003. namespace PrimesHelpers
  5004. {
  5005. static void createSmallSieve (const int numBits, BigInteger& result)
  5006. {
  5007. result.setBit (numBits);
  5008. result.clearBit (numBits); // to enlarge the array
  5009. result.setBit (0);
  5010. int n = 2;
  5011. do
  5012. {
  5013. for (int i = n + n; i < numBits; i += n)
  5014. result.setBit (i);
  5015. n = result.findNextClearBit (n + 1);
  5016. }
  5017. while (n <= (numBits >> 1));
  5018. }
  5019. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5020. const BigInteger& smallSieve, const int smallSieveSize)
  5021. {
  5022. jassert (! base[0]); // must be even!
  5023. result.setBit (numBits);
  5024. result.clearBit (numBits); // to enlarge the array
  5025. int index = smallSieve.findNextClearBit (0);
  5026. do
  5027. {
  5028. const int prime = (index << 1) + 1;
  5029. BigInteger r (base), remainder;
  5030. r.divideBy (prime, remainder);
  5031. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5032. if (r.isZero())
  5033. i += prime;
  5034. if ((i & 1) == 0)
  5035. i += prime;
  5036. i = (i - 1) >> 1;
  5037. while (i < numBits)
  5038. {
  5039. result.setBit (i);
  5040. i += prime;
  5041. }
  5042. index = smallSieve.findNextClearBit (index + 1);
  5043. }
  5044. while (index < smallSieveSize);
  5045. }
  5046. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5047. const int numBits, BigInteger& result, const int certainty)
  5048. {
  5049. for (int i = 0; i < numBits; ++i)
  5050. {
  5051. if (! sieve[i])
  5052. {
  5053. result = base + (unsigned int) ((i << 1) + 1);
  5054. if (Primes::isProbablyPrime (result, certainty))
  5055. return true;
  5056. }
  5057. }
  5058. return false;
  5059. }
  5060. static bool passesMillerRabin (const BigInteger& n, int iterations)
  5061. {
  5062. const BigInteger one (1), two (2);
  5063. const BigInteger nMinusOne (n - one);
  5064. BigInteger d (nMinusOne);
  5065. const int s = d.findNextSetBit (0);
  5066. d >>= s;
  5067. BigInteger smallPrimes;
  5068. int numBitsInSmallPrimes = 0;
  5069. for (;;)
  5070. {
  5071. numBitsInSmallPrimes += 256;
  5072. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5073. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5074. if (numPrimesFound > iterations + 1)
  5075. break;
  5076. }
  5077. int smallPrime = 2;
  5078. while (--iterations >= 0)
  5079. {
  5080. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5081. BigInteger r (smallPrime);
  5082. r.exponentModulo (d, n);
  5083. if (r != one && r != nMinusOne)
  5084. {
  5085. for (int j = 0; j < s; ++j)
  5086. {
  5087. r.exponentModulo (two, n);
  5088. if (r == nMinusOne)
  5089. break;
  5090. }
  5091. if (r != nMinusOne)
  5092. return false;
  5093. }
  5094. }
  5095. return true;
  5096. }
  5097. }
  5098. const BigInteger Primes::createProbablePrime (const int bitLength,
  5099. const int certainty,
  5100. const int* randomSeeds,
  5101. int numRandomSeeds)
  5102. {
  5103. using namespace PrimesHelpers;
  5104. int defaultSeeds [16];
  5105. if (numRandomSeeds <= 0)
  5106. {
  5107. randomSeeds = defaultSeeds;
  5108. numRandomSeeds = numElementsInArray (defaultSeeds);
  5109. Random r (0);
  5110. for (int j = 10; --j >= 0;)
  5111. {
  5112. r.setSeedRandomly();
  5113. for (int i = numRandomSeeds; --i >= 0;)
  5114. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5115. }
  5116. }
  5117. BigInteger smallSieve;
  5118. const int smallSieveSize = 15000;
  5119. createSmallSieve (smallSieveSize, smallSieve);
  5120. BigInteger p;
  5121. for (int i = numRandomSeeds; --i >= 0;)
  5122. {
  5123. BigInteger p2;
  5124. Random r (randomSeeds[i]);
  5125. r.fillBitsRandomly (p2, 0, bitLength);
  5126. p ^= p2;
  5127. }
  5128. p.setBit (bitLength - 1);
  5129. p.clearBit (0);
  5130. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5131. while (p.getHighestBit() < bitLength)
  5132. {
  5133. p += 2 * searchLen;
  5134. BigInteger sieve;
  5135. bigSieve (p, searchLen, sieve,
  5136. smallSieve, smallSieveSize);
  5137. BigInteger candidate;
  5138. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5139. return candidate;
  5140. }
  5141. jassertfalse;
  5142. return BigInteger();
  5143. }
  5144. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5145. {
  5146. using namespace PrimesHelpers;
  5147. if (! number[0])
  5148. return false;
  5149. if (number.getHighestBit() <= 10)
  5150. {
  5151. const int num = number.getBitRangeAsInt (0, 10);
  5152. for (int i = num / 2; --i > 1;)
  5153. if (num % i == 0)
  5154. return false;
  5155. return true;
  5156. }
  5157. else
  5158. {
  5159. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5160. return false;
  5161. return passesMillerRabin (number, certainty);
  5162. }
  5163. }
  5164. END_JUCE_NAMESPACE
  5165. /*** End of inlined file: juce_Primes.cpp ***/
  5166. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5167. BEGIN_JUCE_NAMESPACE
  5168. RSAKey::RSAKey()
  5169. {
  5170. }
  5171. RSAKey::RSAKey (const String& s)
  5172. {
  5173. if (s.containsChar (','))
  5174. {
  5175. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5176. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5177. }
  5178. else
  5179. {
  5180. // the string needs to be two hex numbers, comma-separated..
  5181. jassertfalse;
  5182. }
  5183. }
  5184. RSAKey::~RSAKey()
  5185. {
  5186. }
  5187. bool RSAKey::operator== (const RSAKey& other) const throw()
  5188. {
  5189. return part1 == other.part1 && part2 == other.part2;
  5190. }
  5191. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5192. {
  5193. return ! operator== (other);
  5194. }
  5195. const String RSAKey::toString() const
  5196. {
  5197. return part1.toString (16) + "," + part2.toString (16);
  5198. }
  5199. bool RSAKey::applyToValue (BigInteger& value) const
  5200. {
  5201. if (part1.isZero() || part2.isZero() || value <= 0)
  5202. {
  5203. jassertfalse; // using an uninitialised key
  5204. value.clear();
  5205. return false;
  5206. }
  5207. BigInteger result;
  5208. while (! value.isZero())
  5209. {
  5210. result *= part2;
  5211. BigInteger remainder;
  5212. value.divideBy (part2, remainder);
  5213. remainder.exponentModulo (part1, part2);
  5214. result += remainder;
  5215. }
  5216. value.swapWith (result);
  5217. return true;
  5218. }
  5219. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5220. {
  5221. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5222. // are fast to divide + multiply
  5223. for (int i = 2; i <= 65536; i *= 2)
  5224. {
  5225. const BigInteger e (1 + i);
  5226. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5227. return e;
  5228. }
  5229. BigInteger e (4);
  5230. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5231. ++e;
  5232. return e;
  5233. }
  5234. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5235. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5236. {
  5237. jassert (numBits > 16); // not much point using less than this..
  5238. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5239. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5240. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5241. const BigInteger n (p * q);
  5242. const BigInteger m (--p * --q);
  5243. const BigInteger e (findBestCommonDivisor (p, q));
  5244. BigInteger d (e);
  5245. d.inverseModulo (m);
  5246. publicKey.part1 = e;
  5247. publicKey.part2 = n;
  5248. privateKey.part1 = d;
  5249. privateKey.part2 = n;
  5250. }
  5251. END_JUCE_NAMESPACE
  5252. /*** End of inlined file: juce_RSAKey.cpp ***/
  5253. /*** Start of inlined file: juce_InputStream.cpp ***/
  5254. BEGIN_JUCE_NAMESPACE
  5255. char InputStream::readByte()
  5256. {
  5257. char temp = 0;
  5258. read (&temp, 1);
  5259. return temp;
  5260. }
  5261. bool InputStream::readBool()
  5262. {
  5263. return readByte() != 0;
  5264. }
  5265. short InputStream::readShort()
  5266. {
  5267. char temp[2];
  5268. if (read (temp, 2) == 2)
  5269. return (short) ByteOrder::littleEndianShort (temp);
  5270. return 0;
  5271. }
  5272. short InputStream::readShortBigEndian()
  5273. {
  5274. char temp[2];
  5275. if (read (temp, 2) == 2)
  5276. return (short) ByteOrder::bigEndianShort (temp);
  5277. return 0;
  5278. }
  5279. int InputStream::readInt()
  5280. {
  5281. char temp[4];
  5282. if (read (temp, 4) == 4)
  5283. return (int) ByteOrder::littleEndianInt (temp);
  5284. return 0;
  5285. }
  5286. int InputStream::readIntBigEndian()
  5287. {
  5288. char temp[4];
  5289. if (read (temp, 4) == 4)
  5290. return (int) ByteOrder::bigEndianInt (temp);
  5291. return 0;
  5292. }
  5293. int InputStream::readCompressedInt()
  5294. {
  5295. const unsigned char sizeByte = readByte();
  5296. if (sizeByte == 0)
  5297. return 0;
  5298. const int numBytes = (sizeByte & 0x7f);
  5299. if (numBytes > 4)
  5300. {
  5301. jassertfalse; // trying to read corrupt data - this method must only be used
  5302. // to read data that was written by OutputStream::writeCompressedInt()
  5303. return 0;
  5304. }
  5305. char bytes[4] = { 0, 0, 0, 0 };
  5306. if (read (bytes, numBytes) != numBytes)
  5307. return 0;
  5308. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5309. return (sizeByte >> 7) ? -num : num;
  5310. }
  5311. int64 InputStream::readInt64()
  5312. {
  5313. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5314. if (read (n.asBytes, 8) == 8)
  5315. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5316. return 0;
  5317. }
  5318. int64 InputStream::readInt64BigEndian()
  5319. {
  5320. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5321. if (read (n.asBytes, 8) == 8)
  5322. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5323. return 0;
  5324. }
  5325. float InputStream::readFloat()
  5326. {
  5327. // the union below relies on these types being the same size...
  5328. static_jassert (sizeof (int32) == sizeof (float));
  5329. union { int32 asInt; float asFloat; } n;
  5330. n.asInt = (int32) readInt();
  5331. return n.asFloat;
  5332. }
  5333. float InputStream::readFloatBigEndian()
  5334. {
  5335. union { int32 asInt; float asFloat; } n;
  5336. n.asInt = (int32) readIntBigEndian();
  5337. return n.asFloat;
  5338. }
  5339. double InputStream::readDouble()
  5340. {
  5341. union { int64 asInt; double asDouble; } n;
  5342. n.asInt = readInt64();
  5343. return n.asDouble;
  5344. }
  5345. double InputStream::readDoubleBigEndian()
  5346. {
  5347. union { int64 asInt; double asDouble; } n;
  5348. n.asInt = readInt64BigEndian();
  5349. return n.asDouble;
  5350. }
  5351. const String InputStream::readString()
  5352. {
  5353. MemoryBlock buffer (256);
  5354. char* data = static_cast<char*> (buffer.getData());
  5355. size_t i = 0;
  5356. while ((data[i] = readByte()) != 0)
  5357. {
  5358. if (++i >= buffer.getSize())
  5359. {
  5360. buffer.setSize (buffer.getSize() + 512);
  5361. data = static_cast<char*> (buffer.getData());
  5362. }
  5363. }
  5364. return String::fromUTF8 (data, (int) i);
  5365. }
  5366. const String InputStream::readNextLine()
  5367. {
  5368. MemoryBlock buffer (256);
  5369. char* data = static_cast<char*> (buffer.getData());
  5370. size_t i = 0;
  5371. while ((data[i] = readByte()) != 0)
  5372. {
  5373. if (data[i] == '\n')
  5374. break;
  5375. if (data[i] == '\r')
  5376. {
  5377. const int64 lastPos = getPosition();
  5378. if (readByte() != '\n')
  5379. setPosition (lastPos);
  5380. break;
  5381. }
  5382. if (++i >= buffer.getSize())
  5383. {
  5384. buffer.setSize (buffer.getSize() + 512);
  5385. data = static_cast<char*> (buffer.getData());
  5386. }
  5387. }
  5388. return String::fromUTF8 (data, (int) i);
  5389. }
  5390. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5391. {
  5392. MemoryOutputStream mo (block, true);
  5393. return mo.writeFromInputStream (*this, numBytes);
  5394. }
  5395. const String InputStream::readEntireStreamAsString()
  5396. {
  5397. MemoryOutputStream mo;
  5398. mo.writeFromInputStream (*this, -1);
  5399. return mo.toString();
  5400. }
  5401. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5402. {
  5403. if (numBytesToSkip > 0)
  5404. {
  5405. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5406. HeapBlock<char> temp (skipBufferSize);
  5407. while (numBytesToSkip > 0 && ! isExhausted())
  5408. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5409. }
  5410. }
  5411. END_JUCE_NAMESPACE
  5412. /*** End of inlined file: juce_InputStream.cpp ***/
  5413. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5414. BEGIN_JUCE_NAMESPACE
  5415. #if JUCE_DEBUG
  5416. static Array<void*, CriticalSection> activeStreams;
  5417. void juce_CheckForDanglingStreams()
  5418. {
  5419. /*
  5420. It's always a bad idea to leak any object, but if you're leaking output
  5421. streams, then there's a good chance that you're failing to flush a file
  5422. to disk properly, which could result in corrupted data and other similar
  5423. nastiness..
  5424. */
  5425. jassert (activeStreams.size() == 0);
  5426. };
  5427. #endif
  5428. OutputStream::OutputStream()
  5429. {
  5430. #if JUCE_DEBUG
  5431. activeStreams.add (this);
  5432. #endif
  5433. }
  5434. OutputStream::~OutputStream()
  5435. {
  5436. #if JUCE_DEBUG
  5437. activeStreams.removeValue (this);
  5438. #endif
  5439. }
  5440. void OutputStream::writeBool (const bool b)
  5441. {
  5442. writeByte (b ? (char) 1
  5443. : (char) 0);
  5444. }
  5445. void OutputStream::writeByte (char byte)
  5446. {
  5447. write (&byte, 1);
  5448. }
  5449. void OutputStream::writeShort (short value)
  5450. {
  5451. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5452. write (&v, 2);
  5453. }
  5454. void OutputStream::writeShortBigEndian (short value)
  5455. {
  5456. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5457. write (&v, 2);
  5458. }
  5459. void OutputStream::writeInt (int value)
  5460. {
  5461. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5462. write (&v, 4);
  5463. }
  5464. void OutputStream::writeIntBigEndian (int value)
  5465. {
  5466. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5467. write (&v, 4);
  5468. }
  5469. void OutputStream::writeCompressedInt (int value)
  5470. {
  5471. unsigned int un = (value < 0) ? (unsigned int) -value
  5472. : (unsigned int) value;
  5473. uint8 data[5];
  5474. int num = 0;
  5475. while (un > 0)
  5476. {
  5477. data[++num] = (uint8) un;
  5478. un >>= 8;
  5479. }
  5480. data[0] = (uint8) num;
  5481. if (value < 0)
  5482. data[0] |= 0x80;
  5483. write (data, num + 1);
  5484. }
  5485. void OutputStream::writeInt64 (int64 value)
  5486. {
  5487. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5488. write (&v, 8);
  5489. }
  5490. void OutputStream::writeInt64BigEndian (int64 value)
  5491. {
  5492. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5493. write (&v, 8);
  5494. }
  5495. void OutputStream::writeFloat (float value)
  5496. {
  5497. union { int asInt; float asFloat; } n;
  5498. n.asFloat = value;
  5499. writeInt (n.asInt);
  5500. }
  5501. void OutputStream::writeFloatBigEndian (float value)
  5502. {
  5503. union { int asInt; float asFloat; } n;
  5504. n.asFloat = value;
  5505. writeIntBigEndian (n.asInt);
  5506. }
  5507. void OutputStream::writeDouble (double value)
  5508. {
  5509. union { int64 asInt; double asDouble; } n;
  5510. n.asDouble = value;
  5511. writeInt64 (n.asInt);
  5512. }
  5513. void OutputStream::writeDoubleBigEndian (double value)
  5514. {
  5515. union { int64 asInt; double asDouble; } n;
  5516. n.asDouble = value;
  5517. writeInt64BigEndian (n.asInt);
  5518. }
  5519. void OutputStream::writeString (const String& text)
  5520. {
  5521. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5522. // if lots of large, persistent strings were to be written to streams).
  5523. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5524. HeapBlock<char> temp (numBytes);
  5525. text.copyToUTF8 (temp, numBytes);
  5526. write (temp, numBytes);
  5527. }
  5528. void OutputStream::writeText (const String& text, const bool asUnicode,
  5529. const bool writeUnicodeHeaderBytes)
  5530. {
  5531. if (asUnicode)
  5532. {
  5533. if (writeUnicodeHeaderBytes)
  5534. write ("\x0ff\x0fe", 2);
  5535. const juce_wchar* src = text;
  5536. bool lastCharWasReturn = false;
  5537. while (*src != 0)
  5538. {
  5539. if (*src == L'\n' && ! lastCharWasReturn)
  5540. writeShort ((short) L'\r');
  5541. lastCharWasReturn = (*src == L'\r');
  5542. writeShort ((short) *src++);
  5543. }
  5544. }
  5545. else
  5546. {
  5547. const char* src = text.toUTF8();
  5548. const char* t = src;
  5549. for (;;)
  5550. {
  5551. if (*t == '\n')
  5552. {
  5553. if (t > src)
  5554. write (src, (int) (t - src));
  5555. write ("\r\n", 2);
  5556. src = t + 1;
  5557. }
  5558. else if (*t == '\r')
  5559. {
  5560. if (t[1] == '\n')
  5561. ++t;
  5562. }
  5563. else if (*t == 0)
  5564. {
  5565. if (t > src)
  5566. write (src, (int) (t - src));
  5567. break;
  5568. }
  5569. ++t;
  5570. }
  5571. }
  5572. }
  5573. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5574. {
  5575. if (numBytesToWrite < 0)
  5576. numBytesToWrite = std::numeric_limits<int64>::max();
  5577. int numWritten = 0;
  5578. while (numBytesToWrite > 0 && ! source.isExhausted())
  5579. {
  5580. char buffer [8192];
  5581. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5582. if (num <= 0)
  5583. break;
  5584. write (buffer, num);
  5585. numBytesToWrite -= num;
  5586. numWritten += num;
  5587. }
  5588. return numWritten;
  5589. }
  5590. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5591. {
  5592. return stream << String (number);
  5593. }
  5594. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5595. {
  5596. return stream << String (number);
  5597. }
  5598. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5599. {
  5600. stream.writeByte (character);
  5601. return stream;
  5602. }
  5603. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5604. {
  5605. stream.write (text, (int) strlen (text));
  5606. return stream;
  5607. }
  5608. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5609. {
  5610. stream.write (data.getData(), (int) data.getSize());
  5611. return stream;
  5612. }
  5613. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5614. {
  5615. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5616. if (in != 0)
  5617. stream.writeFromInputStream (*in, -1);
  5618. return stream;
  5619. }
  5620. END_JUCE_NAMESPACE
  5621. /*** End of inlined file: juce_OutputStream.cpp ***/
  5622. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5623. BEGIN_JUCE_NAMESPACE
  5624. DirectoryIterator::DirectoryIterator (const File& directory,
  5625. bool isRecursive_,
  5626. const String& wildCard_,
  5627. const int whatToLookFor_)
  5628. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5629. wildCard (wildCard_),
  5630. path (File::addTrailingSeparator (directory.getFullPathName())),
  5631. index (-1),
  5632. totalNumFiles (-1),
  5633. whatToLookFor (whatToLookFor_),
  5634. isRecursive (isRecursive_),
  5635. hasBeenAdvanced (false)
  5636. {
  5637. // you have to specify the type of files you're looking for!
  5638. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5639. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5640. }
  5641. DirectoryIterator::~DirectoryIterator()
  5642. {
  5643. }
  5644. bool DirectoryIterator::next()
  5645. {
  5646. return next (0, 0, 0, 0, 0, 0);
  5647. }
  5648. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5649. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5650. {
  5651. hasBeenAdvanced = true;
  5652. if (subIterator != 0)
  5653. {
  5654. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5655. return true;
  5656. subIterator = 0;
  5657. }
  5658. String filename;
  5659. bool isDirectory, isHidden;
  5660. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5661. {
  5662. ++index;
  5663. if (! filename.containsOnly ("."))
  5664. {
  5665. const File fileFound (path + filename, 0);
  5666. bool matches = false;
  5667. if (isDirectory)
  5668. {
  5669. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5670. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5671. matches = (whatToLookFor & File::findDirectories) != 0;
  5672. }
  5673. else
  5674. {
  5675. matches = (whatToLookFor & File::findFiles) != 0;
  5676. }
  5677. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5678. if (matches && isRecursive)
  5679. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5680. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5681. matches = ! isHidden;
  5682. if (matches)
  5683. {
  5684. currentFile = fileFound;
  5685. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5686. if (isDirResult != 0) *isDirResult = isDirectory;
  5687. return true;
  5688. }
  5689. else if (subIterator != 0)
  5690. {
  5691. return next();
  5692. }
  5693. }
  5694. }
  5695. return false;
  5696. }
  5697. const File DirectoryIterator::getFile() const
  5698. {
  5699. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5700. return subIterator->getFile();
  5701. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5702. jassert (hasBeenAdvanced);
  5703. return currentFile;
  5704. }
  5705. float DirectoryIterator::getEstimatedProgress() const
  5706. {
  5707. if (totalNumFiles < 0)
  5708. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5709. if (totalNumFiles <= 0)
  5710. return 0.0f;
  5711. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5712. : (float) index;
  5713. return detailedIndex / totalNumFiles;
  5714. }
  5715. END_JUCE_NAMESPACE
  5716. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5717. /*** Start of inlined file: juce_File.cpp ***/
  5718. #if ! JUCE_WINDOWS
  5719. #include <pwd.h>
  5720. #endif
  5721. BEGIN_JUCE_NAMESPACE
  5722. File::File (const String& fullPathName)
  5723. : fullPath (parseAbsolutePath (fullPathName))
  5724. {
  5725. }
  5726. File::File (const String& path, int)
  5727. : fullPath (path)
  5728. {
  5729. }
  5730. const File File::createFileWithoutCheckingPath (const String& path)
  5731. {
  5732. return File (path, 0);
  5733. }
  5734. File::File (const File& other)
  5735. : fullPath (other.fullPath)
  5736. {
  5737. }
  5738. File& File::operator= (const String& newPath)
  5739. {
  5740. fullPath = parseAbsolutePath (newPath);
  5741. return *this;
  5742. }
  5743. File& File::operator= (const File& other)
  5744. {
  5745. fullPath = other.fullPath;
  5746. return *this;
  5747. }
  5748. const File File::nonexistent;
  5749. const String File::parseAbsolutePath (const String& p)
  5750. {
  5751. if (p.isEmpty())
  5752. return String::empty;
  5753. #if JUCE_WINDOWS
  5754. // Windows..
  5755. String path (p.replaceCharacter ('/', '\\'));
  5756. if (path.startsWithChar (File::separator))
  5757. {
  5758. if (path[1] != File::separator)
  5759. {
  5760. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5761. If you're trying to parse a string that may be either a relative path or an absolute path,
  5762. you MUST provide a context against which the partial path can be evaluated - you can do
  5763. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5764. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5765. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5766. */
  5767. jassertfalse;
  5768. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5769. }
  5770. }
  5771. else if (! path.containsChar (':'))
  5772. {
  5773. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5774. If you're trying to parse a string that may be either a relative path or an absolute path,
  5775. you MUST provide a context against which the partial path can be evaluated - you can do
  5776. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5777. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5778. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5779. */
  5780. jassertfalse;
  5781. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5782. }
  5783. #else
  5784. // Mac or Linux..
  5785. String path (p.replaceCharacter ('\\', '/'));
  5786. if (path.startsWithChar ('~'))
  5787. {
  5788. if (path[1] == File::separator || path[1] == 0)
  5789. {
  5790. // expand a name of the form "~/abc"
  5791. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5792. + path.substring (1);
  5793. }
  5794. else
  5795. {
  5796. // expand a name of type "~dave/abc"
  5797. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5798. struct passwd* const pw = getpwnam (userName.toUTF8());
  5799. if (pw != 0)
  5800. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5801. }
  5802. }
  5803. else if (! path.startsWithChar (File::separator))
  5804. {
  5805. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5806. If you're trying to parse a string that may be either a relative path or an absolute path,
  5807. you MUST provide a context against which the partial path can be evaluated - you can do
  5808. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5809. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5810. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5811. */
  5812. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5813. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5814. }
  5815. #endif
  5816. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5817. path = path.dropLastCharacters (1);
  5818. return path;
  5819. }
  5820. const String File::addTrailingSeparator (const String& path)
  5821. {
  5822. return path.endsWithChar (File::separator) ? path
  5823. : path + File::separator;
  5824. }
  5825. #if JUCE_LINUX
  5826. #define NAMES_ARE_CASE_SENSITIVE 1
  5827. #endif
  5828. bool File::areFileNamesCaseSensitive()
  5829. {
  5830. #if NAMES_ARE_CASE_SENSITIVE
  5831. return true;
  5832. #else
  5833. return false;
  5834. #endif
  5835. }
  5836. bool File::operator== (const File& other) const
  5837. {
  5838. #if NAMES_ARE_CASE_SENSITIVE
  5839. return fullPath == other.fullPath;
  5840. #else
  5841. return fullPath.equalsIgnoreCase (other.fullPath);
  5842. #endif
  5843. }
  5844. bool File::operator!= (const File& other) const
  5845. {
  5846. return ! operator== (other);
  5847. }
  5848. bool File::operator< (const File& other) const
  5849. {
  5850. #if NAMES_ARE_CASE_SENSITIVE
  5851. return fullPath < other.fullPath;
  5852. #else
  5853. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5854. #endif
  5855. }
  5856. bool File::operator> (const File& other) const
  5857. {
  5858. #if NAMES_ARE_CASE_SENSITIVE
  5859. return fullPath > other.fullPath;
  5860. #else
  5861. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5862. #endif
  5863. }
  5864. bool File::setReadOnly (const bool shouldBeReadOnly,
  5865. const bool applyRecursively) const
  5866. {
  5867. bool worked = true;
  5868. if (applyRecursively && isDirectory())
  5869. {
  5870. Array <File> subFiles;
  5871. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5872. for (int i = subFiles.size(); --i >= 0;)
  5873. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5874. }
  5875. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5876. }
  5877. bool File::deleteRecursively() const
  5878. {
  5879. bool worked = true;
  5880. if (isDirectory())
  5881. {
  5882. Array<File> subFiles;
  5883. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5884. for (int i = subFiles.size(); --i >= 0;)
  5885. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5886. }
  5887. return deleteFile() && worked;
  5888. }
  5889. bool File::moveFileTo (const File& newFile) const
  5890. {
  5891. if (newFile.fullPath == fullPath)
  5892. return true;
  5893. #if ! NAMES_ARE_CASE_SENSITIVE
  5894. if (*this != newFile)
  5895. #endif
  5896. if (! newFile.deleteFile())
  5897. return false;
  5898. return moveInternal (newFile);
  5899. }
  5900. bool File::copyFileTo (const File& newFile) const
  5901. {
  5902. return (*this == newFile)
  5903. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5904. }
  5905. bool File::copyDirectoryTo (const File& newDirectory) const
  5906. {
  5907. if (isDirectory() && newDirectory.createDirectory())
  5908. {
  5909. Array<File> subFiles;
  5910. findChildFiles (subFiles, File::findFiles, false);
  5911. int i;
  5912. for (i = 0; i < subFiles.size(); ++i)
  5913. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5914. return false;
  5915. subFiles.clear();
  5916. findChildFiles (subFiles, File::findDirectories, false);
  5917. for (i = 0; i < subFiles.size(); ++i)
  5918. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5919. return false;
  5920. return true;
  5921. }
  5922. return false;
  5923. }
  5924. const String File::getPathUpToLastSlash() const
  5925. {
  5926. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5927. if (lastSlash > 0)
  5928. return fullPath.substring (0, lastSlash);
  5929. else if (lastSlash == 0)
  5930. return separatorString;
  5931. else
  5932. return fullPath;
  5933. }
  5934. const File File::getParentDirectory() const
  5935. {
  5936. return File (getPathUpToLastSlash(), (int) 0);
  5937. }
  5938. const String File::getFileName() const
  5939. {
  5940. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5941. }
  5942. int File::hashCode() const
  5943. {
  5944. return fullPath.hashCode();
  5945. }
  5946. int64 File::hashCode64() const
  5947. {
  5948. return fullPath.hashCode64();
  5949. }
  5950. const String File::getFileNameWithoutExtension() const
  5951. {
  5952. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5953. const int lastDot = fullPath.lastIndexOfChar ('.');
  5954. if (lastDot > lastSlash)
  5955. return fullPath.substring (lastSlash, lastDot);
  5956. else
  5957. return fullPath.substring (lastSlash);
  5958. }
  5959. bool File::isAChildOf (const File& potentialParent) const
  5960. {
  5961. if (potentialParent == File::nonexistent)
  5962. return false;
  5963. const String ourPath (getPathUpToLastSlash());
  5964. #if NAMES_ARE_CASE_SENSITIVE
  5965. if (potentialParent.fullPath == ourPath)
  5966. #else
  5967. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5968. #endif
  5969. {
  5970. return true;
  5971. }
  5972. else if (potentialParent.fullPath.length() >= ourPath.length())
  5973. {
  5974. return false;
  5975. }
  5976. else
  5977. {
  5978. return getParentDirectory().isAChildOf (potentialParent);
  5979. }
  5980. }
  5981. bool File::isAbsolutePath (const String& path)
  5982. {
  5983. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5984. #if JUCE_WINDOWS
  5985. || (path.isNotEmpty() && path[1] == ':');
  5986. #else
  5987. || path.startsWithChar ('~');
  5988. #endif
  5989. }
  5990. const File File::getChildFile (String relativePath) const
  5991. {
  5992. if (isAbsolutePath (relativePath))
  5993. {
  5994. // the path is really absolute..
  5995. return File (relativePath);
  5996. }
  5997. else
  5998. {
  5999. // it's relative, so remove any ../ or ./ bits at the start.
  6000. String path (fullPath);
  6001. if (relativePath[0] == '.')
  6002. {
  6003. #if JUCE_WINDOWS
  6004. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6005. #else
  6006. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  6007. #endif
  6008. while (relativePath[0] == '.')
  6009. {
  6010. if (relativePath[1] == '.')
  6011. {
  6012. if (relativePath [2] == 0 || relativePath[2] == separator)
  6013. {
  6014. const int lastSlash = path.lastIndexOfChar (separator);
  6015. if (lastSlash >= 0)
  6016. path = path.substring (0, lastSlash);
  6017. relativePath = relativePath.substring (3);
  6018. }
  6019. else
  6020. {
  6021. break;
  6022. }
  6023. }
  6024. else if (relativePath[1] == separator)
  6025. {
  6026. relativePath = relativePath.substring (2);
  6027. }
  6028. else
  6029. {
  6030. break;
  6031. }
  6032. }
  6033. }
  6034. return File (addTrailingSeparator (path) + relativePath);
  6035. }
  6036. }
  6037. const File File::getSiblingFile (const String& fileName) const
  6038. {
  6039. return getParentDirectory().getChildFile (fileName);
  6040. }
  6041. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6042. {
  6043. if (bytes == 1)
  6044. {
  6045. return "1 byte";
  6046. }
  6047. else if (bytes < 1024)
  6048. {
  6049. return String ((int) bytes) + " bytes";
  6050. }
  6051. else if (bytes < 1024 * 1024)
  6052. {
  6053. return String (bytes / 1024.0, 1) + " KB";
  6054. }
  6055. else if (bytes < 1024 * 1024 * 1024)
  6056. {
  6057. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6058. }
  6059. else
  6060. {
  6061. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6062. }
  6063. }
  6064. bool File::create() const
  6065. {
  6066. if (exists())
  6067. return true;
  6068. {
  6069. const File parentDir (getParentDirectory());
  6070. if (parentDir == *this || ! parentDir.createDirectory())
  6071. return false;
  6072. FileOutputStream fo (*this, 8);
  6073. }
  6074. return exists();
  6075. }
  6076. bool File::createDirectory() const
  6077. {
  6078. if (! isDirectory())
  6079. {
  6080. const File parentDir (getParentDirectory());
  6081. if (parentDir == *this || ! parentDir.createDirectory())
  6082. return false;
  6083. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6084. return isDirectory();
  6085. }
  6086. return true;
  6087. }
  6088. const Time File::getCreationTime() const
  6089. {
  6090. int64 m, a, c;
  6091. getFileTimesInternal (m, a, c);
  6092. return Time (c);
  6093. }
  6094. const Time File::getLastModificationTime() const
  6095. {
  6096. int64 m, a, c;
  6097. getFileTimesInternal (m, a, c);
  6098. return Time (m);
  6099. }
  6100. const Time File::getLastAccessTime() const
  6101. {
  6102. int64 m, a, c;
  6103. getFileTimesInternal (m, a, c);
  6104. return Time (a);
  6105. }
  6106. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6107. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6108. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6109. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6110. {
  6111. if (! existsAsFile())
  6112. return false;
  6113. FileInputStream in (*this);
  6114. return getSize() == in.readIntoMemoryBlock (destBlock);
  6115. }
  6116. const String File::loadFileAsString() const
  6117. {
  6118. if (! existsAsFile())
  6119. return String::empty;
  6120. FileInputStream in (*this);
  6121. return in.readEntireStreamAsString();
  6122. }
  6123. int File::findChildFiles (Array<File>& results,
  6124. const int whatToLookFor,
  6125. const bool searchRecursively,
  6126. const String& wildCardPattern) const
  6127. {
  6128. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6129. int total = 0;
  6130. while (di.next())
  6131. {
  6132. results.add (di.getFile());
  6133. ++total;
  6134. }
  6135. return total;
  6136. }
  6137. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6138. {
  6139. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6140. int total = 0;
  6141. while (di.next())
  6142. ++total;
  6143. return total;
  6144. }
  6145. bool File::containsSubDirectories() const
  6146. {
  6147. if (isDirectory())
  6148. {
  6149. DirectoryIterator di (*this, false, "*", findDirectories);
  6150. return di.next();
  6151. }
  6152. return false;
  6153. }
  6154. const File File::getNonexistentChildFile (const String& prefix_,
  6155. const String& suffix,
  6156. bool putNumbersInBrackets) const
  6157. {
  6158. File f (getChildFile (prefix_ + suffix));
  6159. if (f.exists())
  6160. {
  6161. int num = 2;
  6162. String prefix (prefix_);
  6163. // remove any bracketed numbers that may already be on the end..
  6164. if (prefix.trim().endsWithChar (')'))
  6165. {
  6166. putNumbersInBrackets = true;
  6167. const int openBracks = prefix.lastIndexOfChar ('(');
  6168. const int closeBracks = prefix.lastIndexOfChar (')');
  6169. if (openBracks > 0
  6170. && closeBracks > openBracks
  6171. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6172. {
  6173. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6174. prefix = prefix.substring (0, openBracks);
  6175. }
  6176. }
  6177. // also use brackets if it ends in a digit.
  6178. putNumbersInBrackets = putNumbersInBrackets
  6179. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6180. do
  6181. {
  6182. if (putNumbersInBrackets)
  6183. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6184. else
  6185. f = getChildFile (prefix + String (num++) + suffix);
  6186. } while (f.exists());
  6187. }
  6188. return f;
  6189. }
  6190. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6191. {
  6192. if (exists())
  6193. {
  6194. return getParentDirectory()
  6195. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6196. getFileExtension(),
  6197. putNumbersInBrackets);
  6198. }
  6199. else
  6200. {
  6201. return *this;
  6202. }
  6203. }
  6204. const String File::getFileExtension() const
  6205. {
  6206. String ext;
  6207. if (! isDirectory())
  6208. {
  6209. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6210. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6211. ext = fullPath.substring (indexOfDot);
  6212. }
  6213. return ext;
  6214. }
  6215. bool File::hasFileExtension (const String& possibleSuffix) const
  6216. {
  6217. if (possibleSuffix.isEmpty())
  6218. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6219. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6220. if (semicolon >= 0)
  6221. {
  6222. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6223. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6224. }
  6225. else
  6226. {
  6227. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6228. {
  6229. if (possibleSuffix.startsWithChar ('.'))
  6230. return true;
  6231. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6232. if (dotPos >= 0)
  6233. return fullPath [dotPos] == '.';
  6234. }
  6235. }
  6236. return false;
  6237. }
  6238. const File File::withFileExtension (const String& newExtension) const
  6239. {
  6240. if (fullPath.isEmpty())
  6241. return File::nonexistent;
  6242. String filePart (getFileName());
  6243. int i = filePart.lastIndexOfChar ('.');
  6244. if (i >= 0)
  6245. filePart = filePart.substring (0, i);
  6246. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6247. filePart << '.';
  6248. return getSiblingFile (filePart + newExtension);
  6249. }
  6250. bool File::startAsProcess (const String& parameters) const
  6251. {
  6252. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6253. }
  6254. FileInputStream* File::createInputStream() const
  6255. {
  6256. if (existsAsFile())
  6257. return new FileInputStream (*this);
  6258. return 0;
  6259. }
  6260. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6261. {
  6262. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6263. if (out->failedToOpen())
  6264. return 0;
  6265. return out.release();
  6266. }
  6267. bool File::appendData (const void* const dataToAppend,
  6268. const int numberOfBytes) const
  6269. {
  6270. if (numberOfBytes > 0)
  6271. {
  6272. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6273. if (out == 0)
  6274. return false;
  6275. out->write (dataToAppend, numberOfBytes);
  6276. }
  6277. return true;
  6278. }
  6279. bool File::replaceWithData (const void* const dataToWrite,
  6280. const int numberOfBytes) const
  6281. {
  6282. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6283. if (numberOfBytes <= 0)
  6284. return deleteFile();
  6285. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6286. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6287. return tempFile.overwriteTargetFileWithTemporary();
  6288. }
  6289. bool File::appendText (const String& text,
  6290. const bool asUnicode,
  6291. const bool writeUnicodeHeaderBytes) const
  6292. {
  6293. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6294. if (out != 0)
  6295. {
  6296. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6297. return true;
  6298. }
  6299. return false;
  6300. }
  6301. bool File::replaceWithText (const String& textToWrite,
  6302. const bool asUnicode,
  6303. const bool writeUnicodeHeaderBytes) const
  6304. {
  6305. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6306. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6307. return tempFile.overwriteTargetFileWithTemporary();
  6308. }
  6309. bool File::hasIdenticalContentTo (const File& other) const
  6310. {
  6311. if (other == *this)
  6312. return true;
  6313. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6314. {
  6315. FileInputStream in1 (*this), in2 (other);
  6316. const int bufferSize = 4096;
  6317. HeapBlock <char> buffer1, buffer2;
  6318. buffer1.malloc (bufferSize);
  6319. buffer2.malloc (bufferSize);
  6320. for (;;)
  6321. {
  6322. const int num1 = in1.read (buffer1, bufferSize);
  6323. const int num2 = in2.read (buffer2, bufferSize);
  6324. if (num1 != num2)
  6325. break;
  6326. if (num1 <= 0)
  6327. return true;
  6328. if (memcmp (buffer1, buffer2, num1) != 0)
  6329. break;
  6330. }
  6331. }
  6332. return false;
  6333. }
  6334. const String File::createLegalPathName (const String& original)
  6335. {
  6336. String s (original);
  6337. String start;
  6338. if (s[1] == ':')
  6339. {
  6340. start = s.substring (0, 2);
  6341. s = s.substring (2);
  6342. }
  6343. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6344. .substring (0, 1024);
  6345. }
  6346. const String File::createLegalFileName (const String& original)
  6347. {
  6348. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6349. const int maxLength = 128; // only the length of the filename, not the whole path
  6350. const int len = s.length();
  6351. if (len > maxLength)
  6352. {
  6353. const int lastDot = s.lastIndexOfChar ('.');
  6354. if (lastDot > jmax (0, len - 12))
  6355. {
  6356. s = s.substring (0, maxLength - (len - lastDot))
  6357. + s.substring (lastDot);
  6358. }
  6359. else
  6360. {
  6361. s = s.substring (0, maxLength);
  6362. }
  6363. }
  6364. return s;
  6365. }
  6366. const String File::getRelativePathFrom (const File& dir) const
  6367. {
  6368. String thisPath (fullPath);
  6369. {
  6370. int len = thisPath.length();
  6371. while (--len >= 0 && thisPath [len] == File::separator)
  6372. thisPath [len] = 0;
  6373. }
  6374. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6375. : dir.fullPath));
  6376. const int len = jmin (thisPath.length(), dirPath.length());
  6377. int commonBitLength = 0;
  6378. for (int i = 0; i < len; ++i)
  6379. {
  6380. #if NAMES_ARE_CASE_SENSITIVE
  6381. if (thisPath[i] != dirPath[i])
  6382. #else
  6383. if (CharacterFunctions::toLowerCase (thisPath[i])
  6384. != CharacterFunctions::toLowerCase (dirPath[i]))
  6385. #endif
  6386. {
  6387. break;
  6388. }
  6389. ++commonBitLength;
  6390. }
  6391. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6392. --commonBitLength;
  6393. // if the only common bit is the root, then just return the full path..
  6394. if (commonBitLength <= 0
  6395. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6396. return fullPath;
  6397. thisPath = thisPath.substring (commonBitLength);
  6398. dirPath = dirPath.substring (commonBitLength);
  6399. while (dirPath.isNotEmpty())
  6400. {
  6401. #if JUCE_WINDOWS
  6402. thisPath = "..\\" + thisPath;
  6403. #else
  6404. thisPath = "../" + thisPath;
  6405. #endif
  6406. const int sep = dirPath.indexOfChar (separator);
  6407. if (sep >= 0)
  6408. dirPath = dirPath.substring (sep + 1);
  6409. else
  6410. dirPath = String::empty;
  6411. }
  6412. return thisPath;
  6413. }
  6414. const File File::createTempFile (const String& fileNameEnding)
  6415. {
  6416. const File tempFile (getSpecialLocation (tempDirectory)
  6417. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6418. .withFileExtension (fileNameEnding));
  6419. if (tempFile.exists())
  6420. return createTempFile (fileNameEnding);
  6421. else
  6422. return tempFile;
  6423. }
  6424. #if JUCE_UNIT_TESTS
  6425. class FileTests : public UnitTest
  6426. {
  6427. public:
  6428. FileTests() : UnitTest ("Files") {}
  6429. void runTest()
  6430. {
  6431. beginTest ("Reading");
  6432. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6433. const File temp (File::getSpecialLocation (File::tempDirectory));
  6434. expect (! File::nonexistent.exists());
  6435. expect (home.isDirectory());
  6436. expect (home.exists());
  6437. expect (! home.existsAsFile());
  6438. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6439. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6440. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6441. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6442. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6443. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6444. expect (home.getBytesFreeOnVolume() > 0);
  6445. expect (! home.isHidden());
  6446. expect (home.isOnHardDisk());
  6447. expect (! home.isOnCDRomDrive());
  6448. expect (File::getCurrentWorkingDirectory().exists());
  6449. expect (home.setAsCurrentWorkingDirectory());
  6450. expect (File::getCurrentWorkingDirectory() == home);
  6451. {
  6452. Array<File> roots;
  6453. File::findFileSystemRoots (roots);
  6454. expect (roots.size() > 0);
  6455. int numRootsExisting = 0;
  6456. for (int i = 0; i < roots.size(); ++i)
  6457. if (roots[i].exists())
  6458. ++numRootsExisting;
  6459. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6460. expect (numRootsExisting > 0);
  6461. }
  6462. beginTest ("Writing");
  6463. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6464. expect (demoFolder.deleteRecursively());
  6465. expect (demoFolder.createDirectory());
  6466. expect (demoFolder.isDirectory());
  6467. expect (demoFolder.getParentDirectory() == temp);
  6468. expect (temp.isDirectory());
  6469. {
  6470. Array<File> files;
  6471. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6472. expect (files.contains (demoFolder));
  6473. }
  6474. {
  6475. Array<File> files;
  6476. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6477. expect (files.contains (demoFolder));
  6478. }
  6479. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6480. expect (tempFile.getFileExtension() == ".txt");
  6481. expect (tempFile.hasFileExtension (".txt"));
  6482. expect (tempFile.hasFileExtension ("txt"));
  6483. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6484. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6485. expect (tempFile.hasWriteAccess());
  6486. {
  6487. FileOutputStream fo (tempFile);
  6488. fo.write ("0123456789", 10);
  6489. }
  6490. expect (tempFile.exists());
  6491. expect (tempFile.getSize() == 10);
  6492. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6493. expect (tempFile.loadFileAsString() == "0123456789");
  6494. expect (! demoFolder.containsSubDirectories());
  6495. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6496. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6497. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6498. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6499. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6500. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6501. expect (demoFolder.containsSubDirectories());
  6502. expect (tempFile.hasWriteAccess());
  6503. tempFile.setReadOnly (true);
  6504. expect (! tempFile.hasWriteAccess());
  6505. tempFile.setReadOnly (false);
  6506. expect (tempFile.hasWriteAccess());
  6507. Time t (Time::getCurrentTime());
  6508. tempFile.setLastModificationTime (t);
  6509. Time t2 = tempFile.getLastModificationTime();
  6510. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6511. {
  6512. MemoryBlock mb;
  6513. tempFile.loadFileAsData (mb);
  6514. expect (mb.getSize() == 10);
  6515. expect (mb[0] == '0');
  6516. }
  6517. expect (tempFile.appendData ("abcdefghij", 10));
  6518. expect (tempFile.getSize() == 20);
  6519. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6520. expect (tempFile.getSize() == 10);
  6521. File tempFile2 (tempFile.getNonexistentSibling (false));
  6522. expect (tempFile.copyFileTo (tempFile2));
  6523. expect (tempFile2.exists());
  6524. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6525. expect (tempFile.deleteFile());
  6526. expect (! tempFile.exists());
  6527. expect (tempFile2.moveFileTo (tempFile));
  6528. expect (tempFile.exists());
  6529. expect (! tempFile2.exists());
  6530. expect (demoFolder.deleteRecursively());
  6531. expect (! demoFolder.exists());
  6532. }
  6533. };
  6534. static FileTests fileUnitTests;
  6535. #endif
  6536. END_JUCE_NAMESPACE
  6537. /*** End of inlined file: juce_File.cpp ***/
  6538. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6539. BEGIN_JUCE_NAMESPACE
  6540. int64 juce_fileSetPosition (void* handle, int64 pos);
  6541. FileInputStream::FileInputStream (const File& f)
  6542. : file (f),
  6543. fileHandle (0),
  6544. currentPosition (0),
  6545. totalSize (0),
  6546. needToSeek (true)
  6547. {
  6548. openHandle();
  6549. }
  6550. FileInputStream::~FileInputStream()
  6551. {
  6552. closeHandle();
  6553. }
  6554. int64 FileInputStream::getTotalLength()
  6555. {
  6556. return totalSize;
  6557. }
  6558. int FileInputStream::read (void* buffer, int bytesToRead)
  6559. {
  6560. int num = 0;
  6561. if (needToSeek)
  6562. {
  6563. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6564. return 0;
  6565. needToSeek = false;
  6566. }
  6567. num = readInternal (buffer, bytesToRead);
  6568. currentPosition += num;
  6569. return num;
  6570. }
  6571. bool FileInputStream::isExhausted()
  6572. {
  6573. return currentPosition >= totalSize;
  6574. }
  6575. int64 FileInputStream::getPosition()
  6576. {
  6577. return currentPosition;
  6578. }
  6579. bool FileInputStream::setPosition (int64 pos)
  6580. {
  6581. pos = jlimit ((int64) 0, totalSize, pos);
  6582. needToSeek |= (currentPosition != pos);
  6583. currentPosition = pos;
  6584. return true;
  6585. }
  6586. END_JUCE_NAMESPACE
  6587. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6588. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6589. BEGIN_JUCE_NAMESPACE
  6590. int64 juce_fileSetPosition (void* handle, int64 pos);
  6591. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6592. : file (f),
  6593. fileHandle (0),
  6594. currentPosition (0),
  6595. bufferSize (bufferSize_),
  6596. bytesInBuffer (0),
  6597. buffer (jmax (bufferSize_, 16))
  6598. {
  6599. openHandle();
  6600. }
  6601. FileOutputStream::~FileOutputStream()
  6602. {
  6603. flush();
  6604. closeHandle();
  6605. }
  6606. int64 FileOutputStream::getPosition()
  6607. {
  6608. return currentPosition;
  6609. }
  6610. bool FileOutputStream::setPosition (int64 newPosition)
  6611. {
  6612. if (newPosition != currentPosition)
  6613. {
  6614. flush();
  6615. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6616. }
  6617. return newPosition == currentPosition;
  6618. }
  6619. void FileOutputStream::flush()
  6620. {
  6621. if (bytesInBuffer > 0)
  6622. {
  6623. writeInternal (buffer, bytesInBuffer);
  6624. bytesInBuffer = 0;
  6625. }
  6626. flushInternal();
  6627. }
  6628. bool FileOutputStream::write (const void* const src, const int numBytes)
  6629. {
  6630. if (bytesInBuffer + numBytes < bufferSize)
  6631. {
  6632. memcpy (buffer + bytesInBuffer, src, numBytes);
  6633. bytesInBuffer += numBytes;
  6634. currentPosition += numBytes;
  6635. }
  6636. else
  6637. {
  6638. if (bytesInBuffer > 0)
  6639. {
  6640. // flush the reservoir
  6641. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6642. bytesInBuffer = 0;
  6643. if (! wroteOk)
  6644. return false;
  6645. }
  6646. if (numBytes < bufferSize)
  6647. {
  6648. memcpy (buffer + bytesInBuffer, src, numBytes);
  6649. bytesInBuffer += numBytes;
  6650. currentPosition += numBytes;
  6651. }
  6652. else
  6653. {
  6654. const int bytesWritten = writeInternal (src, numBytes);
  6655. if (bytesWritten < 0)
  6656. return false;
  6657. currentPosition += bytesWritten;
  6658. return bytesWritten == numBytes;
  6659. }
  6660. }
  6661. return true;
  6662. }
  6663. END_JUCE_NAMESPACE
  6664. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6665. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6666. BEGIN_JUCE_NAMESPACE
  6667. FileSearchPath::FileSearchPath()
  6668. {
  6669. }
  6670. FileSearchPath::FileSearchPath (const String& path)
  6671. {
  6672. init (path);
  6673. }
  6674. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6675. : directories (other.directories)
  6676. {
  6677. }
  6678. FileSearchPath::~FileSearchPath()
  6679. {
  6680. }
  6681. FileSearchPath& FileSearchPath::operator= (const String& path)
  6682. {
  6683. init (path);
  6684. return *this;
  6685. }
  6686. void FileSearchPath::init (const String& path)
  6687. {
  6688. directories.clear();
  6689. directories.addTokens (path, ";", "\"");
  6690. directories.trim();
  6691. directories.removeEmptyStrings();
  6692. for (int i = directories.size(); --i >= 0;)
  6693. directories.set (i, directories[i].unquoted());
  6694. }
  6695. int FileSearchPath::getNumPaths() const
  6696. {
  6697. return directories.size();
  6698. }
  6699. const File FileSearchPath::operator[] (const int index) const
  6700. {
  6701. return File (directories [index]);
  6702. }
  6703. const String FileSearchPath::toString() const
  6704. {
  6705. StringArray directories2 (directories);
  6706. for (int i = directories2.size(); --i >= 0;)
  6707. if (directories2[i].containsChar (';'))
  6708. directories2.set (i, directories2[i].quoted());
  6709. return directories2.joinIntoString (";");
  6710. }
  6711. void FileSearchPath::add (const File& dir, const int insertIndex)
  6712. {
  6713. directories.insert (insertIndex, dir.getFullPathName());
  6714. }
  6715. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6716. {
  6717. for (int i = 0; i < directories.size(); ++i)
  6718. if (File (directories[i]) == dir)
  6719. return;
  6720. add (dir);
  6721. }
  6722. void FileSearchPath::remove (const int index)
  6723. {
  6724. directories.remove (index);
  6725. }
  6726. void FileSearchPath::addPath (const FileSearchPath& other)
  6727. {
  6728. for (int i = 0; i < other.getNumPaths(); ++i)
  6729. addIfNotAlreadyThere (other[i]);
  6730. }
  6731. void FileSearchPath::removeRedundantPaths()
  6732. {
  6733. for (int i = directories.size(); --i >= 0;)
  6734. {
  6735. const File d1 (directories[i]);
  6736. for (int j = directories.size(); --j >= 0;)
  6737. {
  6738. const File d2 (directories[j]);
  6739. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6740. {
  6741. directories.remove (i);
  6742. break;
  6743. }
  6744. }
  6745. }
  6746. }
  6747. void FileSearchPath::removeNonExistentPaths()
  6748. {
  6749. for (int i = directories.size(); --i >= 0;)
  6750. if (! File (directories[i]).isDirectory())
  6751. directories.remove (i);
  6752. }
  6753. int FileSearchPath::findChildFiles (Array<File>& results,
  6754. const int whatToLookFor,
  6755. const bool searchRecursively,
  6756. const String& wildCardPattern) const
  6757. {
  6758. int total = 0;
  6759. for (int i = 0; i < directories.size(); ++i)
  6760. total += operator[] (i).findChildFiles (results,
  6761. whatToLookFor,
  6762. searchRecursively,
  6763. wildCardPattern);
  6764. return total;
  6765. }
  6766. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6767. const bool checkRecursively) const
  6768. {
  6769. for (int i = directories.size(); --i >= 0;)
  6770. {
  6771. const File d (directories[i]);
  6772. if (checkRecursively)
  6773. {
  6774. if (fileToCheck.isAChildOf (d))
  6775. return true;
  6776. }
  6777. else
  6778. {
  6779. if (fileToCheck.getParentDirectory() == d)
  6780. return true;
  6781. }
  6782. }
  6783. return false;
  6784. }
  6785. END_JUCE_NAMESPACE
  6786. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6787. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6788. BEGIN_JUCE_NAMESPACE
  6789. NamedPipe::NamedPipe()
  6790. : internal (0)
  6791. {
  6792. }
  6793. NamedPipe::~NamedPipe()
  6794. {
  6795. close();
  6796. }
  6797. bool NamedPipe::openExisting (const String& pipeName)
  6798. {
  6799. currentPipeName = pipeName;
  6800. return openInternal (pipeName, false);
  6801. }
  6802. bool NamedPipe::createNewPipe (const String& pipeName)
  6803. {
  6804. currentPipeName = pipeName;
  6805. return openInternal (pipeName, true);
  6806. }
  6807. bool NamedPipe::isOpen() const
  6808. {
  6809. return internal != 0;
  6810. }
  6811. const String NamedPipe::getName() const
  6812. {
  6813. return currentPipeName;
  6814. }
  6815. // other methods for this class are implemented in the platform-specific files
  6816. END_JUCE_NAMESPACE
  6817. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6818. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6819. BEGIN_JUCE_NAMESPACE
  6820. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6821. {
  6822. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6823. "temp_" + String (Random::getSystemRandom().nextInt()),
  6824. suffix,
  6825. optionFlags);
  6826. }
  6827. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6828. : targetFile (targetFile_)
  6829. {
  6830. // If you use this constructor, you need to give it a valid target file!
  6831. jassert (targetFile != File::nonexistent);
  6832. createTempFile (targetFile.getParentDirectory(),
  6833. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6834. targetFile.getFileExtension(),
  6835. optionFlags);
  6836. }
  6837. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6838. const String& suffix, const int optionFlags)
  6839. {
  6840. if ((optionFlags & useHiddenFile) != 0)
  6841. name = "." + name;
  6842. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6843. }
  6844. TemporaryFile::~TemporaryFile()
  6845. {
  6846. if (! deleteTemporaryFile())
  6847. {
  6848. /* Failed to delete our temporary file! The most likely reason for this would be
  6849. that you've not closed an output stream that was being used to write to file.
  6850. If you find that something beyond your control is changing permissions on
  6851. your temporary files and preventing them from being deleted, you may want to
  6852. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6853. handle them appropriately.
  6854. */
  6855. jassertfalse;
  6856. }
  6857. }
  6858. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6859. {
  6860. // This method only works if you created this object with the constructor
  6861. // that takes a target file!
  6862. jassert (targetFile != File::nonexistent);
  6863. if (temporaryFile.exists())
  6864. {
  6865. // Have a few attempts at overwriting the file before giving up..
  6866. for (int i = 5; --i >= 0;)
  6867. {
  6868. if (temporaryFile.moveFileTo (targetFile))
  6869. return true;
  6870. Thread::sleep (100);
  6871. }
  6872. }
  6873. else
  6874. {
  6875. // There's no temporary file to use. If your write failed, you should
  6876. // probably check, and not bother calling this method.
  6877. jassertfalse;
  6878. }
  6879. return false;
  6880. }
  6881. bool TemporaryFile::deleteTemporaryFile() const
  6882. {
  6883. // Have a few attempts at deleting the file before giving up..
  6884. for (int i = 5; --i >= 0;)
  6885. {
  6886. if (temporaryFile.deleteFile())
  6887. return true;
  6888. Thread::sleep (50);
  6889. }
  6890. return false;
  6891. }
  6892. END_JUCE_NAMESPACE
  6893. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6894. /*** Start of inlined file: juce_Socket.cpp ***/
  6895. #if JUCE_WINDOWS
  6896. #include <winsock2.h>
  6897. #if JUCE_MSVC
  6898. #pragma warning (push)
  6899. #pragma warning (disable : 4127 4389 4018)
  6900. #endif
  6901. #else
  6902. #if JUCE_LINUX
  6903. #include <sys/types.h>
  6904. #include <sys/socket.h>
  6905. #include <sys/errno.h>
  6906. #include <unistd.h>
  6907. #include <netinet/in.h>
  6908. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6909. #include <CoreServices/CoreServices.h>
  6910. #endif
  6911. #include <fcntl.h>
  6912. #include <netdb.h>
  6913. #include <arpa/inet.h>
  6914. #include <netinet/tcp.h>
  6915. #endif
  6916. BEGIN_JUCE_NAMESPACE
  6917. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6918. typedef socklen_t juce_socklen_t;
  6919. #else
  6920. typedef int juce_socklen_t;
  6921. #endif
  6922. #if JUCE_WINDOWS
  6923. namespace SocketHelpers
  6924. {
  6925. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6926. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6927. }
  6928. static void initWin32Sockets()
  6929. {
  6930. static CriticalSection lock;
  6931. const ScopedLock sl (lock);
  6932. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6933. {
  6934. WSADATA wsaData;
  6935. const WORD wVersionRequested = MAKEWORD (1, 1);
  6936. WSAStartup (wVersionRequested, &wsaData);
  6937. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6938. }
  6939. }
  6940. void juce_shutdownWin32Sockets()
  6941. {
  6942. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6943. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6944. }
  6945. #endif
  6946. namespace SocketHelpers
  6947. {
  6948. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6949. {
  6950. const int sndBufSize = 65536;
  6951. const int rcvBufSize = 65536;
  6952. const int one = 1;
  6953. return handle > 0
  6954. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6955. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6956. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6957. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6958. }
  6959. static bool bindSocketToPort (const int handle, const int port) throw()
  6960. {
  6961. if (handle <= 0 || port <= 0)
  6962. return false;
  6963. struct sockaddr_in servTmpAddr;
  6964. zerostruct (servTmpAddr);
  6965. servTmpAddr.sin_family = PF_INET;
  6966. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6967. servTmpAddr.sin_port = htons ((uint16) port);
  6968. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6969. }
  6970. static int readSocket (const int handle,
  6971. void* const destBuffer, const int maxBytesToRead,
  6972. bool volatile& connected,
  6973. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6974. {
  6975. int bytesRead = 0;
  6976. while (bytesRead < maxBytesToRead)
  6977. {
  6978. int bytesThisTime;
  6979. #if JUCE_WINDOWS
  6980. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6981. #else
  6982. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  6983. && errno == EINTR
  6984. && connected)
  6985. {
  6986. }
  6987. #endif
  6988. if (bytesThisTime <= 0 || ! connected)
  6989. {
  6990. if (bytesRead == 0)
  6991. bytesRead = -1;
  6992. break;
  6993. }
  6994. bytesRead += bytesThisTime;
  6995. if (! blockUntilSpecifiedAmountHasArrived)
  6996. break;
  6997. }
  6998. return bytesRead;
  6999. }
  7000. static int waitForReadiness (const int handle, const bool forReading,
  7001. const int timeoutMsecs) throw()
  7002. {
  7003. struct timeval timeout;
  7004. struct timeval* timeoutp;
  7005. if (timeoutMsecs >= 0)
  7006. {
  7007. timeout.tv_sec = timeoutMsecs / 1000;
  7008. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7009. timeoutp = &timeout;
  7010. }
  7011. else
  7012. {
  7013. timeoutp = 0;
  7014. }
  7015. fd_set rset, wset;
  7016. FD_ZERO (&rset);
  7017. FD_SET (handle, &rset);
  7018. FD_ZERO (&wset);
  7019. FD_SET (handle, &wset);
  7020. fd_set* const prset = forReading ? &rset : 0;
  7021. fd_set* const pwset = forReading ? 0 : &wset;
  7022. #if JUCE_WINDOWS
  7023. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7024. return -1;
  7025. #else
  7026. {
  7027. int result;
  7028. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7029. && errno == EINTR)
  7030. {
  7031. }
  7032. if (result < 0)
  7033. return -1;
  7034. }
  7035. #endif
  7036. {
  7037. int opt;
  7038. juce_socklen_t len = sizeof (opt);
  7039. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7040. || opt != 0)
  7041. return -1;
  7042. }
  7043. if ((forReading && FD_ISSET (handle, &rset))
  7044. || ((! forReading) && FD_ISSET (handle, &wset)))
  7045. return 1;
  7046. return 0;
  7047. }
  7048. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7049. {
  7050. #if JUCE_WINDOWS
  7051. u_long nonBlocking = shouldBlock ? 0 : 1;
  7052. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7053. return false;
  7054. #else
  7055. int socketFlags = fcntl (handle, F_GETFL, 0);
  7056. if (socketFlags == -1)
  7057. return false;
  7058. if (shouldBlock)
  7059. socketFlags &= ~O_NONBLOCK;
  7060. else
  7061. socketFlags |= O_NONBLOCK;
  7062. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7063. return false;
  7064. #endif
  7065. return true;
  7066. }
  7067. static bool connectSocket (int volatile& handle,
  7068. const bool isDatagram,
  7069. void** serverAddress,
  7070. const String& hostName,
  7071. const int portNumber,
  7072. const int timeOutMillisecs) throw()
  7073. {
  7074. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7075. if (hostEnt == 0)
  7076. return false;
  7077. struct in_addr targetAddress;
  7078. memcpy (&targetAddress.s_addr,
  7079. *(hostEnt->h_addr_list),
  7080. sizeof (targetAddress.s_addr));
  7081. struct sockaddr_in servTmpAddr;
  7082. zerostruct (servTmpAddr);
  7083. servTmpAddr.sin_family = PF_INET;
  7084. servTmpAddr.sin_addr = targetAddress;
  7085. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7086. if (handle < 0)
  7087. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7088. if (handle < 0)
  7089. return false;
  7090. if (isDatagram)
  7091. {
  7092. *serverAddress = new struct sockaddr_in();
  7093. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7094. return true;
  7095. }
  7096. setSocketBlockingState (handle, false);
  7097. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7098. if (result < 0)
  7099. {
  7100. #if JUCE_WINDOWS
  7101. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7102. #else
  7103. if (errno == EINPROGRESS)
  7104. #endif
  7105. {
  7106. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7107. {
  7108. setSocketBlockingState (handle, true);
  7109. return false;
  7110. }
  7111. }
  7112. }
  7113. setSocketBlockingState (handle, true);
  7114. resetSocketOptions (handle, false, false);
  7115. return true;
  7116. }
  7117. }
  7118. StreamingSocket::StreamingSocket()
  7119. : portNumber (0),
  7120. handle (-1),
  7121. connected (false),
  7122. isListener (false)
  7123. {
  7124. #if JUCE_WINDOWS
  7125. initWin32Sockets();
  7126. #endif
  7127. }
  7128. StreamingSocket::StreamingSocket (const String& hostName_,
  7129. const int portNumber_,
  7130. const int handle_)
  7131. : hostName (hostName_),
  7132. portNumber (portNumber_),
  7133. handle (handle_),
  7134. connected (true),
  7135. isListener (false)
  7136. {
  7137. #if JUCE_WINDOWS
  7138. initWin32Sockets();
  7139. #endif
  7140. SocketHelpers::resetSocketOptions (handle_, false, false);
  7141. }
  7142. StreamingSocket::~StreamingSocket()
  7143. {
  7144. close();
  7145. }
  7146. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7147. {
  7148. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7149. : -1;
  7150. }
  7151. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7152. {
  7153. if (isListener || ! connected)
  7154. return -1;
  7155. #if JUCE_WINDOWS
  7156. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7157. #else
  7158. int result;
  7159. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7160. && errno == EINTR)
  7161. {
  7162. }
  7163. return result;
  7164. #endif
  7165. }
  7166. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7167. const int timeoutMsecs) const
  7168. {
  7169. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7170. : -1;
  7171. }
  7172. bool StreamingSocket::bindToPort (const int port)
  7173. {
  7174. return SocketHelpers::bindSocketToPort (handle, port);
  7175. }
  7176. bool StreamingSocket::connect (const String& remoteHostName,
  7177. const int remotePortNumber,
  7178. const int timeOutMillisecs)
  7179. {
  7180. if (isListener)
  7181. {
  7182. jassertfalse; // a listener socket can't connect to another one!
  7183. return false;
  7184. }
  7185. if (connected)
  7186. close();
  7187. hostName = remoteHostName;
  7188. portNumber = remotePortNumber;
  7189. isListener = false;
  7190. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7191. remotePortNumber, timeOutMillisecs);
  7192. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7193. {
  7194. close();
  7195. return false;
  7196. }
  7197. return true;
  7198. }
  7199. void StreamingSocket::close()
  7200. {
  7201. #if JUCE_WINDOWS
  7202. if (handle != SOCKET_ERROR || connected)
  7203. closesocket (handle);
  7204. connected = false;
  7205. #else
  7206. if (connected)
  7207. {
  7208. connected = false;
  7209. if (isListener)
  7210. {
  7211. // need to do this to interrupt the accept() function..
  7212. StreamingSocket temp;
  7213. temp.connect ("localhost", portNumber, 1000);
  7214. }
  7215. }
  7216. if (handle != -1)
  7217. ::close (handle);
  7218. #endif
  7219. hostName = String::empty;
  7220. portNumber = 0;
  7221. handle = -1;
  7222. isListener = false;
  7223. }
  7224. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7225. {
  7226. if (connected)
  7227. close();
  7228. hostName = "listener";
  7229. portNumber = newPortNumber;
  7230. isListener = true;
  7231. struct sockaddr_in servTmpAddr;
  7232. zerostruct (servTmpAddr);
  7233. servTmpAddr.sin_family = PF_INET;
  7234. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7235. if (localHostName.isNotEmpty())
  7236. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7237. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7238. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7239. if (handle < 0)
  7240. return false;
  7241. const int reuse = 1;
  7242. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7243. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7244. || listen (handle, SOMAXCONN) < 0)
  7245. {
  7246. close();
  7247. return false;
  7248. }
  7249. connected = true;
  7250. return true;
  7251. }
  7252. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7253. {
  7254. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7255. // prepare this socket as a listener.
  7256. if (connected && isListener)
  7257. {
  7258. struct sockaddr address;
  7259. juce_socklen_t len = sizeof (sockaddr);
  7260. const int newSocket = (int) accept (handle, &address, &len);
  7261. if (newSocket >= 0 && connected)
  7262. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7263. portNumber, newSocket);
  7264. }
  7265. return 0;
  7266. }
  7267. bool StreamingSocket::isLocal() const throw()
  7268. {
  7269. return hostName == "127.0.0.1";
  7270. }
  7271. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7272. : portNumber (0),
  7273. handle (-1),
  7274. connected (true),
  7275. allowBroadcast (allowBroadcast_),
  7276. serverAddress (0)
  7277. {
  7278. #if JUCE_WINDOWS
  7279. initWin32Sockets();
  7280. #endif
  7281. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7282. bindToPort (localPortNumber);
  7283. }
  7284. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7285. const int handle_, const int localPortNumber)
  7286. : hostName (hostName_),
  7287. portNumber (portNumber_),
  7288. handle (handle_),
  7289. connected (true),
  7290. allowBroadcast (false),
  7291. serverAddress (0)
  7292. {
  7293. #if JUCE_WINDOWS
  7294. initWin32Sockets();
  7295. #endif
  7296. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7297. bindToPort (localPortNumber);
  7298. }
  7299. DatagramSocket::~DatagramSocket()
  7300. {
  7301. close();
  7302. delete static_cast <struct sockaddr_in*> (serverAddress);
  7303. serverAddress = 0;
  7304. }
  7305. void DatagramSocket::close()
  7306. {
  7307. #if JUCE_WINDOWS
  7308. closesocket (handle);
  7309. connected = false;
  7310. #else
  7311. connected = false;
  7312. ::close (handle);
  7313. #endif
  7314. hostName = String::empty;
  7315. portNumber = 0;
  7316. handle = -1;
  7317. }
  7318. bool DatagramSocket::bindToPort (const int port)
  7319. {
  7320. return SocketHelpers::bindSocketToPort (handle, port);
  7321. }
  7322. bool DatagramSocket::connect (const String& remoteHostName,
  7323. const int remotePortNumber,
  7324. const int timeOutMillisecs)
  7325. {
  7326. if (connected)
  7327. close();
  7328. hostName = remoteHostName;
  7329. portNumber = remotePortNumber;
  7330. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7331. remoteHostName, remotePortNumber,
  7332. timeOutMillisecs);
  7333. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7334. {
  7335. close();
  7336. return false;
  7337. }
  7338. return true;
  7339. }
  7340. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7341. {
  7342. struct sockaddr address;
  7343. juce_socklen_t len = sizeof (sockaddr);
  7344. while (waitUntilReady (true, -1) == 1)
  7345. {
  7346. char buf[1];
  7347. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7348. {
  7349. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7350. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7351. -1, -1);
  7352. }
  7353. }
  7354. return 0;
  7355. }
  7356. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7357. const int timeoutMsecs) const
  7358. {
  7359. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7360. : -1;
  7361. }
  7362. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7363. {
  7364. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7365. : -1;
  7366. }
  7367. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7368. {
  7369. // You need to call connect() first to set the server address..
  7370. jassert (serverAddress != 0 && connected);
  7371. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7372. numBytesToWrite, 0,
  7373. (const struct sockaddr*) serverAddress,
  7374. sizeof (struct sockaddr_in))
  7375. : -1;
  7376. }
  7377. bool DatagramSocket::isLocal() const throw()
  7378. {
  7379. return hostName == "127.0.0.1";
  7380. }
  7381. #if JUCE_MSVC
  7382. #pragma warning (pop)
  7383. #endif
  7384. END_JUCE_NAMESPACE
  7385. /*** End of inlined file: juce_Socket.cpp ***/
  7386. /*** Start of inlined file: juce_URL.cpp ***/
  7387. BEGIN_JUCE_NAMESPACE
  7388. URL::URL()
  7389. {
  7390. }
  7391. URL::URL (const String& url_)
  7392. : url (url_)
  7393. {
  7394. int i = url.indexOfChar ('?');
  7395. if (i >= 0)
  7396. {
  7397. do
  7398. {
  7399. const int nextAmp = url.indexOfChar (i + 1, '&');
  7400. const int equalsPos = url.indexOfChar (i + 1, '=');
  7401. if (equalsPos > i + 1)
  7402. {
  7403. if (nextAmp < 0)
  7404. {
  7405. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7406. removeEscapeChars (url.substring (equalsPos + 1)));
  7407. }
  7408. else if (nextAmp > 0 && equalsPos < nextAmp)
  7409. {
  7410. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7411. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7412. }
  7413. }
  7414. i = nextAmp;
  7415. }
  7416. while (i >= 0);
  7417. url = url.upToFirstOccurrenceOf ("?", false, false);
  7418. }
  7419. }
  7420. URL::URL (const URL& other)
  7421. : url (other.url),
  7422. postData (other.postData),
  7423. parameters (other.parameters),
  7424. filesToUpload (other.filesToUpload),
  7425. mimeTypes (other.mimeTypes)
  7426. {
  7427. }
  7428. URL& URL::operator= (const URL& other)
  7429. {
  7430. url = other.url;
  7431. postData = other.postData;
  7432. parameters = other.parameters;
  7433. filesToUpload = other.filesToUpload;
  7434. mimeTypes = other.mimeTypes;
  7435. return *this;
  7436. }
  7437. URL::~URL()
  7438. {
  7439. }
  7440. static const String getMangledParameters (const StringPairArray& parameters)
  7441. {
  7442. String p;
  7443. for (int i = 0; i < parameters.size(); ++i)
  7444. {
  7445. if (i > 0)
  7446. p << '&';
  7447. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7448. << '='
  7449. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7450. }
  7451. return p;
  7452. }
  7453. const String URL::toString (const bool includeGetParameters) const
  7454. {
  7455. if (includeGetParameters && parameters.size() > 0)
  7456. return url + "?" + getMangledParameters (parameters);
  7457. else
  7458. return url;
  7459. }
  7460. bool URL::isWellFormed() const
  7461. {
  7462. //xxx TODO
  7463. return url.isNotEmpty();
  7464. }
  7465. static int findStartOfDomain (const String& url)
  7466. {
  7467. int i = 0;
  7468. while (CharacterFunctions::isLetterOrDigit (url[i])
  7469. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7470. ++i;
  7471. return url[i] == ':' ? i + 1 : 0;
  7472. }
  7473. const String URL::getDomain() const
  7474. {
  7475. int start = findStartOfDomain (url);
  7476. while (url[start] == '/')
  7477. ++start;
  7478. const int end1 = url.indexOfChar (start, '/');
  7479. const int end2 = url.indexOfChar (start, ':');
  7480. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7481. : jmin (end1, end2);
  7482. return url.substring (start, end);
  7483. }
  7484. const String URL::getSubPath() const
  7485. {
  7486. int start = findStartOfDomain (url);
  7487. while (url[start] == '/')
  7488. ++start;
  7489. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7490. return startOfPath <= 0 ? String::empty
  7491. : url.substring (startOfPath);
  7492. }
  7493. const String URL::getScheme() const
  7494. {
  7495. return url.substring (0, findStartOfDomain (url) - 1);
  7496. }
  7497. const URL URL::withNewSubPath (const String& newPath) const
  7498. {
  7499. int start = findStartOfDomain (url);
  7500. while (url[start] == '/')
  7501. ++start;
  7502. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7503. URL u (*this);
  7504. if (startOfPath > 0)
  7505. u.url = url.substring (0, startOfPath);
  7506. if (! u.url.endsWithChar ('/'))
  7507. u.url << '/';
  7508. if (newPath.startsWithChar ('/'))
  7509. u.url << newPath.substring (1);
  7510. else
  7511. u.url << newPath;
  7512. return u;
  7513. }
  7514. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7515. {
  7516. if (possibleURL.startsWithIgnoreCase ("http:")
  7517. || possibleURL.startsWithIgnoreCase ("ftp:"))
  7518. return true;
  7519. if (possibleURL.startsWithIgnoreCase ("file:")
  7520. || possibleURL.containsChar ('@')
  7521. || possibleURL.endsWithChar ('.')
  7522. || (! possibleURL.containsChar ('.')))
  7523. return false;
  7524. if (possibleURL.startsWithIgnoreCase ("www.")
  7525. && possibleURL.substring (5).containsChar ('.'))
  7526. return true;
  7527. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  7528. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  7529. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  7530. return true;
  7531. return false;
  7532. }
  7533. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7534. {
  7535. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7536. return atSign > 0
  7537. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7538. && (! possibleEmailAddress.endsWithChar ('.'));
  7539. }
  7540. void* juce_openInternetFile (const String& url,
  7541. const String& headers,
  7542. const MemoryBlock& optionalPostData,
  7543. const bool isPost,
  7544. URL::OpenStreamProgressCallback* callback,
  7545. void* callbackContext,
  7546. int timeOutMs);
  7547. void juce_closeInternetFile (void* handle);
  7548. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  7549. int juce_seekInInternetFile (void* handle, int newPosition);
  7550. int64 juce_getInternetFileContentLength (void* handle);
  7551. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  7552. class WebInputStream : public InputStream
  7553. {
  7554. public:
  7555. WebInputStream (const URL& url,
  7556. const bool isPost_,
  7557. URL::OpenStreamProgressCallback* const progressCallback_,
  7558. void* const progressCallbackContext_,
  7559. const String& extraHeaders,
  7560. const int timeOutMs_,
  7561. StringPairArray* const responseHeaders)
  7562. : position (0),
  7563. finished (false),
  7564. isPost (isPost_),
  7565. progressCallback (progressCallback_),
  7566. progressCallbackContext (progressCallbackContext_),
  7567. timeOutMs (timeOutMs_)
  7568. {
  7569. server = url.toString (! isPost);
  7570. if (isPost_)
  7571. createHeadersAndPostData (url);
  7572. headers += extraHeaders;
  7573. if (! headers.endsWithChar ('\n'))
  7574. headers << "\r\n";
  7575. handle = juce_openInternetFile (server, headers, postData, isPost,
  7576. progressCallback_, progressCallbackContext_,
  7577. timeOutMs);
  7578. if (responseHeaders != 0)
  7579. juce_getInternetFileHeaders (handle, *responseHeaders);
  7580. }
  7581. ~WebInputStream()
  7582. {
  7583. juce_closeInternetFile (handle);
  7584. }
  7585. bool isError() const { return handle == 0; }
  7586. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  7587. bool isExhausted() { return finished; }
  7588. int64 getPosition() { return position; }
  7589. int read (void* dest, int bytes)
  7590. {
  7591. if (finished || isError())
  7592. {
  7593. return 0;
  7594. }
  7595. else
  7596. {
  7597. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  7598. position += bytesRead;
  7599. if (bytesRead == 0)
  7600. finished = true;
  7601. return bytesRead;
  7602. }
  7603. }
  7604. bool setPosition (int64 wantedPos)
  7605. {
  7606. if (wantedPos != position)
  7607. {
  7608. finished = false;
  7609. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  7610. if (actualPos == wantedPos)
  7611. {
  7612. position = wantedPos;
  7613. }
  7614. else
  7615. {
  7616. if (wantedPos < position)
  7617. {
  7618. juce_closeInternetFile (handle);
  7619. position = 0;
  7620. finished = false;
  7621. handle = juce_openInternetFile (server, headers, postData, isPost,
  7622. progressCallback, progressCallbackContext,
  7623. timeOutMs);
  7624. }
  7625. skipNextBytes (wantedPos - position);
  7626. }
  7627. }
  7628. return true;
  7629. }
  7630. juce_UseDebuggingNewOperator
  7631. private:
  7632. String server, headers;
  7633. MemoryBlock postData;
  7634. int64 position;
  7635. bool finished;
  7636. const bool isPost;
  7637. void* handle;
  7638. URL::OpenStreamProgressCallback* const progressCallback;
  7639. void* const progressCallbackContext;
  7640. const int timeOutMs;
  7641. void createHeadersAndPostData (const URL& url)
  7642. {
  7643. MemoryOutputStream data (postData, false);
  7644. if (url.getFilesToUpload().size() > 0)
  7645. {
  7646. // need to upload some files, so do it as multi-part...
  7647. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7648. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7649. data << "--" << boundary;
  7650. int i;
  7651. for (i = 0; i < url.getParameters().size(); ++i)
  7652. {
  7653. data << "\r\nContent-Disposition: form-data; name=\""
  7654. << url.getParameters().getAllKeys() [i]
  7655. << "\"\r\n\r\n"
  7656. << url.getParameters().getAllValues() [i]
  7657. << "\r\n--"
  7658. << boundary;
  7659. }
  7660. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7661. {
  7662. const File file (url.getFilesToUpload().getAllValues() [i]);
  7663. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7664. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7665. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7666. const String mimeType (url.getMimeTypesOfUploadFiles()
  7667. .getValue (paramName, String::empty));
  7668. if (mimeType.isNotEmpty())
  7669. data << "Content-Type: " << mimeType << "\r\n";
  7670. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7671. << file << "\r\n--" << boundary;
  7672. }
  7673. data << "--\r\n";
  7674. data.flush();
  7675. }
  7676. else
  7677. {
  7678. data << getMangledParameters (url.getParameters())
  7679. << url.getPostData();
  7680. data.flush();
  7681. // just a short text attachment, so use simple url encoding..
  7682. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7683. + String ((unsigned int) postData.getSize())
  7684. + "\r\n";
  7685. }
  7686. }
  7687. WebInputStream (const WebInputStream&);
  7688. WebInputStream& operator= (const WebInputStream&);
  7689. };
  7690. InputStream* URL::createInputStream (const bool usePostCommand,
  7691. OpenStreamProgressCallback* const progressCallback,
  7692. void* const progressCallbackContext,
  7693. const String& extraHeaders,
  7694. const int timeOutMs,
  7695. StringPairArray* const responseHeaders) const
  7696. {
  7697. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  7698. progressCallback, progressCallbackContext,
  7699. extraHeaders, timeOutMs, responseHeaders));
  7700. return wi->isError() ? 0 : wi.release();
  7701. }
  7702. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7703. const bool usePostCommand) const
  7704. {
  7705. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7706. if (in != 0)
  7707. {
  7708. in->readIntoMemoryBlock (destData);
  7709. return true;
  7710. }
  7711. return false;
  7712. }
  7713. const String URL::readEntireTextStream (const bool usePostCommand) const
  7714. {
  7715. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7716. if (in != 0)
  7717. return in->readEntireStreamAsString();
  7718. return String::empty;
  7719. }
  7720. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7721. {
  7722. XmlDocument doc (readEntireTextStream (usePostCommand));
  7723. return doc.getDocumentElement();
  7724. }
  7725. const URL URL::withParameter (const String& parameterName,
  7726. const String& parameterValue) const
  7727. {
  7728. URL u (*this);
  7729. u.parameters.set (parameterName, parameterValue);
  7730. return u;
  7731. }
  7732. const URL URL::withFileToUpload (const String& parameterName,
  7733. const File& fileToUpload,
  7734. const String& mimeType) const
  7735. {
  7736. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7737. URL u (*this);
  7738. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7739. u.mimeTypes.set (parameterName, mimeType);
  7740. return u;
  7741. }
  7742. const URL URL::withPOSTData (const String& postData_) const
  7743. {
  7744. URL u (*this);
  7745. u.postData = postData_;
  7746. return u;
  7747. }
  7748. const StringPairArray& URL::getParameters() const
  7749. {
  7750. return parameters;
  7751. }
  7752. const StringPairArray& URL::getFilesToUpload() const
  7753. {
  7754. return filesToUpload;
  7755. }
  7756. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7757. {
  7758. return mimeTypes;
  7759. }
  7760. const String URL::removeEscapeChars (const String& s)
  7761. {
  7762. String result (s.replaceCharacter ('+', ' '));
  7763. if (! result.containsChar ('%'))
  7764. return result;
  7765. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7766. // after all the replacements have been made, so that multi-byte chars are handled.
  7767. Array<char> utf8 (result.toUTF8(), result.getNumBytesAsUTF8());
  7768. for (int i = 0; i < utf8.size(); ++i)
  7769. {
  7770. if (utf8.getUnchecked(i) == '%')
  7771. {
  7772. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7773. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7774. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7775. {
  7776. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7777. utf8.removeRange (i + 1, 2);
  7778. }
  7779. }
  7780. }
  7781. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7782. }
  7783. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7784. {
  7785. const char* const legalChars = isParameter ? "_-.*!'()"
  7786. : ",$_-.*!'()";
  7787. Array<char> utf8 (s.toUTF8(), s.getNumBytesAsUTF8());
  7788. for (int i = 0; i < utf8.size(); ++i)
  7789. {
  7790. const char c = utf8.getUnchecked(i);
  7791. if (! (CharacterFunctions::isLetterOrDigit (c)
  7792. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0))
  7793. {
  7794. if (c == ' ')
  7795. {
  7796. utf8.set (i, '+');
  7797. }
  7798. else
  7799. {
  7800. static const char* const hexDigits = "0123456789abcdef";
  7801. utf8.set (i, '%');
  7802. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7803. utf8.insert (++i, hexDigits [c & 15]);
  7804. }
  7805. }
  7806. }
  7807. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7808. }
  7809. bool URL::launchInDefaultBrowser() const
  7810. {
  7811. String u (toString (true));
  7812. if (u.containsChar ('@') && ! u.containsChar (':'))
  7813. u = "mailto:" + u;
  7814. return PlatformUtilities::openDocument (u, String::empty);
  7815. }
  7816. END_JUCE_NAMESPACE
  7817. /*** End of inlined file: juce_URL.cpp ***/
  7818. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7819. BEGIN_JUCE_NAMESPACE
  7820. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  7821. const int bufferSize_,
  7822. const bool deleteSourceWhenDestroyed)
  7823. : source (source_),
  7824. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  7825. bufferSize (jmax (256, bufferSize_)),
  7826. position (source_->getPosition()),
  7827. lastReadPos (0),
  7828. bufferOverlap (128)
  7829. {
  7830. const int sourceSize = (int) source_->getTotalLength();
  7831. if (sourceSize >= 0)
  7832. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  7833. bufferStart = position;
  7834. buffer.malloc (bufferSize);
  7835. }
  7836. BufferedInputStream::~BufferedInputStream()
  7837. {
  7838. }
  7839. int64 BufferedInputStream::getTotalLength()
  7840. {
  7841. return source->getTotalLength();
  7842. }
  7843. int64 BufferedInputStream::getPosition()
  7844. {
  7845. return position;
  7846. }
  7847. bool BufferedInputStream::setPosition (int64 newPosition)
  7848. {
  7849. position = jmax ((int64) 0, newPosition);
  7850. return true;
  7851. }
  7852. bool BufferedInputStream::isExhausted()
  7853. {
  7854. return (position >= lastReadPos)
  7855. && source->isExhausted();
  7856. }
  7857. void BufferedInputStream::ensureBuffered()
  7858. {
  7859. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7860. if (position < bufferStart || position >= bufferEndOverlap)
  7861. {
  7862. int bytesRead;
  7863. if (position < lastReadPos
  7864. && position >= bufferEndOverlap
  7865. && position >= bufferStart)
  7866. {
  7867. const int bytesToKeep = (int) (lastReadPos - position);
  7868. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7869. bufferStart = position;
  7870. bytesRead = source->read (buffer + bytesToKeep,
  7871. bufferSize - bytesToKeep);
  7872. lastReadPos += bytesRead;
  7873. bytesRead += bytesToKeep;
  7874. }
  7875. else
  7876. {
  7877. bufferStart = position;
  7878. source->setPosition (bufferStart);
  7879. bytesRead = source->read (buffer, bufferSize);
  7880. lastReadPos = bufferStart + bytesRead;
  7881. }
  7882. while (bytesRead < bufferSize)
  7883. buffer [bytesRead++] = 0;
  7884. }
  7885. }
  7886. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7887. {
  7888. if (position >= bufferStart
  7889. && position + maxBytesToRead <= lastReadPos)
  7890. {
  7891. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7892. position += maxBytesToRead;
  7893. return maxBytesToRead;
  7894. }
  7895. else
  7896. {
  7897. if (position < bufferStart || position >= lastReadPos)
  7898. ensureBuffered();
  7899. int bytesRead = 0;
  7900. while (maxBytesToRead > 0)
  7901. {
  7902. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7903. if (bytesAvailable > 0)
  7904. {
  7905. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7906. maxBytesToRead -= bytesAvailable;
  7907. bytesRead += bytesAvailable;
  7908. position += bytesAvailable;
  7909. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7910. }
  7911. const int64 oldLastReadPos = lastReadPos;
  7912. ensureBuffered();
  7913. if (oldLastReadPos == lastReadPos)
  7914. break; // if ensureBuffered() failed to read any more data, bail out
  7915. if (isExhausted())
  7916. break;
  7917. }
  7918. return bytesRead;
  7919. }
  7920. }
  7921. const String BufferedInputStream::readString()
  7922. {
  7923. if (position >= bufferStart
  7924. && position < lastReadPos)
  7925. {
  7926. const int maxChars = (int) (lastReadPos - position);
  7927. const char* const src = buffer + (int) (position - bufferStart);
  7928. for (int i = 0; i < maxChars; ++i)
  7929. {
  7930. if (src[i] == 0)
  7931. {
  7932. position += i + 1;
  7933. return String::fromUTF8 (src, i);
  7934. }
  7935. }
  7936. }
  7937. return InputStream::readString();
  7938. }
  7939. END_JUCE_NAMESPACE
  7940. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7941. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7942. BEGIN_JUCE_NAMESPACE
  7943. FileInputSource::FileInputSource (const File& file_)
  7944. : file (file_)
  7945. {
  7946. }
  7947. FileInputSource::~FileInputSource()
  7948. {
  7949. }
  7950. InputStream* FileInputSource::createInputStream()
  7951. {
  7952. return file.createInputStream();
  7953. }
  7954. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7955. {
  7956. return file.getSiblingFile (relatedItemPath).createInputStream();
  7957. }
  7958. int64 FileInputSource::hashCode() const
  7959. {
  7960. return file.hashCode();
  7961. }
  7962. END_JUCE_NAMESPACE
  7963. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7964. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7965. BEGIN_JUCE_NAMESPACE
  7966. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7967. const size_t sourceDataSize,
  7968. const bool keepInternalCopy)
  7969. : data (static_cast <const char*> (sourceData)),
  7970. dataSize (sourceDataSize),
  7971. position (0)
  7972. {
  7973. if (keepInternalCopy)
  7974. {
  7975. internalCopy.append (data, sourceDataSize);
  7976. data = static_cast <const char*> (internalCopy.getData());
  7977. }
  7978. }
  7979. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7980. const bool keepInternalCopy)
  7981. : data (static_cast <const char*> (sourceData.getData())),
  7982. dataSize (sourceData.getSize()),
  7983. position (0)
  7984. {
  7985. if (keepInternalCopy)
  7986. {
  7987. internalCopy = sourceData;
  7988. data = static_cast <const char*> (internalCopy.getData());
  7989. }
  7990. }
  7991. MemoryInputStream::~MemoryInputStream()
  7992. {
  7993. }
  7994. int64 MemoryInputStream::getTotalLength()
  7995. {
  7996. return dataSize;
  7997. }
  7998. int MemoryInputStream::read (void* const buffer, const int howMany)
  7999. {
  8000. jassert (howMany >= 0);
  8001. const int num = jmin (howMany, (int) (dataSize - position));
  8002. memcpy (buffer, data + position, num);
  8003. position += num;
  8004. return (int) num;
  8005. }
  8006. bool MemoryInputStream::isExhausted()
  8007. {
  8008. return (position >= dataSize);
  8009. }
  8010. bool MemoryInputStream::setPosition (const int64 pos)
  8011. {
  8012. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  8013. return true;
  8014. }
  8015. int64 MemoryInputStream::getPosition()
  8016. {
  8017. return position;
  8018. }
  8019. #if JUCE_UNIT_TESTS
  8020. class MemoryStreamTests : public UnitTest
  8021. {
  8022. public:
  8023. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  8024. void runTest()
  8025. {
  8026. beginTest ("Basics");
  8027. int randomInt = Random::getSystemRandom().nextInt();
  8028. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8029. double randomDouble = Random::getSystemRandom().nextDouble();
  8030. String randomString;
  8031. for (int i = 50; --i >= 0;)
  8032. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  8033. MemoryOutputStream mo;
  8034. mo.writeInt (randomInt);
  8035. mo.writeIntBigEndian (randomInt);
  8036. mo.writeCompressedInt (randomInt);
  8037. mo.writeString (randomString);
  8038. mo.writeInt64 (randomInt64);
  8039. mo.writeInt64BigEndian (randomInt64);
  8040. mo.writeDouble (randomDouble);
  8041. mo.writeDoubleBigEndian (randomDouble);
  8042. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8043. expect (mi.readInt() == randomInt);
  8044. expect (mi.readIntBigEndian() == randomInt);
  8045. expect (mi.readCompressedInt() == randomInt);
  8046. expect (mi.readString() == randomString);
  8047. expect (mi.readInt64() == randomInt64);
  8048. expect (mi.readInt64BigEndian() == randomInt64);
  8049. expect (mi.readDouble() == randomDouble);
  8050. expect (mi.readDoubleBigEndian() == randomDouble);
  8051. }
  8052. };
  8053. static MemoryStreamTests memoryInputStreamUnitTests;
  8054. #endif
  8055. END_JUCE_NAMESPACE
  8056. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8057. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8058. BEGIN_JUCE_NAMESPACE
  8059. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8060. : data (internalBlock),
  8061. position (0),
  8062. size (0)
  8063. {
  8064. internalBlock.setSize (initialSize, false);
  8065. }
  8066. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8067. const bool appendToExistingBlockContent)
  8068. : data (memoryBlockToWriteTo),
  8069. position (0),
  8070. size (0)
  8071. {
  8072. if (appendToExistingBlockContent)
  8073. position = size = memoryBlockToWriteTo.getSize();
  8074. }
  8075. MemoryOutputStream::~MemoryOutputStream()
  8076. {
  8077. flush();
  8078. }
  8079. void MemoryOutputStream::flush()
  8080. {
  8081. if (&data != &internalBlock)
  8082. data.setSize (size, false);
  8083. }
  8084. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8085. {
  8086. data.ensureSize (bytesToPreallocate + 1);
  8087. }
  8088. void MemoryOutputStream::reset() throw()
  8089. {
  8090. position = 0;
  8091. size = 0;
  8092. }
  8093. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8094. {
  8095. if (howMany > 0)
  8096. {
  8097. const size_t storageNeeded = position + howMany;
  8098. if (storageNeeded >= data.getSize())
  8099. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  8100. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8101. position += howMany;
  8102. size = jmax (size, position);
  8103. }
  8104. return true;
  8105. }
  8106. const void* MemoryOutputStream::getData() const throw()
  8107. {
  8108. void* const d = data.getData();
  8109. if (data.getSize() > size)
  8110. static_cast <char*> (d) [size] = 0;
  8111. return d;
  8112. }
  8113. bool MemoryOutputStream::setPosition (int64 newPosition)
  8114. {
  8115. if (newPosition <= (int64) size)
  8116. {
  8117. // ok to seek backwards
  8118. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8119. return true;
  8120. }
  8121. else
  8122. {
  8123. // trying to make it bigger isn't a good thing to do..
  8124. return false;
  8125. }
  8126. }
  8127. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8128. {
  8129. // before writing from an input, see if we can preallocate to make it more efficient..
  8130. int64 availableData = source.getTotalLength() - source.getPosition();
  8131. if (availableData > 0)
  8132. {
  8133. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8134. availableData = maxNumBytesToWrite;
  8135. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8136. }
  8137. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8138. }
  8139. const String MemoryOutputStream::toUTF8() const
  8140. {
  8141. return String (static_cast <const char*> (getData()), getDataSize());
  8142. }
  8143. const String MemoryOutputStream::toString() const
  8144. {
  8145. return String::createStringFromData (getData(), getDataSize());
  8146. }
  8147. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8148. {
  8149. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  8150. return stream;
  8151. }
  8152. END_JUCE_NAMESPACE
  8153. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8154. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8155. BEGIN_JUCE_NAMESPACE
  8156. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8157. const int64 startPositionInSourceStream_,
  8158. const int64 lengthOfSourceStream_,
  8159. const bool deleteSourceWhenDestroyed)
  8160. : source (sourceStream),
  8161. startPositionInSourceStream (startPositionInSourceStream_),
  8162. lengthOfSourceStream (lengthOfSourceStream_)
  8163. {
  8164. if (deleteSourceWhenDestroyed)
  8165. sourceToDelete = source;
  8166. setPosition (0);
  8167. }
  8168. SubregionStream::~SubregionStream()
  8169. {
  8170. }
  8171. int64 SubregionStream::getTotalLength()
  8172. {
  8173. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8174. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8175. : srcLen;
  8176. }
  8177. int64 SubregionStream::getPosition()
  8178. {
  8179. return source->getPosition() - startPositionInSourceStream;
  8180. }
  8181. bool SubregionStream::setPosition (int64 newPosition)
  8182. {
  8183. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8184. }
  8185. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8186. {
  8187. if (lengthOfSourceStream < 0)
  8188. {
  8189. return source->read (destBuffer, maxBytesToRead);
  8190. }
  8191. else
  8192. {
  8193. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8194. if (maxBytesToRead <= 0)
  8195. return 0;
  8196. return source->read (destBuffer, maxBytesToRead);
  8197. }
  8198. }
  8199. bool SubregionStream::isExhausted()
  8200. {
  8201. if (lengthOfSourceStream >= 0)
  8202. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8203. else
  8204. return source->isExhausted();
  8205. }
  8206. END_JUCE_NAMESPACE
  8207. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8208. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8209. BEGIN_JUCE_NAMESPACE
  8210. PerformanceCounter::PerformanceCounter (const String& name_,
  8211. int runsPerPrintout,
  8212. const File& loggingFile)
  8213. : name (name_),
  8214. numRuns (0),
  8215. runsPerPrint (runsPerPrintout),
  8216. totalTime (0),
  8217. outputFile (loggingFile)
  8218. {
  8219. if (outputFile != File::nonexistent)
  8220. {
  8221. String s ("**** Counter for \"");
  8222. s << name_ << "\" started at: "
  8223. << Time::getCurrentTime().toString (true, true)
  8224. << "\r\n";
  8225. outputFile.appendText (s, false, false);
  8226. }
  8227. }
  8228. PerformanceCounter::~PerformanceCounter()
  8229. {
  8230. printStatistics();
  8231. }
  8232. void PerformanceCounter::start()
  8233. {
  8234. started = Time::getHighResolutionTicks();
  8235. }
  8236. void PerformanceCounter::stop()
  8237. {
  8238. const int64 now = Time::getHighResolutionTicks();
  8239. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8240. if (++numRuns == runsPerPrint)
  8241. printStatistics();
  8242. }
  8243. void PerformanceCounter::printStatistics()
  8244. {
  8245. if (numRuns > 0)
  8246. {
  8247. String s ("Performance count for \"");
  8248. s << name << "\" - average over " << numRuns << " run(s) = ";
  8249. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8250. if (micros > 10000)
  8251. s << (micros/1000) << " millisecs";
  8252. else
  8253. s << micros << " microsecs";
  8254. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8255. Logger::outputDebugString (s);
  8256. s << "\r\n";
  8257. if (outputFile != File::nonexistent)
  8258. outputFile.appendText (s, false, false);
  8259. numRuns = 0;
  8260. totalTime = 0;
  8261. }
  8262. }
  8263. END_JUCE_NAMESPACE
  8264. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8265. /*** Start of inlined file: juce_Uuid.cpp ***/
  8266. BEGIN_JUCE_NAMESPACE
  8267. Uuid::Uuid()
  8268. {
  8269. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8270. // to make it very very unlikely that two UUIDs will ever be the same..
  8271. static int64 macAddresses[2];
  8272. static bool hasCheckedMacAddresses = false;
  8273. if (! hasCheckedMacAddresses)
  8274. {
  8275. hasCheckedMacAddresses = true;
  8276. SystemStats::getMACAddresses (macAddresses, 2);
  8277. }
  8278. value.asInt64[0] = macAddresses[0];
  8279. value.asInt64[1] = macAddresses[1];
  8280. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8281. // whose seed will carry over between calls to this method.
  8282. Random r (macAddresses[0] ^ macAddresses[1]
  8283. ^ Random::getSystemRandom().nextInt64());
  8284. for (int i = 4; --i >= 0;)
  8285. {
  8286. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8287. value.asInt[i] ^= r.nextInt();
  8288. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8289. }
  8290. }
  8291. Uuid::~Uuid() throw()
  8292. {
  8293. }
  8294. Uuid::Uuid (const Uuid& other)
  8295. : value (other.value)
  8296. {
  8297. }
  8298. Uuid& Uuid::operator= (const Uuid& other)
  8299. {
  8300. value = other.value;
  8301. return *this;
  8302. }
  8303. bool Uuid::operator== (const Uuid& other) const
  8304. {
  8305. return value.asInt64[0] == other.value.asInt64[0]
  8306. && value.asInt64[1] == other.value.asInt64[1];
  8307. }
  8308. bool Uuid::operator!= (const Uuid& other) const
  8309. {
  8310. return ! operator== (other);
  8311. }
  8312. bool Uuid::isNull() const throw()
  8313. {
  8314. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8315. }
  8316. const String Uuid::toString() const
  8317. {
  8318. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8319. }
  8320. Uuid::Uuid (const String& uuidString)
  8321. {
  8322. operator= (uuidString);
  8323. }
  8324. Uuid& Uuid::operator= (const String& uuidString)
  8325. {
  8326. MemoryBlock mb;
  8327. mb.loadFromHexString (uuidString);
  8328. mb.ensureSize (sizeof (value.asBytes), true);
  8329. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8330. return *this;
  8331. }
  8332. Uuid::Uuid (const uint8* const rawData)
  8333. {
  8334. operator= (rawData);
  8335. }
  8336. Uuid& Uuid::operator= (const uint8* const rawData)
  8337. {
  8338. if (rawData != 0)
  8339. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8340. else
  8341. zeromem (value.asBytes, sizeof (value.asBytes));
  8342. return *this;
  8343. }
  8344. END_JUCE_NAMESPACE
  8345. /*** End of inlined file: juce_Uuid.cpp ***/
  8346. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8347. BEGIN_JUCE_NAMESPACE
  8348. class ZipFile::ZipEntryInfo
  8349. {
  8350. public:
  8351. ZipFile::ZipEntry entry;
  8352. int streamOffset;
  8353. int compressedSize;
  8354. bool compressed;
  8355. };
  8356. class ZipFile::ZipInputStream : public InputStream
  8357. {
  8358. public:
  8359. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8360. : file (file_),
  8361. zipEntryInfo (zei),
  8362. pos (0),
  8363. headerSize (0),
  8364. inputStream (0)
  8365. {
  8366. inputStream = file_.inputStream;
  8367. if (file_.inputSource != 0)
  8368. {
  8369. inputStream = file.inputSource->createInputStream();
  8370. }
  8371. else
  8372. {
  8373. #if JUCE_DEBUG
  8374. file_.numOpenStreams++;
  8375. #endif
  8376. }
  8377. char buffer [30];
  8378. if (inputStream != 0
  8379. && inputStream->setPosition (zei.streamOffset)
  8380. && inputStream->read (buffer, 30) == 30
  8381. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8382. {
  8383. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8384. + ByteOrder::littleEndianShort (buffer + 28);
  8385. }
  8386. }
  8387. ~ZipInputStream()
  8388. {
  8389. #if JUCE_DEBUG
  8390. if (inputStream != 0 && inputStream == file.inputStream)
  8391. file.numOpenStreams--;
  8392. #endif
  8393. if (inputStream != file.inputStream)
  8394. delete inputStream;
  8395. }
  8396. int64 getTotalLength()
  8397. {
  8398. return zipEntryInfo.compressedSize;
  8399. }
  8400. int read (void* buffer, int howMany)
  8401. {
  8402. if (headerSize <= 0)
  8403. return 0;
  8404. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8405. if (inputStream == 0)
  8406. return 0;
  8407. int num;
  8408. if (inputStream == file.inputStream)
  8409. {
  8410. const ScopedLock sl (file.lock);
  8411. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8412. num = inputStream->read (buffer, howMany);
  8413. }
  8414. else
  8415. {
  8416. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8417. num = inputStream->read (buffer, howMany);
  8418. }
  8419. pos += num;
  8420. return num;
  8421. }
  8422. bool isExhausted()
  8423. {
  8424. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8425. }
  8426. int64 getPosition()
  8427. {
  8428. return pos;
  8429. }
  8430. bool setPosition (int64 newPos)
  8431. {
  8432. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8433. return true;
  8434. }
  8435. private:
  8436. ZipFile& file;
  8437. ZipEntryInfo zipEntryInfo;
  8438. int64 pos;
  8439. int headerSize;
  8440. InputStream* inputStream;
  8441. ZipInputStream (const ZipInputStream&);
  8442. ZipInputStream& operator= (const ZipInputStream&);
  8443. };
  8444. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8445. : inputStream (source_)
  8446. #if JUCE_DEBUG
  8447. , numOpenStreams (0)
  8448. #endif
  8449. {
  8450. if (deleteStreamWhenDestroyed)
  8451. streamToDelete = inputStream;
  8452. init();
  8453. }
  8454. ZipFile::ZipFile (const File& file)
  8455. : inputStream (0)
  8456. #if JUCE_DEBUG
  8457. , numOpenStreams (0)
  8458. #endif
  8459. {
  8460. inputSource = new FileInputSource (file);
  8461. init();
  8462. }
  8463. ZipFile::ZipFile (InputSource* const inputSource_)
  8464. : inputStream (0),
  8465. inputSource (inputSource_)
  8466. #if JUCE_DEBUG
  8467. , numOpenStreams (0)
  8468. #endif
  8469. {
  8470. init();
  8471. }
  8472. ZipFile::~ZipFile()
  8473. {
  8474. #if JUCE_DEBUG
  8475. entries.clear();
  8476. // If you hit this assertion, it means you've created a stream to read
  8477. // one of the items in the zipfile, but you've forgotten to delete that
  8478. // stream object before deleting the file.. Streams can't be kept open
  8479. // after the file is deleted because they need to share the input
  8480. // stream that the file uses to read itself.
  8481. jassert (numOpenStreams == 0);
  8482. #endif
  8483. }
  8484. int ZipFile::getNumEntries() const throw()
  8485. {
  8486. return entries.size();
  8487. }
  8488. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8489. {
  8490. ZipEntryInfo* const zei = entries [index];
  8491. return zei != 0 ? &(zei->entry) : 0;
  8492. }
  8493. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8494. {
  8495. for (int i = 0; i < entries.size(); ++i)
  8496. if (entries.getUnchecked (i)->entry.filename == fileName)
  8497. return i;
  8498. return -1;
  8499. }
  8500. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8501. {
  8502. return getEntry (getIndexOfFileName (fileName));
  8503. }
  8504. InputStream* ZipFile::createStreamForEntry (const int index)
  8505. {
  8506. ZipEntryInfo* const zei = entries[index];
  8507. InputStream* stream = 0;
  8508. if (zei != 0)
  8509. {
  8510. stream = new ZipInputStream (*this, *zei);
  8511. if (zei->compressed)
  8512. {
  8513. stream = new GZIPDecompressorInputStream (stream, true, true,
  8514. zei->entry.uncompressedSize);
  8515. // (much faster to unzip in big blocks using a buffer..)
  8516. stream = new BufferedInputStream (stream, 32768, true);
  8517. }
  8518. }
  8519. return stream;
  8520. }
  8521. class ZipFile::ZipFilenameComparator
  8522. {
  8523. public:
  8524. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8525. {
  8526. return first->entry.filename.compare (second->entry.filename);
  8527. }
  8528. };
  8529. void ZipFile::sortEntriesByFilename()
  8530. {
  8531. ZipFilenameComparator sorter;
  8532. entries.sort (sorter);
  8533. }
  8534. void ZipFile::init()
  8535. {
  8536. ScopedPointer <InputStream> toDelete;
  8537. InputStream* in = inputStream;
  8538. if (inputSource != 0)
  8539. {
  8540. in = inputSource->createInputStream();
  8541. toDelete = in;
  8542. }
  8543. if (in != 0)
  8544. {
  8545. int numEntries = 0;
  8546. int pos = findEndOfZipEntryTable (in, numEntries);
  8547. if (pos >= 0 && pos < in->getTotalLength())
  8548. {
  8549. const int size = (int) (in->getTotalLength() - pos);
  8550. in->setPosition (pos);
  8551. MemoryBlock headerData;
  8552. if (in->readIntoMemoryBlock (headerData, size) == size)
  8553. {
  8554. pos = 0;
  8555. for (int i = 0; i < numEntries; ++i)
  8556. {
  8557. if (pos + 46 > size)
  8558. break;
  8559. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8560. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8561. if (pos + 46 + fileNameLen > size)
  8562. break;
  8563. ZipEntryInfo* const zei = new ZipEntryInfo();
  8564. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8565. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8566. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8567. const int year = 1980 + (date >> 9);
  8568. const int month = ((date >> 5) & 15) - 1;
  8569. const int day = date & 31;
  8570. const int hours = time >> 11;
  8571. const int minutes = (time >> 5) & 63;
  8572. const int seconds = (time & 31) << 1;
  8573. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8574. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8575. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8576. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8577. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8578. entries.add (zei);
  8579. pos += 46 + fileNameLen
  8580. + ByteOrder::littleEndianShort (buffer + 30)
  8581. + ByteOrder::littleEndianShort (buffer + 32);
  8582. }
  8583. }
  8584. }
  8585. }
  8586. }
  8587. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  8588. {
  8589. BufferedInputStream in (input, 8192, false);
  8590. in.setPosition (in.getTotalLength());
  8591. int64 pos = in.getPosition();
  8592. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8593. char buffer [32];
  8594. zeromem (buffer, sizeof (buffer));
  8595. while (pos > lowestPos)
  8596. {
  8597. in.setPosition (pos - 22);
  8598. pos = in.getPosition();
  8599. memcpy (buffer + 22, buffer, 4);
  8600. if (in.read (buffer, 22) != 22)
  8601. return 0;
  8602. for (int i = 0; i < 22; ++i)
  8603. {
  8604. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8605. {
  8606. in.setPosition (pos + i);
  8607. in.read (buffer, 22);
  8608. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8609. return ByteOrder::littleEndianInt (buffer + 16);
  8610. }
  8611. }
  8612. }
  8613. return 0;
  8614. }
  8615. bool ZipFile::uncompressTo (const File& targetDirectory,
  8616. const bool shouldOverwriteFiles)
  8617. {
  8618. for (int i = 0; i < entries.size(); ++i)
  8619. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8620. return false;
  8621. return true;
  8622. }
  8623. bool ZipFile::uncompressEntry (const int index,
  8624. const File& targetDirectory,
  8625. bool shouldOverwriteFiles)
  8626. {
  8627. const ZipEntryInfo* zei = entries [index];
  8628. if (zei != 0)
  8629. {
  8630. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8631. if (zei->entry.filename.endsWithChar ('/'))
  8632. {
  8633. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8634. }
  8635. else
  8636. {
  8637. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8638. if (in != 0)
  8639. {
  8640. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8641. return false;
  8642. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8643. {
  8644. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8645. if (out != 0)
  8646. {
  8647. out->writeFromInputStream (*in, -1);
  8648. out = 0;
  8649. targetFile.setCreationTime (zei->entry.fileTime);
  8650. targetFile.setLastModificationTime (zei->entry.fileTime);
  8651. targetFile.setLastAccessTime (zei->entry.fileTime);
  8652. return true;
  8653. }
  8654. }
  8655. }
  8656. }
  8657. }
  8658. return false;
  8659. }
  8660. END_JUCE_NAMESPACE
  8661. /*** End of inlined file: juce_ZipFile.cpp ***/
  8662. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8663. #if JUCE_MSVC
  8664. #pragma warning (push)
  8665. #pragma warning (disable: 4514 4996)
  8666. #endif
  8667. #include <cwctype>
  8668. #include <cctype>
  8669. #include <ctime>
  8670. BEGIN_JUCE_NAMESPACE
  8671. int CharacterFunctions::length (const char* const s) throw()
  8672. {
  8673. return (int) strlen (s);
  8674. }
  8675. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8676. {
  8677. return (int) wcslen (s);
  8678. }
  8679. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8680. {
  8681. strncpy (dest, src, maxChars);
  8682. }
  8683. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8684. {
  8685. wcsncpy (dest, src, maxChars);
  8686. }
  8687. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8688. {
  8689. mbstowcs (dest, src, maxChars);
  8690. }
  8691. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8692. {
  8693. wcstombs (dest, src, maxChars);
  8694. }
  8695. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8696. {
  8697. return (int) wcstombs (0, src, 0);
  8698. }
  8699. void CharacterFunctions::append (char* dest, const char* src) throw()
  8700. {
  8701. strcat (dest, src);
  8702. }
  8703. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8704. {
  8705. wcscat (dest, src);
  8706. }
  8707. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8708. {
  8709. return strcmp (s1, s2);
  8710. }
  8711. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8712. {
  8713. jassert (s1 != 0 && s2 != 0);
  8714. return wcscmp (s1, s2);
  8715. }
  8716. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8717. {
  8718. jassert (s1 != 0 && s2 != 0);
  8719. return strncmp (s1, s2, maxChars);
  8720. }
  8721. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8722. {
  8723. jassert (s1 != 0 && s2 != 0);
  8724. return wcsncmp (s1, s2, maxChars);
  8725. }
  8726. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8727. {
  8728. jassert (s1 != 0 && s2 != 0);
  8729. for (;;)
  8730. {
  8731. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8732. if (diff != 0)
  8733. return diff;
  8734. else if (*s1 == 0)
  8735. break;
  8736. ++s1;
  8737. ++s2;
  8738. }
  8739. return 0;
  8740. }
  8741. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8742. {
  8743. return -compare (s2, s1);
  8744. }
  8745. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8746. {
  8747. jassert (s1 != 0 && s2 != 0);
  8748. #if JUCE_WINDOWS
  8749. return stricmp (s1, s2);
  8750. #else
  8751. return strcasecmp (s1, s2);
  8752. #endif
  8753. }
  8754. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8755. {
  8756. jassert (s1 != 0 && s2 != 0);
  8757. #if JUCE_WINDOWS
  8758. return _wcsicmp (s1, s2);
  8759. #else
  8760. for (;;)
  8761. {
  8762. if (*s1 != *s2)
  8763. {
  8764. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8765. if (diff != 0)
  8766. return diff < 0 ? -1 : 1;
  8767. }
  8768. else if (*s1 == 0)
  8769. break;
  8770. ++s1;
  8771. ++s2;
  8772. }
  8773. return 0;
  8774. #endif
  8775. }
  8776. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8777. {
  8778. jassert (s1 != 0 && s2 != 0);
  8779. for (;;)
  8780. {
  8781. if (*s1 != *s2)
  8782. {
  8783. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8784. if (diff != 0)
  8785. return diff < 0 ? -1 : 1;
  8786. }
  8787. else if (*s1 == 0)
  8788. break;
  8789. ++s1;
  8790. ++s2;
  8791. }
  8792. return 0;
  8793. }
  8794. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8795. {
  8796. jassert (s1 != 0 && s2 != 0);
  8797. #if JUCE_WINDOWS
  8798. return strnicmp (s1, s2, maxChars);
  8799. #else
  8800. return strncasecmp (s1, s2, maxChars);
  8801. #endif
  8802. }
  8803. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8804. {
  8805. jassert (s1 != 0 && s2 != 0);
  8806. #if JUCE_WINDOWS
  8807. return _wcsnicmp (s1, s2, maxChars);
  8808. #else
  8809. while (--maxChars >= 0)
  8810. {
  8811. if (*s1 != *s2)
  8812. {
  8813. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8814. if (diff != 0)
  8815. return diff < 0 ? -1 : 1;
  8816. }
  8817. else if (*s1 == 0)
  8818. break;
  8819. ++s1;
  8820. ++s2;
  8821. }
  8822. return 0;
  8823. #endif
  8824. }
  8825. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8826. {
  8827. return strstr (haystack, needle);
  8828. }
  8829. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8830. {
  8831. return wcsstr (haystack, needle);
  8832. }
  8833. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8834. {
  8835. if (haystack != 0)
  8836. {
  8837. int i = 0;
  8838. if (ignoreCase)
  8839. {
  8840. const char n1 = toLowerCase (needle);
  8841. const char n2 = toUpperCase (needle);
  8842. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8843. {
  8844. while (haystack[i] != 0)
  8845. {
  8846. if (haystack[i] == n1 || haystack[i] == n2)
  8847. return i;
  8848. ++i;
  8849. }
  8850. return -1;
  8851. }
  8852. jassert (n1 == needle);
  8853. }
  8854. while (haystack[i] != 0)
  8855. {
  8856. if (haystack[i] == needle)
  8857. return i;
  8858. ++i;
  8859. }
  8860. }
  8861. return -1;
  8862. }
  8863. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8864. {
  8865. if (haystack != 0)
  8866. {
  8867. int i = 0;
  8868. if (ignoreCase)
  8869. {
  8870. const juce_wchar n1 = toLowerCase (needle);
  8871. const juce_wchar n2 = toUpperCase (needle);
  8872. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8873. {
  8874. while (haystack[i] != 0)
  8875. {
  8876. if (haystack[i] == n1 || haystack[i] == n2)
  8877. return i;
  8878. ++i;
  8879. }
  8880. return -1;
  8881. }
  8882. jassert (n1 == needle);
  8883. }
  8884. while (haystack[i] != 0)
  8885. {
  8886. if (haystack[i] == needle)
  8887. return i;
  8888. ++i;
  8889. }
  8890. }
  8891. return -1;
  8892. }
  8893. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8894. {
  8895. jassert (haystack != 0);
  8896. int i = 0;
  8897. while (haystack[i] != 0)
  8898. {
  8899. if (haystack[i] == needle)
  8900. return i;
  8901. ++i;
  8902. }
  8903. return -1;
  8904. }
  8905. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8906. {
  8907. jassert (haystack != 0);
  8908. int i = 0;
  8909. while (haystack[i] != 0)
  8910. {
  8911. if (haystack[i] == needle)
  8912. return i;
  8913. ++i;
  8914. }
  8915. return -1;
  8916. }
  8917. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8918. {
  8919. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8920. }
  8921. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8922. {
  8923. if (allowedChars == 0)
  8924. return 0;
  8925. int i = 0;
  8926. for (;;)
  8927. {
  8928. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8929. break;
  8930. ++i;
  8931. }
  8932. return i;
  8933. }
  8934. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8935. {
  8936. return (int) strftime (dest, maxChars, format, tm);
  8937. }
  8938. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8939. {
  8940. return (int) wcsftime (dest, maxChars, format, tm);
  8941. }
  8942. int CharacterFunctions::getIntValue (const char* const s) throw()
  8943. {
  8944. return atoi (s);
  8945. }
  8946. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  8947. {
  8948. #if JUCE_WINDOWS
  8949. return _wtoi (s);
  8950. #else
  8951. int v = 0;
  8952. while (isWhitespace (*s))
  8953. ++s;
  8954. const bool isNeg = *s == '-';
  8955. if (isNeg)
  8956. ++s;
  8957. for (;;)
  8958. {
  8959. const wchar_t c = *s++;
  8960. if (c >= '0' && c <= '9')
  8961. v = v * 10 + (int) (c - '0');
  8962. else
  8963. break;
  8964. }
  8965. return isNeg ? -v : v;
  8966. #endif
  8967. }
  8968. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8969. {
  8970. #if JUCE_LINUX
  8971. return atoll (s);
  8972. #elif JUCE_WINDOWS
  8973. return _atoi64 (s);
  8974. #else
  8975. int64 v = 0;
  8976. while (isWhitespace (*s))
  8977. ++s;
  8978. const bool isNeg = *s == '-';
  8979. if (isNeg)
  8980. ++s;
  8981. for (;;)
  8982. {
  8983. const char c = *s++;
  8984. if (c >= '0' && c <= '9')
  8985. v = v * 10 + (int64) (c - '0');
  8986. else
  8987. break;
  8988. }
  8989. return isNeg ? -v : v;
  8990. #endif
  8991. }
  8992. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8993. {
  8994. #if JUCE_WINDOWS
  8995. return _wtoi64 (s);
  8996. #else
  8997. int64 v = 0;
  8998. while (isWhitespace (*s))
  8999. ++s;
  9000. const bool isNeg = *s == '-';
  9001. if (isNeg)
  9002. ++s;
  9003. for (;;)
  9004. {
  9005. const juce_wchar c = *s++;
  9006. if (c >= '0' && c <= '9')
  9007. v = v * 10 + (int64) (c - '0');
  9008. else
  9009. break;
  9010. }
  9011. return isNeg ? -v : v;
  9012. #endif
  9013. }
  9014. static double juce_mulexp10 (const double value, int exponent) throw()
  9015. {
  9016. if (exponent == 0)
  9017. return value;
  9018. if (value == 0)
  9019. return 0;
  9020. const bool negative = (exponent < 0);
  9021. if (negative)
  9022. exponent = -exponent;
  9023. double result = 1.0, power = 10.0;
  9024. for (int bit = 1; exponent != 0; bit <<= 1)
  9025. {
  9026. if ((exponent & bit) != 0)
  9027. {
  9028. exponent ^= bit;
  9029. result *= power;
  9030. if (exponent == 0)
  9031. break;
  9032. }
  9033. power *= power;
  9034. }
  9035. return negative ? (value / result) : (value * result);
  9036. }
  9037. template <class CharType>
  9038. double juce_atof (const CharType* const original) throw()
  9039. {
  9040. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  9041. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  9042. int exponent = 0, decPointIndex = 0, digit = 0;
  9043. int lastDigit = 0, numSignificantDigits = 0;
  9044. bool isNegative = false, digitsFound = false;
  9045. const int maxSignificantDigits = 15 + 2;
  9046. const CharType* s = original;
  9047. while (CharacterFunctions::isWhitespace (*s))
  9048. ++s;
  9049. switch (*s)
  9050. {
  9051. case '-': isNegative = true; // fall-through..
  9052. case '+': ++s;
  9053. }
  9054. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  9055. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  9056. for (;;)
  9057. {
  9058. if (CharacterFunctions::isDigit (*s))
  9059. {
  9060. lastDigit = digit;
  9061. digit = *s++ - '0';
  9062. digitsFound = true;
  9063. if (decPointIndex != 0)
  9064. exponentAdjustment[1]++;
  9065. if (numSignificantDigits == 0 && digit == 0)
  9066. continue;
  9067. if (++numSignificantDigits > maxSignificantDigits)
  9068. {
  9069. if (digit > 5)
  9070. ++accumulator [decPointIndex];
  9071. else if (digit == 5 && (lastDigit & 1) != 0)
  9072. ++accumulator [decPointIndex];
  9073. if (decPointIndex > 0)
  9074. exponentAdjustment[1]--;
  9075. else
  9076. exponentAdjustment[0]++;
  9077. while (CharacterFunctions::isDigit (*s))
  9078. {
  9079. ++s;
  9080. if (decPointIndex == 0)
  9081. exponentAdjustment[0]++;
  9082. }
  9083. }
  9084. else
  9085. {
  9086. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  9087. if (accumulator [decPointIndex] > maxAccumulatorValue)
  9088. {
  9089. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  9090. + accumulator [decPointIndex];
  9091. accumulator [decPointIndex] = 0;
  9092. exponentAccumulator [decPointIndex] = 0;
  9093. }
  9094. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  9095. exponentAccumulator [decPointIndex]++;
  9096. }
  9097. }
  9098. else if (decPointIndex == 0 && *s == '.')
  9099. {
  9100. ++s;
  9101. decPointIndex = 1;
  9102. if (numSignificantDigits > maxSignificantDigits)
  9103. {
  9104. while (CharacterFunctions::isDigit (*s))
  9105. ++s;
  9106. break;
  9107. }
  9108. }
  9109. else
  9110. {
  9111. break;
  9112. }
  9113. }
  9114. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  9115. if (decPointIndex != 0)
  9116. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  9117. if ((*s == 'e' || *s == 'E') && digitsFound)
  9118. {
  9119. bool negativeExponent = false;
  9120. switch (*++s)
  9121. {
  9122. case '-': negativeExponent = true; // fall-through..
  9123. case '+': ++s;
  9124. }
  9125. while (CharacterFunctions::isDigit (*s))
  9126. exponent = (exponent * 10) + (*s++ - '0');
  9127. if (negativeExponent)
  9128. exponent = -exponent;
  9129. }
  9130. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  9131. if (decPointIndex != 0)
  9132. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  9133. return isNegative ? -r : r;
  9134. }
  9135. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  9136. {
  9137. return juce_atof <char> (s);
  9138. }
  9139. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  9140. {
  9141. return juce_atof <juce_wchar> (s);
  9142. }
  9143. char CharacterFunctions::toUpperCase (const char character) throw()
  9144. {
  9145. return (char) toupper (character);
  9146. }
  9147. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  9148. {
  9149. return towupper (character);
  9150. }
  9151. void CharacterFunctions::toUpperCase (char* s) throw()
  9152. {
  9153. #if JUCE_WINDOWS
  9154. strupr (s);
  9155. #else
  9156. while (*s != 0)
  9157. {
  9158. *s = toUpperCase (*s);
  9159. ++s;
  9160. }
  9161. #endif
  9162. }
  9163. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  9164. {
  9165. #if JUCE_WINDOWS
  9166. _wcsupr (s);
  9167. #else
  9168. while (*s != 0)
  9169. {
  9170. *s = toUpperCase (*s);
  9171. ++s;
  9172. }
  9173. #endif
  9174. }
  9175. bool CharacterFunctions::isUpperCase (const char character) throw()
  9176. {
  9177. return isupper (character) != 0;
  9178. }
  9179. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  9180. {
  9181. #if JUCE_WINDOWS
  9182. return iswupper (character) != 0;
  9183. #else
  9184. return toLowerCase (character) != character;
  9185. #endif
  9186. }
  9187. char CharacterFunctions::toLowerCase (const char character) throw()
  9188. {
  9189. return (char) tolower (character);
  9190. }
  9191. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  9192. {
  9193. return towlower (character);
  9194. }
  9195. void CharacterFunctions::toLowerCase (char* s) throw()
  9196. {
  9197. #if JUCE_WINDOWS
  9198. strlwr (s);
  9199. #else
  9200. while (*s != 0)
  9201. {
  9202. *s = toLowerCase (*s);
  9203. ++s;
  9204. }
  9205. #endif
  9206. }
  9207. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  9208. {
  9209. #if JUCE_WINDOWS
  9210. _wcslwr (s);
  9211. #else
  9212. while (*s != 0)
  9213. {
  9214. *s = toLowerCase (*s);
  9215. ++s;
  9216. }
  9217. #endif
  9218. }
  9219. bool CharacterFunctions::isLowerCase (const char character) throw()
  9220. {
  9221. return islower (character) != 0;
  9222. }
  9223. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9224. {
  9225. #if JUCE_WINDOWS
  9226. return iswlower (character) != 0;
  9227. #else
  9228. return toUpperCase (character) != character;
  9229. #endif
  9230. }
  9231. bool CharacterFunctions::isWhitespace (const char character) throw()
  9232. {
  9233. return character == ' ' || (character <= 13 && character >= 9);
  9234. }
  9235. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9236. {
  9237. return iswspace (character) != 0;
  9238. }
  9239. bool CharacterFunctions::isDigit (const char character) throw()
  9240. {
  9241. return (character >= '0' && character <= '9');
  9242. }
  9243. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9244. {
  9245. return iswdigit (character) != 0;
  9246. }
  9247. bool CharacterFunctions::isLetter (const char character) throw()
  9248. {
  9249. return (character >= 'a' && character <= 'z')
  9250. || (character >= 'A' && character <= 'Z');
  9251. }
  9252. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9253. {
  9254. return iswalpha (character) != 0;
  9255. }
  9256. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9257. {
  9258. return (character >= 'a' && character <= 'z')
  9259. || (character >= 'A' && character <= 'Z')
  9260. || (character >= '0' && character <= '9');
  9261. }
  9262. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9263. {
  9264. return iswalnum (character) != 0;
  9265. }
  9266. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9267. {
  9268. unsigned int d = digit - '0';
  9269. if (d < (unsigned int) 10)
  9270. return (int) d;
  9271. d += (unsigned int) ('0' - 'a');
  9272. if (d < (unsigned int) 6)
  9273. return (int) d + 10;
  9274. d += (unsigned int) ('a' - 'A');
  9275. if (d < (unsigned int) 6)
  9276. return (int) d + 10;
  9277. return -1;
  9278. }
  9279. #if JUCE_MSVC
  9280. #pragma warning (pop)
  9281. #endif
  9282. END_JUCE_NAMESPACE
  9283. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9284. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9285. BEGIN_JUCE_NAMESPACE
  9286. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9287. {
  9288. loadFromText (fileContents);
  9289. }
  9290. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9291. {
  9292. loadFromText (fileToLoad.loadFileAsString());
  9293. }
  9294. LocalisedStrings::~LocalisedStrings()
  9295. {
  9296. }
  9297. const String LocalisedStrings::translate (const String& text) const
  9298. {
  9299. return translations.getValue (text, text);
  9300. }
  9301. static int findCloseQuote (const String& text, int startPos)
  9302. {
  9303. juce_wchar lastChar = 0;
  9304. for (;;)
  9305. {
  9306. const juce_wchar c = text [startPos];
  9307. if (c == 0 || (c == '"' && lastChar != '\\'))
  9308. break;
  9309. lastChar = c;
  9310. ++startPos;
  9311. }
  9312. return startPos;
  9313. }
  9314. static const String unescapeString (const String& s)
  9315. {
  9316. return s.replace ("\\\"", "\"")
  9317. .replace ("\\\'", "\'")
  9318. .replace ("\\t", "\t")
  9319. .replace ("\\r", "\r")
  9320. .replace ("\\n", "\n");
  9321. }
  9322. void LocalisedStrings::loadFromText (const String& fileContents)
  9323. {
  9324. StringArray lines;
  9325. lines.addLines (fileContents);
  9326. for (int i = 0; i < lines.size(); ++i)
  9327. {
  9328. String line (lines[i].trim());
  9329. if (line.startsWithChar ('"'))
  9330. {
  9331. int closeQuote = findCloseQuote (line, 1);
  9332. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9333. if (originalText.isNotEmpty())
  9334. {
  9335. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9336. closeQuote = findCloseQuote (line, openingQuote + 1);
  9337. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9338. if (newText.isNotEmpty())
  9339. translations.set (originalText, newText);
  9340. }
  9341. }
  9342. else if (line.startsWithIgnoreCase ("language:"))
  9343. {
  9344. languageName = line.substring (9).trim();
  9345. }
  9346. else if (line.startsWithIgnoreCase ("countries:"))
  9347. {
  9348. countryCodes.addTokens (line.substring (10).trim(), true);
  9349. countryCodes.trim();
  9350. countryCodes.removeEmptyStrings();
  9351. }
  9352. }
  9353. }
  9354. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9355. {
  9356. translations.setIgnoresCase (shouldIgnoreCase);
  9357. }
  9358. static CriticalSection currentMappingsLock;
  9359. static LocalisedStrings* currentMappings = 0;
  9360. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9361. {
  9362. const ScopedLock sl (currentMappingsLock);
  9363. delete currentMappings;
  9364. currentMappings = newTranslations;
  9365. }
  9366. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9367. {
  9368. return currentMappings;
  9369. }
  9370. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9371. {
  9372. const ScopedLock sl (currentMappingsLock);
  9373. if (currentMappings != 0)
  9374. return currentMappings->translate (text);
  9375. return text;
  9376. }
  9377. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9378. {
  9379. return translateWithCurrentMappings (String (text));
  9380. }
  9381. END_JUCE_NAMESPACE
  9382. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9383. /*** Start of inlined file: juce_String.cpp ***/
  9384. #if JUCE_MSVC
  9385. #pragma warning (push)
  9386. #pragma warning (disable: 4514)
  9387. #endif
  9388. #include <locale>
  9389. BEGIN_JUCE_NAMESPACE
  9390. #if JUCE_MSVC
  9391. #pragma warning (pop)
  9392. #endif
  9393. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9394. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9395. #endif
  9396. class StringHolder
  9397. {
  9398. public:
  9399. StringHolder()
  9400. : refCount (0x3fffffff), allocatedNumChars (0)
  9401. {
  9402. text[0] = 0;
  9403. }
  9404. static juce_wchar* createUninitialised (const size_t numChars)
  9405. {
  9406. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9407. s->refCount.value = 0;
  9408. s->allocatedNumChars = numChars;
  9409. return &(s->text[0]);
  9410. }
  9411. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9412. {
  9413. juce_wchar* const dest = createUninitialised (numChars);
  9414. copyChars (dest, src, numChars);
  9415. return dest;
  9416. }
  9417. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9418. {
  9419. juce_wchar* const dest = createUninitialised (numChars);
  9420. CharacterFunctions::copy (dest, src, (int) numChars);
  9421. dest [numChars] = 0;
  9422. return dest;
  9423. }
  9424. static inline juce_wchar* getEmpty() throw()
  9425. {
  9426. return &(empty.text[0]);
  9427. }
  9428. static void retain (juce_wchar* const text) throw()
  9429. {
  9430. ++(bufferFromText (text)->refCount);
  9431. }
  9432. static inline void release (StringHolder* const b) throw()
  9433. {
  9434. if (--(b->refCount) == -1 && b != &empty)
  9435. delete[] reinterpret_cast <char*> (b);
  9436. }
  9437. static void release (juce_wchar* const text) throw()
  9438. {
  9439. release (bufferFromText (text));
  9440. }
  9441. static juce_wchar* makeUnique (juce_wchar* const text)
  9442. {
  9443. StringHolder* const b = bufferFromText (text);
  9444. if (b->refCount.get() <= 0)
  9445. return text;
  9446. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9447. release (b);
  9448. return newText;
  9449. }
  9450. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9451. {
  9452. StringHolder* const b = bufferFromText (text);
  9453. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9454. return text;
  9455. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9456. copyChars (newText, text, b->allocatedNumChars);
  9457. release (b);
  9458. return newText;
  9459. }
  9460. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9461. {
  9462. return bufferFromText (text)->allocatedNumChars;
  9463. }
  9464. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9465. {
  9466. jassert (src != 0 && dest != 0);
  9467. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9468. dest [numChars] = 0;
  9469. }
  9470. Atomic<int> refCount;
  9471. size_t allocatedNumChars;
  9472. juce_wchar text[1];
  9473. static StringHolder empty;
  9474. private:
  9475. static inline StringHolder* bufferFromText (void* const text) throw()
  9476. {
  9477. // (Can't use offsetof() here because of warnings about this not being a POD)
  9478. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9479. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9480. }
  9481. };
  9482. StringHolder StringHolder::empty;
  9483. const String String::empty;
  9484. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9485. {
  9486. jassert (t[numChars] == 0); // must have a null terminator
  9487. text = StringHolder::createCopy (t, numChars);
  9488. }
  9489. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9490. {
  9491. if (numExtraChars > 0)
  9492. {
  9493. const int oldLen = length();
  9494. const int newTotalLen = oldLen + numExtraChars;
  9495. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9496. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9497. }
  9498. }
  9499. void String::preallocateStorage (const size_t numChars)
  9500. {
  9501. text = StringHolder::makeUniqueWithSize (text, numChars);
  9502. }
  9503. String::String() throw()
  9504. : text (StringHolder::getEmpty())
  9505. {
  9506. }
  9507. String::~String() throw()
  9508. {
  9509. StringHolder::release (text);
  9510. }
  9511. String::String (const String& other) throw()
  9512. : text (other.text)
  9513. {
  9514. StringHolder::retain (text);
  9515. }
  9516. void String::swapWith (String& other) throw()
  9517. {
  9518. swapVariables (text, other.text);
  9519. }
  9520. String& String::operator= (const String& other) throw()
  9521. {
  9522. juce_wchar* const newText = other.text;
  9523. StringHolder::retain (newText);
  9524. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  9525. return *this;
  9526. }
  9527. String::String (const size_t numChars, const int /*dummyVariable*/)
  9528. : text (StringHolder::createUninitialised (numChars))
  9529. {
  9530. }
  9531. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9532. {
  9533. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9534. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9535. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9536. }
  9537. String::String (const char* const t)
  9538. {
  9539. if (t != 0 && *t != 0)
  9540. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9541. else
  9542. text = StringHolder::getEmpty();
  9543. }
  9544. String::String (const juce_wchar* const t)
  9545. {
  9546. if (t != 0 && *t != 0)
  9547. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9548. else
  9549. text = StringHolder::getEmpty();
  9550. }
  9551. String::String (const char* const t, const size_t maxChars)
  9552. {
  9553. int i;
  9554. for (i = 0; (size_t) i < maxChars; ++i)
  9555. if (t[i] == 0)
  9556. break;
  9557. if (i > 0)
  9558. text = StringHolder::createCopy (t, i);
  9559. else
  9560. text = StringHolder::getEmpty();
  9561. }
  9562. String::String (const juce_wchar* const t, const size_t maxChars)
  9563. {
  9564. int i;
  9565. for (i = 0; (size_t) i < maxChars; ++i)
  9566. if (t[i] == 0)
  9567. break;
  9568. if (i > 0)
  9569. text = StringHolder::createCopy (t, i);
  9570. else
  9571. text = StringHolder::getEmpty();
  9572. }
  9573. const String String::charToString (const juce_wchar character)
  9574. {
  9575. String result ((size_t) 1, (int) 0);
  9576. result.text[0] = character;
  9577. result.text[1] = 0;
  9578. return result;
  9579. }
  9580. namespace NumberToStringConverters
  9581. {
  9582. // pass in a pointer to the END of a buffer..
  9583. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9584. {
  9585. *--t = 0;
  9586. int64 v = (n >= 0) ? n : -n;
  9587. do
  9588. {
  9589. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9590. v /= 10;
  9591. } while (v > 0);
  9592. if (n < 0)
  9593. *--t = '-';
  9594. return t;
  9595. }
  9596. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9597. {
  9598. *--t = 0;
  9599. do
  9600. {
  9601. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9602. v /= 10;
  9603. } while (v > 0);
  9604. return t;
  9605. }
  9606. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9607. {
  9608. if (n == (int) 0x80000000) // (would cause an overflow)
  9609. return int64ToString (t, n);
  9610. *--t = 0;
  9611. int v = abs (n);
  9612. do
  9613. {
  9614. *--t = (juce_wchar) ('0' + (v % 10));
  9615. v /= 10;
  9616. } while (v > 0);
  9617. if (n < 0)
  9618. *--t = '-';
  9619. return t;
  9620. }
  9621. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9622. {
  9623. *--t = 0;
  9624. do
  9625. {
  9626. *--t = (juce_wchar) ('0' + (v % 10));
  9627. v /= 10;
  9628. } while (v > 0);
  9629. return t;
  9630. }
  9631. static juce_wchar getDecimalPoint()
  9632. {
  9633. #if JUCE_MSVC && _MSC_VER < 1400
  9634. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9635. #else
  9636. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9637. #endif
  9638. return dp;
  9639. }
  9640. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9641. {
  9642. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9643. {
  9644. juce_wchar* const end = buffer + numChars;
  9645. juce_wchar* t = end;
  9646. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9647. *--t = (juce_wchar) 0;
  9648. while (numDecPlaces >= 0 || v > 0)
  9649. {
  9650. if (numDecPlaces == 0)
  9651. *--t = getDecimalPoint();
  9652. *--t = (juce_wchar) ('0' + (v % 10));
  9653. v /= 10;
  9654. --numDecPlaces;
  9655. }
  9656. if (n < 0)
  9657. *--t = '-';
  9658. len = end - t - 1;
  9659. return t;
  9660. }
  9661. else
  9662. {
  9663. #if JUCE_WINDOWS
  9664. #if JUCE_MSVC && _MSC_VER <= 1400
  9665. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9666. #else
  9667. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9668. #endif
  9669. #else
  9670. len = swprintf (buffer, numChars, L"%.9g", n);
  9671. #endif
  9672. return buffer;
  9673. }
  9674. }
  9675. }
  9676. String::String (const int number)
  9677. {
  9678. juce_wchar buffer [16];
  9679. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9680. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9681. createInternal (start, end - start - 1);
  9682. }
  9683. String::String (const unsigned int number)
  9684. {
  9685. juce_wchar buffer [16];
  9686. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9687. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9688. createInternal (start, end - start - 1);
  9689. }
  9690. String::String (const short number)
  9691. {
  9692. juce_wchar buffer [16];
  9693. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9694. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9695. createInternal (start, end - start - 1);
  9696. }
  9697. String::String (const unsigned short number)
  9698. {
  9699. juce_wchar buffer [16];
  9700. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9701. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9702. createInternal (start, end - start - 1);
  9703. }
  9704. String::String (const int64 number)
  9705. {
  9706. juce_wchar buffer [32];
  9707. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9708. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9709. createInternal (start, end - start - 1);
  9710. }
  9711. String::String (const uint64 number)
  9712. {
  9713. juce_wchar buffer [32];
  9714. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9715. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9716. createInternal (start, end - start - 1);
  9717. }
  9718. String::String (const float number, const int numberOfDecimalPlaces)
  9719. {
  9720. juce_wchar buffer [48];
  9721. size_t len;
  9722. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9723. createInternal (start, len);
  9724. }
  9725. String::String (const double number, const int numberOfDecimalPlaces)
  9726. {
  9727. juce_wchar buffer [48];
  9728. size_t len;
  9729. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9730. createInternal (start, len);
  9731. }
  9732. int String::length() const throw()
  9733. {
  9734. return CharacterFunctions::length (text);
  9735. }
  9736. int String::hashCode() const throw()
  9737. {
  9738. const juce_wchar* t = text;
  9739. int result = 0;
  9740. while (*t != (juce_wchar) 0)
  9741. result = 31 * result + *t++;
  9742. return result;
  9743. }
  9744. int64 String::hashCode64() const throw()
  9745. {
  9746. const juce_wchar* t = text;
  9747. int64 result = 0;
  9748. while (*t != (juce_wchar) 0)
  9749. result = 101 * result + *t++;
  9750. return result;
  9751. }
  9752. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const String& string2) throw()
  9753. {
  9754. return string1.compare (string2) == 0;
  9755. }
  9756. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const char* string2) throw()
  9757. {
  9758. return string1.compare (string2) == 0;
  9759. }
  9760. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const juce_wchar* string2) throw()
  9761. {
  9762. return string1.compare (string2) == 0;
  9763. }
  9764. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const String& string2) throw()
  9765. {
  9766. return string1.compare (string2) != 0;
  9767. }
  9768. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const char* string2) throw()
  9769. {
  9770. return string1.compare (string2) != 0;
  9771. }
  9772. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const juce_wchar* string2) throw()
  9773. {
  9774. return string1.compare (string2) != 0;
  9775. }
  9776. bool JUCE_PUBLIC_FUNCTION operator> (const String& string1, const String& string2) throw()
  9777. {
  9778. return string1.compare (string2) > 0;
  9779. }
  9780. bool JUCE_PUBLIC_FUNCTION operator< (const String& string1, const String& string2) throw()
  9781. {
  9782. return string1.compare (string2) < 0;
  9783. }
  9784. bool JUCE_PUBLIC_FUNCTION operator>= (const String& string1, const String& string2) throw()
  9785. {
  9786. return string1.compare (string2) >= 0;
  9787. }
  9788. bool JUCE_PUBLIC_FUNCTION operator<= (const String& string1, const String& string2) throw()
  9789. {
  9790. return string1.compare (string2) <= 0;
  9791. }
  9792. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9793. {
  9794. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9795. : isEmpty();
  9796. }
  9797. bool String::equalsIgnoreCase (const char* t) const throw()
  9798. {
  9799. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9800. : isEmpty();
  9801. }
  9802. bool String::equalsIgnoreCase (const String& other) const throw()
  9803. {
  9804. return text == other.text
  9805. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9806. }
  9807. int String::compare (const String& other) const throw()
  9808. {
  9809. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9810. }
  9811. int String::compare (const char* other) const throw()
  9812. {
  9813. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9814. }
  9815. int String::compare (const juce_wchar* other) const throw()
  9816. {
  9817. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9818. }
  9819. int String::compareIgnoreCase (const String& other) const throw()
  9820. {
  9821. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9822. }
  9823. int String::compareLexicographically (const String& other) const throw()
  9824. {
  9825. const juce_wchar* s1 = text;
  9826. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9827. ++s1;
  9828. const juce_wchar* s2 = other.text;
  9829. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9830. ++s2;
  9831. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9832. }
  9833. String& String::operator+= (const juce_wchar* const t)
  9834. {
  9835. if (t != 0)
  9836. appendInternal (t, CharacterFunctions::length (t));
  9837. return *this;
  9838. }
  9839. String& String::operator+= (const String& other)
  9840. {
  9841. if (isEmpty())
  9842. operator= (other);
  9843. else
  9844. appendInternal (other.text, other.length());
  9845. return *this;
  9846. }
  9847. String& String::operator+= (const char ch)
  9848. {
  9849. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9850. return operator+= (static_cast <const juce_wchar*> (asString));
  9851. }
  9852. String& String::operator+= (const juce_wchar ch)
  9853. {
  9854. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9855. return operator+= (static_cast <const juce_wchar*> (asString));
  9856. }
  9857. String& String::operator+= (const int number)
  9858. {
  9859. juce_wchar buffer [16];
  9860. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9861. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9862. appendInternal (start, (int) (end - start));
  9863. return *this;
  9864. }
  9865. String& String::operator+= (const unsigned int number)
  9866. {
  9867. juce_wchar buffer [16];
  9868. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9869. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9870. appendInternal (start, (int) (end - start));
  9871. return *this;
  9872. }
  9873. void String::append (const juce_wchar* const other, const int howMany)
  9874. {
  9875. if (howMany > 0)
  9876. {
  9877. int i;
  9878. for (i = 0; i < howMany; ++i)
  9879. if (other[i] == 0)
  9880. break;
  9881. appendInternal (other, i);
  9882. }
  9883. }
  9884. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1, const String& string2)
  9885. {
  9886. String s (string1);
  9887. return s += string2;
  9888. }
  9889. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1, const String& string2)
  9890. {
  9891. String s (string1);
  9892. return s += string2;
  9893. }
  9894. const String JUCE_PUBLIC_FUNCTION operator+ (const char string1, const String& string2)
  9895. {
  9896. return String::charToString (string1) + string2;
  9897. }
  9898. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar string1, const String& string2)
  9899. {
  9900. return String::charToString (string1) + string2;
  9901. }
  9902. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const String& string2)
  9903. {
  9904. return string1 += string2;
  9905. }
  9906. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char* const string2)
  9907. {
  9908. return string1 += string2;
  9909. }
  9910. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar* const string2)
  9911. {
  9912. return string1 += string2;
  9913. }
  9914. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char string2)
  9915. {
  9916. return string1 += string2;
  9917. }
  9918. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar string2)
  9919. {
  9920. return string1 += string2;
  9921. }
  9922. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char characterToAppend)
  9923. {
  9924. return string1 += characterToAppend;
  9925. }
  9926. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar characterToAppend)
  9927. {
  9928. return string1 += characterToAppend;
  9929. }
  9930. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char* const string2)
  9931. {
  9932. return string1 += string2;
  9933. }
  9934. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar* const string2)
  9935. {
  9936. return string1 += string2;
  9937. }
  9938. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const String& string2)
  9939. {
  9940. return string1 += string2;
  9941. }
  9942. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const short number)
  9943. {
  9944. return string1 += (int) number;
  9945. }
  9946. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const int number)
  9947. {
  9948. return string1 += number;
  9949. }
  9950. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned int number)
  9951. {
  9952. return string1 += number;
  9953. }
  9954. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const long number)
  9955. {
  9956. return string1 += (int) number;
  9957. }
  9958. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned long number)
  9959. {
  9960. return string1 += (unsigned int) number;
  9961. }
  9962. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const float number)
  9963. {
  9964. return string1 += String (number);
  9965. }
  9966. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const double number)
  9967. {
  9968. return string1 += String (number);
  9969. }
  9970. OutputStream& JUCE_PUBLIC_FUNCTION operator<< (OutputStream& stream, const String& text)
  9971. {
  9972. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9973. // if lots of large, persistent strings were to be written to streams).
  9974. const int numBytes = text.getNumBytesAsUTF8();
  9975. HeapBlock<char> temp (numBytes + 1);
  9976. text.copyToUTF8 (temp, numBytes + 1);
  9977. stream.write (temp, numBytes);
  9978. return stream;
  9979. }
  9980. int String::indexOfChar (const juce_wchar character) const throw()
  9981. {
  9982. const juce_wchar* t = text;
  9983. for (;;)
  9984. {
  9985. if (*t == character)
  9986. return (int) (t - text);
  9987. if (*t++ == 0)
  9988. return -1;
  9989. }
  9990. }
  9991. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9992. {
  9993. for (int i = length(); --i >= 0;)
  9994. if (text[i] == character)
  9995. return i;
  9996. return -1;
  9997. }
  9998. int String::indexOf (const String& t) const throw()
  9999. {
  10000. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  10001. return r == 0 ? -1 : (int) (r - text);
  10002. }
  10003. int String::indexOfChar (const int startIndex,
  10004. const juce_wchar character) const throw()
  10005. {
  10006. if (startIndex > 0 && startIndex >= length())
  10007. return -1;
  10008. const juce_wchar* t = text + jmax (0, startIndex);
  10009. for (;;)
  10010. {
  10011. if (*t == character)
  10012. return (int) (t - text);
  10013. if (*t == 0)
  10014. return -1;
  10015. ++t;
  10016. }
  10017. }
  10018. int String::indexOfAnyOf (const String& charactersToLookFor,
  10019. const int startIndex,
  10020. const bool ignoreCase) const throw()
  10021. {
  10022. if (startIndex > 0 && startIndex >= length())
  10023. return -1;
  10024. const juce_wchar* t = text + jmax (0, startIndex);
  10025. while (*t != 0)
  10026. {
  10027. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  10028. return (int) (t - text);
  10029. ++t;
  10030. }
  10031. return -1;
  10032. }
  10033. int String::indexOf (const int startIndex, const String& other) const throw()
  10034. {
  10035. if (startIndex > 0 && startIndex >= length())
  10036. return -1;
  10037. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  10038. return found == 0 ? -1 : (int) (found - text);
  10039. }
  10040. int String::indexOfIgnoreCase (const String& other) const throw()
  10041. {
  10042. if (other.isNotEmpty())
  10043. {
  10044. const int len = other.length();
  10045. const int end = length() - len;
  10046. for (int i = 0; i <= end; ++i)
  10047. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10048. return i;
  10049. }
  10050. return -1;
  10051. }
  10052. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  10053. {
  10054. if (other.isNotEmpty())
  10055. {
  10056. const int len = other.length();
  10057. const int end = length() - len;
  10058. for (int i = jmax (0, startIndex); i <= end; ++i)
  10059. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10060. return i;
  10061. }
  10062. return -1;
  10063. }
  10064. int String::lastIndexOf (const String& other) const throw()
  10065. {
  10066. if (other.isNotEmpty())
  10067. {
  10068. const int len = other.length();
  10069. int i = length() - len;
  10070. if (i >= 0)
  10071. {
  10072. const juce_wchar* n = text + i;
  10073. while (i >= 0)
  10074. {
  10075. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  10076. return i;
  10077. --i;
  10078. }
  10079. }
  10080. }
  10081. return -1;
  10082. }
  10083. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  10084. {
  10085. if (other.isNotEmpty())
  10086. {
  10087. const int len = other.length();
  10088. int i = length() - len;
  10089. if (i >= 0)
  10090. {
  10091. const juce_wchar* n = text + i;
  10092. while (i >= 0)
  10093. {
  10094. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  10095. return i;
  10096. --i;
  10097. }
  10098. }
  10099. }
  10100. return -1;
  10101. }
  10102. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  10103. {
  10104. for (int i = length(); --i >= 0;)
  10105. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  10106. return i;
  10107. return -1;
  10108. }
  10109. bool String::contains (const String& other) const throw()
  10110. {
  10111. return indexOf (other) >= 0;
  10112. }
  10113. bool String::containsChar (const juce_wchar character) const throw()
  10114. {
  10115. const juce_wchar* t = text;
  10116. for (;;)
  10117. {
  10118. if (*t == 0)
  10119. return false;
  10120. if (*t == character)
  10121. return true;
  10122. ++t;
  10123. }
  10124. }
  10125. bool String::containsIgnoreCase (const String& t) const throw()
  10126. {
  10127. return indexOfIgnoreCase (t) >= 0;
  10128. }
  10129. int String::indexOfWholeWord (const String& word) const throw()
  10130. {
  10131. if (word.isNotEmpty())
  10132. {
  10133. const int wordLen = word.length();
  10134. const int end = length() - wordLen;
  10135. const juce_wchar* t = text;
  10136. for (int i = 0; i <= end; ++i)
  10137. {
  10138. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  10139. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10140. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10141. {
  10142. return i;
  10143. }
  10144. ++t;
  10145. }
  10146. }
  10147. return -1;
  10148. }
  10149. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10150. {
  10151. if (word.isNotEmpty())
  10152. {
  10153. const int wordLen = word.length();
  10154. const int end = length() - wordLen;
  10155. const juce_wchar* t = text;
  10156. for (int i = 0; i <= end; ++i)
  10157. {
  10158. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  10159. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10160. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10161. {
  10162. return i;
  10163. }
  10164. ++t;
  10165. }
  10166. }
  10167. return -1;
  10168. }
  10169. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10170. {
  10171. return indexOfWholeWord (wordToLookFor) >= 0;
  10172. }
  10173. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10174. {
  10175. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10176. }
  10177. static int indexOfMatch (const juce_wchar* const wildcard,
  10178. const juce_wchar* const test,
  10179. const bool ignoreCase) throw()
  10180. {
  10181. int start = 0;
  10182. while (test [start] != 0)
  10183. {
  10184. int i = 0;
  10185. for (;;)
  10186. {
  10187. const juce_wchar wc = wildcard [i];
  10188. const juce_wchar c = test [i + start];
  10189. if (wc == c
  10190. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10191. || (wc == '?' && c != 0))
  10192. {
  10193. if (wc == 0)
  10194. return start;
  10195. ++i;
  10196. }
  10197. else
  10198. {
  10199. if (wc == '*' && (wildcard [i + 1] == 0
  10200. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  10201. {
  10202. return start;
  10203. }
  10204. break;
  10205. }
  10206. }
  10207. ++start;
  10208. }
  10209. return -1;
  10210. }
  10211. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10212. {
  10213. int i = 0;
  10214. for (;;)
  10215. {
  10216. const juce_wchar wc = wildcard.text [i];
  10217. const juce_wchar c = text [i];
  10218. if (wc == c
  10219. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10220. || (wc == '?' && c != 0))
  10221. {
  10222. if (wc == 0)
  10223. return true;
  10224. ++i;
  10225. }
  10226. else
  10227. {
  10228. return wc == '*' && (wildcard [i + 1] == 0
  10229. || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  10230. }
  10231. }
  10232. }
  10233. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10234. {
  10235. const int len = stringToRepeat.length();
  10236. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  10237. juce_wchar* n = result.text;
  10238. *n = 0;
  10239. while (--numberOfTimesToRepeat >= 0)
  10240. {
  10241. StringHolder::copyChars (n, stringToRepeat.text, len);
  10242. n += len;
  10243. }
  10244. return result;
  10245. }
  10246. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10247. {
  10248. jassert (padCharacter != 0);
  10249. const int len = length();
  10250. if (len >= minimumLength || padCharacter == 0)
  10251. return *this;
  10252. String result ((size_t) minimumLength + 1, (int) 0);
  10253. juce_wchar* n = result.text;
  10254. minimumLength -= len;
  10255. while (--minimumLength >= 0)
  10256. *n++ = padCharacter;
  10257. StringHolder::copyChars (n, text, len);
  10258. return result;
  10259. }
  10260. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10261. {
  10262. jassert (padCharacter != 0);
  10263. const int len = length();
  10264. if (len >= minimumLength || padCharacter == 0)
  10265. return *this;
  10266. String result (*this, (size_t) minimumLength);
  10267. juce_wchar* n = result.text + len;
  10268. minimumLength -= len;
  10269. while (--minimumLength >= 0)
  10270. *n++ = padCharacter;
  10271. *n = 0;
  10272. return result;
  10273. }
  10274. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10275. {
  10276. if (index < 0)
  10277. {
  10278. // a negative index to replace from?
  10279. jassertfalse;
  10280. index = 0;
  10281. }
  10282. if (numCharsToReplace < 0)
  10283. {
  10284. // replacing a negative number of characters?
  10285. numCharsToReplace = 0;
  10286. jassertfalse;
  10287. }
  10288. const int len = length();
  10289. if (index + numCharsToReplace > len)
  10290. {
  10291. if (index > len)
  10292. {
  10293. // replacing beyond the end of the string?
  10294. index = len;
  10295. jassertfalse;
  10296. }
  10297. numCharsToReplace = len - index;
  10298. }
  10299. const int newStringLen = stringToInsert.length();
  10300. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10301. if (newTotalLen <= 0)
  10302. return String::empty;
  10303. String result ((size_t) newTotalLen, (int) 0);
  10304. StringHolder::copyChars (result.text, text, index);
  10305. if (newStringLen > 0)
  10306. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10307. const int endStringLen = newTotalLen - (index + newStringLen);
  10308. if (endStringLen > 0)
  10309. StringHolder::copyChars (result.text + (index + newStringLen),
  10310. text + (index + numCharsToReplace),
  10311. endStringLen);
  10312. return result;
  10313. }
  10314. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10315. {
  10316. const int stringToReplaceLen = stringToReplace.length();
  10317. const int stringToInsertLen = stringToInsert.length();
  10318. int i = 0;
  10319. String result (*this);
  10320. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10321. : result.indexOf (i, stringToReplace))) >= 0)
  10322. {
  10323. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10324. i += stringToInsertLen;
  10325. }
  10326. return result;
  10327. }
  10328. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10329. {
  10330. const int index = indexOfChar (charToReplace);
  10331. if (index < 0)
  10332. return *this;
  10333. String result (*this, size_t());
  10334. juce_wchar* t = result.text + index;
  10335. while (*t != 0)
  10336. {
  10337. if (*t == charToReplace)
  10338. *t = charToInsert;
  10339. ++t;
  10340. }
  10341. return result;
  10342. }
  10343. const String String::replaceCharacters (const String& charactersToReplace,
  10344. const String& charactersToInsertInstead) const
  10345. {
  10346. String result (*this, size_t());
  10347. juce_wchar* t = result.text;
  10348. const int len2 = charactersToInsertInstead.length();
  10349. // the two strings passed in are supposed to be the same length!
  10350. jassert (len2 == charactersToReplace.length());
  10351. while (*t != 0)
  10352. {
  10353. const int index = charactersToReplace.indexOfChar (*t);
  10354. if (((unsigned int) index) < (unsigned int) len2)
  10355. *t = charactersToInsertInstead [index];
  10356. ++t;
  10357. }
  10358. return result;
  10359. }
  10360. bool String::startsWith (const String& other) const throw()
  10361. {
  10362. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10363. }
  10364. bool String::startsWithIgnoreCase (const String& other) const throw()
  10365. {
  10366. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10367. }
  10368. bool String::startsWithChar (const juce_wchar character) const throw()
  10369. {
  10370. jassert (character != 0); // strings can't contain a null character!
  10371. return text[0] == character;
  10372. }
  10373. bool String::endsWithChar (const juce_wchar character) const throw()
  10374. {
  10375. jassert (character != 0); // strings can't contain a null character!
  10376. return text[0] != 0
  10377. && text [length() - 1] == character;
  10378. }
  10379. bool String::endsWith (const String& other) const throw()
  10380. {
  10381. const int thisLen = length();
  10382. const int otherLen = other.length();
  10383. return thisLen >= otherLen
  10384. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10385. }
  10386. bool String::endsWithIgnoreCase (const String& other) const throw()
  10387. {
  10388. const int thisLen = length();
  10389. const int otherLen = other.length();
  10390. return thisLen >= otherLen
  10391. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10392. }
  10393. const String String::toUpperCase() const
  10394. {
  10395. String result (*this, size_t());
  10396. CharacterFunctions::toUpperCase (result.text);
  10397. return result;
  10398. }
  10399. const String String::toLowerCase() const
  10400. {
  10401. String result (*this, size_t());
  10402. CharacterFunctions::toLowerCase (result.text);
  10403. return result;
  10404. }
  10405. juce_wchar& String::operator[] (const int index)
  10406. {
  10407. jassert (((unsigned int) index) <= (unsigned int) length());
  10408. text = StringHolder::makeUnique (text);
  10409. return text [index];
  10410. }
  10411. juce_wchar String::getLastCharacter() const throw()
  10412. {
  10413. return isEmpty() ? juce_wchar() : text [length() - 1];
  10414. }
  10415. const String String::substring (int start, int end) const
  10416. {
  10417. if (start < 0)
  10418. start = 0;
  10419. else if (end <= start)
  10420. return empty;
  10421. int len = 0;
  10422. while (len <= end && text [len] != 0)
  10423. ++len;
  10424. if (end >= len)
  10425. {
  10426. if (start == 0)
  10427. return *this;
  10428. end = len;
  10429. }
  10430. return String (text + start, end - start);
  10431. }
  10432. const String String::substring (const int start) const
  10433. {
  10434. if (start <= 0)
  10435. return *this;
  10436. const int len = length();
  10437. if (start >= len)
  10438. return empty;
  10439. return String (text + start, len - start);
  10440. }
  10441. const String String::dropLastCharacters (const int numberToDrop) const
  10442. {
  10443. return String (text, jmax (0, length() - numberToDrop));
  10444. }
  10445. const String String::getLastCharacters (const int numCharacters) const
  10446. {
  10447. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10448. }
  10449. const String String::fromFirstOccurrenceOf (const String& sub,
  10450. const bool includeSubString,
  10451. const bool ignoreCase) const
  10452. {
  10453. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10454. : indexOf (sub);
  10455. if (i < 0)
  10456. return empty;
  10457. return substring (includeSubString ? i : i + sub.length());
  10458. }
  10459. const String String::fromLastOccurrenceOf (const String& sub,
  10460. const bool includeSubString,
  10461. const bool ignoreCase) const
  10462. {
  10463. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10464. : lastIndexOf (sub);
  10465. if (i < 0)
  10466. return *this;
  10467. return substring (includeSubString ? i : i + sub.length());
  10468. }
  10469. const String String::upToFirstOccurrenceOf (const String& sub,
  10470. const bool includeSubString,
  10471. const bool ignoreCase) const
  10472. {
  10473. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10474. : indexOf (sub);
  10475. if (i < 0)
  10476. return *this;
  10477. return substring (0, includeSubString ? i + sub.length() : i);
  10478. }
  10479. const String String::upToLastOccurrenceOf (const String& sub,
  10480. const bool includeSubString,
  10481. const bool ignoreCase) const
  10482. {
  10483. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10484. : lastIndexOf (sub);
  10485. if (i < 0)
  10486. return *this;
  10487. return substring (0, includeSubString ? i + sub.length() : i);
  10488. }
  10489. bool String::isQuotedString() const
  10490. {
  10491. const String trimmed (trimStart());
  10492. return trimmed[0] == '"'
  10493. || trimmed[0] == '\'';
  10494. }
  10495. const String String::unquoted() const
  10496. {
  10497. String s (*this);
  10498. if (s.text[0] == '"' || s.text[0] == '\'')
  10499. s = s.substring (1);
  10500. const int lastCharIndex = s.length() - 1;
  10501. if (lastCharIndex >= 0
  10502. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10503. s [lastCharIndex] = 0;
  10504. return s;
  10505. }
  10506. const String String::quoted (const juce_wchar quoteCharacter) const
  10507. {
  10508. if (isEmpty())
  10509. return charToString (quoteCharacter) + quoteCharacter;
  10510. String t (*this);
  10511. if (! t.startsWithChar (quoteCharacter))
  10512. t = charToString (quoteCharacter) + t;
  10513. if (! t.endsWithChar (quoteCharacter))
  10514. t += quoteCharacter;
  10515. return t;
  10516. }
  10517. const String String::trim() const
  10518. {
  10519. if (isEmpty())
  10520. return empty;
  10521. int start = 0;
  10522. while (CharacterFunctions::isWhitespace (text [start]))
  10523. ++start;
  10524. const int len = length();
  10525. int end = len - 1;
  10526. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10527. --end;
  10528. ++end;
  10529. if (end <= start)
  10530. return empty;
  10531. else if (start > 0 || end < len)
  10532. return String (text + start, end - start);
  10533. return *this;
  10534. }
  10535. const String String::trimStart() const
  10536. {
  10537. if (isEmpty())
  10538. return empty;
  10539. const juce_wchar* t = text;
  10540. while (CharacterFunctions::isWhitespace (*t))
  10541. ++t;
  10542. if (t == text)
  10543. return *this;
  10544. return String (t);
  10545. }
  10546. const String String::trimEnd() const
  10547. {
  10548. if (isEmpty())
  10549. return empty;
  10550. const juce_wchar* endT = text + (length() - 1);
  10551. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10552. --endT;
  10553. return String (text, (int) (++endT - text));
  10554. }
  10555. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10556. {
  10557. const juce_wchar* t = text;
  10558. while (charactersToTrim.containsChar (*t))
  10559. ++t;
  10560. return t == text ? *this : String (t);
  10561. }
  10562. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10563. {
  10564. if (isEmpty())
  10565. return empty;
  10566. const int len = length();
  10567. const juce_wchar* endT = text + (len - 1);
  10568. int numToRemove = 0;
  10569. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10570. {
  10571. ++numToRemove;
  10572. --endT;
  10573. }
  10574. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10575. }
  10576. const String String::retainCharacters (const String& charactersToRetain) const
  10577. {
  10578. if (isEmpty())
  10579. return empty;
  10580. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10581. juce_wchar* dst = result.text;
  10582. const juce_wchar* src = text;
  10583. while (*src != 0)
  10584. {
  10585. if (charactersToRetain.containsChar (*src))
  10586. *dst++ = *src;
  10587. ++src;
  10588. }
  10589. *dst = 0;
  10590. return result;
  10591. }
  10592. const String String::removeCharacters (const String& charactersToRemove) const
  10593. {
  10594. if (isEmpty())
  10595. return empty;
  10596. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10597. juce_wchar* dst = result.text;
  10598. const juce_wchar* src = text;
  10599. while (*src != 0)
  10600. {
  10601. if (! charactersToRemove.containsChar (*src))
  10602. *dst++ = *src;
  10603. ++src;
  10604. }
  10605. *dst = 0;
  10606. return result;
  10607. }
  10608. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10609. {
  10610. int i = 0;
  10611. for (;;)
  10612. {
  10613. if (! permittedCharacters.containsChar (text[i]))
  10614. break;
  10615. ++i;
  10616. }
  10617. return substring (0, i);
  10618. }
  10619. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10620. {
  10621. const juce_wchar* const t = text;
  10622. int i = 0;
  10623. while (t[i] != 0)
  10624. {
  10625. if (charactersToStopAt.containsChar (t[i]))
  10626. return String (text, i);
  10627. ++i;
  10628. }
  10629. return empty;
  10630. }
  10631. bool String::containsOnly (const String& chars) const throw()
  10632. {
  10633. const juce_wchar* t = text;
  10634. while (*t != 0)
  10635. if (! chars.containsChar (*t++))
  10636. return false;
  10637. return true;
  10638. }
  10639. bool String::containsAnyOf (const String& chars) const throw()
  10640. {
  10641. const juce_wchar* t = text;
  10642. while (*t != 0)
  10643. if (chars.containsChar (*t++))
  10644. return true;
  10645. return false;
  10646. }
  10647. bool String::containsNonWhitespaceChars() const throw()
  10648. {
  10649. const juce_wchar* t = text;
  10650. while (*t != 0)
  10651. if (! CharacterFunctions::isWhitespace (*t++))
  10652. return true;
  10653. return false;
  10654. }
  10655. const String String::formatted (const juce_wchar* const pf, ... )
  10656. {
  10657. jassert (pf != 0);
  10658. va_list args;
  10659. va_start (args, pf);
  10660. size_t bufferSize = 256;
  10661. String result (bufferSize, (int) 0);
  10662. result.text[0] = 0;
  10663. for (;;)
  10664. {
  10665. #if JUCE_LINUX && JUCE_64BIT
  10666. va_list tempArgs;
  10667. va_copy (tempArgs, args);
  10668. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10669. va_end (tempArgs);
  10670. #elif JUCE_WINDOWS
  10671. #if JUCE_MSVC
  10672. #pragma warning (push)
  10673. #pragma warning (disable: 4996)
  10674. #endif
  10675. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10676. #if JUCE_MSVC
  10677. #pragma warning (pop)
  10678. #endif
  10679. #else
  10680. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10681. #endif
  10682. if (num > 0)
  10683. return result;
  10684. bufferSize += 256;
  10685. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10686. break; // returns -1 because of an error rather than because it needs more space.
  10687. result.preallocateStorage (bufferSize);
  10688. }
  10689. return empty;
  10690. }
  10691. int String::getIntValue() const throw()
  10692. {
  10693. return CharacterFunctions::getIntValue (text);
  10694. }
  10695. int String::getTrailingIntValue() const throw()
  10696. {
  10697. int n = 0;
  10698. int mult = 1;
  10699. const juce_wchar* t = text + length();
  10700. while (--t >= text)
  10701. {
  10702. const juce_wchar c = *t;
  10703. if (! CharacterFunctions::isDigit (c))
  10704. {
  10705. if (c == '-')
  10706. n = -n;
  10707. break;
  10708. }
  10709. n += mult * (c - '0');
  10710. mult *= 10;
  10711. }
  10712. return n;
  10713. }
  10714. int64 String::getLargeIntValue() const throw()
  10715. {
  10716. return CharacterFunctions::getInt64Value (text);
  10717. }
  10718. float String::getFloatValue() const throw()
  10719. {
  10720. return (float) CharacterFunctions::getDoubleValue (text);
  10721. }
  10722. double String::getDoubleValue() const throw()
  10723. {
  10724. return CharacterFunctions::getDoubleValue (text);
  10725. }
  10726. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10727. const String String::toHexString (const int number)
  10728. {
  10729. juce_wchar buffer[32];
  10730. juce_wchar* const end = buffer + 32;
  10731. juce_wchar* t = end;
  10732. *--t = 0;
  10733. unsigned int v = (unsigned int) number;
  10734. do
  10735. {
  10736. *--t = hexDigits [v & 15];
  10737. v >>= 4;
  10738. } while (v != 0);
  10739. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10740. }
  10741. const String String::toHexString (const int64 number)
  10742. {
  10743. juce_wchar buffer[32];
  10744. juce_wchar* const end = buffer + 32;
  10745. juce_wchar* t = end;
  10746. *--t = 0;
  10747. uint64 v = (uint64) number;
  10748. do
  10749. {
  10750. *--t = hexDigits [(int) (v & 15)];
  10751. v >>= 4;
  10752. } while (v != 0);
  10753. return String (t, (int) (((char*) end) - (char*) t));
  10754. }
  10755. const String String::toHexString (const short number)
  10756. {
  10757. return toHexString ((int) (unsigned short) number);
  10758. }
  10759. const String String::toHexString (const unsigned char* data,
  10760. const int size,
  10761. const int groupSize)
  10762. {
  10763. if (size <= 0)
  10764. return empty;
  10765. int numChars = (size * 2) + 2;
  10766. if (groupSize > 0)
  10767. numChars += size / groupSize;
  10768. String s ((size_t) numChars, (int) 0);
  10769. juce_wchar* d = s.text;
  10770. for (int i = 0; i < size; ++i)
  10771. {
  10772. *d++ = hexDigits [(*data) >> 4];
  10773. *d++ = hexDigits [(*data) & 0xf];
  10774. ++data;
  10775. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10776. *d++ = ' ';
  10777. }
  10778. *d = 0;
  10779. return s;
  10780. }
  10781. int String::getHexValue32() const throw()
  10782. {
  10783. int result = 0;
  10784. const juce_wchar* c = text;
  10785. for (;;)
  10786. {
  10787. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10788. if (hexValue >= 0)
  10789. result = (result << 4) | hexValue;
  10790. else if (*c == 0)
  10791. break;
  10792. ++c;
  10793. }
  10794. return result;
  10795. }
  10796. int64 String::getHexValue64() const throw()
  10797. {
  10798. int64 result = 0;
  10799. const juce_wchar* c = text;
  10800. for (;;)
  10801. {
  10802. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10803. if (hexValue >= 0)
  10804. result = (result << 4) | hexValue;
  10805. else if (*c == 0)
  10806. break;
  10807. ++c;
  10808. }
  10809. return result;
  10810. }
  10811. const String String::createStringFromData (const void* const data_, const int size)
  10812. {
  10813. const char* const data = static_cast <const char*> (data_);
  10814. if (size <= 0 || data == 0)
  10815. {
  10816. return empty;
  10817. }
  10818. else if (size < 2)
  10819. {
  10820. return charToString (data[0]);
  10821. }
  10822. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10823. || (data[0] == (char)-1 && data[1] == (char)-2))
  10824. {
  10825. // assume it's 16-bit unicode
  10826. const bool bigEndian = (data[0] == (char)-2);
  10827. const int numChars = size / 2 - 1;
  10828. String result;
  10829. result.preallocateStorage (numChars + 2);
  10830. const uint16* const src = (const uint16*) (data + 2);
  10831. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10832. if (bigEndian)
  10833. {
  10834. for (int i = 0; i < numChars; ++i)
  10835. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10836. }
  10837. else
  10838. {
  10839. for (int i = 0; i < numChars; ++i)
  10840. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10841. }
  10842. dst [numChars] = 0;
  10843. return result;
  10844. }
  10845. else
  10846. {
  10847. return String::fromUTF8 (data, size);
  10848. }
  10849. }
  10850. const char* String::toUTF8() const
  10851. {
  10852. if (isEmpty())
  10853. {
  10854. return reinterpret_cast <const char*> (text);
  10855. }
  10856. else
  10857. {
  10858. const int currentLen = length() + 1;
  10859. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10860. String* const mutableThis = const_cast <String*> (this);
  10861. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10862. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10863. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10864. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10865. #endif
  10866. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10867. return otherCopy;
  10868. }
  10869. }
  10870. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10871. {
  10872. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10873. int num = 0, index = 0;
  10874. for (;;)
  10875. {
  10876. const uint32 c = (uint32) text [index++];
  10877. if (c >= 0x80)
  10878. {
  10879. int numExtraBytes = 1;
  10880. if (c >= 0x800)
  10881. {
  10882. ++numExtraBytes;
  10883. if (c >= 0x10000)
  10884. {
  10885. ++numExtraBytes;
  10886. if (c >= 0x200000)
  10887. {
  10888. ++numExtraBytes;
  10889. if (c >= 0x4000000)
  10890. ++numExtraBytes;
  10891. }
  10892. }
  10893. }
  10894. if (buffer != 0)
  10895. {
  10896. if (num + numExtraBytes >= maxBufferSizeBytes)
  10897. {
  10898. buffer [num++] = 0;
  10899. break;
  10900. }
  10901. else
  10902. {
  10903. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10904. while (--numExtraBytes >= 0)
  10905. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10906. }
  10907. }
  10908. else
  10909. {
  10910. num += numExtraBytes + 1;
  10911. }
  10912. }
  10913. else
  10914. {
  10915. if (buffer != 0)
  10916. {
  10917. if (num + 1 >= maxBufferSizeBytes)
  10918. {
  10919. buffer [num++] = 0;
  10920. break;
  10921. }
  10922. buffer [num] = (uint8) c;
  10923. }
  10924. ++num;
  10925. }
  10926. if (c == 0)
  10927. break;
  10928. }
  10929. return num;
  10930. }
  10931. int String::getNumBytesAsUTF8() const throw()
  10932. {
  10933. int num = 0;
  10934. const juce_wchar* t = text;
  10935. for (;;)
  10936. {
  10937. const uint32 c = (uint32) *t;
  10938. if (c >= 0x80)
  10939. {
  10940. ++num;
  10941. if (c >= 0x800)
  10942. {
  10943. ++num;
  10944. if (c >= 0x10000)
  10945. {
  10946. ++num;
  10947. if (c >= 0x200000)
  10948. {
  10949. ++num;
  10950. if (c >= 0x4000000)
  10951. ++num;
  10952. }
  10953. }
  10954. }
  10955. }
  10956. else if (c == 0)
  10957. break;
  10958. ++num;
  10959. ++t;
  10960. }
  10961. return num;
  10962. }
  10963. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10964. {
  10965. if (buffer == 0)
  10966. return empty;
  10967. if (bufferSizeBytes < 0)
  10968. bufferSizeBytes = std::numeric_limits<int>::max();
  10969. size_t numBytes;
  10970. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10971. if (buffer [numBytes] == 0)
  10972. break;
  10973. String result ((size_t) numBytes + 1, (int) 0);
  10974. juce_wchar* dest = result.text;
  10975. size_t i = 0;
  10976. while (i < numBytes)
  10977. {
  10978. const char c = buffer [i++];
  10979. if (c < 0)
  10980. {
  10981. unsigned int mask = 0x7f;
  10982. int bit = 0x40;
  10983. int numExtraValues = 0;
  10984. while (bit != 0 && (c & bit) != 0)
  10985. {
  10986. bit >>= 1;
  10987. mask >>= 1;
  10988. ++numExtraValues;
  10989. }
  10990. int n = (mask & (unsigned char) c);
  10991. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10992. {
  10993. const char nextByte = buffer[i];
  10994. if ((nextByte & 0xc0) != 0x80)
  10995. break;
  10996. n <<= 6;
  10997. n |= (nextByte & 0x3f);
  10998. ++i;
  10999. }
  11000. *dest++ = (juce_wchar) n;
  11001. }
  11002. else
  11003. {
  11004. *dest++ = (juce_wchar) c;
  11005. }
  11006. }
  11007. *dest = 0;
  11008. return result;
  11009. }
  11010. const char* String::toCString() const
  11011. {
  11012. if (isEmpty())
  11013. {
  11014. return reinterpret_cast <const char*> (text);
  11015. }
  11016. else
  11017. {
  11018. const int len = length();
  11019. String* const mutableThis = const_cast <String*> (this);
  11020. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  11021. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  11022. CharacterFunctions::copy (otherCopy, text, len);
  11023. otherCopy [len] = 0;
  11024. return otherCopy;
  11025. }
  11026. }
  11027. #if JUCE_MSVC
  11028. #pragma warning (push)
  11029. #pragma warning (disable: 4514 4996)
  11030. #endif
  11031. int String::getNumBytesAsCString() const throw()
  11032. {
  11033. return (int) wcstombs (0, text, 0);
  11034. }
  11035. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  11036. {
  11037. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  11038. if (destBuffer != 0 && numBytes >= 0)
  11039. destBuffer [numBytes] = 0;
  11040. return numBytes;
  11041. }
  11042. #if JUCE_MSVC
  11043. #pragma warning (pop)
  11044. #endif
  11045. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  11046. {
  11047. jassert (destBuffer != 0 && maxCharsToCopy >= 0);
  11048. if (destBuffer != 0 && maxCharsToCopy >= 0)
  11049. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  11050. }
  11051. String::Concatenator::Concatenator (String& stringToAppendTo)
  11052. : result (stringToAppendTo),
  11053. nextIndex (stringToAppendTo.length())
  11054. {
  11055. }
  11056. String::Concatenator::~Concatenator()
  11057. {
  11058. }
  11059. void String::Concatenator::append (const String& s)
  11060. {
  11061. const int len = s.length();
  11062. if (len > 0)
  11063. {
  11064. result.preallocateStorage (nextIndex + len);
  11065. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  11066. nextIndex += len;
  11067. }
  11068. }
  11069. #if JUCE_UNIT_TESTS
  11070. class StringTests : public UnitTest
  11071. {
  11072. public:
  11073. StringTests() : UnitTest ("String class") {}
  11074. void runTest()
  11075. {
  11076. {
  11077. beginTest ("Basics");
  11078. expect (String().length() == 0);
  11079. expect (String() == String::empty);
  11080. String s1, s2 ("abcd");
  11081. expect (s1.isEmpty() && ! s1.isNotEmpty());
  11082. expect (s2.isNotEmpty() && ! s2.isEmpty());
  11083. expect (s2.length() == 4);
  11084. s1 = "abcd";
  11085. expect (s2 == s1 && s1 == s2);
  11086. expect (s1 == "abcd" && s1 == L"abcd");
  11087. expect (String ("abcd") == String (L"abcd"));
  11088. expect (String ("abcdefg", 4) == L"abcd");
  11089. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  11090. expect (String::charToString ('x') == "x");
  11091. expect (String::charToString (0) == String::empty);
  11092. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  11093. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  11094. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  11095. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  11096. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  11097. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  11098. expect (s1.indexOf (String::empty) == 0);
  11099. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  11100. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  11101. expect (s1.containsChar ('a') && ! s1.containsChar (0));
  11102. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  11103. }
  11104. {
  11105. beginTest ("Operations");
  11106. String s ("012345678");
  11107. expect (s.hashCode() != 0);
  11108. expect (s.hashCode64() != 0);
  11109. expect (s.hashCode() != (s + s).hashCode());
  11110. expect (s.hashCode64() != (s + s).hashCode64());
  11111. expect (s.compare (String ("012345678")) == 0);
  11112. expect (s.compare (String ("012345679")) < 0);
  11113. expect (s.compare (String ("012345676")) > 0);
  11114. expect (s.substring (2, 3) == String::charToString (s[2]));
  11115. expect (s.substring (0, 1) == String::charToString (s[0]));
  11116. expect (s.getLastCharacter() == s [s.length() - 1]);
  11117. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  11118. expect (s.substring (0, 3) == L"012");
  11119. expect (s.substring (0, 100) == s);
  11120. expect (s.substring (-1, 100) == s);
  11121. expect (s.substring (3) == "345678");
  11122. expect (s.indexOf (L"45") == 4);
  11123. expect (String ("444445").indexOf ("45") == 4);
  11124. expect (String ("444445").lastIndexOfChar ('4') == 4);
  11125. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  11126. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  11127. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  11128. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("Ab") == 6);
  11129. expect (s.indexOfChar (L'4') == 4);
  11130. expect (s + s == "012345678012345678");
  11131. expect (s.startsWith (s));
  11132. expect (s.startsWith (s.substring (0, 4)));
  11133. expect (s.startsWith (s.dropLastCharacters (4)));
  11134. expect (s.endsWith (s.substring (5)));
  11135. expect (s.endsWith (s));
  11136. expect (s.contains (s.substring (3, 6)));
  11137. expect (s.contains (s.substring (3)));
  11138. expect (s.startsWithChar (s[0]));
  11139. expect (s.endsWithChar (s.getLastCharacter()));
  11140. expect (s [s.length()] == 0);
  11141. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  11142. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  11143. String s2 ("123");
  11144. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  11145. s2 += "xyz";
  11146. expect (s2 == "1234567890xyz");
  11147. beginTest ("Numeric conversions");
  11148. expect (String::empty.getIntValue() == 0);
  11149. expect (String::empty.getDoubleValue() == 0.0);
  11150. expect (String::empty.getFloatValue() == 0.0f);
  11151. expect (s.getIntValue() == 12345678);
  11152. expect (s.getLargeIntValue() == (int64) 12345678);
  11153. expect (s.getDoubleValue() == 12345678.0);
  11154. expect (s.getFloatValue() == 12345678.0f);
  11155. expect (String (-1234).getIntValue() == -1234);
  11156. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  11157. expect (String (-1234.56).getDoubleValue() == -1234.56);
  11158. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  11159. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  11160. expect (s.getHexValue32() == 0x12345678);
  11161. expect (s.getHexValue64() == (int64) 0x12345678);
  11162. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11163. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11164. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  11165. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  11166. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  11167. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  11168. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  11169. beginTest ("Subsections");
  11170. String s3;
  11171. s3 = "abcdeFGHIJ";
  11172. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  11173. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  11174. expect (s3.containsIgnoreCase (s3.substring (3)));
  11175. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  11176. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  11177. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  11178. expect (s3.containsAnyOf (L"zzzFs"));
  11179. expect (s3.startsWith ("abcd"));
  11180. expect (s3.startsWithIgnoreCase (L"abCD"));
  11181. expect (s3.startsWith (String::empty));
  11182. expect (s3.startsWithChar ('a'));
  11183. expect (s3.endsWith (String ("HIJ")));
  11184. expect (s3.endsWithIgnoreCase (L"Hij"));
  11185. expect (s3.endsWith (String::empty));
  11186. expect (s3.endsWithChar (L'J'));
  11187. expect (s3.indexOf ("HIJ") == 7);
  11188. expect (s3.indexOf (L"HIJK") == -1);
  11189. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11190. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11191. String s4 (s3);
  11192. s4.append (String ("xyz123"), 3);
  11193. expect (s4 == s3 + "xyz");
  11194. expect (String (1234) < String (1235));
  11195. expect (String (1235) > String (1234));
  11196. expect (String (1234) >= String (1234));
  11197. expect (String (1234) <= String (1234));
  11198. expect (String (1235) >= String (1234));
  11199. expect (String (1234) <= String (1235));
  11200. String s5 ("word word2 word3");
  11201. expect (s5.containsWholeWord (String ("word2")));
  11202. expect (s5.indexOfWholeWord ("word2") == 5);
  11203. expect (s5.containsWholeWord (L"word"));
  11204. expect (s5.containsWholeWord ("word3"));
  11205. expect (s5.containsWholeWord (s5));
  11206. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11207. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11208. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11209. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11210. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11211. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11212. expect (s5.containsNonWhitespaceChars());
  11213. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11214. expect (s5.matchesWildcard (L"wor*", false));
  11215. expect (s5.matchesWildcard ("wOr*", true));
  11216. expect (s5.matchesWildcard (L"*word3", true));
  11217. expect (s5.matchesWildcard ("*word?", true));
  11218. expect (s5.matchesWildcard (L"Word*3", true));
  11219. expect (s5.fromFirstOccurrenceOf (String::empty, true, false) == s5);
  11220. expect (s5.fromFirstOccurrenceOf ("xword2", true, false) == s5.substring (100));
  11221. expect (s5.fromFirstOccurrenceOf (L"word2", true, false) == s5.substring (5));
  11222. expect (s5.fromFirstOccurrenceOf ("Word2", true, true) == s5.substring (5));
  11223. expect (s5.fromFirstOccurrenceOf ("word2", false, false) == s5.getLastCharacters (6));
  11224. expect (s5.fromFirstOccurrenceOf (L"Word2", false, true) == s5.getLastCharacters (6));
  11225. expect (s5.fromLastOccurrenceOf (String::empty, true, false) == s5);
  11226. expect (s5.fromLastOccurrenceOf (L"wordx", true, false) == s5);
  11227. expect (s5.fromLastOccurrenceOf ("word", true, false) == s5.getLastCharacters (5));
  11228. expect (s5.fromLastOccurrenceOf (L"worD", true, true) == s5.getLastCharacters (5));
  11229. expect (s5.fromLastOccurrenceOf ("word", false, false) == s5.getLastCharacters (1));
  11230. expect (s5.fromLastOccurrenceOf (L"worD", false, true) == s5.getLastCharacters (1));
  11231. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11232. expect (s5.upToFirstOccurrenceOf ("word4", true, false) == s5);
  11233. expect (s5.upToFirstOccurrenceOf (L"word2", true, false) == s5.substring (0, 10));
  11234. expect (s5.upToFirstOccurrenceOf ("Word2", true, true) == s5.substring (0, 10));
  11235. expect (s5.upToFirstOccurrenceOf (L"word2", false, false) == s5.substring (0, 5));
  11236. expect (s5.upToFirstOccurrenceOf ("Word2", false, true) == s5.substring (0, 5));
  11237. expect (s5.upToLastOccurrenceOf (String::empty, true, false) == s5);
  11238. expect (s5.upToLastOccurrenceOf ("zword", true, false) == s5);
  11239. expect (s5.upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11240. expect (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11241. expect (s5.upToLastOccurrenceOf ("Word", true, true) == s5.dropLastCharacters (1));
  11242. expect (s5.upToLastOccurrenceOf ("word", false, false) == s5.dropLastCharacters (5));
  11243. expect (s5.upToLastOccurrenceOf ("Word", false, true) == s5.dropLastCharacters (5));
  11244. expect (s5.replace ("word", L"xyz", false) == String ("xyz xyz2 xyz3"));
  11245. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11246. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11247. expect (s5.replace ("Word", "", true) == " 2 3");
  11248. expect (s5.replace ("Word2", L"xyz", true) == String ("word xyz word3"));
  11249. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11250. expect (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w') == s5);
  11251. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11252. expect (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo") == s5);
  11253. expect (s5.retainCharacters ("1wordxya") == String ("wordwordword"));
  11254. expect (s5.retainCharacters (String::empty).isEmpty());
  11255. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11256. expect (s5.removeCharacters (String::empty) == s5);
  11257. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11258. expect (s5.initialSectionNotContaining (String ("xyz ")) == String ("word"));
  11259. expect (! s5.isQuotedString());
  11260. expect (s5.quoted().isQuotedString());
  11261. expect (! s5.quoted().unquoted().isQuotedString());
  11262. expect (! String ("x'").isQuotedString());
  11263. expect (String ("'x").isQuotedString());
  11264. String s6 (" \t xyz \t\r\n");
  11265. expect (s6.trim() == String ("xyz"));
  11266. expect (s6.trim().trim() == "xyz");
  11267. expect (s5.trim() == s5);
  11268. expect (s6.trimStart().trimEnd() == s6.trim());
  11269. expect (s6.trimStart().trimEnd() == s6.trimEnd().trimStart());
  11270. expect (s6.trimStart().trimStart().trimEnd().trimEnd() == s6.trimEnd().trimStart());
  11271. expect (s6.trimStart() != s6.trimEnd());
  11272. expect (("\t\r\n " + s6 + "\t\n \r").trim() == s6.trim());
  11273. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11274. }
  11275. {
  11276. beginTest ("UTF8");
  11277. String s ("word word2 word3");
  11278. {
  11279. char buffer [100];
  11280. memset (buffer, 0xff, sizeof (buffer));
  11281. s.copyToUTF8 (buffer, 100);
  11282. expect (String::fromUTF8 (buffer, 100) == s);
  11283. juce_wchar bufferUnicode [100];
  11284. memset (bufferUnicode, 0xff, sizeof (bufferUnicode));
  11285. s.copyToUnicode (bufferUnicode, 100);
  11286. expect (String (bufferUnicode, 100) == s);
  11287. }
  11288. {
  11289. juce_wchar wideBuffer [50];
  11290. zerostruct (wideBuffer);
  11291. for (int i = 0; i < numElementsInArray (wideBuffer) - 1; ++i)
  11292. wideBuffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (std::numeric_limits<juce_wchar>::max() - 1));
  11293. String wide (wideBuffer);
  11294. expect (wide == (const juce_wchar*) wideBuffer);
  11295. expect (wide.length() == numElementsInArray (wideBuffer) - 1);
  11296. expect (String::fromUTF8 (wide.toUTF8()) == wide);
  11297. expect (String::fromUTF8 (wide.toUTF8()) == wideBuffer);
  11298. }
  11299. }
  11300. }
  11301. };
  11302. static StringTests stringUnitTests;
  11303. #endif
  11304. END_JUCE_NAMESPACE
  11305. /*** End of inlined file: juce_String.cpp ***/
  11306. /*** Start of inlined file: juce_StringArray.cpp ***/
  11307. BEGIN_JUCE_NAMESPACE
  11308. StringArray::StringArray() throw()
  11309. {
  11310. }
  11311. StringArray::StringArray (const StringArray& other)
  11312. : strings (other.strings)
  11313. {
  11314. }
  11315. StringArray::StringArray (const String& firstValue)
  11316. {
  11317. strings.add (firstValue);
  11318. }
  11319. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11320. const int numberOfStrings)
  11321. {
  11322. for (int i = 0; i < numberOfStrings; ++i)
  11323. strings.add (initialStrings [i]);
  11324. }
  11325. StringArray::StringArray (const char* const* const initialStrings,
  11326. const int numberOfStrings)
  11327. {
  11328. for (int i = 0; i < numberOfStrings; ++i)
  11329. strings.add (initialStrings [i]);
  11330. }
  11331. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11332. {
  11333. int i = 0;
  11334. while (initialStrings[i] != 0)
  11335. strings.add (initialStrings [i++]);
  11336. }
  11337. StringArray::StringArray (const char* const* const initialStrings)
  11338. {
  11339. int i = 0;
  11340. while (initialStrings[i] != 0)
  11341. strings.add (initialStrings [i++]);
  11342. }
  11343. StringArray& StringArray::operator= (const StringArray& other)
  11344. {
  11345. strings = other.strings;
  11346. return *this;
  11347. }
  11348. StringArray::~StringArray()
  11349. {
  11350. }
  11351. bool StringArray::operator== (const StringArray& other) const throw()
  11352. {
  11353. if (other.size() != size())
  11354. return false;
  11355. for (int i = size(); --i >= 0;)
  11356. if (other.strings.getReference(i) != strings.getReference(i))
  11357. return false;
  11358. return true;
  11359. }
  11360. bool StringArray::operator!= (const StringArray& other) const throw()
  11361. {
  11362. return ! operator== (other);
  11363. }
  11364. void StringArray::clear()
  11365. {
  11366. strings.clear();
  11367. }
  11368. const String& StringArray::operator[] (const int index) const throw()
  11369. {
  11370. if (((unsigned int) index) < (unsigned int) strings.size())
  11371. return strings.getReference (index);
  11372. return String::empty;
  11373. }
  11374. String& StringArray::getReference (const int index) throw()
  11375. {
  11376. jassert (((unsigned int) index) < (unsigned int) strings.size());
  11377. return strings.getReference (index);
  11378. }
  11379. void StringArray::add (const String& newString)
  11380. {
  11381. strings.add (newString);
  11382. }
  11383. void StringArray::insert (const int index, const String& newString)
  11384. {
  11385. strings.insert (index, newString);
  11386. }
  11387. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11388. {
  11389. if (! contains (newString, ignoreCase))
  11390. add (newString);
  11391. }
  11392. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11393. {
  11394. if (startIndex < 0)
  11395. {
  11396. jassertfalse;
  11397. startIndex = 0;
  11398. }
  11399. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11400. numElementsToAdd = otherArray.size() - startIndex;
  11401. while (--numElementsToAdd >= 0)
  11402. strings.add (otherArray.strings.getReference (startIndex++));
  11403. }
  11404. void StringArray::set (const int index, const String& newString)
  11405. {
  11406. strings.set (index, newString);
  11407. }
  11408. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11409. {
  11410. if (ignoreCase)
  11411. {
  11412. for (int i = size(); --i >= 0;)
  11413. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11414. return true;
  11415. }
  11416. else
  11417. {
  11418. for (int i = size(); --i >= 0;)
  11419. if (stringToLookFor == strings.getReference(i))
  11420. return true;
  11421. }
  11422. return false;
  11423. }
  11424. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11425. {
  11426. if (i < 0)
  11427. i = 0;
  11428. const int numElements = size();
  11429. if (ignoreCase)
  11430. {
  11431. while (i < numElements)
  11432. {
  11433. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11434. return i;
  11435. ++i;
  11436. }
  11437. }
  11438. else
  11439. {
  11440. while (i < numElements)
  11441. {
  11442. if (stringToLookFor == strings.getReference (i))
  11443. return i;
  11444. ++i;
  11445. }
  11446. }
  11447. return -1;
  11448. }
  11449. void StringArray::remove (const int index)
  11450. {
  11451. strings.remove (index);
  11452. }
  11453. void StringArray::removeString (const String& stringToRemove,
  11454. const bool ignoreCase)
  11455. {
  11456. if (ignoreCase)
  11457. {
  11458. for (int i = size(); --i >= 0;)
  11459. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11460. strings.remove (i);
  11461. }
  11462. else
  11463. {
  11464. for (int i = size(); --i >= 0;)
  11465. if (stringToRemove == strings.getReference (i))
  11466. strings.remove (i);
  11467. }
  11468. }
  11469. void StringArray::removeRange (int startIndex, int numberToRemove)
  11470. {
  11471. strings.removeRange (startIndex, numberToRemove);
  11472. }
  11473. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11474. {
  11475. if (removeWhitespaceStrings)
  11476. {
  11477. for (int i = size(); --i >= 0;)
  11478. if (! strings.getReference(i).containsNonWhitespaceChars())
  11479. strings.remove (i);
  11480. }
  11481. else
  11482. {
  11483. for (int i = size(); --i >= 0;)
  11484. if (strings.getReference(i).isEmpty())
  11485. strings.remove (i);
  11486. }
  11487. }
  11488. void StringArray::trim()
  11489. {
  11490. for (int i = size(); --i >= 0;)
  11491. {
  11492. String& s = strings.getReference(i);
  11493. s = s.trim();
  11494. }
  11495. }
  11496. class InternalStringArrayComparator_CaseSensitive
  11497. {
  11498. public:
  11499. static int compareElements (String& first, String& second) { return first.compare (second); }
  11500. };
  11501. class InternalStringArrayComparator_CaseInsensitive
  11502. {
  11503. public:
  11504. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11505. };
  11506. void StringArray::sort (const bool ignoreCase)
  11507. {
  11508. if (ignoreCase)
  11509. {
  11510. InternalStringArrayComparator_CaseInsensitive comp;
  11511. strings.sort (comp);
  11512. }
  11513. else
  11514. {
  11515. InternalStringArrayComparator_CaseSensitive comp;
  11516. strings.sort (comp);
  11517. }
  11518. }
  11519. void StringArray::move (const int currentIndex, int newIndex) throw()
  11520. {
  11521. strings.move (currentIndex, newIndex);
  11522. }
  11523. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11524. {
  11525. const int last = (numberToJoin < 0) ? size()
  11526. : jmin (size(), start + numberToJoin);
  11527. if (start < 0)
  11528. start = 0;
  11529. if (start >= last)
  11530. return String::empty;
  11531. if (start == last - 1)
  11532. return strings.getReference (start);
  11533. const int separatorLen = separator.length();
  11534. int charsNeeded = separatorLen * (last - start - 1);
  11535. for (int i = start; i < last; ++i)
  11536. charsNeeded += strings.getReference(i).length();
  11537. String result;
  11538. result.preallocateStorage (charsNeeded);
  11539. juce_wchar* dest = result;
  11540. while (start < last)
  11541. {
  11542. const String& s = strings.getReference (start);
  11543. const int len = s.length();
  11544. if (len > 0)
  11545. {
  11546. s.copyToUnicode (dest, len);
  11547. dest += len;
  11548. }
  11549. if (++start < last && separatorLen > 0)
  11550. {
  11551. separator.copyToUnicode (dest, separatorLen);
  11552. dest += separatorLen;
  11553. }
  11554. }
  11555. *dest = 0;
  11556. return result;
  11557. }
  11558. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11559. {
  11560. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11561. }
  11562. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11563. {
  11564. int num = 0;
  11565. if (text.isNotEmpty())
  11566. {
  11567. bool insideQuotes = false;
  11568. juce_wchar currentQuoteChar = 0;
  11569. int i = 0;
  11570. int tokenStart = 0;
  11571. for (;;)
  11572. {
  11573. const juce_wchar c = text[i];
  11574. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11575. if (! isBreak)
  11576. {
  11577. if (quoteCharacters.containsChar (c))
  11578. {
  11579. if (insideQuotes)
  11580. {
  11581. // only break out of quotes-mode if we find a matching quote to the
  11582. // one that we opened with..
  11583. if (currentQuoteChar == c)
  11584. insideQuotes = false;
  11585. }
  11586. else
  11587. {
  11588. insideQuotes = true;
  11589. currentQuoteChar = c;
  11590. }
  11591. }
  11592. }
  11593. else
  11594. {
  11595. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11596. ++num;
  11597. tokenStart = i + 1;
  11598. }
  11599. if (c == 0)
  11600. break;
  11601. ++i;
  11602. }
  11603. }
  11604. return num;
  11605. }
  11606. int StringArray::addLines (const String& sourceText)
  11607. {
  11608. int numLines = 0;
  11609. const juce_wchar* text = sourceText;
  11610. while (*text != 0)
  11611. {
  11612. const juce_wchar* const startOfLine = text;
  11613. while (*text != 0)
  11614. {
  11615. if (*text == '\r')
  11616. {
  11617. ++text;
  11618. if (*text == '\n')
  11619. ++text;
  11620. break;
  11621. }
  11622. if (*text == '\n')
  11623. {
  11624. ++text;
  11625. break;
  11626. }
  11627. ++text;
  11628. }
  11629. const juce_wchar* endOfLine = text;
  11630. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11631. --endOfLine;
  11632. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11633. --endOfLine;
  11634. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11635. ++numLines;
  11636. }
  11637. return numLines;
  11638. }
  11639. void StringArray::removeDuplicates (const bool ignoreCase)
  11640. {
  11641. for (int i = 0; i < size() - 1; ++i)
  11642. {
  11643. const String s (strings.getReference(i));
  11644. int nextIndex = i + 1;
  11645. for (;;)
  11646. {
  11647. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11648. if (nextIndex < 0)
  11649. break;
  11650. strings.remove (nextIndex);
  11651. }
  11652. }
  11653. }
  11654. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11655. const bool appendNumberToFirstInstance,
  11656. const juce_wchar* preNumberString,
  11657. const juce_wchar* postNumberString)
  11658. {
  11659. if (preNumberString == 0)
  11660. preNumberString = L" (";
  11661. if (postNumberString == 0)
  11662. postNumberString = L")";
  11663. for (int i = 0; i < size() - 1; ++i)
  11664. {
  11665. String& s = strings.getReference(i);
  11666. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11667. if (nextIndex >= 0)
  11668. {
  11669. const String original (s);
  11670. int number = 0;
  11671. if (appendNumberToFirstInstance)
  11672. s = original + preNumberString + String (++number) + postNumberString;
  11673. else
  11674. ++number;
  11675. while (nextIndex >= 0)
  11676. {
  11677. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11678. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11679. }
  11680. }
  11681. }
  11682. }
  11683. void StringArray::minimiseStorageOverheads()
  11684. {
  11685. strings.minimiseStorageOverheads();
  11686. }
  11687. END_JUCE_NAMESPACE
  11688. /*** End of inlined file: juce_StringArray.cpp ***/
  11689. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11690. BEGIN_JUCE_NAMESPACE
  11691. StringPairArray::StringPairArray (const bool ignoreCase_)
  11692. : ignoreCase (ignoreCase_)
  11693. {
  11694. }
  11695. StringPairArray::StringPairArray (const StringPairArray& other)
  11696. : keys (other.keys),
  11697. values (other.values),
  11698. ignoreCase (other.ignoreCase)
  11699. {
  11700. }
  11701. StringPairArray::~StringPairArray()
  11702. {
  11703. }
  11704. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11705. {
  11706. keys = other.keys;
  11707. values = other.values;
  11708. return *this;
  11709. }
  11710. bool StringPairArray::operator== (const StringPairArray& other) const
  11711. {
  11712. for (int i = keys.size(); --i >= 0;)
  11713. if (other [keys[i]] != values[i])
  11714. return false;
  11715. return true;
  11716. }
  11717. bool StringPairArray::operator!= (const StringPairArray& other) const
  11718. {
  11719. return ! operator== (other);
  11720. }
  11721. const String& StringPairArray::operator[] (const String& key) const
  11722. {
  11723. return values [keys.indexOf (key, ignoreCase)];
  11724. }
  11725. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11726. {
  11727. const int i = keys.indexOf (key, ignoreCase);
  11728. if (i >= 0)
  11729. return values[i];
  11730. return defaultReturnValue;
  11731. }
  11732. void StringPairArray::set (const String& key, const String& value)
  11733. {
  11734. const int i = keys.indexOf (key, ignoreCase);
  11735. if (i >= 0)
  11736. {
  11737. values.set (i, value);
  11738. }
  11739. else
  11740. {
  11741. keys.add (key);
  11742. values.add (value);
  11743. }
  11744. }
  11745. void StringPairArray::addArray (const StringPairArray& other)
  11746. {
  11747. for (int i = 0; i < other.size(); ++i)
  11748. set (other.keys[i], other.values[i]);
  11749. }
  11750. void StringPairArray::clear()
  11751. {
  11752. keys.clear();
  11753. values.clear();
  11754. }
  11755. void StringPairArray::remove (const String& key)
  11756. {
  11757. remove (keys.indexOf (key, ignoreCase));
  11758. }
  11759. void StringPairArray::remove (const int index)
  11760. {
  11761. keys.remove (index);
  11762. values.remove (index);
  11763. }
  11764. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11765. {
  11766. ignoreCase = shouldIgnoreCase;
  11767. }
  11768. const String StringPairArray::getDescription() const
  11769. {
  11770. String s;
  11771. for (int i = 0; i < keys.size(); ++i)
  11772. {
  11773. s << keys[i] << " = " << values[i];
  11774. if (i < keys.size())
  11775. s << ", ";
  11776. }
  11777. return s;
  11778. }
  11779. void StringPairArray::minimiseStorageOverheads()
  11780. {
  11781. keys.minimiseStorageOverheads();
  11782. values.minimiseStorageOverheads();
  11783. }
  11784. END_JUCE_NAMESPACE
  11785. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11786. /*** Start of inlined file: juce_StringPool.cpp ***/
  11787. BEGIN_JUCE_NAMESPACE
  11788. StringPool::StringPool() throw() {}
  11789. StringPool::~StringPool() {}
  11790. template <class StringType>
  11791. static const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11792. {
  11793. int start = 0;
  11794. int end = strings.size();
  11795. for (;;)
  11796. {
  11797. if (start >= end)
  11798. {
  11799. jassert (start <= end);
  11800. strings.insert (start, newString);
  11801. return strings.getReference (start);
  11802. }
  11803. else
  11804. {
  11805. const String& startString = strings.getReference (start);
  11806. if (startString == newString)
  11807. return startString;
  11808. const int halfway = (start + end) >> 1;
  11809. if (halfway == start)
  11810. {
  11811. if (startString.compare (newString) < 0)
  11812. ++start;
  11813. strings.insert (start, newString);
  11814. return strings.getReference (start);
  11815. }
  11816. const int comp = strings.getReference (halfway).compare (newString);
  11817. if (comp == 0)
  11818. return strings.getReference (halfway);
  11819. else if (comp < 0)
  11820. start = halfway;
  11821. else
  11822. end = halfway;
  11823. }
  11824. }
  11825. }
  11826. const juce_wchar* StringPool::getPooledString (const String& s)
  11827. {
  11828. if (s.isEmpty())
  11829. return String::empty;
  11830. return getPooledStringFromArray (strings, s);
  11831. }
  11832. const juce_wchar* StringPool::getPooledString (const char* const s)
  11833. {
  11834. if (s == 0 || *s == 0)
  11835. return String::empty;
  11836. return getPooledStringFromArray (strings, s);
  11837. }
  11838. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11839. {
  11840. if (s == 0 || *s == 0)
  11841. return String::empty;
  11842. return getPooledStringFromArray (strings, s);
  11843. }
  11844. int StringPool::size() const throw()
  11845. {
  11846. return strings.size();
  11847. }
  11848. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11849. {
  11850. return strings [index];
  11851. }
  11852. END_JUCE_NAMESPACE
  11853. /*** End of inlined file: juce_StringPool.cpp ***/
  11854. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11855. BEGIN_JUCE_NAMESPACE
  11856. XmlDocument::XmlDocument (const String& documentText)
  11857. : originalText (documentText),
  11858. ignoreEmptyTextElements (true)
  11859. {
  11860. }
  11861. XmlDocument::XmlDocument (const File& file)
  11862. : ignoreEmptyTextElements (true)
  11863. {
  11864. inputSource = new FileInputSource (file);
  11865. }
  11866. XmlDocument::~XmlDocument()
  11867. {
  11868. }
  11869. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11870. {
  11871. inputSource = newSource;
  11872. }
  11873. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11874. {
  11875. ignoreEmptyTextElements = shouldBeIgnored;
  11876. }
  11877. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  11878. {
  11879. return CharacterFunctions::isLetterOrDigit (c)
  11880. || c == '_' || c == '-' || c == ':' || c == '.';
  11881. }
  11882. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  11883. {
  11884. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  11885. : isXmlIdentifierCharSlow (c);
  11886. }
  11887. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11888. {
  11889. String textToParse (originalText);
  11890. if (textToParse.isEmpty() && inputSource != 0)
  11891. {
  11892. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11893. if (in != 0)
  11894. {
  11895. MemoryOutputStream data;
  11896. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11897. textToParse = data.toString();
  11898. if (! onlyReadOuterDocumentElement)
  11899. originalText = textToParse;
  11900. }
  11901. }
  11902. input = textToParse;
  11903. lastError = String::empty;
  11904. errorOccurred = false;
  11905. outOfData = false;
  11906. needToLoadDTD = true;
  11907. for (int i = 0; i < 128; ++i)
  11908. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  11909. if (textToParse.isEmpty())
  11910. {
  11911. lastError = "not enough input";
  11912. }
  11913. else
  11914. {
  11915. skipHeader();
  11916. if (input != 0)
  11917. {
  11918. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11919. if (! errorOccurred)
  11920. return result.release();
  11921. }
  11922. else
  11923. {
  11924. lastError = "incorrect xml header";
  11925. }
  11926. }
  11927. return 0;
  11928. }
  11929. const String& XmlDocument::getLastParseError() const throw()
  11930. {
  11931. return lastError;
  11932. }
  11933. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11934. {
  11935. lastError = desc;
  11936. errorOccurred = ! carryOn;
  11937. }
  11938. const String XmlDocument::getFileContents (const String& filename) const
  11939. {
  11940. if (inputSource != 0)
  11941. {
  11942. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11943. if (in != 0)
  11944. return in->readEntireStreamAsString();
  11945. }
  11946. return String::empty;
  11947. }
  11948. juce_wchar XmlDocument::readNextChar() throw()
  11949. {
  11950. if (*input != 0)
  11951. {
  11952. return *input++;
  11953. }
  11954. else
  11955. {
  11956. outOfData = true;
  11957. return 0;
  11958. }
  11959. }
  11960. int XmlDocument::findNextTokenLength() throw()
  11961. {
  11962. int len = 0;
  11963. juce_wchar c = *input;
  11964. while (isXmlIdentifierChar (c))
  11965. c = input [++len];
  11966. return len;
  11967. }
  11968. void XmlDocument::skipHeader()
  11969. {
  11970. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  11971. if (found != 0)
  11972. {
  11973. input = found;
  11974. input = CharacterFunctions::find (input, JUCE_T("?>"));
  11975. if (input == 0)
  11976. return;
  11977. input += 2;
  11978. }
  11979. skipNextWhiteSpace();
  11980. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  11981. if (docType == 0)
  11982. return;
  11983. input = docType + 9;
  11984. int n = 1;
  11985. while (n > 0)
  11986. {
  11987. const juce_wchar c = readNextChar();
  11988. if (outOfData)
  11989. return;
  11990. if (c == '<')
  11991. ++n;
  11992. else if (c == '>')
  11993. --n;
  11994. }
  11995. docType += 9;
  11996. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  11997. }
  11998. void XmlDocument::skipNextWhiteSpace()
  11999. {
  12000. for (;;)
  12001. {
  12002. juce_wchar c = *input;
  12003. while (CharacterFunctions::isWhitespace (c))
  12004. c = *++input;
  12005. if (c == 0)
  12006. {
  12007. outOfData = true;
  12008. break;
  12009. }
  12010. else if (c == '<')
  12011. {
  12012. if (input[1] == '!'
  12013. && input[2] == '-'
  12014. && input[3] == '-')
  12015. {
  12016. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  12017. if (closeComment == 0)
  12018. {
  12019. outOfData = true;
  12020. break;
  12021. }
  12022. input = closeComment + 3;
  12023. continue;
  12024. }
  12025. else if (input[1] == '?')
  12026. {
  12027. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  12028. if (closeBracket == 0)
  12029. {
  12030. outOfData = true;
  12031. break;
  12032. }
  12033. input = closeBracket + 2;
  12034. continue;
  12035. }
  12036. }
  12037. break;
  12038. }
  12039. }
  12040. void XmlDocument::readQuotedString (String& result)
  12041. {
  12042. const juce_wchar quote = readNextChar();
  12043. while (! outOfData)
  12044. {
  12045. const juce_wchar c = readNextChar();
  12046. if (c == quote)
  12047. break;
  12048. if (c == '&')
  12049. {
  12050. --input;
  12051. readEntity (result);
  12052. }
  12053. else
  12054. {
  12055. --input;
  12056. const juce_wchar* const start = input;
  12057. for (;;)
  12058. {
  12059. const juce_wchar character = *input;
  12060. if (character == quote)
  12061. {
  12062. result.append (start, (int) (input - start));
  12063. ++input;
  12064. return;
  12065. }
  12066. else if (character == '&')
  12067. {
  12068. result.append (start, (int) (input - start));
  12069. break;
  12070. }
  12071. else if (character == 0)
  12072. {
  12073. outOfData = true;
  12074. setLastError ("unmatched quotes", false);
  12075. break;
  12076. }
  12077. ++input;
  12078. }
  12079. }
  12080. }
  12081. }
  12082. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  12083. {
  12084. XmlElement* node = 0;
  12085. skipNextWhiteSpace();
  12086. if (outOfData)
  12087. return 0;
  12088. input = CharacterFunctions::find (input, JUCE_T("<"));
  12089. if (input != 0)
  12090. {
  12091. ++input;
  12092. int tagLen = findNextTokenLength();
  12093. if (tagLen == 0)
  12094. {
  12095. // no tag name - but allow for a gap after the '<' before giving an error
  12096. skipNextWhiteSpace();
  12097. tagLen = findNextTokenLength();
  12098. if (tagLen == 0)
  12099. {
  12100. setLastError ("tag name missing", false);
  12101. return node;
  12102. }
  12103. }
  12104. node = new XmlElement (String (input, tagLen));
  12105. input += tagLen;
  12106. XmlElement::XmlAttributeNode* lastAttribute = 0;
  12107. // look for attributes
  12108. for (;;)
  12109. {
  12110. skipNextWhiteSpace();
  12111. const juce_wchar c = *input;
  12112. // empty tag..
  12113. if (c == '/' && input[1] == '>')
  12114. {
  12115. input += 2;
  12116. break;
  12117. }
  12118. // parse the guts of the element..
  12119. if (c == '>')
  12120. {
  12121. ++input;
  12122. if (alsoParseSubElements)
  12123. readChildElements (node);
  12124. break;
  12125. }
  12126. // get an attribute..
  12127. if (isXmlIdentifierChar (c))
  12128. {
  12129. const int attNameLen = findNextTokenLength();
  12130. if (attNameLen > 0)
  12131. {
  12132. const juce_wchar* attNameStart = input;
  12133. input += attNameLen;
  12134. skipNextWhiteSpace();
  12135. if (readNextChar() == '=')
  12136. {
  12137. skipNextWhiteSpace();
  12138. const juce_wchar nextChar = *input;
  12139. if (nextChar == '"' || nextChar == '\'')
  12140. {
  12141. XmlElement::XmlAttributeNode* const newAtt
  12142. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  12143. String::empty);
  12144. readQuotedString (newAtt->value);
  12145. if (lastAttribute == 0)
  12146. node->attributes = newAtt;
  12147. else
  12148. lastAttribute->next = newAtt;
  12149. lastAttribute = newAtt;
  12150. continue;
  12151. }
  12152. }
  12153. }
  12154. }
  12155. else
  12156. {
  12157. if (! outOfData)
  12158. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  12159. }
  12160. break;
  12161. }
  12162. }
  12163. return node;
  12164. }
  12165. void XmlDocument::readChildElements (XmlElement* parent)
  12166. {
  12167. XmlElement* lastChildNode = 0;
  12168. for (;;)
  12169. {
  12170. const juce_wchar* const preWhitespaceInput = input;
  12171. skipNextWhiteSpace();
  12172. if (outOfData)
  12173. {
  12174. setLastError ("unmatched tags", false);
  12175. break;
  12176. }
  12177. if (*input == '<')
  12178. {
  12179. if (input[1] == '/')
  12180. {
  12181. // our close tag..
  12182. input = CharacterFunctions::find (input, JUCE_T(">"));
  12183. ++input;
  12184. break;
  12185. }
  12186. else if (input[1] == '!'
  12187. && input[2] == '['
  12188. && input[3] == 'C'
  12189. && input[4] == 'D'
  12190. && input[5] == 'A'
  12191. && input[6] == 'T'
  12192. && input[7] == 'A'
  12193. && input[8] == '[')
  12194. {
  12195. input += 9;
  12196. const juce_wchar* const inputStart = input;
  12197. int len = 0;
  12198. for (;;)
  12199. {
  12200. if (*input == 0)
  12201. {
  12202. setLastError ("unterminated CDATA section", false);
  12203. outOfData = true;
  12204. break;
  12205. }
  12206. else if (input[0] == ']'
  12207. && input[1] == ']'
  12208. && input[2] == '>')
  12209. {
  12210. input += 3;
  12211. break;
  12212. }
  12213. ++input;
  12214. ++len;
  12215. }
  12216. XmlElement* const e = XmlElement::createTextElement (String (inputStart, len));
  12217. if (lastChildNode != 0)
  12218. lastChildNode->nextElement = e;
  12219. else
  12220. parent->addChildElement (e);
  12221. lastChildNode = e;
  12222. }
  12223. else
  12224. {
  12225. // this is some other element, so parse and add it..
  12226. XmlElement* const n = readNextElement (true);
  12227. if (n != 0)
  12228. {
  12229. if (lastChildNode == 0)
  12230. parent->addChildElement (n);
  12231. else
  12232. lastChildNode->nextElement = n;
  12233. lastChildNode = n;
  12234. }
  12235. else
  12236. {
  12237. return;
  12238. }
  12239. }
  12240. }
  12241. else // must be a character block
  12242. {
  12243. input = preWhitespaceInput; // roll back to include the leading whitespace
  12244. String textElementContent;
  12245. for (;;)
  12246. {
  12247. const juce_wchar c = *input;
  12248. if (c == '<')
  12249. break;
  12250. if (c == 0)
  12251. {
  12252. setLastError ("unmatched tags", false);
  12253. outOfData = true;
  12254. return;
  12255. }
  12256. if (c == '&')
  12257. {
  12258. String entity;
  12259. readEntity (entity);
  12260. if (entity.startsWithChar ('<') && entity [1] != 0)
  12261. {
  12262. const juce_wchar* const oldInput = input;
  12263. const bool oldOutOfData = outOfData;
  12264. input = entity;
  12265. outOfData = false;
  12266. for (;;)
  12267. {
  12268. XmlElement* const n = readNextElement (true);
  12269. if (n == 0)
  12270. break;
  12271. if (lastChildNode == 0)
  12272. parent->addChildElement (n);
  12273. else
  12274. lastChildNode->nextElement = n;
  12275. lastChildNode = n;
  12276. }
  12277. input = oldInput;
  12278. outOfData = oldOutOfData;
  12279. }
  12280. else
  12281. {
  12282. textElementContent += entity;
  12283. }
  12284. }
  12285. else
  12286. {
  12287. const juce_wchar* start = input;
  12288. int len = 0;
  12289. for (;;)
  12290. {
  12291. const juce_wchar nextChar = *input;
  12292. if (nextChar == '<' || nextChar == '&')
  12293. {
  12294. break;
  12295. }
  12296. else if (nextChar == 0)
  12297. {
  12298. setLastError ("unmatched tags", false);
  12299. outOfData = true;
  12300. return;
  12301. }
  12302. ++input;
  12303. ++len;
  12304. }
  12305. textElementContent.append (start, len);
  12306. }
  12307. }
  12308. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12309. {
  12310. XmlElement* const textElement = XmlElement::createTextElement (textElementContent);
  12311. if (lastChildNode != 0)
  12312. lastChildNode->nextElement = textElement;
  12313. else
  12314. parent->addChildElement (textElement);
  12315. lastChildNode = textElement;
  12316. }
  12317. }
  12318. }
  12319. }
  12320. void XmlDocument::readEntity (String& result)
  12321. {
  12322. // skip over the ampersand
  12323. ++input;
  12324. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  12325. {
  12326. input += 4;
  12327. result += '&';
  12328. }
  12329. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  12330. {
  12331. input += 5;
  12332. result += '"';
  12333. }
  12334. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  12335. {
  12336. input += 5;
  12337. result += '\'';
  12338. }
  12339. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  12340. {
  12341. input += 3;
  12342. result += '<';
  12343. }
  12344. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  12345. {
  12346. input += 3;
  12347. result += '>';
  12348. }
  12349. else if (*input == '#')
  12350. {
  12351. int charCode = 0;
  12352. ++input;
  12353. if (*input == 'x' || *input == 'X')
  12354. {
  12355. ++input;
  12356. int numChars = 0;
  12357. while (input[0] != ';')
  12358. {
  12359. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12360. if (hexValue < 0 || ++numChars > 8)
  12361. {
  12362. setLastError ("illegal escape sequence", true);
  12363. break;
  12364. }
  12365. charCode = (charCode << 4) | hexValue;
  12366. ++input;
  12367. }
  12368. ++input;
  12369. }
  12370. else if (input[0] >= '0' && input[0] <= '9')
  12371. {
  12372. int numChars = 0;
  12373. while (input[0] != ';')
  12374. {
  12375. if (++numChars > 12)
  12376. {
  12377. setLastError ("illegal escape sequence", true);
  12378. break;
  12379. }
  12380. charCode = charCode * 10 + (input[0] - '0');
  12381. ++input;
  12382. }
  12383. ++input;
  12384. }
  12385. else
  12386. {
  12387. setLastError ("illegal escape sequence", true);
  12388. result += '&';
  12389. return;
  12390. }
  12391. result << (juce_wchar) charCode;
  12392. }
  12393. else
  12394. {
  12395. const juce_wchar* const entityNameStart = input;
  12396. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  12397. if (closingSemiColon == 0)
  12398. {
  12399. outOfData = true;
  12400. result += '&';
  12401. }
  12402. else
  12403. {
  12404. input = closingSemiColon + 1;
  12405. result += expandExternalEntity (String (entityNameStart,
  12406. (int) (closingSemiColon - entityNameStart)));
  12407. }
  12408. }
  12409. }
  12410. const String XmlDocument::expandEntity (const String& ent)
  12411. {
  12412. if (ent.equalsIgnoreCase ("amp"))
  12413. return String::charToString ('&');
  12414. if (ent.equalsIgnoreCase ("quot"))
  12415. return String::charToString ('"');
  12416. if (ent.equalsIgnoreCase ("apos"))
  12417. return String::charToString ('\'');
  12418. if (ent.equalsIgnoreCase ("lt"))
  12419. return String::charToString ('<');
  12420. if (ent.equalsIgnoreCase ("gt"))
  12421. return String::charToString ('>');
  12422. if (ent[0] == '#')
  12423. {
  12424. if (ent[1] == 'x' || ent[1] == 'X')
  12425. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12426. if (ent[1] >= '0' && ent[1] <= '9')
  12427. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12428. setLastError ("illegal escape sequence", false);
  12429. return String::charToString ('&');
  12430. }
  12431. return expandExternalEntity (ent);
  12432. }
  12433. const String XmlDocument::expandExternalEntity (const String& entity)
  12434. {
  12435. if (needToLoadDTD)
  12436. {
  12437. if (dtdText.isNotEmpty())
  12438. {
  12439. dtdText = dtdText.trimCharactersAtEnd (">");
  12440. tokenisedDTD.addTokens (dtdText, true);
  12441. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12442. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12443. {
  12444. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12445. tokenisedDTD.clear();
  12446. tokenisedDTD.addTokens (getFileContents (fn), true);
  12447. }
  12448. else
  12449. {
  12450. tokenisedDTD.clear();
  12451. const int openBracket = dtdText.indexOfChar ('[');
  12452. if (openBracket > 0)
  12453. {
  12454. const int closeBracket = dtdText.lastIndexOfChar (']');
  12455. if (closeBracket > openBracket)
  12456. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12457. closeBracket), true);
  12458. }
  12459. }
  12460. for (int i = tokenisedDTD.size(); --i >= 0;)
  12461. {
  12462. if (tokenisedDTD[i].startsWithChar ('%')
  12463. && tokenisedDTD[i].endsWithChar (';'))
  12464. {
  12465. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12466. StringArray newToks;
  12467. newToks.addTokens (parsed, true);
  12468. tokenisedDTD.remove (i);
  12469. for (int j = newToks.size(); --j >= 0;)
  12470. tokenisedDTD.insert (i, newToks[j]);
  12471. }
  12472. }
  12473. }
  12474. needToLoadDTD = false;
  12475. }
  12476. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12477. {
  12478. if (tokenisedDTD[i] == entity)
  12479. {
  12480. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12481. {
  12482. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12483. // check for sub-entities..
  12484. int ampersand = ent.indexOfChar ('&');
  12485. while (ampersand >= 0)
  12486. {
  12487. const int semiColon = ent.indexOf (i + 1, ";");
  12488. if (semiColon < 0)
  12489. {
  12490. setLastError ("entity without terminating semi-colon", false);
  12491. break;
  12492. }
  12493. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12494. ent = ent.substring (0, ampersand)
  12495. + resolved
  12496. + ent.substring (semiColon + 1);
  12497. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12498. }
  12499. return ent;
  12500. }
  12501. }
  12502. }
  12503. setLastError ("unknown entity", true);
  12504. return entity;
  12505. }
  12506. const String XmlDocument::getParameterEntity (const String& entity)
  12507. {
  12508. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12509. {
  12510. if (tokenisedDTD[i] == entity)
  12511. {
  12512. if (tokenisedDTD [i - 1] == "%"
  12513. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12514. {
  12515. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12516. if (ent.equalsIgnoreCase ("system"))
  12517. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12518. else
  12519. return ent.trim().unquoted();
  12520. }
  12521. }
  12522. }
  12523. return entity;
  12524. }
  12525. END_JUCE_NAMESPACE
  12526. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12527. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12528. BEGIN_JUCE_NAMESPACE
  12529. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12530. : name (other.name),
  12531. value (other.value),
  12532. next (0)
  12533. {
  12534. }
  12535. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12536. : name (name_),
  12537. value (value_),
  12538. next (0)
  12539. {
  12540. }
  12541. XmlElement::XmlElement (const String& tagName_) throw()
  12542. : tagName (tagName_),
  12543. firstChildElement (0),
  12544. nextElement (0),
  12545. attributes (0)
  12546. {
  12547. // the tag name mustn't be empty, or it'll look like a text element!
  12548. jassert (tagName_.containsNonWhitespaceChars())
  12549. // The tag can't contain spaces or other characters that would create invalid XML!
  12550. jassert (! tagName_.containsAnyOf (" <>/&"));
  12551. }
  12552. XmlElement::XmlElement (int /*dummy*/) throw()
  12553. : firstChildElement (0),
  12554. nextElement (0),
  12555. attributes (0)
  12556. {
  12557. }
  12558. XmlElement::XmlElement (const XmlElement& other)
  12559. : tagName (other.tagName),
  12560. firstChildElement (0),
  12561. nextElement (0),
  12562. attributes (0)
  12563. {
  12564. copyChildrenAndAttributesFrom (other);
  12565. }
  12566. XmlElement& XmlElement::operator= (const XmlElement& other)
  12567. {
  12568. if (this != &other)
  12569. {
  12570. removeAllAttributes();
  12571. deleteAllChildElements();
  12572. tagName = other.tagName;
  12573. copyChildrenAndAttributesFrom (other);
  12574. }
  12575. return *this;
  12576. }
  12577. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12578. {
  12579. XmlElement* child = other.firstChildElement;
  12580. XmlElement* lastChild = 0;
  12581. while (child != 0)
  12582. {
  12583. XmlElement* const copiedChild = new XmlElement (*child);
  12584. if (lastChild != 0)
  12585. lastChild->nextElement = copiedChild;
  12586. else
  12587. firstChildElement = copiedChild;
  12588. lastChild = copiedChild;
  12589. child = child->nextElement;
  12590. }
  12591. const XmlAttributeNode* att = other.attributes;
  12592. XmlAttributeNode* lastAtt = 0;
  12593. while (att != 0)
  12594. {
  12595. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  12596. if (lastAtt != 0)
  12597. lastAtt->next = newAtt;
  12598. else
  12599. attributes = newAtt;
  12600. lastAtt = newAtt;
  12601. att = att->next;
  12602. }
  12603. }
  12604. XmlElement::~XmlElement() throw()
  12605. {
  12606. XmlElement* child = firstChildElement;
  12607. while (child != 0)
  12608. {
  12609. XmlElement* const nextChild = child->nextElement;
  12610. delete child;
  12611. child = nextChild;
  12612. }
  12613. XmlAttributeNode* att = attributes;
  12614. while (att != 0)
  12615. {
  12616. XmlAttributeNode* const nextAtt = att->next;
  12617. delete att;
  12618. att = nextAtt;
  12619. }
  12620. }
  12621. namespace XmlOutputFunctions
  12622. {
  12623. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12624. {
  12625. if ((character >= 'a' && character <= 'z')
  12626. || (character >= 'A' && character <= 'Z')
  12627. || (character >= '0' && character <= '9'))
  12628. return true;
  12629. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12630. do
  12631. {
  12632. if (((juce_wchar) (uint8) *t) == character)
  12633. return true;
  12634. }
  12635. while (*++t != 0);
  12636. return false;
  12637. }
  12638. static void generateLegalCharConstants()
  12639. {
  12640. uint8 n[32];
  12641. zerostruct (n);
  12642. for (int i = 0; i < 256; ++i)
  12643. if (isLegalXmlCharSlow (i))
  12644. n[i >> 3] |= (1 << (i & 7));
  12645. String s;
  12646. for (int i = 0; i < 32; ++i)
  12647. s << (int) n[i] << ", ";
  12648. DBG (s);
  12649. }*/
  12650. static bool isLegalXmlChar (const uint32 c) throw()
  12651. {
  12652. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12653. return c < sizeof (legalChars) * 8
  12654. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12655. }
  12656. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12657. {
  12658. const juce_wchar* t = text;
  12659. for (;;)
  12660. {
  12661. const juce_wchar character = *t++;
  12662. if (character == 0)
  12663. break;
  12664. if (isLegalXmlChar ((uint32) character))
  12665. {
  12666. outputStream << (char) character;
  12667. }
  12668. else
  12669. {
  12670. switch (character)
  12671. {
  12672. case '&': outputStream << "&amp;"; break;
  12673. case '"': outputStream << "&quot;"; break;
  12674. case '>': outputStream << "&gt;"; break;
  12675. case '<': outputStream << "&lt;"; break;
  12676. case '\n':
  12677. if (changeNewLines)
  12678. outputStream << "&#10;";
  12679. else
  12680. outputStream << (char) character;
  12681. break;
  12682. case '\r':
  12683. if (changeNewLines)
  12684. outputStream << "&#13;";
  12685. else
  12686. outputStream << (char) character;
  12687. break;
  12688. default:
  12689. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12690. break;
  12691. }
  12692. }
  12693. }
  12694. }
  12695. static void writeSpaces (OutputStream& out, int numSpaces)
  12696. {
  12697. if (numSpaces > 0)
  12698. {
  12699. const char blanks[] = " ";
  12700. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12701. while (numSpaces > blankSize)
  12702. {
  12703. out.write (blanks, blankSize);
  12704. numSpaces -= blankSize;
  12705. }
  12706. out.write (blanks, numSpaces);
  12707. }
  12708. }
  12709. static void writeNewLine (OutputStream& out)
  12710. {
  12711. out.write ("\r\n", 2);
  12712. }
  12713. }
  12714. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12715. const int indentationLevel,
  12716. const int lineWrapLength) const
  12717. {
  12718. using namespace XmlOutputFunctions;
  12719. writeSpaces (outputStream, indentationLevel);
  12720. if (! isTextElement())
  12721. {
  12722. outputStream.writeByte ('<');
  12723. outputStream << tagName;
  12724. {
  12725. const int attIndent = indentationLevel + tagName.length() + 1;
  12726. int lineLen = 0;
  12727. const XmlAttributeNode* att = attributes;
  12728. while (att != 0)
  12729. {
  12730. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12731. {
  12732. writeNewLine (outputStream);
  12733. writeSpaces (outputStream, attIndent);
  12734. lineLen = 0;
  12735. }
  12736. const int64 startPos = outputStream.getPosition();
  12737. outputStream.writeByte (' ');
  12738. outputStream << att->name;
  12739. outputStream.write ("=\"", 2);
  12740. escapeIllegalXmlChars (outputStream, att->value, true);
  12741. outputStream.writeByte ('"');
  12742. lineLen += (int) (outputStream.getPosition() - startPos);
  12743. att = att->next;
  12744. }
  12745. }
  12746. if (firstChildElement != 0)
  12747. {
  12748. outputStream.writeByte ('>');
  12749. XmlElement* child = firstChildElement;
  12750. bool lastWasTextNode = false;
  12751. while (child != 0)
  12752. {
  12753. if (child->isTextElement())
  12754. {
  12755. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12756. lastWasTextNode = true;
  12757. }
  12758. else
  12759. {
  12760. if (indentationLevel >= 0 && ! lastWasTextNode)
  12761. writeNewLine (outputStream);
  12762. child->writeElementAsText (outputStream,
  12763. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12764. lastWasTextNode = false;
  12765. }
  12766. child = child->nextElement;
  12767. }
  12768. if (indentationLevel >= 0 && ! lastWasTextNode)
  12769. {
  12770. writeNewLine (outputStream);
  12771. writeSpaces (outputStream, indentationLevel);
  12772. }
  12773. outputStream.write ("</", 2);
  12774. outputStream << tagName;
  12775. outputStream.writeByte ('>');
  12776. }
  12777. else
  12778. {
  12779. outputStream.write ("/>", 2);
  12780. }
  12781. }
  12782. else
  12783. {
  12784. escapeIllegalXmlChars (outputStream, getText(), false);
  12785. }
  12786. }
  12787. const String XmlElement::createDocument (const String& dtdToUse,
  12788. const bool allOnOneLine,
  12789. const bool includeXmlHeader,
  12790. const String& encodingType,
  12791. const int lineWrapLength) const
  12792. {
  12793. MemoryOutputStream mem (2048);
  12794. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12795. return mem.toUTF8();
  12796. }
  12797. void XmlElement::writeToStream (OutputStream& output,
  12798. const String& dtdToUse,
  12799. const bool allOnOneLine,
  12800. const bool includeXmlHeader,
  12801. const String& encodingType,
  12802. const int lineWrapLength) const
  12803. {
  12804. using namespace XmlOutputFunctions;
  12805. if (includeXmlHeader)
  12806. {
  12807. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12808. if (allOnOneLine)
  12809. {
  12810. output.writeByte (' ');
  12811. }
  12812. else
  12813. {
  12814. writeNewLine (output);
  12815. writeNewLine (output);
  12816. }
  12817. }
  12818. if (dtdToUse.isNotEmpty())
  12819. {
  12820. output << dtdToUse;
  12821. if (allOnOneLine)
  12822. output.writeByte (' ');
  12823. else
  12824. writeNewLine (output);
  12825. }
  12826. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12827. if (! allOnOneLine)
  12828. writeNewLine (output);
  12829. }
  12830. bool XmlElement::writeToFile (const File& file,
  12831. const String& dtdToUse,
  12832. const String& encodingType,
  12833. const int lineWrapLength) const
  12834. {
  12835. if (file.hasWriteAccess())
  12836. {
  12837. TemporaryFile tempFile (file);
  12838. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12839. if (out != 0)
  12840. {
  12841. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12842. out = 0;
  12843. return tempFile.overwriteTargetFileWithTemporary();
  12844. }
  12845. }
  12846. return false;
  12847. }
  12848. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12849. {
  12850. #if JUCE_DEBUG
  12851. // if debugging, check that the case is actually the same, because
  12852. // valid xml is case-sensitive, and although this lets it pass, it's
  12853. // better not to..
  12854. if (tagName.equalsIgnoreCase (tagNameWanted))
  12855. {
  12856. jassert (tagName == tagNameWanted);
  12857. return true;
  12858. }
  12859. else
  12860. {
  12861. return false;
  12862. }
  12863. #else
  12864. return tagName.equalsIgnoreCase (tagNameWanted);
  12865. #endif
  12866. }
  12867. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12868. {
  12869. XmlElement* e = nextElement;
  12870. while (e != 0 && ! e->hasTagName (requiredTagName))
  12871. e = e->nextElement;
  12872. return e;
  12873. }
  12874. int XmlElement::getNumAttributes() const throw()
  12875. {
  12876. const XmlAttributeNode* att = attributes;
  12877. int count = 0;
  12878. while (att != 0)
  12879. {
  12880. att = att->next;
  12881. ++count;
  12882. }
  12883. return count;
  12884. }
  12885. const String& XmlElement::getAttributeName (const int index) const throw()
  12886. {
  12887. const XmlAttributeNode* att = attributes;
  12888. int count = 0;
  12889. while (att != 0)
  12890. {
  12891. if (count == index)
  12892. return att->name;
  12893. att = att->next;
  12894. ++count;
  12895. }
  12896. return String::empty;
  12897. }
  12898. const String& XmlElement::getAttributeValue (const int index) const throw()
  12899. {
  12900. const XmlAttributeNode* att = attributes;
  12901. int count = 0;
  12902. while (att != 0)
  12903. {
  12904. if (count == index)
  12905. return att->value;
  12906. att = att->next;
  12907. ++count;
  12908. }
  12909. return String::empty;
  12910. }
  12911. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12912. {
  12913. const XmlAttributeNode* att = attributes;
  12914. while (att != 0)
  12915. {
  12916. if (att->name.equalsIgnoreCase (attributeName))
  12917. return true;
  12918. att = att->next;
  12919. }
  12920. return false;
  12921. }
  12922. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12923. {
  12924. const XmlAttributeNode* att = attributes;
  12925. while (att != 0)
  12926. {
  12927. if (att->name.equalsIgnoreCase (attributeName))
  12928. return att->value;
  12929. att = att->next;
  12930. }
  12931. return String::empty;
  12932. }
  12933. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12934. {
  12935. const XmlAttributeNode* att = attributes;
  12936. while (att != 0)
  12937. {
  12938. if (att->name.equalsIgnoreCase (attributeName))
  12939. return att->value;
  12940. att = att->next;
  12941. }
  12942. return defaultReturnValue;
  12943. }
  12944. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12945. {
  12946. const XmlAttributeNode* att = attributes;
  12947. while (att != 0)
  12948. {
  12949. if (att->name.equalsIgnoreCase (attributeName))
  12950. return att->value.getIntValue();
  12951. att = att->next;
  12952. }
  12953. return defaultReturnValue;
  12954. }
  12955. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12956. {
  12957. const XmlAttributeNode* att = attributes;
  12958. while (att != 0)
  12959. {
  12960. if (att->name.equalsIgnoreCase (attributeName))
  12961. return att->value.getDoubleValue();
  12962. att = att->next;
  12963. }
  12964. return defaultReturnValue;
  12965. }
  12966. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12967. {
  12968. const XmlAttributeNode* att = attributes;
  12969. while (att != 0)
  12970. {
  12971. if (att->name.equalsIgnoreCase (attributeName))
  12972. {
  12973. juce_wchar firstChar = att->value[0];
  12974. if (CharacterFunctions::isWhitespace (firstChar))
  12975. firstChar = att->value.trimStart() [0];
  12976. return firstChar == '1'
  12977. || firstChar == 't'
  12978. || firstChar == 'y'
  12979. || firstChar == 'T'
  12980. || firstChar == 'Y';
  12981. }
  12982. att = att->next;
  12983. }
  12984. return defaultReturnValue;
  12985. }
  12986. bool XmlElement::compareAttribute (const String& attributeName,
  12987. const String& stringToCompareAgainst,
  12988. const bool ignoreCase) const throw()
  12989. {
  12990. const XmlAttributeNode* att = attributes;
  12991. while (att != 0)
  12992. {
  12993. if (att->name.equalsIgnoreCase (attributeName))
  12994. {
  12995. if (ignoreCase)
  12996. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  12997. else
  12998. return att->value == stringToCompareAgainst;
  12999. }
  13000. att = att->next;
  13001. }
  13002. return false;
  13003. }
  13004. void XmlElement::setAttribute (const String& attributeName, const String& value)
  13005. {
  13006. #if JUCE_DEBUG
  13007. // check the identifier being passed in is legal..
  13008. const juce_wchar* t = attributeName;
  13009. while (*t != 0)
  13010. {
  13011. jassert (CharacterFunctions::isLetterOrDigit (*t)
  13012. || *t == '_'
  13013. || *t == '-'
  13014. || *t == ':');
  13015. ++t;
  13016. }
  13017. #endif
  13018. if (attributes == 0)
  13019. {
  13020. attributes = new XmlAttributeNode (attributeName, value);
  13021. }
  13022. else
  13023. {
  13024. XmlAttributeNode* att = attributes;
  13025. for (;;)
  13026. {
  13027. if (att->name.equalsIgnoreCase (attributeName))
  13028. {
  13029. att->value = value;
  13030. break;
  13031. }
  13032. else if (att->next == 0)
  13033. {
  13034. att->next = new XmlAttributeNode (attributeName, value);
  13035. break;
  13036. }
  13037. att = att->next;
  13038. }
  13039. }
  13040. }
  13041. void XmlElement::setAttribute (const String& attributeName, const int number)
  13042. {
  13043. setAttribute (attributeName, String (number));
  13044. }
  13045. void XmlElement::setAttribute (const String& attributeName, const double number)
  13046. {
  13047. setAttribute (attributeName, String (number));
  13048. }
  13049. void XmlElement::removeAttribute (const String& attributeName) throw()
  13050. {
  13051. XmlAttributeNode* att = attributes;
  13052. XmlAttributeNode* lastAtt = 0;
  13053. while (att != 0)
  13054. {
  13055. if (att->name.equalsIgnoreCase (attributeName))
  13056. {
  13057. if (lastAtt == 0)
  13058. attributes = att->next;
  13059. else
  13060. lastAtt->next = att->next;
  13061. delete att;
  13062. break;
  13063. }
  13064. lastAtt = att;
  13065. att = att->next;
  13066. }
  13067. }
  13068. void XmlElement::removeAllAttributes() throw()
  13069. {
  13070. while (attributes != 0)
  13071. {
  13072. XmlAttributeNode* const nextAtt = attributes->next;
  13073. delete attributes;
  13074. attributes = nextAtt;
  13075. }
  13076. }
  13077. int XmlElement::getNumChildElements() const throw()
  13078. {
  13079. int count = 0;
  13080. const XmlElement* child = firstChildElement;
  13081. while (child != 0)
  13082. {
  13083. ++count;
  13084. child = child->nextElement;
  13085. }
  13086. return count;
  13087. }
  13088. XmlElement* XmlElement::getChildElement (const int index) const throw()
  13089. {
  13090. int count = 0;
  13091. XmlElement* child = firstChildElement;
  13092. while (child != 0 && count < index)
  13093. {
  13094. child = child->nextElement;
  13095. ++count;
  13096. }
  13097. return child;
  13098. }
  13099. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  13100. {
  13101. XmlElement* child = firstChildElement;
  13102. while (child != 0)
  13103. {
  13104. if (child->hasTagName (childName))
  13105. break;
  13106. child = child->nextElement;
  13107. }
  13108. return child;
  13109. }
  13110. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  13111. {
  13112. if (newNode != 0)
  13113. {
  13114. if (firstChildElement == 0)
  13115. {
  13116. firstChildElement = newNode;
  13117. }
  13118. else
  13119. {
  13120. XmlElement* child = firstChildElement;
  13121. while (child->nextElement != 0)
  13122. child = child->nextElement;
  13123. child->nextElement = newNode;
  13124. // if this is non-zero, then something's probably
  13125. // gone wrong..
  13126. jassert (newNode->nextElement == 0);
  13127. }
  13128. }
  13129. }
  13130. void XmlElement::insertChildElement (XmlElement* const newNode,
  13131. int indexToInsertAt) throw()
  13132. {
  13133. if (newNode != 0)
  13134. {
  13135. removeChildElement (newNode, false);
  13136. if (indexToInsertAt == 0)
  13137. {
  13138. newNode->nextElement = firstChildElement;
  13139. firstChildElement = newNode;
  13140. }
  13141. else
  13142. {
  13143. if (firstChildElement == 0)
  13144. {
  13145. firstChildElement = newNode;
  13146. }
  13147. else
  13148. {
  13149. if (indexToInsertAt < 0)
  13150. indexToInsertAt = std::numeric_limits<int>::max();
  13151. XmlElement* child = firstChildElement;
  13152. while (child->nextElement != 0 && --indexToInsertAt > 0)
  13153. child = child->nextElement;
  13154. newNode->nextElement = child->nextElement;
  13155. child->nextElement = newNode;
  13156. }
  13157. }
  13158. }
  13159. }
  13160. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  13161. {
  13162. XmlElement* const newElement = new XmlElement (childTagName);
  13163. addChildElement (newElement);
  13164. return newElement;
  13165. }
  13166. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  13167. XmlElement* const newNode) throw()
  13168. {
  13169. if (newNode != 0)
  13170. {
  13171. XmlElement* child = firstChildElement;
  13172. XmlElement* previousNode = 0;
  13173. while (child != 0)
  13174. {
  13175. if (child == currentChildElement)
  13176. {
  13177. if (child != newNode)
  13178. {
  13179. if (previousNode == 0)
  13180. firstChildElement = newNode;
  13181. else
  13182. previousNode->nextElement = newNode;
  13183. newNode->nextElement = child->nextElement;
  13184. delete child;
  13185. }
  13186. return true;
  13187. }
  13188. previousNode = child;
  13189. child = child->nextElement;
  13190. }
  13191. }
  13192. return false;
  13193. }
  13194. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  13195. const bool shouldDeleteTheChild) throw()
  13196. {
  13197. if (childToRemove != 0)
  13198. {
  13199. if (firstChildElement == childToRemove)
  13200. {
  13201. firstChildElement = childToRemove->nextElement;
  13202. childToRemove->nextElement = 0;
  13203. }
  13204. else
  13205. {
  13206. XmlElement* child = firstChildElement;
  13207. XmlElement* last = 0;
  13208. while (child != 0)
  13209. {
  13210. if (child == childToRemove)
  13211. {
  13212. if (last == 0)
  13213. firstChildElement = child->nextElement;
  13214. else
  13215. last->nextElement = child->nextElement;
  13216. childToRemove->nextElement = 0;
  13217. break;
  13218. }
  13219. last = child;
  13220. child = child->nextElement;
  13221. }
  13222. }
  13223. if (shouldDeleteTheChild)
  13224. delete childToRemove;
  13225. }
  13226. }
  13227. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  13228. const bool ignoreOrderOfAttributes) const throw()
  13229. {
  13230. if (this != other)
  13231. {
  13232. if (other == 0 || tagName != other->tagName)
  13233. return false;
  13234. if (ignoreOrderOfAttributes)
  13235. {
  13236. int totalAtts = 0;
  13237. const XmlAttributeNode* att = attributes;
  13238. while (att != 0)
  13239. {
  13240. if (! other->compareAttribute (att->name, att->value))
  13241. return false;
  13242. att = att->next;
  13243. ++totalAtts;
  13244. }
  13245. if (totalAtts != other->getNumAttributes())
  13246. return false;
  13247. }
  13248. else
  13249. {
  13250. const XmlAttributeNode* thisAtt = attributes;
  13251. const XmlAttributeNode* otherAtt = other->attributes;
  13252. for (;;)
  13253. {
  13254. if (thisAtt == 0 || otherAtt == 0)
  13255. {
  13256. if (thisAtt == otherAtt) // both 0, so it's a match
  13257. break;
  13258. return false;
  13259. }
  13260. if (thisAtt->name != otherAtt->name
  13261. || thisAtt->value != otherAtt->value)
  13262. {
  13263. return false;
  13264. }
  13265. thisAtt = thisAtt->next;
  13266. otherAtt = otherAtt->next;
  13267. }
  13268. }
  13269. const XmlElement* thisChild = firstChildElement;
  13270. const XmlElement* otherChild = other->firstChildElement;
  13271. for (;;)
  13272. {
  13273. if (thisChild == 0 || otherChild == 0)
  13274. {
  13275. if (thisChild == otherChild) // both 0, so it's a match
  13276. break;
  13277. return false;
  13278. }
  13279. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  13280. return false;
  13281. thisChild = thisChild->nextElement;
  13282. otherChild = otherChild->nextElement;
  13283. }
  13284. }
  13285. return true;
  13286. }
  13287. void XmlElement::deleteAllChildElements() throw()
  13288. {
  13289. while (firstChildElement != 0)
  13290. {
  13291. XmlElement* const nextChild = firstChildElement->nextElement;
  13292. delete firstChildElement;
  13293. firstChildElement = nextChild;
  13294. }
  13295. }
  13296. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  13297. {
  13298. XmlElement* child = firstChildElement;
  13299. while (child != 0)
  13300. {
  13301. if (child->hasTagName (name))
  13302. {
  13303. XmlElement* const nextChild = child->nextElement;
  13304. removeChildElement (child, true);
  13305. child = nextChild;
  13306. }
  13307. else
  13308. {
  13309. child = child->nextElement;
  13310. }
  13311. }
  13312. }
  13313. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  13314. {
  13315. const XmlElement* child = firstChildElement;
  13316. while (child != 0)
  13317. {
  13318. if (child == possibleChild)
  13319. return true;
  13320. child = child->nextElement;
  13321. }
  13322. return false;
  13323. }
  13324. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  13325. {
  13326. if (this == elementToLookFor || elementToLookFor == 0)
  13327. return 0;
  13328. XmlElement* child = firstChildElement;
  13329. while (child != 0)
  13330. {
  13331. if (elementToLookFor == child)
  13332. return this;
  13333. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  13334. if (found != 0)
  13335. return found;
  13336. child = child->nextElement;
  13337. }
  13338. return 0;
  13339. }
  13340. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  13341. {
  13342. XmlElement* e = firstChildElement;
  13343. while (e != 0)
  13344. {
  13345. *elems++ = e;
  13346. e = e->nextElement;
  13347. }
  13348. }
  13349. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  13350. {
  13351. XmlElement* e = firstChildElement = elems[0];
  13352. for (int i = 1; i < num; ++i)
  13353. {
  13354. e->nextElement = elems[i];
  13355. e = e->nextElement;
  13356. }
  13357. e->nextElement = 0;
  13358. }
  13359. bool XmlElement::isTextElement() const throw()
  13360. {
  13361. return tagName.isEmpty();
  13362. }
  13363. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  13364. const String& XmlElement::getText() const throw()
  13365. {
  13366. jassert (isTextElement()); // you're trying to get the text from an element that
  13367. // isn't actually a text element.. If this contains text sub-nodes, you
  13368. // probably want to use getAllSubText instead.
  13369. return getStringAttribute (juce_xmltextContentAttributeName);
  13370. }
  13371. void XmlElement::setText (const String& newText)
  13372. {
  13373. if (isTextElement())
  13374. setAttribute (juce_xmltextContentAttributeName, newText);
  13375. else
  13376. jassertfalse; // you can only change the text in a text element, not a normal one.
  13377. }
  13378. const String XmlElement::getAllSubText() const
  13379. {
  13380. if (isTextElement())
  13381. return getText();
  13382. String result;
  13383. String::Concatenator concatenator (result);
  13384. const XmlElement* child = firstChildElement;
  13385. while (child != 0)
  13386. {
  13387. concatenator.append (child->getAllSubText());
  13388. child = child->nextElement;
  13389. }
  13390. return result;
  13391. }
  13392. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  13393. const String& defaultReturnValue) const
  13394. {
  13395. const XmlElement* const child = getChildByName (childTagName);
  13396. if (child != 0)
  13397. return child->getAllSubText();
  13398. return defaultReturnValue;
  13399. }
  13400. XmlElement* XmlElement::createTextElement (const String& text)
  13401. {
  13402. XmlElement* const e = new XmlElement ((int) 0);
  13403. e->setAttribute (juce_xmltextContentAttributeName, text);
  13404. return e;
  13405. }
  13406. void XmlElement::addTextElement (const String& text)
  13407. {
  13408. addChildElement (createTextElement (text));
  13409. }
  13410. void XmlElement::deleteAllTextElements() throw()
  13411. {
  13412. XmlElement* child = firstChildElement;
  13413. while (child != 0)
  13414. {
  13415. XmlElement* const next = child->nextElement;
  13416. if (child->isTextElement())
  13417. removeChildElement (child, true);
  13418. child = next;
  13419. }
  13420. }
  13421. END_JUCE_NAMESPACE
  13422. /*** End of inlined file: juce_XmlElement.cpp ***/
  13423. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13424. BEGIN_JUCE_NAMESPACE
  13425. ReadWriteLock::ReadWriteLock() throw()
  13426. : numWaitingWriters (0),
  13427. numWriters (0),
  13428. writerThreadId (0)
  13429. {
  13430. }
  13431. ReadWriteLock::~ReadWriteLock() throw()
  13432. {
  13433. jassert (readerThreads.size() == 0);
  13434. jassert (numWriters == 0);
  13435. }
  13436. void ReadWriteLock::enterRead() const throw()
  13437. {
  13438. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13439. const ScopedLock sl (accessLock);
  13440. for (;;)
  13441. {
  13442. jassert (readerThreads.size() % 2 == 0);
  13443. int i;
  13444. for (i = 0; i < readerThreads.size(); i += 2)
  13445. if (readerThreads.getUnchecked(i) == threadId)
  13446. break;
  13447. if (i < readerThreads.size()
  13448. || numWriters + numWaitingWriters == 0
  13449. || (threadId == writerThreadId && numWriters > 0))
  13450. {
  13451. if (i < readerThreads.size())
  13452. {
  13453. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13454. }
  13455. else
  13456. {
  13457. readerThreads.add (threadId);
  13458. readerThreads.add ((Thread::ThreadID) 1);
  13459. }
  13460. return;
  13461. }
  13462. const ScopedUnlock ul (accessLock);
  13463. waitEvent.wait (100);
  13464. }
  13465. }
  13466. void ReadWriteLock::exitRead() const throw()
  13467. {
  13468. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13469. const ScopedLock sl (accessLock);
  13470. for (int i = 0; i < readerThreads.size(); i += 2)
  13471. {
  13472. if (readerThreads.getUnchecked(i) == threadId)
  13473. {
  13474. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13475. if (newCount == 0)
  13476. {
  13477. readerThreads.removeRange (i, 2);
  13478. waitEvent.signal();
  13479. }
  13480. else
  13481. {
  13482. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13483. }
  13484. return;
  13485. }
  13486. }
  13487. jassertfalse; // unlocking a lock that wasn't locked..
  13488. }
  13489. void ReadWriteLock::enterWrite() const throw()
  13490. {
  13491. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13492. const ScopedLock sl (accessLock);
  13493. for (;;)
  13494. {
  13495. if (readerThreads.size() + numWriters == 0
  13496. || threadId == writerThreadId
  13497. || (readerThreads.size() == 2
  13498. && readerThreads.getUnchecked(0) == threadId))
  13499. {
  13500. writerThreadId = threadId;
  13501. ++numWriters;
  13502. break;
  13503. }
  13504. ++numWaitingWriters;
  13505. accessLock.exit();
  13506. waitEvent.wait (100);
  13507. accessLock.enter();
  13508. --numWaitingWriters;
  13509. }
  13510. }
  13511. bool ReadWriteLock::tryEnterWrite() const throw()
  13512. {
  13513. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13514. const ScopedLock sl (accessLock);
  13515. if (readerThreads.size() + numWriters == 0
  13516. || threadId == writerThreadId
  13517. || (readerThreads.size() == 2
  13518. && readerThreads.getUnchecked(0) == threadId))
  13519. {
  13520. writerThreadId = threadId;
  13521. ++numWriters;
  13522. return true;
  13523. }
  13524. return false;
  13525. }
  13526. void ReadWriteLock::exitWrite() const throw()
  13527. {
  13528. const ScopedLock sl (accessLock);
  13529. // check this thread actually had the lock..
  13530. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13531. if (--numWriters == 0)
  13532. {
  13533. writerThreadId = 0;
  13534. waitEvent.signal();
  13535. }
  13536. }
  13537. END_JUCE_NAMESPACE
  13538. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13539. /*** Start of inlined file: juce_Thread.cpp ***/
  13540. BEGIN_JUCE_NAMESPACE
  13541. // these functions are implemented in the platform-specific code.
  13542. void* juce_createThread (void* userData);
  13543. void juce_killThread (void* handle);
  13544. bool juce_setThreadPriority (void* handle, int priority);
  13545. void juce_setCurrentThreadName (const String& name);
  13546. #if JUCE_WINDOWS
  13547. void juce_CloseThreadHandle (void* handle);
  13548. #endif
  13549. void Thread::threadEntryPoint (Thread* const thread)
  13550. {
  13551. {
  13552. const ScopedLock sl (runningThreadsLock);
  13553. runningThreads.add (thread);
  13554. }
  13555. JUCE_TRY
  13556. {
  13557. thread->threadId_ = Thread::getCurrentThreadId();
  13558. if (thread->threadName_.isNotEmpty())
  13559. juce_setCurrentThreadName (thread->threadName_);
  13560. if (thread->startSuspensionEvent_.wait (10000))
  13561. {
  13562. if (thread->affinityMask_ != 0)
  13563. setCurrentThreadAffinityMask (thread->affinityMask_);
  13564. thread->run();
  13565. }
  13566. }
  13567. JUCE_CATCH_ALL_ASSERT
  13568. {
  13569. const ScopedLock sl (runningThreadsLock);
  13570. jassert (runningThreads.contains (thread));
  13571. runningThreads.removeValue (thread);
  13572. }
  13573. #if JUCE_WINDOWS
  13574. juce_CloseThreadHandle (thread->threadHandle_);
  13575. #endif
  13576. thread->threadHandle_ = 0;
  13577. thread->threadId_ = 0;
  13578. }
  13579. // used to wrap the incoming call from the platform-specific code
  13580. void JUCE_API juce_threadEntryPoint (void* userData)
  13581. {
  13582. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  13583. }
  13584. Thread::Thread (const String& threadName)
  13585. : threadName_ (threadName),
  13586. threadHandle_ (0),
  13587. threadPriority_ (5),
  13588. threadId_ (0),
  13589. affinityMask_ (0),
  13590. threadShouldExit_ (false)
  13591. {
  13592. }
  13593. Thread::~Thread()
  13594. {
  13595. stopThread (100);
  13596. }
  13597. void Thread::startThread()
  13598. {
  13599. const ScopedLock sl (startStopLock);
  13600. threadShouldExit_ = false;
  13601. if (threadHandle_ == 0)
  13602. {
  13603. threadHandle_ = juce_createThread (this);
  13604. juce_setThreadPriority (threadHandle_, threadPriority_);
  13605. startSuspensionEvent_.signal();
  13606. }
  13607. }
  13608. void Thread::startThread (const int priority)
  13609. {
  13610. const ScopedLock sl (startStopLock);
  13611. if (threadHandle_ == 0)
  13612. {
  13613. threadPriority_ = priority;
  13614. startThread();
  13615. }
  13616. else
  13617. {
  13618. setPriority (priority);
  13619. }
  13620. }
  13621. bool Thread::isThreadRunning() const
  13622. {
  13623. return threadHandle_ != 0;
  13624. }
  13625. void Thread::signalThreadShouldExit()
  13626. {
  13627. threadShouldExit_ = true;
  13628. }
  13629. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13630. {
  13631. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13632. jassert (getThreadId() != getCurrentThreadId());
  13633. const int sleepMsPerIteration = 5;
  13634. int count = timeOutMilliseconds / sleepMsPerIteration;
  13635. while (isThreadRunning())
  13636. {
  13637. if (timeOutMilliseconds > 0 && --count < 0)
  13638. return false;
  13639. sleep (sleepMsPerIteration);
  13640. }
  13641. return true;
  13642. }
  13643. void Thread::stopThread (const int timeOutMilliseconds)
  13644. {
  13645. // agh! You can't stop the thread that's calling this method! How on earth
  13646. // would that work??
  13647. jassert (getCurrentThreadId() != getThreadId());
  13648. const ScopedLock sl (startStopLock);
  13649. if (isThreadRunning())
  13650. {
  13651. signalThreadShouldExit();
  13652. notify();
  13653. if (timeOutMilliseconds != 0)
  13654. waitForThreadToExit (timeOutMilliseconds);
  13655. if (isThreadRunning())
  13656. {
  13657. // very bad karma if this point is reached, as
  13658. // there are bound to be locks and events left in
  13659. // silly states when a thread is killed by force..
  13660. jassertfalse;
  13661. Logger::writeToLog ("!! killing thread by force !!");
  13662. juce_killThread (threadHandle_);
  13663. threadHandle_ = 0;
  13664. threadId_ = 0;
  13665. const ScopedLock sl2 (runningThreadsLock);
  13666. runningThreads.removeValue (this);
  13667. }
  13668. }
  13669. }
  13670. bool Thread::setPriority (const int priority)
  13671. {
  13672. const ScopedLock sl (startStopLock);
  13673. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  13674. if (worked)
  13675. threadPriority_ = priority;
  13676. return worked;
  13677. }
  13678. bool Thread::setCurrentThreadPriority (const int priority)
  13679. {
  13680. return juce_setThreadPriority (0, priority);
  13681. }
  13682. void Thread::setAffinityMask (const uint32 affinityMask)
  13683. {
  13684. affinityMask_ = affinityMask;
  13685. }
  13686. bool Thread::wait (const int timeOutMilliseconds) const
  13687. {
  13688. return defaultEvent_.wait (timeOutMilliseconds);
  13689. }
  13690. void Thread::notify() const
  13691. {
  13692. defaultEvent_.signal();
  13693. }
  13694. int Thread::getNumRunningThreads()
  13695. {
  13696. return runningThreads.size();
  13697. }
  13698. Thread* Thread::getCurrentThread()
  13699. {
  13700. const ThreadID thisId = getCurrentThreadId();
  13701. const ScopedLock sl (runningThreadsLock);
  13702. for (int i = runningThreads.size(); --i >= 0;)
  13703. {
  13704. Thread* const t = runningThreads.getUnchecked(i);
  13705. if (t->threadId_ == thisId)
  13706. return t;
  13707. }
  13708. return 0;
  13709. }
  13710. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13711. {
  13712. {
  13713. const ScopedLock sl (runningThreadsLock);
  13714. for (int i = runningThreads.size(); --i >= 0;)
  13715. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  13716. }
  13717. for (;;)
  13718. {
  13719. Thread* firstThread;
  13720. {
  13721. const ScopedLock sl (runningThreadsLock);
  13722. firstThread = runningThreads.getFirst();
  13723. }
  13724. if (firstThread == 0)
  13725. break;
  13726. firstThread->stopThread (timeOutMilliseconds);
  13727. }
  13728. }
  13729. Array<Thread*> Thread::runningThreads;
  13730. CriticalSection Thread::runningThreadsLock;
  13731. END_JUCE_NAMESPACE
  13732. /*** End of inlined file: juce_Thread.cpp ***/
  13733. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13734. BEGIN_JUCE_NAMESPACE
  13735. ThreadPoolJob::ThreadPoolJob (const String& name)
  13736. : jobName (name),
  13737. pool (0),
  13738. shouldStop (false),
  13739. isActive (false),
  13740. shouldBeDeleted (false)
  13741. {
  13742. }
  13743. ThreadPoolJob::~ThreadPoolJob()
  13744. {
  13745. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13746. // to remove it first!
  13747. jassert (pool == 0 || ! pool->contains (this));
  13748. }
  13749. const String ThreadPoolJob::getJobName() const
  13750. {
  13751. return jobName;
  13752. }
  13753. void ThreadPoolJob::setJobName (const String& newName)
  13754. {
  13755. jobName = newName;
  13756. }
  13757. void ThreadPoolJob::signalJobShouldExit()
  13758. {
  13759. shouldStop = true;
  13760. }
  13761. class ThreadPool::ThreadPoolThread : public Thread
  13762. {
  13763. public:
  13764. ThreadPoolThread (ThreadPool& pool_)
  13765. : Thread ("Pool"),
  13766. pool (pool_),
  13767. busy (false)
  13768. {
  13769. }
  13770. ~ThreadPoolThread()
  13771. {
  13772. }
  13773. void run()
  13774. {
  13775. while (! threadShouldExit())
  13776. {
  13777. if (! pool.runNextJob())
  13778. wait (500);
  13779. }
  13780. }
  13781. private:
  13782. ThreadPool& pool;
  13783. bool volatile busy;
  13784. ThreadPoolThread (const ThreadPoolThread&);
  13785. ThreadPoolThread& operator= (const ThreadPoolThread&);
  13786. };
  13787. ThreadPool::ThreadPool (const int numThreads,
  13788. const bool startThreadsOnlyWhenNeeded,
  13789. const int stopThreadsWhenNotUsedTimeoutMs)
  13790. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13791. priority (5)
  13792. {
  13793. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13794. for (int i = jmax (1, numThreads); --i >= 0;)
  13795. threads.add (new ThreadPoolThread (*this));
  13796. if (! startThreadsOnlyWhenNeeded)
  13797. for (int i = threads.size(); --i >= 0;)
  13798. threads.getUnchecked(i)->startThread (priority);
  13799. }
  13800. ThreadPool::~ThreadPool()
  13801. {
  13802. removeAllJobs (true, 4000);
  13803. int i;
  13804. for (i = threads.size(); --i >= 0;)
  13805. threads.getUnchecked(i)->signalThreadShouldExit();
  13806. for (i = threads.size(); --i >= 0;)
  13807. threads.getUnchecked(i)->stopThread (500);
  13808. }
  13809. void ThreadPool::addJob (ThreadPoolJob* const job)
  13810. {
  13811. jassert (job != 0);
  13812. jassert (job->pool == 0);
  13813. if (job->pool == 0)
  13814. {
  13815. job->pool = this;
  13816. job->shouldStop = false;
  13817. job->isActive = false;
  13818. {
  13819. const ScopedLock sl (lock);
  13820. jobs.add (job);
  13821. int numRunning = 0;
  13822. for (int i = threads.size(); --i >= 0;)
  13823. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13824. ++numRunning;
  13825. if (numRunning < threads.size())
  13826. {
  13827. bool startedOne = false;
  13828. int n = 1000;
  13829. while (--n >= 0 && ! startedOne)
  13830. {
  13831. for (int i = threads.size(); --i >= 0;)
  13832. {
  13833. if (! threads.getUnchecked(i)->isThreadRunning())
  13834. {
  13835. threads.getUnchecked(i)->startThread (priority);
  13836. startedOne = true;
  13837. break;
  13838. }
  13839. }
  13840. if (! startedOne)
  13841. Thread::sleep (2);
  13842. }
  13843. }
  13844. }
  13845. for (int i = threads.size(); --i >= 0;)
  13846. threads.getUnchecked(i)->notify();
  13847. }
  13848. }
  13849. int ThreadPool::getNumJobs() const
  13850. {
  13851. return jobs.size();
  13852. }
  13853. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13854. {
  13855. const ScopedLock sl (lock);
  13856. return jobs [index];
  13857. }
  13858. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13859. {
  13860. const ScopedLock sl (lock);
  13861. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13862. }
  13863. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13864. {
  13865. const ScopedLock sl (lock);
  13866. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13867. }
  13868. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13869. const int timeOutMs) const
  13870. {
  13871. if (job != 0)
  13872. {
  13873. const uint32 start = Time::getMillisecondCounter();
  13874. while (contains (job))
  13875. {
  13876. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13877. return false;
  13878. jobFinishedSignal.wait (2);
  13879. }
  13880. }
  13881. return true;
  13882. }
  13883. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13884. const bool interruptIfRunning,
  13885. const int timeOutMs)
  13886. {
  13887. bool dontWait = true;
  13888. if (job != 0)
  13889. {
  13890. const ScopedLock sl (lock);
  13891. if (jobs.contains (job))
  13892. {
  13893. if (job->isActive)
  13894. {
  13895. if (interruptIfRunning)
  13896. job->signalJobShouldExit();
  13897. dontWait = false;
  13898. }
  13899. else
  13900. {
  13901. jobs.removeValue (job);
  13902. job->pool = 0;
  13903. }
  13904. }
  13905. }
  13906. return dontWait || waitForJobToFinish (job, timeOutMs);
  13907. }
  13908. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13909. const int timeOutMs,
  13910. const bool deleteInactiveJobs,
  13911. ThreadPool::JobSelector* selectedJobsToRemove)
  13912. {
  13913. Array <ThreadPoolJob*> jobsToWaitFor;
  13914. {
  13915. const ScopedLock sl (lock);
  13916. for (int i = jobs.size(); --i >= 0;)
  13917. {
  13918. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13919. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13920. {
  13921. if (job->isActive)
  13922. {
  13923. jobsToWaitFor.add (job);
  13924. if (interruptRunningJobs)
  13925. job->signalJobShouldExit();
  13926. }
  13927. else
  13928. {
  13929. jobs.remove (i);
  13930. if (deleteInactiveJobs)
  13931. delete job;
  13932. else
  13933. job->pool = 0;
  13934. }
  13935. }
  13936. }
  13937. }
  13938. const uint32 start = Time::getMillisecondCounter();
  13939. for (;;)
  13940. {
  13941. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13942. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13943. jobsToWaitFor.remove (i);
  13944. if (jobsToWaitFor.size() == 0)
  13945. break;
  13946. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13947. return false;
  13948. jobFinishedSignal.wait (20);
  13949. }
  13950. return true;
  13951. }
  13952. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13953. {
  13954. StringArray s;
  13955. const ScopedLock sl (lock);
  13956. for (int i = 0; i < jobs.size(); ++i)
  13957. {
  13958. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13959. if (job->isActive || ! onlyReturnActiveJobs)
  13960. s.add (job->getJobName());
  13961. }
  13962. return s;
  13963. }
  13964. bool ThreadPool::setThreadPriorities (const int newPriority)
  13965. {
  13966. bool ok = true;
  13967. if (priority != newPriority)
  13968. {
  13969. priority = newPriority;
  13970. for (int i = threads.size(); --i >= 0;)
  13971. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13972. ok = false;
  13973. }
  13974. return ok;
  13975. }
  13976. bool ThreadPool::runNextJob()
  13977. {
  13978. ThreadPoolJob* job = 0;
  13979. {
  13980. const ScopedLock sl (lock);
  13981. for (int i = 0; i < jobs.size(); ++i)
  13982. {
  13983. job = jobs[i];
  13984. if (job != 0 && ! (job->isActive || job->shouldStop))
  13985. break;
  13986. job = 0;
  13987. }
  13988. if (job != 0)
  13989. job->isActive = true;
  13990. }
  13991. if (job != 0)
  13992. {
  13993. JUCE_TRY
  13994. {
  13995. ThreadPoolJob::JobStatus result = job->runJob();
  13996. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13997. const ScopedLock sl (lock);
  13998. if (jobs.contains (job))
  13999. {
  14000. job->isActive = false;
  14001. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  14002. {
  14003. job->pool = 0;
  14004. job->shouldStop = true;
  14005. jobs.removeValue (job);
  14006. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  14007. delete job;
  14008. jobFinishedSignal.signal();
  14009. }
  14010. else
  14011. {
  14012. // move the job to the end of the queue if it wants another go
  14013. jobs.move (jobs.indexOf (job), -1);
  14014. }
  14015. }
  14016. }
  14017. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  14018. catch (...)
  14019. {
  14020. const ScopedLock sl (lock);
  14021. jobs.removeValue (job);
  14022. }
  14023. #endif
  14024. }
  14025. else
  14026. {
  14027. if (threadStopTimeout > 0
  14028. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  14029. {
  14030. const ScopedLock sl (lock);
  14031. if (jobs.size() == 0)
  14032. for (int i = threads.size(); --i >= 0;)
  14033. threads.getUnchecked(i)->signalThreadShouldExit();
  14034. }
  14035. else
  14036. {
  14037. return false;
  14038. }
  14039. }
  14040. return true;
  14041. }
  14042. END_JUCE_NAMESPACE
  14043. /*** End of inlined file: juce_ThreadPool.cpp ***/
  14044. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  14045. BEGIN_JUCE_NAMESPACE
  14046. TimeSliceThread::TimeSliceThread (const String& threadName)
  14047. : Thread (threadName),
  14048. index (0),
  14049. clientBeingCalled (0),
  14050. clientsChanged (false)
  14051. {
  14052. }
  14053. TimeSliceThread::~TimeSliceThread()
  14054. {
  14055. stopThread (2000);
  14056. }
  14057. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  14058. {
  14059. const ScopedLock sl (listLock);
  14060. clients.addIfNotAlreadyThere (client);
  14061. clientsChanged = true;
  14062. notify();
  14063. }
  14064. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  14065. {
  14066. const ScopedLock sl1 (listLock);
  14067. clientsChanged = true;
  14068. // if there's a chance we're in the middle of calling this client, we need to
  14069. // also lock the outer lock..
  14070. if (clientBeingCalled == client)
  14071. {
  14072. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  14073. const ScopedLock sl2 (callbackLock);
  14074. const ScopedLock sl3 (listLock);
  14075. clients.removeValue (client);
  14076. }
  14077. else
  14078. {
  14079. clients.removeValue (client);
  14080. }
  14081. }
  14082. int TimeSliceThread::getNumClients() const
  14083. {
  14084. return clients.size();
  14085. }
  14086. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  14087. {
  14088. const ScopedLock sl (listLock);
  14089. return clients [i];
  14090. }
  14091. void TimeSliceThread::run()
  14092. {
  14093. int numCallsSinceBusy = 0;
  14094. while (! threadShouldExit())
  14095. {
  14096. int timeToWait = 500;
  14097. {
  14098. const ScopedLock sl (callbackLock);
  14099. {
  14100. const ScopedLock sl2 (listLock);
  14101. if (clients.size() > 0)
  14102. {
  14103. index = (index + 1) % clients.size();
  14104. clientBeingCalled = clients [index];
  14105. }
  14106. else
  14107. {
  14108. index = 0;
  14109. clientBeingCalled = 0;
  14110. }
  14111. if (clientsChanged)
  14112. {
  14113. clientsChanged = false;
  14114. numCallsSinceBusy = 0;
  14115. }
  14116. }
  14117. if (clientBeingCalled != 0)
  14118. {
  14119. if (clientBeingCalled->useTimeSlice())
  14120. numCallsSinceBusy = 0;
  14121. else
  14122. ++numCallsSinceBusy;
  14123. if (numCallsSinceBusy >= clients.size())
  14124. timeToWait = 500;
  14125. else if (index == 0)
  14126. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  14127. else
  14128. timeToWait = 0;
  14129. }
  14130. }
  14131. if (timeToWait > 0)
  14132. wait (timeToWait);
  14133. }
  14134. }
  14135. END_JUCE_NAMESPACE
  14136. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  14137. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  14138. BEGIN_JUCE_NAMESPACE
  14139. DeletedAtShutdown::DeletedAtShutdown()
  14140. {
  14141. const ScopedLock sl (getLock());
  14142. getObjects().add (this);
  14143. }
  14144. DeletedAtShutdown::~DeletedAtShutdown()
  14145. {
  14146. const ScopedLock sl (getLock());
  14147. getObjects().removeValue (this);
  14148. }
  14149. void DeletedAtShutdown::deleteAll()
  14150. {
  14151. // make a local copy of the array, so it can't get into a loop if something
  14152. // creates another DeletedAtShutdown object during its destructor.
  14153. Array <DeletedAtShutdown*> localCopy;
  14154. {
  14155. const ScopedLock sl (getLock());
  14156. localCopy = getObjects();
  14157. }
  14158. for (int i = localCopy.size(); --i >= 0;)
  14159. {
  14160. JUCE_TRY
  14161. {
  14162. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  14163. // double-check that it's not already been deleted during another object's destructor.
  14164. {
  14165. const ScopedLock sl (getLock());
  14166. if (! getObjects().contains (deletee))
  14167. deletee = 0;
  14168. }
  14169. delete deletee;
  14170. }
  14171. JUCE_CATCH_EXCEPTION
  14172. }
  14173. // if no objects got re-created during shutdown, this should have been emptied by their
  14174. // destructors
  14175. jassert (getObjects().size() == 0);
  14176. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  14177. }
  14178. CriticalSection& DeletedAtShutdown::getLock()
  14179. {
  14180. static CriticalSection lock;
  14181. return lock;
  14182. }
  14183. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  14184. {
  14185. static Array <DeletedAtShutdown*> objects;
  14186. return objects;
  14187. }
  14188. END_JUCE_NAMESPACE
  14189. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  14190. /*** Start of inlined file: juce_UnitTest.cpp ***/
  14191. BEGIN_JUCE_NAMESPACE
  14192. UnitTest::UnitTest (const String& name_)
  14193. : name (name_), runner (0)
  14194. {
  14195. getAllTests().add (this);
  14196. }
  14197. UnitTest::~UnitTest()
  14198. {
  14199. getAllTests().removeValue (this);
  14200. }
  14201. Array<UnitTest*>& UnitTest::getAllTests()
  14202. {
  14203. static Array<UnitTest*> tests;
  14204. return tests;
  14205. }
  14206. void UnitTest::performTest (UnitTestRunner* const runner_)
  14207. {
  14208. jassert (runner_ != 0);
  14209. runner = runner_;
  14210. runTest();
  14211. }
  14212. void UnitTest::logMessage (const String& message)
  14213. {
  14214. runner->logMessage (message);
  14215. }
  14216. void UnitTest::beginTest (const String& testName)
  14217. {
  14218. runner->beginNewTest (this, testName);
  14219. }
  14220. void UnitTest::expect (const bool result, const String& failureMessage)
  14221. {
  14222. if (result)
  14223. runner->addPass();
  14224. else
  14225. runner->addFail (failureMessage);
  14226. }
  14227. UnitTestRunner::UnitTestRunner()
  14228. : currentTest (0), assertOnFailure (false)
  14229. {
  14230. }
  14231. UnitTestRunner::~UnitTestRunner()
  14232. {
  14233. }
  14234. void UnitTestRunner::resultsUpdated()
  14235. {
  14236. }
  14237. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14238. {
  14239. results.clear();
  14240. assertOnFailure = assertOnFailure_;
  14241. resultsUpdated();
  14242. for (int i = 0; i < tests.size(); ++i)
  14243. {
  14244. try
  14245. {
  14246. tests.getUnchecked(i)->performTest (this);
  14247. }
  14248. catch (...)
  14249. {
  14250. addFail ("An unhandled exception was thrown!");
  14251. }
  14252. }
  14253. endTest();
  14254. }
  14255. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14256. {
  14257. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14258. }
  14259. void UnitTestRunner::logMessage (const String& message)
  14260. {
  14261. Logger::writeToLog (message);
  14262. }
  14263. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14264. {
  14265. endTest();
  14266. currentTest = test;
  14267. TestResult* const r = new TestResult();
  14268. r->unitTestName = test->getName();
  14269. r->subcategoryName = subCategory;
  14270. r->passes = 0;
  14271. r->failures = 0;
  14272. results.add (r);
  14273. logMessage ("-----------------------------------------------------------------");
  14274. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14275. resultsUpdated();
  14276. }
  14277. void UnitTestRunner::endTest()
  14278. {
  14279. if (results.size() > 0)
  14280. {
  14281. TestResult* const r = results.getLast();
  14282. if (r->failures > 0)
  14283. {
  14284. String m ("FAILED!!");
  14285. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14286. << " failed, out of a total of " << (r->passes + r->failures);
  14287. logMessage (String::empty);
  14288. logMessage (m);
  14289. logMessage (String::empty);
  14290. }
  14291. else
  14292. {
  14293. logMessage ("All tests completed successfully");
  14294. }
  14295. }
  14296. }
  14297. void UnitTestRunner::addPass()
  14298. {
  14299. {
  14300. const ScopedLock sl (results.getLock());
  14301. TestResult* const r = results.getLast();
  14302. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14303. r->passes++;
  14304. String message ("Test ");
  14305. message << (r->failures + r->passes) << " passed";
  14306. logMessage (message);
  14307. }
  14308. resultsUpdated();
  14309. }
  14310. void UnitTestRunner::addFail (const String& failureMessage)
  14311. {
  14312. {
  14313. const ScopedLock sl (results.getLock());
  14314. TestResult* const r = results.getLast();
  14315. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14316. r->failures++;
  14317. String message ("!!! Test ");
  14318. message << (r->failures + r->passes) << " failed";
  14319. if (failureMessage.isNotEmpty())
  14320. message << ": " << failureMessage;
  14321. r->messages.add (message);
  14322. logMessage (message);
  14323. }
  14324. resultsUpdated();
  14325. if (assertOnFailure) { jassertfalse }
  14326. }
  14327. END_JUCE_NAMESPACE
  14328. /*** End of inlined file: juce_UnitTest.cpp ***/
  14329. #endif
  14330. #if JUCE_BUILD_MISC
  14331. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14332. BEGIN_JUCE_NAMESPACE
  14333. class ValueTree::SetPropertyAction : public UndoableAction
  14334. {
  14335. public:
  14336. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14337. const var& newValue_, const var& oldValue_,
  14338. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14339. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14340. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14341. {
  14342. }
  14343. ~SetPropertyAction() {}
  14344. bool perform()
  14345. {
  14346. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14347. if (isDeletingProperty)
  14348. target->removeProperty (name, 0);
  14349. else
  14350. target->setProperty (name, newValue, 0);
  14351. return true;
  14352. }
  14353. bool undo()
  14354. {
  14355. if (isAddingNewProperty)
  14356. target->removeProperty (name, 0);
  14357. else
  14358. target->setProperty (name, oldValue, 0);
  14359. return true;
  14360. }
  14361. int getSizeInUnits()
  14362. {
  14363. return (int) sizeof (*this); //xxx should be more accurate
  14364. }
  14365. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14366. {
  14367. if (! (isAddingNewProperty || isDeletingProperty))
  14368. {
  14369. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14370. if (next != 0 && next->target == target && next->name == name
  14371. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14372. {
  14373. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14374. }
  14375. }
  14376. return 0;
  14377. }
  14378. private:
  14379. const SharedObjectPtr target;
  14380. const Identifier name;
  14381. const var newValue;
  14382. var oldValue;
  14383. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14384. SetPropertyAction (const SetPropertyAction&);
  14385. SetPropertyAction& operator= (const SetPropertyAction&);
  14386. };
  14387. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14388. {
  14389. public:
  14390. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14391. const SharedObjectPtr& newChild_)
  14392. : target (target_),
  14393. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14394. childIndex (childIndex_),
  14395. isDeleting (newChild_ == 0)
  14396. {
  14397. jassert (child != 0);
  14398. }
  14399. ~AddOrRemoveChildAction() {}
  14400. bool perform()
  14401. {
  14402. if (isDeleting)
  14403. target->removeChild (childIndex, 0);
  14404. else
  14405. target->addChild (child, childIndex, 0);
  14406. return true;
  14407. }
  14408. bool undo()
  14409. {
  14410. if (isDeleting)
  14411. {
  14412. target->addChild (child, childIndex, 0);
  14413. }
  14414. else
  14415. {
  14416. // If you hit this, it seems that your object's state is getting confused - probably
  14417. // because you've interleaved some undoable and non-undoable operations?
  14418. jassert (childIndex < target->children.size());
  14419. target->removeChild (childIndex, 0);
  14420. }
  14421. return true;
  14422. }
  14423. int getSizeInUnits()
  14424. {
  14425. return (int) sizeof (*this); //xxx should be more accurate
  14426. }
  14427. private:
  14428. const SharedObjectPtr target, child;
  14429. const int childIndex;
  14430. const bool isDeleting;
  14431. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  14432. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  14433. };
  14434. class ValueTree::MoveChildAction : public UndoableAction
  14435. {
  14436. public:
  14437. MoveChildAction (const SharedObjectPtr& parent_,
  14438. const int startIndex_, const int endIndex_)
  14439. : parent (parent_),
  14440. startIndex (startIndex_),
  14441. endIndex (endIndex_)
  14442. {
  14443. }
  14444. ~MoveChildAction() {}
  14445. bool perform()
  14446. {
  14447. parent->moveChild (startIndex, endIndex, 0);
  14448. return true;
  14449. }
  14450. bool undo()
  14451. {
  14452. parent->moveChild (endIndex, startIndex, 0);
  14453. return true;
  14454. }
  14455. int getSizeInUnits()
  14456. {
  14457. return (int) sizeof (*this); //xxx should be more accurate
  14458. }
  14459. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14460. {
  14461. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14462. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14463. return new MoveChildAction (parent, startIndex, next->endIndex);
  14464. return 0;
  14465. }
  14466. private:
  14467. const SharedObjectPtr parent;
  14468. const int startIndex, endIndex;
  14469. MoveChildAction (const MoveChildAction&);
  14470. MoveChildAction& operator= (const MoveChildAction&);
  14471. };
  14472. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14473. : type (type_), parent (0)
  14474. {
  14475. }
  14476. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14477. : type (other.type), properties (other.properties), parent (0)
  14478. {
  14479. for (int i = 0; i < other.children.size(); ++i)
  14480. {
  14481. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14482. child->parent = this;
  14483. children.add (child);
  14484. }
  14485. }
  14486. ValueTree::SharedObject::~SharedObject()
  14487. {
  14488. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14489. for (int i = children.size(); --i >= 0;)
  14490. {
  14491. const SharedObjectPtr c (children.getUnchecked(i));
  14492. c->parent = 0;
  14493. children.remove (i);
  14494. c->sendParentChangeMessage();
  14495. }
  14496. }
  14497. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14498. {
  14499. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14500. {
  14501. ValueTree* const v = valueTreesWithListeners[i];
  14502. if (v != 0)
  14503. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14504. }
  14505. }
  14506. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14507. {
  14508. ValueTree tree (this);
  14509. ValueTree::SharedObject* t = this;
  14510. while (t != 0)
  14511. {
  14512. t->sendPropertyChangeMessage (tree, property);
  14513. t = t->parent;
  14514. }
  14515. }
  14516. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14517. {
  14518. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14519. {
  14520. ValueTree* const v = valueTreesWithListeners[i];
  14521. if (v != 0)
  14522. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14523. }
  14524. }
  14525. void ValueTree::SharedObject::sendChildChangeMessage()
  14526. {
  14527. ValueTree tree (this);
  14528. ValueTree::SharedObject* t = this;
  14529. while (t != 0)
  14530. {
  14531. t->sendChildChangeMessage (tree);
  14532. t = t->parent;
  14533. }
  14534. }
  14535. void ValueTree::SharedObject::sendParentChangeMessage()
  14536. {
  14537. ValueTree tree (this);
  14538. int i;
  14539. for (i = children.size(); --i >= 0;)
  14540. {
  14541. SharedObject* const t = children[i];
  14542. if (t != 0)
  14543. t->sendParentChangeMessage();
  14544. }
  14545. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14546. {
  14547. ValueTree* const v = valueTreesWithListeners[i];
  14548. if (v != 0)
  14549. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14550. }
  14551. }
  14552. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14553. {
  14554. return properties [name];
  14555. }
  14556. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14557. {
  14558. return properties.getWithDefault (name, defaultReturnValue);
  14559. }
  14560. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14561. {
  14562. if (undoManager == 0)
  14563. {
  14564. if (properties.set (name, newValue))
  14565. sendPropertyChangeMessage (name);
  14566. }
  14567. else
  14568. {
  14569. var* const existingValue = properties.getItem (name);
  14570. if (existingValue != 0)
  14571. {
  14572. if (*existingValue != newValue)
  14573. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14574. }
  14575. else
  14576. {
  14577. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14578. }
  14579. }
  14580. }
  14581. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14582. {
  14583. return properties.contains (name);
  14584. }
  14585. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14586. {
  14587. if (undoManager == 0)
  14588. {
  14589. if (properties.remove (name))
  14590. sendPropertyChangeMessage (name);
  14591. }
  14592. else
  14593. {
  14594. if (properties.contains (name))
  14595. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14596. }
  14597. }
  14598. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14599. {
  14600. if (undoManager == 0)
  14601. {
  14602. while (properties.size() > 0)
  14603. {
  14604. const Identifier name (properties.getName (properties.size() - 1));
  14605. properties.remove (name);
  14606. sendPropertyChangeMessage (name);
  14607. }
  14608. }
  14609. else
  14610. {
  14611. for (int i = properties.size(); --i >= 0;)
  14612. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14613. }
  14614. }
  14615. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14616. {
  14617. for (int i = 0; i < children.size(); ++i)
  14618. if (children.getUnchecked(i)->type == typeToMatch)
  14619. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14620. return ValueTree::invalid;
  14621. }
  14622. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14623. {
  14624. for (int i = 0; i < children.size(); ++i)
  14625. if (children.getUnchecked(i)->type == typeToMatch)
  14626. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14627. SharedObject* const newObject = new SharedObject (typeToMatch);
  14628. addChild (newObject, -1, undoManager);
  14629. return ValueTree (newObject);
  14630. }
  14631. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14632. {
  14633. for (int i = 0; i < children.size(); ++i)
  14634. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14635. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14636. return ValueTree::invalid;
  14637. }
  14638. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14639. {
  14640. const SharedObject* p = parent;
  14641. while (p != 0)
  14642. {
  14643. if (p == possibleParent)
  14644. return true;
  14645. p = p->parent;
  14646. }
  14647. return false;
  14648. }
  14649. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14650. {
  14651. return children.indexOf (child.object);
  14652. }
  14653. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14654. {
  14655. if (child != 0 && child->parent != this)
  14656. {
  14657. if (child != this && ! isAChildOf (child))
  14658. {
  14659. // You should always make sure that a child is removed from its previous parent before
  14660. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14661. // undomanager should be used when removing it from its current parent..
  14662. jassert (child->parent == 0);
  14663. if (child->parent != 0)
  14664. {
  14665. jassert (child->parent->children.indexOf (child) >= 0);
  14666. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14667. }
  14668. if (undoManager == 0)
  14669. {
  14670. children.insert (index, child);
  14671. child->parent = this;
  14672. sendChildChangeMessage();
  14673. child->sendParentChangeMessage();
  14674. }
  14675. else
  14676. {
  14677. if (index < 0)
  14678. index = children.size();
  14679. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14680. }
  14681. }
  14682. else
  14683. {
  14684. // You're attempting to create a recursive loop! A node
  14685. // can't be a child of one of its own children!
  14686. jassertfalse;
  14687. }
  14688. }
  14689. }
  14690. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14691. {
  14692. const SharedObjectPtr child (children [childIndex]);
  14693. if (child != 0)
  14694. {
  14695. if (undoManager == 0)
  14696. {
  14697. children.remove (childIndex);
  14698. child->parent = 0;
  14699. sendChildChangeMessage();
  14700. child->sendParentChangeMessage();
  14701. }
  14702. else
  14703. {
  14704. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14705. }
  14706. }
  14707. }
  14708. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14709. {
  14710. while (children.size() > 0)
  14711. removeChild (children.size() - 1, undoManager);
  14712. }
  14713. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14714. {
  14715. // The source index must be a valid index!
  14716. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  14717. if (currentIndex != newIndex
  14718. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  14719. {
  14720. if (undoManager == 0)
  14721. {
  14722. children.move (currentIndex, newIndex);
  14723. sendChildChangeMessage();
  14724. }
  14725. else
  14726. {
  14727. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  14728. newIndex = children.size() - 1;
  14729. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14730. }
  14731. }
  14732. }
  14733. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14734. {
  14735. if (type != other.type
  14736. || properties.size() != other.properties.size()
  14737. || children.size() != other.children.size()
  14738. || properties != other.properties)
  14739. return false;
  14740. for (int i = 0; i < children.size(); ++i)
  14741. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14742. return false;
  14743. return true;
  14744. }
  14745. ValueTree::ValueTree() throw()
  14746. : object (0)
  14747. {
  14748. }
  14749. const ValueTree ValueTree::invalid;
  14750. ValueTree::ValueTree (const Identifier& type_)
  14751. : object (new ValueTree::SharedObject (type_))
  14752. {
  14753. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14754. }
  14755. ValueTree::ValueTree (SharedObject* const object_)
  14756. : object (object_)
  14757. {
  14758. }
  14759. ValueTree::ValueTree (const ValueTree& other)
  14760. : object (other.object)
  14761. {
  14762. }
  14763. ValueTree& ValueTree::operator= (const ValueTree& other)
  14764. {
  14765. if (listeners.size() > 0)
  14766. {
  14767. if (object != 0)
  14768. object->valueTreesWithListeners.removeValue (this);
  14769. if (other.object != 0)
  14770. other.object->valueTreesWithListeners.add (this);
  14771. }
  14772. object = other.object;
  14773. return *this;
  14774. }
  14775. ValueTree::~ValueTree()
  14776. {
  14777. if (listeners.size() > 0 && object != 0)
  14778. object->valueTreesWithListeners.removeValue (this);
  14779. }
  14780. bool ValueTree::operator== (const ValueTree& other) const throw()
  14781. {
  14782. return object == other.object;
  14783. }
  14784. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14785. {
  14786. return object != other.object;
  14787. }
  14788. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14789. {
  14790. return object == other.object
  14791. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14792. }
  14793. ValueTree ValueTree::createCopy() const
  14794. {
  14795. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14796. }
  14797. bool ValueTree::hasType (const Identifier& typeName) const
  14798. {
  14799. return object != 0 && object->type == typeName;
  14800. }
  14801. const Identifier ValueTree::getType() const
  14802. {
  14803. return object != 0 ? object->type : Identifier();
  14804. }
  14805. ValueTree ValueTree::getParent() const
  14806. {
  14807. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14808. }
  14809. ValueTree ValueTree::getSibling (const int delta) const
  14810. {
  14811. if (object == 0 || object->parent == 0)
  14812. return invalid;
  14813. const int index = object->parent->indexOf (*this) + delta;
  14814. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  14815. }
  14816. const var& ValueTree::operator[] (const Identifier& name) const
  14817. {
  14818. return object == 0 ? var::null : object->getProperty (name);
  14819. }
  14820. const var& ValueTree::getProperty (const Identifier& name) const
  14821. {
  14822. return object == 0 ? var::null : object->getProperty (name);
  14823. }
  14824. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14825. {
  14826. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14827. }
  14828. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14829. {
  14830. jassert (name.toString().isNotEmpty());
  14831. if (object != 0 && name.toString().isNotEmpty())
  14832. object->setProperty (name, newValue, undoManager);
  14833. }
  14834. bool ValueTree::hasProperty (const Identifier& name) const
  14835. {
  14836. return object != 0 && object->hasProperty (name);
  14837. }
  14838. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14839. {
  14840. if (object != 0)
  14841. object->removeProperty (name, undoManager);
  14842. }
  14843. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14844. {
  14845. if (object != 0)
  14846. object->removeAllProperties (undoManager);
  14847. }
  14848. int ValueTree::getNumProperties() const
  14849. {
  14850. return object == 0 ? 0 : object->properties.size();
  14851. }
  14852. const Identifier ValueTree::getPropertyName (const int index) const
  14853. {
  14854. return object == 0 ? Identifier()
  14855. : object->properties.getName (index);
  14856. }
  14857. class ValueTreePropertyValueSource : public Value::ValueSource,
  14858. public ValueTree::Listener
  14859. {
  14860. public:
  14861. ValueTreePropertyValueSource (const ValueTree& tree_,
  14862. const Identifier& property_,
  14863. UndoManager* const undoManager_)
  14864. : tree (tree_),
  14865. property (property_),
  14866. undoManager (undoManager_)
  14867. {
  14868. tree.addListener (this);
  14869. }
  14870. ~ValueTreePropertyValueSource()
  14871. {
  14872. tree.removeListener (this);
  14873. }
  14874. const var getValue() const
  14875. {
  14876. return tree [property];
  14877. }
  14878. void setValue (const var& newValue)
  14879. {
  14880. tree.setProperty (property, newValue, undoManager);
  14881. }
  14882. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14883. {
  14884. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14885. sendChangeMessage (false);
  14886. }
  14887. void valueTreeChildrenChanged (ValueTree&) {}
  14888. void valueTreeParentChanged (ValueTree&) {}
  14889. private:
  14890. ValueTree tree;
  14891. const Identifier property;
  14892. UndoManager* const undoManager;
  14893. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14894. };
  14895. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14896. {
  14897. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14898. }
  14899. int ValueTree::getNumChildren() const
  14900. {
  14901. return object == 0 ? 0 : object->children.size();
  14902. }
  14903. ValueTree ValueTree::getChild (int index) const
  14904. {
  14905. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14906. }
  14907. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14908. {
  14909. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14910. }
  14911. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14912. {
  14913. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14914. }
  14915. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14916. {
  14917. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14918. }
  14919. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14920. {
  14921. return object != 0 && object->isAChildOf (possibleParent.object);
  14922. }
  14923. int ValueTree::indexOf (const ValueTree& child) const
  14924. {
  14925. return object != 0 ? object->indexOf (child) : -1;
  14926. }
  14927. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14928. {
  14929. if (object != 0)
  14930. object->addChild (child.object, index, undoManager);
  14931. }
  14932. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14933. {
  14934. if (object != 0)
  14935. object->removeChild (childIndex, undoManager);
  14936. }
  14937. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14938. {
  14939. if (object != 0)
  14940. object->removeChild (object->children.indexOf (child.object), undoManager);
  14941. }
  14942. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14943. {
  14944. if (object != 0)
  14945. object->removeAllChildren (undoManager);
  14946. }
  14947. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14948. {
  14949. if (object != 0)
  14950. object->moveChild (currentIndex, newIndex, undoManager);
  14951. }
  14952. void ValueTree::addListener (Listener* listener)
  14953. {
  14954. if (listener != 0)
  14955. {
  14956. if (listeners.size() == 0 && object != 0)
  14957. object->valueTreesWithListeners.add (this);
  14958. listeners.add (listener);
  14959. }
  14960. }
  14961. void ValueTree::removeListener (Listener* listener)
  14962. {
  14963. listeners.remove (listener);
  14964. if (listeners.size() == 0 && object != 0)
  14965. object->valueTreesWithListeners.removeValue (this);
  14966. }
  14967. XmlElement* ValueTree::SharedObject::createXml() const
  14968. {
  14969. XmlElement* xml = new XmlElement (type.toString());
  14970. int i;
  14971. for (i = 0; i < properties.size(); ++i)
  14972. {
  14973. Identifier name (properties.getName(i));
  14974. const var& v = properties [name];
  14975. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  14976. xml->setAttribute (name.toString(), v.toString());
  14977. }
  14978. for (i = 0; i < children.size(); ++i)
  14979. xml->addChildElement (children.getUnchecked(i)->createXml());
  14980. return xml;
  14981. }
  14982. XmlElement* ValueTree::createXml() const
  14983. {
  14984. return object != 0 ? object->createXml() : 0;
  14985. }
  14986. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14987. {
  14988. ValueTree v (xml.getTagName());
  14989. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  14990. for (int i = 0; i < numAtts; ++i)
  14991. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  14992. forEachXmlChildElement (xml, e)
  14993. {
  14994. v.addChild (fromXml (*e), -1, 0);
  14995. }
  14996. return v;
  14997. }
  14998. void ValueTree::writeToStream (OutputStream& output)
  14999. {
  15000. output.writeString (getType().toString());
  15001. const int numProps = getNumProperties();
  15002. output.writeCompressedInt (numProps);
  15003. int i;
  15004. for (i = 0; i < numProps; ++i)
  15005. {
  15006. const Identifier name (getPropertyName(i));
  15007. output.writeString (name.toString());
  15008. getProperty(name).writeToStream (output);
  15009. }
  15010. const int numChildren = getNumChildren();
  15011. output.writeCompressedInt (numChildren);
  15012. for (i = 0; i < numChildren; ++i)
  15013. getChild (i).writeToStream (output);
  15014. }
  15015. ValueTree ValueTree::readFromStream (InputStream& input)
  15016. {
  15017. const String type (input.readString());
  15018. if (type.isEmpty())
  15019. return ValueTree::invalid;
  15020. ValueTree v (type);
  15021. const int numProps = input.readCompressedInt();
  15022. if (numProps < 0)
  15023. {
  15024. jassertfalse; // trying to read corrupted data!
  15025. return v;
  15026. }
  15027. int i;
  15028. for (i = 0; i < numProps; ++i)
  15029. {
  15030. const String name (input.readString());
  15031. jassert (name.isNotEmpty());
  15032. const var value (var::readFromStream (input));
  15033. v.setProperty (name, value, 0);
  15034. }
  15035. const int numChildren = input.readCompressedInt();
  15036. for (i = 0; i < numChildren; ++i)
  15037. v.addChild (readFromStream (input), -1, 0);
  15038. return v;
  15039. }
  15040. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  15041. {
  15042. MemoryInputStream in (data, numBytes, false);
  15043. return readFromStream (in);
  15044. }
  15045. END_JUCE_NAMESPACE
  15046. /*** End of inlined file: juce_ValueTree.cpp ***/
  15047. /*** Start of inlined file: juce_Value.cpp ***/
  15048. BEGIN_JUCE_NAMESPACE
  15049. Value::ValueSource::ValueSource()
  15050. {
  15051. }
  15052. Value::ValueSource::~ValueSource()
  15053. {
  15054. }
  15055. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  15056. {
  15057. if (synchronous)
  15058. {
  15059. for (int i = valuesWithListeners.size(); --i >= 0;)
  15060. {
  15061. Value* const v = valuesWithListeners[i];
  15062. if (v != 0)
  15063. v->callListeners();
  15064. }
  15065. }
  15066. else
  15067. {
  15068. triggerAsyncUpdate();
  15069. }
  15070. }
  15071. void Value::ValueSource::handleAsyncUpdate()
  15072. {
  15073. sendChangeMessage (true);
  15074. }
  15075. class SimpleValueSource : public Value::ValueSource
  15076. {
  15077. public:
  15078. SimpleValueSource()
  15079. {
  15080. }
  15081. SimpleValueSource (const var& initialValue)
  15082. : value (initialValue)
  15083. {
  15084. }
  15085. ~SimpleValueSource()
  15086. {
  15087. }
  15088. const var getValue() const
  15089. {
  15090. return value;
  15091. }
  15092. void setValue (const var& newValue)
  15093. {
  15094. if (newValue != value)
  15095. {
  15096. value = newValue;
  15097. sendChangeMessage (false);
  15098. }
  15099. }
  15100. private:
  15101. var value;
  15102. SimpleValueSource (const SimpleValueSource&);
  15103. SimpleValueSource& operator= (const SimpleValueSource&);
  15104. };
  15105. Value::Value()
  15106. : value (new SimpleValueSource())
  15107. {
  15108. }
  15109. Value::Value (ValueSource* const value_)
  15110. : value (value_)
  15111. {
  15112. jassert (value_ != 0);
  15113. }
  15114. Value::Value (const var& initialValue)
  15115. : value (new SimpleValueSource (initialValue))
  15116. {
  15117. }
  15118. Value::Value (const Value& other)
  15119. : value (other.value)
  15120. {
  15121. }
  15122. Value& Value::operator= (const Value& other)
  15123. {
  15124. value = other.value;
  15125. return *this;
  15126. }
  15127. Value::~Value()
  15128. {
  15129. if (listeners.size() > 0)
  15130. value->valuesWithListeners.removeValue (this);
  15131. }
  15132. const var Value::getValue() const
  15133. {
  15134. return value->getValue();
  15135. }
  15136. Value::operator const var() const
  15137. {
  15138. return getValue();
  15139. }
  15140. void Value::setValue (const var& newValue)
  15141. {
  15142. value->setValue (newValue);
  15143. }
  15144. const String Value::toString() const
  15145. {
  15146. return value->getValue().toString();
  15147. }
  15148. Value& Value::operator= (const var& newValue)
  15149. {
  15150. value->setValue (newValue);
  15151. return *this;
  15152. }
  15153. void Value::referTo (const Value& valueToReferTo)
  15154. {
  15155. if (valueToReferTo.value != value)
  15156. {
  15157. if (listeners.size() > 0)
  15158. {
  15159. value->valuesWithListeners.removeValue (this);
  15160. valueToReferTo.value->valuesWithListeners.add (this);
  15161. }
  15162. value = valueToReferTo.value;
  15163. callListeners();
  15164. }
  15165. }
  15166. bool Value::refersToSameSourceAs (const Value& other) const
  15167. {
  15168. return value == other.value;
  15169. }
  15170. bool Value::operator== (const Value& other) const
  15171. {
  15172. return value == other.value || value->getValue() == other.getValue();
  15173. }
  15174. bool Value::operator!= (const Value& other) const
  15175. {
  15176. return value != other.value && value->getValue() != other.getValue();
  15177. }
  15178. void Value::addListener (Listener* const listener)
  15179. {
  15180. if (listener != 0)
  15181. {
  15182. if (listeners.size() == 0)
  15183. value->valuesWithListeners.add (this);
  15184. listeners.add (listener);
  15185. }
  15186. }
  15187. void Value::removeListener (Listener* const listener)
  15188. {
  15189. listeners.remove (listener);
  15190. if (listeners.size() == 0)
  15191. value->valuesWithListeners.removeValue (this);
  15192. }
  15193. void Value::callListeners()
  15194. {
  15195. Value v (*this); // (create a copy in case this gets deleted by a callback)
  15196. listeners.call (&Value::Listener::valueChanged, v);
  15197. }
  15198. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  15199. {
  15200. return stream << value.toString();
  15201. }
  15202. END_JUCE_NAMESPACE
  15203. /*** End of inlined file: juce_Value.cpp ***/
  15204. /*** Start of inlined file: juce_Application.cpp ***/
  15205. BEGIN_JUCE_NAMESPACE
  15206. #if JUCE_MAC
  15207. extern void juce_initialiseMacMainMenu();
  15208. #endif
  15209. JUCEApplication::JUCEApplication()
  15210. : appReturnValue (0),
  15211. stillInitialising (true)
  15212. {
  15213. jassert (isStandaloneApp() && appInstance == 0);
  15214. appInstance = this;
  15215. }
  15216. JUCEApplication::~JUCEApplication()
  15217. {
  15218. if (appLock != 0)
  15219. {
  15220. appLock->exit();
  15221. appLock = 0;
  15222. }
  15223. jassert (appInstance == this);
  15224. appInstance = 0;
  15225. }
  15226. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  15227. JUCEApplication* JUCEApplication::appInstance = 0;
  15228. bool JUCEApplication::moreThanOneInstanceAllowed()
  15229. {
  15230. return true;
  15231. }
  15232. void JUCEApplication::anotherInstanceStarted (const String&)
  15233. {
  15234. }
  15235. void JUCEApplication::systemRequestedQuit()
  15236. {
  15237. quit();
  15238. }
  15239. void JUCEApplication::quit()
  15240. {
  15241. MessageManager::getInstance()->stopDispatchLoop();
  15242. }
  15243. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15244. {
  15245. appReturnValue = newReturnValue;
  15246. }
  15247. void JUCEApplication::actionListenerCallback (const String& message)
  15248. {
  15249. if (message.startsWith (getApplicationName() + "/"))
  15250. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15251. }
  15252. void JUCEApplication::unhandledException (const std::exception*,
  15253. const String&,
  15254. const int)
  15255. {
  15256. jassertfalse;
  15257. }
  15258. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15259. const char* const sourceFile,
  15260. const int lineNumber)
  15261. {
  15262. if (appInstance != 0)
  15263. appInstance->unhandledException (e, sourceFile, lineNumber);
  15264. }
  15265. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15266. {
  15267. return 0;
  15268. }
  15269. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15270. {
  15271. commands.add (StandardApplicationCommandIDs::quit);
  15272. }
  15273. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15274. {
  15275. if (commandID == StandardApplicationCommandIDs::quit)
  15276. {
  15277. result.setInfo (TRANS("Quit"),
  15278. TRANS("Quits the application"),
  15279. "Application",
  15280. 0);
  15281. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15282. }
  15283. }
  15284. bool JUCEApplication::perform (const InvocationInfo& info)
  15285. {
  15286. if (info.commandID == StandardApplicationCommandIDs::quit)
  15287. {
  15288. systemRequestedQuit();
  15289. return true;
  15290. }
  15291. return false;
  15292. }
  15293. bool JUCEApplication::initialiseApp (const String& commandLine)
  15294. {
  15295. commandLineParameters = commandLine.trim();
  15296. #if ! JUCE_IOS
  15297. jassert (appLock == 0); // initialiseApp must only be called once!
  15298. if (! moreThanOneInstanceAllowed())
  15299. {
  15300. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15301. if (! appLock->enter(0))
  15302. {
  15303. appLock = 0;
  15304. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15305. DBG ("Another instance is running - quitting...");
  15306. return false;
  15307. }
  15308. }
  15309. #endif
  15310. // let the app do its setting-up..
  15311. initialise (commandLineParameters);
  15312. #if JUCE_MAC
  15313. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15314. #endif
  15315. // register for broadcast new app messages
  15316. MessageManager::getInstance()->registerBroadcastListener (this);
  15317. stillInitialising = false;
  15318. return true;
  15319. }
  15320. int JUCEApplication::shutdownApp()
  15321. {
  15322. jassert (appInstance == this);
  15323. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15324. JUCE_TRY
  15325. {
  15326. // give the app a chance to clean up..
  15327. shutdown();
  15328. }
  15329. JUCE_CATCH_EXCEPTION
  15330. return getApplicationReturnValue();
  15331. }
  15332. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  15333. void JUCEApplication::appWillTerminateByForce()
  15334. {
  15335. {
  15336. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  15337. if (app != 0)
  15338. app->shutdownApp();
  15339. }
  15340. shutdownJuce_GUI();
  15341. }
  15342. int JUCEApplication::main (const String& commandLine)
  15343. {
  15344. ScopedJuceInitialiser_GUI libraryInitialiser;
  15345. jassert (createInstance != 0);
  15346. int returnCode = 0;
  15347. {
  15348. const ScopedPointer<JUCEApplication> app (createInstance());
  15349. if (! app->initialiseApp (commandLine))
  15350. return 0;
  15351. JUCE_TRY
  15352. {
  15353. // loop until a quit message is received..
  15354. MessageManager::getInstance()->runDispatchLoop();
  15355. }
  15356. JUCE_CATCH_EXCEPTION
  15357. returnCode = app->shutdownApp();
  15358. }
  15359. return returnCode;
  15360. }
  15361. #if JUCE_IOS
  15362. extern int juce_iOSMain (int argc, const char* argv[]);
  15363. #endif
  15364. #if ! JUCE_WINDOWS
  15365. extern const char* juce_Argv0;
  15366. #endif
  15367. int JUCEApplication::main (int argc, const char* argv[])
  15368. {
  15369. JUCE_AUTORELEASEPOOL
  15370. #if ! JUCE_WINDOWS
  15371. jassert (createInstance != 0);
  15372. juce_Argv0 = argv[0];
  15373. #endif
  15374. #if JUCE_IOS
  15375. return juce_iOSMain (argc, argv);
  15376. #else
  15377. String cmd;
  15378. for (int i = 1; i < argc; ++i)
  15379. cmd << argv[i] << ' ';
  15380. return JUCEApplication::main (cmd);
  15381. #endif
  15382. }
  15383. END_JUCE_NAMESPACE
  15384. /*** End of inlined file: juce_Application.cpp ***/
  15385. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15386. BEGIN_JUCE_NAMESPACE
  15387. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15388. : commandID (commandID_),
  15389. flags (0)
  15390. {
  15391. }
  15392. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15393. const String& description_,
  15394. const String& categoryName_,
  15395. const int flags_) throw()
  15396. {
  15397. shortName = shortName_;
  15398. description = description_;
  15399. categoryName = categoryName_;
  15400. flags = flags_;
  15401. }
  15402. void ApplicationCommandInfo::setActive (const bool b) throw()
  15403. {
  15404. if (b)
  15405. flags &= ~isDisabled;
  15406. else
  15407. flags |= isDisabled;
  15408. }
  15409. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15410. {
  15411. if (b)
  15412. flags |= isTicked;
  15413. else
  15414. flags &= ~isTicked;
  15415. }
  15416. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15417. {
  15418. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15419. }
  15420. END_JUCE_NAMESPACE
  15421. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15422. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15423. BEGIN_JUCE_NAMESPACE
  15424. ApplicationCommandManager::ApplicationCommandManager()
  15425. : firstTarget (0)
  15426. {
  15427. keyMappings = new KeyPressMappingSet (this);
  15428. Desktop::getInstance().addFocusChangeListener (this);
  15429. }
  15430. ApplicationCommandManager::~ApplicationCommandManager()
  15431. {
  15432. Desktop::getInstance().removeFocusChangeListener (this);
  15433. keyMappings = 0;
  15434. }
  15435. void ApplicationCommandManager::clearCommands()
  15436. {
  15437. commands.clear();
  15438. keyMappings->clearAllKeyPresses();
  15439. triggerAsyncUpdate();
  15440. }
  15441. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15442. {
  15443. // zero isn't a valid command ID!
  15444. jassert (newCommand.commandID != 0);
  15445. // the name isn't optional!
  15446. jassert (newCommand.shortName.isNotEmpty());
  15447. if (getCommandForID (newCommand.commandID) == 0)
  15448. {
  15449. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15450. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15451. commands.add (newInfo);
  15452. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15453. triggerAsyncUpdate();
  15454. }
  15455. else
  15456. {
  15457. // trying to re-register the same command with different parameters?
  15458. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15459. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15460. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15461. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15462. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15463. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15464. }
  15465. }
  15466. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15467. {
  15468. if (target != 0)
  15469. {
  15470. Array <CommandID> commandIDs;
  15471. target->getAllCommands (commandIDs);
  15472. for (int i = 0; i < commandIDs.size(); ++i)
  15473. {
  15474. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15475. target->getCommandInfo (info.commandID, info);
  15476. registerCommand (info);
  15477. }
  15478. }
  15479. }
  15480. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15481. {
  15482. for (int i = commands.size(); --i >= 0;)
  15483. {
  15484. if (commands.getUnchecked (i)->commandID == commandID)
  15485. {
  15486. commands.remove (i);
  15487. triggerAsyncUpdate();
  15488. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15489. for (int j = keys.size(); --j >= 0;)
  15490. keyMappings->removeKeyPress (keys.getReference (j));
  15491. }
  15492. }
  15493. }
  15494. void ApplicationCommandManager::commandStatusChanged()
  15495. {
  15496. triggerAsyncUpdate();
  15497. }
  15498. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15499. {
  15500. for (int i = commands.size(); --i >= 0;)
  15501. if (commands.getUnchecked(i)->commandID == commandID)
  15502. return commands.getUnchecked(i);
  15503. return 0;
  15504. }
  15505. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15506. {
  15507. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15508. return (ci != 0) ? ci->shortName : String::empty;
  15509. }
  15510. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15511. {
  15512. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15513. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15514. : String::empty;
  15515. }
  15516. const StringArray ApplicationCommandManager::getCommandCategories() const
  15517. {
  15518. StringArray s;
  15519. for (int i = 0; i < commands.size(); ++i)
  15520. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15521. return s;
  15522. }
  15523. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15524. {
  15525. Array <CommandID> results;
  15526. for (int i = 0; i < commands.size(); ++i)
  15527. if (commands.getUnchecked(i)->categoryName == categoryName)
  15528. results.add (commands.getUnchecked(i)->commandID);
  15529. return results;
  15530. }
  15531. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15532. {
  15533. ApplicationCommandTarget::InvocationInfo info (commandID);
  15534. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15535. return invoke (info, asynchronously);
  15536. }
  15537. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15538. {
  15539. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15540. // manager first..
  15541. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15542. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  15543. if (target == 0)
  15544. return false;
  15545. ApplicationCommandInfo commandInfo (0);
  15546. target->getCommandInfo (info_.commandID, commandInfo);
  15547. ApplicationCommandTarget::InvocationInfo info (info_);
  15548. info.commandFlags = commandInfo.flags;
  15549. sendListenerInvokeCallback (info);
  15550. const bool ok = target->invoke (info, asynchronously);
  15551. commandStatusChanged();
  15552. return ok;
  15553. }
  15554. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15555. {
  15556. return firstTarget != 0 ? firstTarget
  15557. : findDefaultComponentTarget();
  15558. }
  15559. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15560. {
  15561. firstTarget = newTarget;
  15562. }
  15563. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15564. ApplicationCommandInfo& upToDateInfo)
  15565. {
  15566. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15567. if (target == 0)
  15568. target = JUCEApplication::getInstance();
  15569. if (target != 0)
  15570. target = target->getTargetForCommand (commandID);
  15571. if (target != 0)
  15572. target->getCommandInfo (commandID, upToDateInfo);
  15573. return target;
  15574. }
  15575. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15576. {
  15577. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15578. if (target == 0 && c != 0)
  15579. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15580. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15581. return target;
  15582. }
  15583. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15584. {
  15585. Component* c = Component::getCurrentlyFocusedComponent();
  15586. if (c == 0)
  15587. {
  15588. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15589. if (activeWindow != 0)
  15590. {
  15591. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15592. if (c == 0)
  15593. c = activeWindow;
  15594. }
  15595. }
  15596. if (c == 0 && Process::isForegroundProcess())
  15597. {
  15598. // getting a bit desperate now - try all desktop comps..
  15599. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15600. {
  15601. ApplicationCommandTarget* const target
  15602. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15603. ->getPeer()->getLastFocusedSubcomponent());
  15604. if (target != 0)
  15605. return target;
  15606. }
  15607. }
  15608. if (c != 0)
  15609. {
  15610. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15611. // if we're focused on a ResizableWindow, chances are that it's the content
  15612. // component that really should get the event. And if not, the event will
  15613. // still be passed up to the top level window anyway, so let's send it to the
  15614. // content comp.
  15615. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15616. c = resizableWindow->getContentComponent();
  15617. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15618. if (target != 0)
  15619. return target;
  15620. }
  15621. return JUCEApplication::getInstance();
  15622. }
  15623. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15624. {
  15625. listeners.add (listener);
  15626. }
  15627. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15628. {
  15629. listeners.remove (listener);
  15630. }
  15631. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15632. {
  15633. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15634. }
  15635. void ApplicationCommandManager::handleAsyncUpdate()
  15636. {
  15637. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15638. }
  15639. void ApplicationCommandManager::globalFocusChanged (Component*)
  15640. {
  15641. commandStatusChanged();
  15642. }
  15643. END_JUCE_NAMESPACE
  15644. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15645. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15646. BEGIN_JUCE_NAMESPACE
  15647. ApplicationCommandTarget::ApplicationCommandTarget()
  15648. {
  15649. }
  15650. ApplicationCommandTarget::~ApplicationCommandTarget()
  15651. {
  15652. messageInvoker = 0;
  15653. }
  15654. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15655. {
  15656. if (isCommandActive (info.commandID))
  15657. {
  15658. if (async)
  15659. {
  15660. if (messageInvoker == 0)
  15661. messageInvoker = new CommandTargetMessageInvoker (this);
  15662. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15663. return true;
  15664. }
  15665. else
  15666. {
  15667. const bool success = perform (info);
  15668. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15669. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15670. // returns the command's info.
  15671. return success;
  15672. }
  15673. }
  15674. return false;
  15675. }
  15676. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15677. {
  15678. Component* c = dynamic_cast <Component*> (this);
  15679. if (c != 0)
  15680. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15681. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15682. return 0;
  15683. }
  15684. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15685. {
  15686. ApplicationCommandTarget* target = this;
  15687. int depth = 0;
  15688. while (target != 0)
  15689. {
  15690. Array <CommandID> commandIDs;
  15691. target->getAllCommands (commandIDs);
  15692. if (commandIDs.contains (commandID))
  15693. return target;
  15694. target = target->getNextCommandTarget();
  15695. ++depth;
  15696. jassert (depth < 100); // could be a recursive command chain??
  15697. jassert (target != this); // definitely a recursive command chain!
  15698. if (depth > 100 || target == this)
  15699. break;
  15700. }
  15701. if (target == 0)
  15702. {
  15703. target = JUCEApplication::getInstance();
  15704. if (target != 0)
  15705. {
  15706. Array <CommandID> commandIDs;
  15707. target->getAllCommands (commandIDs);
  15708. if (commandIDs.contains (commandID))
  15709. return target;
  15710. }
  15711. }
  15712. return 0;
  15713. }
  15714. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15715. {
  15716. ApplicationCommandInfo info (commandID);
  15717. info.flags = ApplicationCommandInfo::isDisabled;
  15718. getCommandInfo (commandID, info);
  15719. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15720. }
  15721. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15722. {
  15723. ApplicationCommandTarget* target = this;
  15724. int depth = 0;
  15725. while (target != 0)
  15726. {
  15727. if (target->tryToInvoke (info, async))
  15728. return true;
  15729. target = target->getNextCommandTarget();
  15730. ++depth;
  15731. jassert (depth < 100); // could be a recursive command chain??
  15732. jassert (target != this); // definitely a recursive command chain!
  15733. if (depth > 100 || target == this)
  15734. break;
  15735. }
  15736. if (target == 0)
  15737. {
  15738. target = JUCEApplication::getInstance();
  15739. if (target != 0)
  15740. return target->tryToInvoke (info, async);
  15741. }
  15742. return false;
  15743. }
  15744. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15745. {
  15746. ApplicationCommandTarget::InvocationInfo info (commandID);
  15747. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15748. return invoke (info, asynchronously);
  15749. }
  15750. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15751. : commandID (commandID_),
  15752. commandFlags (0),
  15753. invocationMethod (direct),
  15754. originatingComponent (0),
  15755. isKeyDown (false),
  15756. millisecsSinceKeyPressed (0)
  15757. {
  15758. }
  15759. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15760. : owner (owner_)
  15761. {
  15762. }
  15763. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15764. {
  15765. }
  15766. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15767. {
  15768. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15769. owner->tryToInvoke (*info, false);
  15770. }
  15771. END_JUCE_NAMESPACE
  15772. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15773. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15774. BEGIN_JUCE_NAMESPACE
  15775. juce_ImplementSingleton (ApplicationProperties)
  15776. ApplicationProperties::ApplicationProperties()
  15777. : msBeforeSaving (3000),
  15778. options (PropertiesFile::storeAsBinary),
  15779. commonSettingsAreReadOnly (0),
  15780. processLock (0)
  15781. {
  15782. }
  15783. ApplicationProperties::~ApplicationProperties()
  15784. {
  15785. closeFiles();
  15786. clearSingletonInstance();
  15787. }
  15788. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15789. const String& fileNameSuffix,
  15790. const String& folderName_,
  15791. const int millisecondsBeforeSaving,
  15792. const int propertiesFileOptions,
  15793. InterProcessLock* processLock_)
  15794. {
  15795. appName = applicationName;
  15796. fileSuffix = fileNameSuffix;
  15797. folderName = folderName_;
  15798. msBeforeSaving = millisecondsBeforeSaving;
  15799. options = propertiesFileOptions;
  15800. processLock = processLock_;
  15801. }
  15802. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15803. const bool testCommonSettings,
  15804. const bool showWarningDialogOnFailure)
  15805. {
  15806. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15807. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15808. if (! (userOk && commonOk))
  15809. {
  15810. if (showWarningDialogOnFailure)
  15811. {
  15812. String filenames;
  15813. if (userProps != 0 && ! userOk)
  15814. filenames << '\n' << userProps->getFile().getFullPathName();
  15815. if (commonProps != 0 && ! commonOk)
  15816. filenames << '\n' << commonProps->getFile().getFullPathName();
  15817. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15818. appName + TRANS(" - Unable to save settings"),
  15819. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15820. + appName + TRANS(" needs to be able to write to the following files:\n")
  15821. + filenames
  15822. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15823. }
  15824. return false;
  15825. }
  15826. return true;
  15827. }
  15828. void ApplicationProperties::openFiles()
  15829. {
  15830. // You need to call setStorageParameters() before trying to get hold of the
  15831. // properties!
  15832. jassert (appName.isNotEmpty());
  15833. if (appName.isNotEmpty())
  15834. {
  15835. if (userProps == 0)
  15836. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15837. false, msBeforeSaving, options, processLock);
  15838. if (commonProps == 0)
  15839. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15840. true, msBeforeSaving, options, processLock);
  15841. userProps->setFallbackPropertySet (commonProps);
  15842. }
  15843. }
  15844. PropertiesFile* ApplicationProperties::getUserSettings()
  15845. {
  15846. if (userProps == 0)
  15847. openFiles();
  15848. return userProps;
  15849. }
  15850. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15851. {
  15852. if (commonProps == 0)
  15853. openFiles();
  15854. if (returnUserPropsIfReadOnly)
  15855. {
  15856. if (commonSettingsAreReadOnly == 0)
  15857. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15858. if (commonSettingsAreReadOnly > 0)
  15859. return userProps;
  15860. }
  15861. return commonProps;
  15862. }
  15863. bool ApplicationProperties::saveIfNeeded()
  15864. {
  15865. return (userProps == 0 || userProps->saveIfNeeded())
  15866. && (commonProps == 0 || commonProps->saveIfNeeded());
  15867. }
  15868. void ApplicationProperties::closeFiles()
  15869. {
  15870. userProps = 0;
  15871. commonProps = 0;
  15872. }
  15873. END_JUCE_NAMESPACE
  15874. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15875. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15876. BEGIN_JUCE_NAMESPACE
  15877. namespace PropertyFileConstants
  15878. {
  15879. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15880. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15881. static const char* const fileTag = "PROPERTIES";
  15882. static const char* const valueTag = "VALUE";
  15883. static const char* const nameAttribute = "name";
  15884. static const char* const valueAttribute = "val";
  15885. }
  15886. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15887. const int options_, InterProcessLock* const processLock_)
  15888. : PropertySet (ignoreCaseOfKeyNames),
  15889. file (f),
  15890. timerInterval (millisecondsBeforeSaving),
  15891. options (options_),
  15892. loadedOk (false),
  15893. needsWriting (false),
  15894. processLock (processLock_)
  15895. {
  15896. // You need to correctly specify just one storage format for the file
  15897. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15898. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15899. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15900. ProcessScopedLock pl (createProcessLock());
  15901. if (pl != 0 && ! pl->isLocked())
  15902. return; // locking failure..
  15903. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15904. if (fileStream != 0)
  15905. {
  15906. int magicNumber = fileStream->readInt();
  15907. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15908. {
  15909. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15910. magicNumber = PropertyFileConstants::magicNumber;
  15911. }
  15912. if (magicNumber == PropertyFileConstants::magicNumber)
  15913. {
  15914. loadedOk = true;
  15915. BufferedInputStream in (fileStream.release(), 2048, true);
  15916. int numValues = in.readInt();
  15917. while (--numValues >= 0 && ! in.isExhausted())
  15918. {
  15919. const String key (in.readString());
  15920. const String value (in.readString());
  15921. jassert (key.isNotEmpty());
  15922. if (key.isNotEmpty())
  15923. getAllProperties().set (key, value);
  15924. }
  15925. }
  15926. else
  15927. {
  15928. // Not a binary props file - let's see if it's XML..
  15929. fileStream = 0;
  15930. XmlDocument parser (f);
  15931. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15932. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15933. {
  15934. doc = parser.getDocumentElement();
  15935. if (doc != 0)
  15936. {
  15937. loadedOk = true;
  15938. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15939. {
  15940. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15941. if (name.isNotEmpty())
  15942. {
  15943. getAllProperties().set (name,
  15944. e->getFirstChildElement() != 0
  15945. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15946. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15947. }
  15948. }
  15949. }
  15950. else
  15951. {
  15952. // must be a pretty broken XML file we're trying to parse here,
  15953. // or a sign that this object needs an InterProcessLock,
  15954. // or just a failure reading the file. This last reason is why
  15955. // we don't jassertfalse here.
  15956. }
  15957. }
  15958. }
  15959. }
  15960. else
  15961. {
  15962. loadedOk = ! f.exists();
  15963. }
  15964. }
  15965. PropertiesFile::~PropertiesFile()
  15966. {
  15967. if (! saveIfNeeded())
  15968. jassertfalse;
  15969. }
  15970. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15971. {
  15972. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15973. }
  15974. bool PropertiesFile::saveIfNeeded()
  15975. {
  15976. const ScopedLock sl (getLock());
  15977. return (! needsWriting) || save();
  15978. }
  15979. bool PropertiesFile::needsToBeSaved() const
  15980. {
  15981. const ScopedLock sl (getLock());
  15982. return needsWriting;
  15983. }
  15984. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15985. {
  15986. const ScopedLock sl (getLock());
  15987. needsWriting = needsToBeSaved_;
  15988. }
  15989. bool PropertiesFile::save()
  15990. {
  15991. const ScopedLock sl (getLock());
  15992. stopTimer();
  15993. if (file == File::nonexistent
  15994. || file.isDirectory()
  15995. || ! file.getParentDirectory().createDirectory())
  15996. return false;
  15997. if ((options & storeAsXML) != 0)
  15998. {
  15999. XmlElement doc (PropertyFileConstants::fileTag);
  16000. for (int i = 0; i < getAllProperties().size(); ++i)
  16001. {
  16002. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  16003. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  16004. // if the value seems to contain xml, store it as such..
  16005. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  16006. XmlElement* const childElement = xmlContent.getDocumentElement();
  16007. if (childElement != 0)
  16008. e->addChildElement (childElement);
  16009. else
  16010. e->setAttribute (PropertyFileConstants::valueAttribute,
  16011. getAllProperties().getAllValues() [i]);
  16012. }
  16013. ProcessScopedLock pl (createProcessLock());
  16014. if (pl != 0 && ! pl->isLocked())
  16015. return false; // locking failure..
  16016. if (doc.writeToFile (file, String::empty))
  16017. {
  16018. needsWriting = false;
  16019. return true;
  16020. }
  16021. }
  16022. else
  16023. {
  16024. ProcessScopedLock pl (createProcessLock());
  16025. if (pl != 0 && ! pl->isLocked())
  16026. return false; // locking failure..
  16027. TemporaryFile tempFile (file);
  16028. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  16029. if (out != 0)
  16030. {
  16031. if ((options & storeAsCompressedBinary) != 0)
  16032. {
  16033. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  16034. out->flush();
  16035. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  16036. }
  16037. else
  16038. {
  16039. // have you set up the storage option flags correctly?
  16040. jassert ((options & storeAsBinary) != 0);
  16041. out->writeInt (PropertyFileConstants::magicNumber);
  16042. }
  16043. const int numProperties = getAllProperties().size();
  16044. out->writeInt (numProperties);
  16045. for (int i = 0; i < numProperties; ++i)
  16046. {
  16047. out->writeString (getAllProperties().getAllKeys() [i]);
  16048. out->writeString (getAllProperties().getAllValues() [i]);
  16049. }
  16050. out = 0;
  16051. if (tempFile.overwriteTargetFileWithTemporary())
  16052. {
  16053. needsWriting = false;
  16054. return true;
  16055. }
  16056. }
  16057. }
  16058. return false;
  16059. }
  16060. void PropertiesFile::timerCallback()
  16061. {
  16062. saveIfNeeded();
  16063. }
  16064. void PropertiesFile::propertyChanged()
  16065. {
  16066. sendChangeMessage (this);
  16067. needsWriting = true;
  16068. if (timerInterval > 0)
  16069. startTimer (timerInterval);
  16070. else if (timerInterval == 0)
  16071. saveIfNeeded();
  16072. }
  16073. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  16074. const String& fileNameSuffix,
  16075. const String& folderName,
  16076. const bool commonToAllUsers)
  16077. {
  16078. // mustn't have illegal characters in this name..
  16079. jassert (applicationName == File::createLegalFileName (applicationName));
  16080. #if JUCE_MAC || JUCE_IOS
  16081. File dir (commonToAllUsers ? "/Library/Preferences"
  16082. : "~/Library/Preferences");
  16083. if (folderName.isNotEmpty())
  16084. dir = dir.getChildFile (folderName);
  16085. #endif
  16086. #ifdef JUCE_LINUX
  16087. const File dir ((commonToAllUsers ? "/var/" : "~/")
  16088. + (folderName.isNotEmpty() ? folderName
  16089. : ("." + applicationName)));
  16090. #endif
  16091. #if JUCE_WINDOWS
  16092. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  16093. : File::userApplicationDataDirectory));
  16094. if (dir == File::nonexistent)
  16095. return File::nonexistent;
  16096. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  16097. : applicationName);
  16098. #endif
  16099. return dir.getChildFile (applicationName)
  16100. .withFileExtension (fileNameSuffix);
  16101. }
  16102. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  16103. const String& fileNameSuffix,
  16104. const String& folderName,
  16105. const bool commonToAllUsers,
  16106. const int millisecondsBeforeSaving,
  16107. const int propertiesFileOptions,
  16108. InterProcessLock* processLock_)
  16109. {
  16110. const File file (getDefaultAppSettingsFile (applicationName,
  16111. fileNameSuffix,
  16112. folderName,
  16113. commonToAllUsers));
  16114. jassert (file != File::nonexistent);
  16115. if (file == File::nonexistent)
  16116. return 0;
  16117. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  16118. }
  16119. END_JUCE_NAMESPACE
  16120. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  16121. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  16122. BEGIN_JUCE_NAMESPACE
  16123. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  16124. const String& fileWildcard_,
  16125. const String& openFileDialogTitle_,
  16126. const String& saveFileDialogTitle_)
  16127. : changedSinceSave (false),
  16128. fileExtension (fileExtension_),
  16129. fileWildcard (fileWildcard_),
  16130. openFileDialogTitle (openFileDialogTitle_),
  16131. saveFileDialogTitle (saveFileDialogTitle_)
  16132. {
  16133. }
  16134. FileBasedDocument::~FileBasedDocument()
  16135. {
  16136. }
  16137. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  16138. {
  16139. if (changedSinceSave != hasChanged)
  16140. {
  16141. changedSinceSave = hasChanged;
  16142. sendChangeMessage (this);
  16143. }
  16144. }
  16145. void FileBasedDocument::changed()
  16146. {
  16147. changedSinceSave = true;
  16148. sendChangeMessage (this);
  16149. }
  16150. void FileBasedDocument::setFile (const File& newFile)
  16151. {
  16152. if (documentFile != newFile)
  16153. {
  16154. documentFile = newFile;
  16155. changed();
  16156. }
  16157. }
  16158. bool FileBasedDocument::loadFrom (const File& newFile,
  16159. const bool showMessageOnFailure)
  16160. {
  16161. MouseCursor::showWaitCursor();
  16162. const File oldFile (documentFile);
  16163. documentFile = newFile;
  16164. String error;
  16165. if (newFile.existsAsFile())
  16166. {
  16167. error = loadDocument (newFile);
  16168. if (error.isEmpty())
  16169. {
  16170. setChangedFlag (false);
  16171. MouseCursor::hideWaitCursor();
  16172. setLastDocumentOpened (newFile);
  16173. return true;
  16174. }
  16175. }
  16176. else
  16177. {
  16178. error = "The file doesn't exist";
  16179. }
  16180. documentFile = oldFile;
  16181. MouseCursor::hideWaitCursor();
  16182. if (showMessageOnFailure)
  16183. {
  16184. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16185. TRANS("Failed to open file..."),
  16186. TRANS("There was an error while trying to load the file:\n\n")
  16187. + newFile.getFullPathName()
  16188. + "\n\n"
  16189. + error);
  16190. }
  16191. return false;
  16192. }
  16193. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  16194. {
  16195. FileChooser fc (openFileDialogTitle,
  16196. getLastDocumentOpened(),
  16197. fileWildcard);
  16198. if (fc.browseForFileToOpen())
  16199. return loadFrom (fc.getResult(), showMessageOnFailure);
  16200. return false;
  16201. }
  16202. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  16203. const bool showMessageOnFailure)
  16204. {
  16205. return saveAs (documentFile,
  16206. false,
  16207. askUserForFileIfNotSpecified,
  16208. showMessageOnFailure);
  16209. }
  16210. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  16211. const bool warnAboutOverwritingExistingFiles,
  16212. const bool askUserForFileIfNotSpecified,
  16213. const bool showMessageOnFailure)
  16214. {
  16215. if (newFile == File::nonexistent)
  16216. {
  16217. if (askUserForFileIfNotSpecified)
  16218. {
  16219. return saveAsInteractive (true);
  16220. }
  16221. else
  16222. {
  16223. // can't save to an unspecified file
  16224. jassertfalse;
  16225. return failedToWriteToFile;
  16226. }
  16227. }
  16228. if (warnAboutOverwritingExistingFiles && newFile.exists())
  16229. {
  16230. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16231. TRANS("File already exists"),
  16232. TRANS("There's already a file called:\n\n")
  16233. + newFile.getFullPathName()
  16234. + TRANS("\n\nAre you sure you want to overwrite it?"),
  16235. TRANS("overwrite"),
  16236. TRANS("cancel")))
  16237. {
  16238. return userCancelledSave;
  16239. }
  16240. }
  16241. MouseCursor::showWaitCursor();
  16242. const File oldFile (documentFile);
  16243. documentFile = newFile;
  16244. String error (saveDocument (newFile));
  16245. if (error.isEmpty())
  16246. {
  16247. setChangedFlag (false);
  16248. MouseCursor::hideWaitCursor();
  16249. return savedOk;
  16250. }
  16251. documentFile = oldFile;
  16252. MouseCursor::hideWaitCursor();
  16253. if (showMessageOnFailure)
  16254. {
  16255. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16256. TRANS("Error writing to file..."),
  16257. TRANS("An error occurred while trying to save \"")
  16258. + getDocumentTitle()
  16259. + TRANS("\" to the file:\n\n")
  16260. + newFile.getFullPathName()
  16261. + "\n\n"
  16262. + error);
  16263. }
  16264. return failedToWriteToFile;
  16265. }
  16266. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16267. {
  16268. if (! hasChangedSinceSaved())
  16269. return savedOk;
  16270. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16271. TRANS("Closing document..."),
  16272. TRANS("Do you want to save the changes to \"")
  16273. + getDocumentTitle() + "\"?",
  16274. TRANS("save"),
  16275. TRANS("discard changes"),
  16276. TRANS("cancel"));
  16277. if (r == 1)
  16278. {
  16279. // save changes
  16280. return save (true, true);
  16281. }
  16282. else if (r == 2)
  16283. {
  16284. // discard changes
  16285. return savedOk;
  16286. }
  16287. return userCancelledSave;
  16288. }
  16289. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16290. {
  16291. File f;
  16292. if (documentFile.existsAsFile())
  16293. f = documentFile;
  16294. else
  16295. f = getLastDocumentOpened();
  16296. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16297. if (legalFilename.isEmpty())
  16298. legalFilename = "unnamed";
  16299. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16300. f = f.getSiblingFile (legalFilename);
  16301. else
  16302. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16303. f = f.withFileExtension (fileExtension)
  16304. .getNonexistentSibling (true);
  16305. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16306. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16307. {
  16308. File chosen (fc.getResult());
  16309. if (chosen.getFileExtension().isEmpty())
  16310. {
  16311. chosen = chosen.withFileExtension (fileExtension);
  16312. if (chosen.exists())
  16313. {
  16314. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16315. TRANS("File already exists"),
  16316. TRANS("There's already a file called:")
  16317. + "\n\n" + chosen.getFullPathName()
  16318. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16319. TRANS("overwrite"),
  16320. TRANS("cancel")))
  16321. {
  16322. return userCancelledSave;
  16323. }
  16324. }
  16325. }
  16326. setLastDocumentOpened (chosen);
  16327. return saveAs (chosen, false, false, true);
  16328. }
  16329. return userCancelledSave;
  16330. }
  16331. END_JUCE_NAMESPACE
  16332. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16333. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16334. BEGIN_JUCE_NAMESPACE
  16335. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16336. : maxNumberOfItems (10)
  16337. {
  16338. }
  16339. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16340. {
  16341. }
  16342. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16343. {
  16344. maxNumberOfItems = jmax (1, newMaxNumber);
  16345. while (getNumFiles() > maxNumberOfItems)
  16346. files.remove (getNumFiles() - 1);
  16347. }
  16348. int RecentlyOpenedFilesList::getNumFiles() const
  16349. {
  16350. return files.size();
  16351. }
  16352. const File RecentlyOpenedFilesList::getFile (const int index) const
  16353. {
  16354. return File (files [index]);
  16355. }
  16356. void RecentlyOpenedFilesList::clear()
  16357. {
  16358. files.clear();
  16359. }
  16360. void RecentlyOpenedFilesList::addFile (const File& file)
  16361. {
  16362. const String path (file.getFullPathName());
  16363. files.removeString (path, true);
  16364. files.insert (0, path);
  16365. setMaxNumberOfItems (maxNumberOfItems);
  16366. }
  16367. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16368. {
  16369. for (int i = getNumFiles(); --i >= 0;)
  16370. if (! getFile(i).exists())
  16371. files.remove (i);
  16372. }
  16373. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16374. const int baseItemId,
  16375. const bool showFullPaths,
  16376. const bool dontAddNonExistentFiles,
  16377. const File** filesToAvoid)
  16378. {
  16379. int num = 0;
  16380. for (int i = 0; i < getNumFiles(); ++i)
  16381. {
  16382. const File f (getFile(i));
  16383. if ((! dontAddNonExistentFiles) || f.exists())
  16384. {
  16385. bool needsAvoiding = false;
  16386. if (filesToAvoid != 0)
  16387. {
  16388. const File** avoid = filesToAvoid;
  16389. while (*avoid != 0)
  16390. {
  16391. if (f == **avoid)
  16392. {
  16393. needsAvoiding = true;
  16394. break;
  16395. }
  16396. ++avoid;
  16397. }
  16398. }
  16399. if (! needsAvoiding)
  16400. {
  16401. menuToAddTo.addItem (baseItemId + i,
  16402. showFullPaths ? f.getFullPathName()
  16403. : f.getFileName());
  16404. ++num;
  16405. }
  16406. }
  16407. }
  16408. return num;
  16409. }
  16410. const String RecentlyOpenedFilesList::toString() const
  16411. {
  16412. return files.joinIntoString ("\n");
  16413. }
  16414. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16415. {
  16416. clear();
  16417. files.addLines (stringifiedVersion);
  16418. setMaxNumberOfItems (maxNumberOfItems);
  16419. }
  16420. END_JUCE_NAMESPACE
  16421. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16422. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16423. BEGIN_JUCE_NAMESPACE
  16424. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16425. const int minimumTransactions)
  16426. : totalUnitsStored (0),
  16427. nextIndex (0),
  16428. newTransaction (true),
  16429. reentrancyCheck (false)
  16430. {
  16431. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16432. minimumTransactions);
  16433. }
  16434. UndoManager::~UndoManager()
  16435. {
  16436. clearUndoHistory();
  16437. }
  16438. void UndoManager::clearUndoHistory()
  16439. {
  16440. transactions.clear();
  16441. transactionNames.clear();
  16442. totalUnitsStored = 0;
  16443. nextIndex = 0;
  16444. sendChangeMessage (this);
  16445. }
  16446. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16447. {
  16448. return totalUnitsStored;
  16449. }
  16450. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16451. const int minimumTransactions)
  16452. {
  16453. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16454. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16455. }
  16456. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16457. {
  16458. if (command_ != 0)
  16459. {
  16460. ScopedPointer<UndoableAction> command (command_);
  16461. if (actionName.isNotEmpty())
  16462. currentTransactionName = actionName;
  16463. if (reentrancyCheck)
  16464. {
  16465. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16466. // undo() methods, or else these actions won't actually get done.
  16467. return false;
  16468. }
  16469. else if (command->perform())
  16470. {
  16471. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16472. if (commandSet != 0 && ! newTransaction)
  16473. {
  16474. UndoableAction* lastAction = commandSet->getLast();
  16475. if (lastAction != 0)
  16476. {
  16477. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16478. if (coalescedAction != 0)
  16479. {
  16480. command = coalescedAction;
  16481. totalUnitsStored -= lastAction->getSizeInUnits();
  16482. commandSet->removeLast();
  16483. }
  16484. }
  16485. }
  16486. else
  16487. {
  16488. commandSet = new OwnedArray<UndoableAction>();
  16489. transactions.insert (nextIndex, commandSet);
  16490. transactionNames.insert (nextIndex, currentTransactionName);
  16491. ++nextIndex;
  16492. }
  16493. totalUnitsStored += command->getSizeInUnits();
  16494. commandSet->add (command.release());
  16495. newTransaction = false;
  16496. while (nextIndex < transactions.size())
  16497. {
  16498. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16499. for (int i = lastSet->size(); --i >= 0;)
  16500. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16501. transactions.removeLast();
  16502. transactionNames.remove (transactionNames.size() - 1);
  16503. }
  16504. while (nextIndex > 0
  16505. && totalUnitsStored > maxNumUnitsToKeep
  16506. && transactions.size() > minimumTransactionsToKeep)
  16507. {
  16508. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16509. for (int i = firstSet->size(); --i >= 0;)
  16510. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16511. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16512. transactions.remove (0);
  16513. transactionNames.remove (0);
  16514. --nextIndex;
  16515. }
  16516. sendChangeMessage (this);
  16517. return true;
  16518. }
  16519. }
  16520. return false;
  16521. }
  16522. void UndoManager::beginNewTransaction (const String& actionName)
  16523. {
  16524. newTransaction = true;
  16525. currentTransactionName = actionName;
  16526. }
  16527. void UndoManager::setCurrentTransactionName (const String& newName)
  16528. {
  16529. currentTransactionName = newName;
  16530. }
  16531. bool UndoManager::canUndo() const
  16532. {
  16533. return nextIndex > 0;
  16534. }
  16535. bool UndoManager::canRedo() const
  16536. {
  16537. return nextIndex < transactions.size();
  16538. }
  16539. const String UndoManager::getUndoDescription() const
  16540. {
  16541. return transactionNames [nextIndex - 1];
  16542. }
  16543. const String UndoManager::getRedoDescription() const
  16544. {
  16545. return transactionNames [nextIndex];
  16546. }
  16547. bool UndoManager::undo()
  16548. {
  16549. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16550. if (commandSet == 0)
  16551. return false;
  16552. reentrancyCheck = true;
  16553. bool failed = false;
  16554. for (int i = commandSet->size(); --i >= 0;)
  16555. {
  16556. if (! commandSet->getUnchecked(i)->undo())
  16557. {
  16558. jassertfalse;
  16559. failed = true;
  16560. break;
  16561. }
  16562. }
  16563. reentrancyCheck = false;
  16564. if (failed)
  16565. clearUndoHistory();
  16566. else
  16567. --nextIndex;
  16568. beginNewTransaction();
  16569. sendChangeMessage (this);
  16570. return true;
  16571. }
  16572. bool UndoManager::redo()
  16573. {
  16574. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16575. if (commandSet == 0)
  16576. return false;
  16577. reentrancyCheck = true;
  16578. bool failed = false;
  16579. for (int i = 0; i < commandSet->size(); ++i)
  16580. {
  16581. if (! commandSet->getUnchecked(i)->perform())
  16582. {
  16583. jassertfalse;
  16584. failed = true;
  16585. break;
  16586. }
  16587. }
  16588. reentrancyCheck = false;
  16589. if (failed)
  16590. clearUndoHistory();
  16591. else
  16592. ++nextIndex;
  16593. beginNewTransaction();
  16594. sendChangeMessage (this);
  16595. return true;
  16596. }
  16597. bool UndoManager::undoCurrentTransactionOnly()
  16598. {
  16599. return newTransaction ? false : undo();
  16600. }
  16601. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16602. {
  16603. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16604. if (commandSet != 0 && ! newTransaction)
  16605. {
  16606. for (int i = 0; i < commandSet->size(); ++i)
  16607. actionsFound.add (commandSet->getUnchecked(i));
  16608. }
  16609. }
  16610. int UndoManager::getNumActionsInCurrentTransaction() const
  16611. {
  16612. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16613. if (commandSet != 0 && ! newTransaction)
  16614. return commandSet->size();
  16615. return 0;
  16616. }
  16617. END_JUCE_NAMESPACE
  16618. /*** End of inlined file: juce_UndoManager.cpp ***/
  16619. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16620. BEGIN_JUCE_NAMESPACE
  16621. static const char* const aiffFormatName = "AIFF file";
  16622. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16623. class AiffAudioFormatReader : public AudioFormatReader
  16624. {
  16625. public:
  16626. int bytesPerFrame;
  16627. int64 dataChunkStart;
  16628. bool littleEndian;
  16629. AiffAudioFormatReader (InputStream* in)
  16630. : AudioFormatReader (in, TRANS (aiffFormatName))
  16631. {
  16632. if (input->readInt() == chunkName ("FORM"))
  16633. {
  16634. const int len = input->readIntBigEndian();
  16635. const int64 end = input->getPosition() + len;
  16636. const int nextType = input->readInt();
  16637. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16638. {
  16639. bool hasGotVer = false;
  16640. bool hasGotData = false;
  16641. bool hasGotType = false;
  16642. while (input->getPosition() < end)
  16643. {
  16644. const int type = input->readInt();
  16645. const uint32 length = (uint32) input->readIntBigEndian();
  16646. const int64 chunkEnd = input->getPosition() + length;
  16647. if (type == chunkName ("FVER"))
  16648. {
  16649. hasGotVer = true;
  16650. const int ver = input->readIntBigEndian();
  16651. if (ver != 0 && ver != (int) 0xa2805140)
  16652. break;
  16653. }
  16654. else if (type == chunkName ("COMM"))
  16655. {
  16656. hasGotType = true;
  16657. numChannels = (unsigned int) input->readShortBigEndian();
  16658. lengthInSamples = input->readIntBigEndian();
  16659. bitsPerSample = input->readShortBigEndian();
  16660. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16661. unsigned char sampleRateBytes[10];
  16662. input->read (sampleRateBytes, 10);
  16663. const int byte0 = sampleRateBytes[0];
  16664. if ((byte0 & 0x80) != 0
  16665. || byte0 <= 0x3F || byte0 > 0x40
  16666. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16667. break;
  16668. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16669. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16670. sampleRate = (int) sampRate;
  16671. if (length <= 18)
  16672. {
  16673. // some types don't have a chunk large enough to include a compression
  16674. // type, so assume it's just big-endian pcm
  16675. littleEndian = false;
  16676. }
  16677. else
  16678. {
  16679. const int compType = input->readInt();
  16680. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16681. {
  16682. littleEndian = false;
  16683. }
  16684. else if (compType == chunkName ("sowt"))
  16685. {
  16686. littleEndian = true;
  16687. }
  16688. else
  16689. {
  16690. sampleRate = 0;
  16691. break;
  16692. }
  16693. }
  16694. }
  16695. else if (type == chunkName ("SSND"))
  16696. {
  16697. hasGotData = true;
  16698. const int offset = input->readIntBigEndian();
  16699. dataChunkStart = input->getPosition() + 4 + offset;
  16700. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16701. }
  16702. else if ((hasGotVer && hasGotData && hasGotType)
  16703. || chunkEnd < input->getPosition()
  16704. || input->isExhausted())
  16705. {
  16706. break;
  16707. }
  16708. input->setPosition (chunkEnd);
  16709. }
  16710. }
  16711. }
  16712. }
  16713. ~AiffAudioFormatReader()
  16714. {
  16715. }
  16716. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16717. int64 startSampleInFile, int numSamples)
  16718. {
  16719. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16720. if (samplesAvailable < numSamples)
  16721. {
  16722. for (int i = numDestChannels; --i >= 0;)
  16723. if (destSamples[i] != 0)
  16724. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16725. numSamples = (int) samplesAvailable;
  16726. }
  16727. if (numSamples <= 0)
  16728. return true;
  16729. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16730. while (numSamples > 0)
  16731. {
  16732. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16733. char tempBuffer [tempBufSize];
  16734. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16735. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16736. if (bytesRead < numThisTime * bytesPerFrame)
  16737. {
  16738. jassert (bytesRead >= 0);
  16739. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16740. }
  16741. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16742. if (littleEndian)
  16743. {
  16744. switch (bitsPerSample)
  16745. {
  16746. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16747. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16748. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16749. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16750. default: jassertfalse; break;
  16751. }
  16752. }
  16753. else
  16754. {
  16755. switch (bitsPerSample)
  16756. {
  16757. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16758. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16759. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16760. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16761. default: jassertfalse; break;
  16762. }
  16763. }
  16764. startOffsetInDestBuffer += numThisTime;
  16765. numSamples -= numThisTime;
  16766. }
  16767. return true;
  16768. }
  16769. juce_UseDebuggingNewOperator
  16770. private:
  16771. AiffAudioFormatReader (const AiffAudioFormatReader&);
  16772. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  16773. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16774. };
  16775. class AiffAudioFormatWriter : public AudioFormatWriter
  16776. {
  16777. public:
  16778. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16779. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16780. lengthInSamples (0),
  16781. bytesWritten (0),
  16782. writeFailed (false)
  16783. {
  16784. headerPosition = out->getPosition();
  16785. writeHeader();
  16786. }
  16787. ~AiffAudioFormatWriter()
  16788. {
  16789. if ((bytesWritten & 1) != 0)
  16790. output->writeByte (0);
  16791. writeHeader();
  16792. }
  16793. bool write (const int** data, int numSamples)
  16794. {
  16795. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16796. if (writeFailed)
  16797. return false;
  16798. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16799. tempBlock.ensureSize (bytes, false);
  16800. switch (bitsPerSample)
  16801. {
  16802. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16803. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16804. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16805. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16806. default: jassertfalse; break;
  16807. }
  16808. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16809. || ! output->write (tempBlock.getData(), bytes))
  16810. {
  16811. // failed to write to disk, so let's try writing the header.
  16812. // If it's just run out of disk space, then if it does manage
  16813. // to write the header, we'll still have a useable file..
  16814. writeHeader();
  16815. writeFailed = true;
  16816. return false;
  16817. }
  16818. else
  16819. {
  16820. bytesWritten += bytes;
  16821. lengthInSamples += numSamples;
  16822. return true;
  16823. }
  16824. }
  16825. juce_UseDebuggingNewOperator
  16826. private:
  16827. MemoryBlock tempBlock;
  16828. uint32 lengthInSamples, bytesWritten;
  16829. int64 headerPosition;
  16830. bool writeFailed;
  16831. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16832. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  16833. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  16834. void writeHeader()
  16835. {
  16836. const bool couldSeekOk = output->setPosition (headerPosition);
  16837. (void) couldSeekOk;
  16838. // if this fails, you've given it an output stream that can't seek! It needs
  16839. // to be able to seek back to write the header
  16840. jassert (couldSeekOk);
  16841. const int headerLen = 54;
  16842. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16843. audioBytes += (audioBytes & 1);
  16844. output->writeInt (chunkName ("FORM"));
  16845. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16846. output->writeInt (chunkName ("AIFF"));
  16847. output->writeInt (chunkName ("COMM"));
  16848. output->writeIntBigEndian (18);
  16849. output->writeShortBigEndian ((short) numChannels);
  16850. output->writeIntBigEndian (lengthInSamples);
  16851. output->writeShortBigEndian ((short) bitsPerSample);
  16852. uint8 sampleRateBytes[10];
  16853. zeromem (sampleRateBytes, 10);
  16854. if (sampleRate <= 1)
  16855. {
  16856. sampleRateBytes[0] = 0x3f;
  16857. sampleRateBytes[1] = 0xff;
  16858. sampleRateBytes[2] = 0x80;
  16859. }
  16860. else
  16861. {
  16862. int mask = 0x40000000;
  16863. sampleRateBytes[0] = 0x40;
  16864. if (sampleRate >= mask)
  16865. {
  16866. jassertfalse;
  16867. sampleRateBytes[1] = 0x1d;
  16868. }
  16869. else
  16870. {
  16871. int n = (int) sampleRate;
  16872. int i;
  16873. for (i = 0; i <= 32 ; ++i)
  16874. {
  16875. if ((n & mask) != 0)
  16876. break;
  16877. mask >>= 1;
  16878. }
  16879. n = n << (i + 1);
  16880. sampleRateBytes[1] = (uint8) (29 - i);
  16881. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16882. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16883. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16884. sampleRateBytes[5] = (uint8) (n & 0xff);
  16885. }
  16886. }
  16887. output->write (sampleRateBytes, 10);
  16888. output->writeInt (chunkName ("SSND"));
  16889. output->writeIntBigEndian (audioBytes + 8);
  16890. output->writeInt (0);
  16891. output->writeInt (0);
  16892. jassert (output->getPosition() == headerLen);
  16893. }
  16894. };
  16895. AiffAudioFormat::AiffAudioFormat()
  16896. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16897. {
  16898. }
  16899. AiffAudioFormat::~AiffAudioFormat()
  16900. {
  16901. }
  16902. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16903. {
  16904. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16905. return Array <int> (rates);
  16906. }
  16907. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16908. {
  16909. const int depths[] = { 8, 16, 24, 0 };
  16910. return Array <int> (depths);
  16911. }
  16912. bool AiffAudioFormat::canDoStereo() { return true; }
  16913. bool AiffAudioFormat::canDoMono() { return true; }
  16914. #if JUCE_MAC
  16915. bool AiffAudioFormat::canHandleFile (const File& f)
  16916. {
  16917. if (AudioFormat::canHandleFile (f))
  16918. return true;
  16919. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16920. return type == 'AIFF' || type == 'AIFC'
  16921. || type == 'aiff' || type == 'aifc';
  16922. }
  16923. #endif
  16924. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16925. {
  16926. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16927. if (w->sampleRate != 0)
  16928. return w.release();
  16929. if (! deleteStreamIfOpeningFails)
  16930. w->input = 0;
  16931. return 0;
  16932. }
  16933. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16934. double sampleRate,
  16935. unsigned int numberOfChannels,
  16936. int bitsPerSample,
  16937. const StringPairArray& /*metadataValues*/,
  16938. int /*qualityOptionIndex*/)
  16939. {
  16940. if (getPossibleBitDepths().contains (bitsPerSample))
  16941. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16942. return 0;
  16943. }
  16944. END_JUCE_NAMESPACE
  16945. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16946. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16947. BEGIN_JUCE_NAMESPACE
  16948. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16949. : formatName (name),
  16950. fileExtensions (extensions)
  16951. {
  16952. }
  16953. AudioFormat::~AudioFormat()
  16954. {
  16955. }
  16956. bool AudioFormat::canHandleFile (const File& f)
  16957. {
  16958. for (int i = 0; i < fileExtensions.size(); ++i)
  16959. if (f.hasFileExtension (fileExtensions[i]))
  16960. return true;
  16961. return false;
  16962. }
  16963. const String& AudioFormat::getFormatName() const { return formatName; }
  16964. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16965. bool AudioFormat::isCompressed() { return false; }
  16966. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16967. END_JUCE_NAMESPACE
  16968. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16969. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  16970. BEGIN_JUCE_NAMESPACE
  16971. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16972. const String& formatName_)
  16973. : sampleRate (0),
  16974. bitsPerSample (0),
  16975. lengthInSamples (0),
  16976. numChannels (0),
  16977. usesFloatingPointData (false),
  16978. input (in),
  16979. formatName (formatName_)
  16980. {
  16981. }
  16982. AudioFormatReader::~AudioFormatReader()
  16983. {
  16984. delete input;
  16985. }
  16986. bool AudioFormatReader::read (int* const* destSamples,
  16987. int numDestChannels,
  16988. int64 startSampleInSource,
  16989. int numSamplesToRead,
  16990. const bool fillLeftoverChannelsWithCopies)
  16991. {
  16992. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16993. int startOffsetInDestBuffer = 0;
  16994. if (startSampleInSource < 0)
  16995. {
  16996. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16997. for (int i = numDestChannels; --i >= 0;)
  16998. if (destSamples[i] != 0)
  16999. zeromem (destSamples[i], sizeof (int) * silence);
  17000. startOffsetInDestBuffer += silence;
  17001. numSamplesToRead -= silence;
  17002. startSampleInSource = 0;
  17003. }
  17004. if (numSamplesToRead <= 0)
  17005. return true;
  17006. if (! readSamples (const_cast<int**> (destSamples),
  17007. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  17008. startSampleInSource, numSamplesToRead))
  17009. return false;
  17010. if (numDestChannels > (int) numChannels)
  17011. {
  17012. if (fillLeftoverChannelsWithCopies)
  17013. {
  17014. int* lastFullChannel = destSamples[0];
  17015. for (int i = (int) numChannels; --i > 0;)
  17016. {
  17017. if (destSamples[i] != 0)
  17018. {
  17019. lastFullChannel = destSamples[i];
  17020. break;
  17021. }
  17022. }
  17023. if (lastFullChannel != 0)
  17024. for (int i = numChannels; i < numDestChannels; ++i)
  17025. if (destSamples[i] != 0)
  17026. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  17027. }
  17028. else
  17029. {
  17030. for (int i = numChannels; i < numDestChannels; ++i)
  17031. if (destSamples[i] != 0)
  17032. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  17033. }
  17034. }
  17035. return true;
  17036. }
  17037. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  17038. {
  17039. float mn = buffer[0];
  17040. float mx = mn;
  17041. for (int i = 1; i < num; ++i)
  17042. {
  17043. const float s = buffer[i];
  17044. if (s > mx) mx = s;
  17045. if (s < mn) mn = s;
  17046. }
  17047. maxVal = mx;
  17048. minVal = mn;
  17049. }
  17050. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  17051. int64 numSamples,
  17052. float& lowestLeft, float& highestLeft,
  17053. float& lowestRight, float& highestRight)
  17054. {
  17055. if (numSamples <= 0)
  17056. {
  17057. lowestLeft = 0;
  17058. lowestRight = 0;
  17059. highestLeft = 0;
  17060. highestRight = 0;
  17061. return;
  17062. }
  17063. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  17064. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17065. int* tempBuffer[3];
  17066. tempBuffer[0] = tempSpace.getData();
  17067. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17068. tempBuffer[2] = 0;
  17069. if (usesFloatingPointData)
  17070. {
  17071. float lmin = 1.0e6f;
  17072. float lmax = -lmin;
  17073. float rmin = lmin;
  17074. float rmax = lmax;
  17075. while (numSamples > 0)
  17076. {
  17077. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17078. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17079. numSamples -= numToDo;
  17080. startSampleInFile += numToDo;
  17081. float bufmin, bufmax;
  17082. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufmax, bufmin);
  17083. lmin = jmin (lmin, bufmin);
  17084. lmax = jmax (lmax, bufmax);
  17085. if (numChannels > 1)
  17086. {
  17087. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufmax, bufmin);
  17088. rmin = jmin (rmin, bufmin);
  17089. rmax = jmax (rmax, bufmax);
  17090. }
  17091. }
  17092. if (numChannels <= 1)
  17093. {
  17094. rmax = lmax;
  17095. rmin = lmin;
  17096. }
  17097. lowestLeft = lmin;
  17098. highestLeft = lmax;
  17099. lowestRight = rmin;
  17100. highestRight = rmax;
  17101. }
  17102. else
  17103. {
  17104. int lmax = std::numeric_limits<int>::min();
  17105. int lmin = std::numeric_limits<int>::max();
  17106. int rmax = std::numeric_limits<int>::min();
  17107. int rmin = std::numeric_limits<int>::max();
  17108. while (numSamples > 0)
  17109. {
  17110. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17111. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17112. numSamples -= numToDo;
  17113. startSampleInFile += numToDo;
  17114. for (int j = numChannels; --j >= 0;)
  17115. {
  17116. int bufMax = std::numeric_limits<int>::min();
  17117. int bufMin = std::numeric_limits<int>::max();
  17118. const int* const b = tempBuffer[j];
  17119. for (int i = 0; i < numToDo; ++i)
  17120. {
  17121. const int samp = b[i];
  17122. if (samp < bufMin)
  17123. bufMin = samp;
  17124. if (samp > bufMax)
  17125. bufMax = samp;
  17126. }
  17127. if (j == 0)
  17128. {
  17129. lmax = jmax (lmax, bufMax);
  17130. lmin = jmin (lmin, bufMin);
  17131. }
  17132. else
  17133. {
  17134. rmax = jmax (rmax, bufMax);
  17135. rmin = jmin (rmin, bufMin);
  17136. }
  17137. }
  17138. }
  17139. if (numChannels <= 1)
  17140. {
  17141. rmax = lmax;
  17142. rmin = lmin;
  17143. }
  17144. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  17145. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  17146. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  17147. highestRight = rmax / (float) std::numeric_limits<int>::max();
  17148. }
  17149. }
  17150. int64 AudioFormatReader::searchForLevel (int64 startSample,
  17151. int64 numSamplesToSearch,
  17152. const double magnitudeRangeMinimum,
  17153. const double magnitudeRangeMaximum,
  17154. const int minimumConsecutiveSamples)
  17155. {
  17156. if (numSamplesToSearch == 0)
  17157. return -1;
  17158. const int bufferSize = 4096;
  17159. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17160. int* tempBuffer[3];
  17161. tempBuffer[0] = tempSpace.getData();
  17162. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17163. tempBuffer[2] = 0;
  17164. int consecutive = 0;
  17165. int64 firstMatchPos = -1;
  17166. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  17167. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  17168. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  17169. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  17170. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  17171. while (numSamplesToSearch != 0)
  17172. {
  17173. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  17174. int64 bufferStart = startSample;
  17175. if (numSamplesToSearch < 0)
  17176. bufferStart -= numThisTime;
  17177. if (bufferStart >= (int) lengthInSamples)
  17178. break;
  17179. read (tempBuffer, 2, bufferStart, numThisTime, false);
  17180. int num = numThisTime;
  17181. while (--num >= 0)
  17182. {
  17183. if (numSamplesToSearch < 0)
  17184. --startSample;
  17185. bool matches = false;
  17186. const int index = (int) (startSample - bufferStart);
  17187. if (usesFloatingPointData)
  17188. {
  17189. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  17190. if (sample1 >= magnitudeRangeMinimum
  17191. && sample1 <= magnitudeRangeMaximum)
  17192. {
  17193. matches = true;
  17194. }
  17195. else if (numChannels > 1)
  17196. {
  17197. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  17198. matches = (sample2 >= magnitudeRangeMinimum
  17199. && sample2 <= magnitudeRangeMaximum);
  17200. }
  17201. }
  17202. else
  17203. {
  17204. const int sample1 = abs (tempBuffer[0] [index]);
  17205. if (sample1 >= intMagnitudeRangeMinimum
  17206. && sample1 <= intMagnitudeRangeMaximum)
  17207. {
  17208. matches = true;
  17209. }
  17210. else if (numChannels > 1)
  17211. {
  17212. const int sample2 = abs (tempBuffer[1][index]);
  17213. matches = (sample2 >= intMagnitudeRangeMinimum
  17214. && sample2 <= intMagnitudeRangeMaximum);
  17215. }
  17216. }
  17217. if (matches)
  17218. {
  17219. if (firstMatchPos < 0)
  17220. firstMatchPos = startSample;
  17221. if (++consecutive >= minimumConsecutiveSamples)
  17222. {
  17223. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  17224. return -1;
  17225. return firstMatchPos;
  17226. }
  17227. }
  17228. else
  17229. {
  17230. consecutive = 0;
  17231. firstMatchPos = -1;
  17232. }
  17233. if (numSamplesToSearch > 0)
  17234. ++startSample;
  17235. }
  17236. if (numSamplesToSearch > 0)
  17237. numSamplesToSearch -= numThisTime;
  17238. else
  17239. numSamplesToSearch += numThisTime;
  17240. }
  17241. return -1;
  17242. }
  17243. END_JUCE_NAMESPACE
  17244. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  17245. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  17246. BEGIN_JUCE_NAMESPACE
  17247. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17248. const String& formatName_,
  17249. const double rate,
  17250. const unsigned int numChannels_,
  17251. const unsigned int bitsPerSample_)
  17252. : sampleRate (rate),
  17253. numChannels (numChannels_),
  17254. bitsPerSample (bitsPerSample_),
  17255. usesFloatingPointData (false),
  17256. output (out),
  17257. formatName (formatName_)
  17258. {
  17259. }
  17260. AudioFormatWriter::~AudioFormatWriter()
  17261. {
  17262. delete output;
  17263. }
  17264. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17265. int64 startSample,
  17266. int64 numSamplesToRead)
  17267. {
  17268. const int bufferSize = 16384;
  17269. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17270. int* buffers [128];
  17271. zerostruct (buffers);
  17272. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17273. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17274. if (numSamplesToRead < 0)
  17275. numSamplesToRead = reader.lengthInSamples;
  17276. while (numSamplesToRead > 0)
  17277. {
  17278. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17279. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17280. return false;
  17281. if (reader.usesFloatingPointData != isFloatingPoint())
  17282. {
  17283. int** bufferChan = buffers;
  17284. while (*bufferChan != 0)
  17285. {
  17286. int* b = *bufferChan++;
  17287. if (isFloatingPoint())
  17288. {
  17289. // int -> float
  17290. const double factor = 1.0 / std::numeric_limits<int>::max();
  17291. for (int i = 0; i < numToDo; ++i)
  17292. ((float*) b)[i] = (float) (factor * b[i]);
  17293. }
  17294. else
  17295. {
  17296. // float -> int
  17297. for (int i = 0; i < numToDo; ++i)
  17298. {
  17299. const double samp = *(const float*) b;
  17300. if (samp <= -1.0)
  17301. *b++ = std::numeric_limits<int>::min();
  17302. else if (samp >= 1.0)
  17303. *b++ = std::numeric_limits<int>::max();
  17304. else
  17305. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17306. }
  17307. }
  17308. }
  17309. }
  17310. if (! write (const_cast<const int**> (buffers), numToDo))
  17311. return false;
  17312. numSamplesToRead -= numToDo;
  17313. startSample += numToDo;
  17314. }
  17315. return true;
  17316. }
  17317. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  17318. {
  17319. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17320. while (numSamplesToRead > 0)
  17321. {
  17322. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17323. AudioSourceChannelInfo info;
  17324. info.buffer = &tempBuffer;
  17325. info.startSample = 0;
  17326. info.numSamples = numToDo;
  17327. info.clearActiveBufferRegion();
  17328. source.getNextAudioBlock (info);
  17329. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  17330. return false;
  17331. numSamplesToRead -= numToDo;
  17332. }
  17333. return true;
  17334. }
  17335. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  17336. {
  17337. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  17338. if (numSamples <= 0)
  17339. return true;
  17340. HeapBlock<int> tempBuffer;
  17341. HeapBlock<int*> chans (numChannels + 1);
  17342. chans [numChannels] = 0;
  17343. if (isFloatingPoint())
  17344. {
  17345. for (int i = numChannels; --i >= 0;)
  17346. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  17347. }
  17348. else
  17349. {
  17350. tempBuffer.malloc (numSamples * numChannels);
  17351. for (unsigned int i = 0; i < numChannels; ++i)
  17352. {
  17353. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  17354. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  17355. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  17356. SourceSampleType sourceData (source.getSampleData (i, startSample));
  17357. destData.convertSamples (sourceData, numSamples);
  17358. }
  17359. }
  17360. return write ((const int**) chans.getData(), numSamples);
  17361. }
  17362. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17363. public AbstractFifo
  17364. {
  17365. public:
  17366. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize)
  17367. : AbstractFifo (bufferSize),
  17368. buffer (numChannels, bufferSize),
  17369. timeSliceThread (timeSliceThread_),
  17370. writer (writer_), isRunning (true)
  17371. {
  17372. timeSliceThread.addTimeSliceClient (this);
  17373. }
  17374. ~Buffer()
  17375. {
  17376. isRunning = false;
  17377. timeSliceThread.removeTimeSliceClient (this);
  17378. while (useTimeSlice())
  17379. {}
  17380. }
  17381. bool write (const float** data, int numSamples)
  17382. {
  17383. if (numSamples <= 0 || ! isRunning)
  17384. return true;
  17385. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17386. int start1, size1, start2, size2;
  17387. prepareToWrite (numSamples, start1, size1, start2, size2);
  17388. if (size1 + size2 < numSamples)
  17389. return false;
  17390. for (int i = buffer.getNumChannels(); --i >= 0;)
  17391. {
  17392. buffer.copyFrom (i, start1, data[i], size1);
  17393. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17394. }
  17395. finishedWrite (size1 + size2);
  17396. timeSliceThread.notify();
  17397. return true;
  17398. }
  17399. bool useTimeSlice()
  17400. {
  17401. const int numToDo = getTotalSize() / 4;
  17402. int start1, size1, start2, size2;
  17403. prepareToRead (numToDo, start1, size1, start2, size2);
  17404. if (size1 <= 0)
  17405. return false;
  17406. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17407. if (size2 > 0)
  17408. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17409. finishedRead (size1 + size2);
  17410. return true;
  17411. }
  17412. private:
  17413. AudioSampleBuffer buffer;
  17414. TimeSliceThread& timeSliceThread;
  17415. ScopedPointer<AudioFormatWriter> writer;
  17416. volatile bool isRunning;
  17417. Buffer (const Buffer&);
  17418. Buffer& operator= (const Buffer&);
  17419. };
  17420. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17421. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17422. {
  17423. }
  17424. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17425. {
  17426. }
  17427. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17428. {
  17429. return buffer->write (data, numSamples);
  17430. }
  17431. END_JUCE_NAMESPACE
  17432. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17433. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17434. BEGIN_JUCE_NAMESPACE
  17435. AudioFormatManager::AudioFormatManager()
  17436. : defaultFormatIndex (0)
  17437. {
  17438. }
  17439. AudioFormatManager::~AudioFormatManager()
  17440. {
  17441. clearFormats();
  17442. clearSingletonInstance();
  17443. }
  17444. juce_ImplementSingleton (AudioFormatManager);
  17445. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  17446. const bool makeThisTheDefaultFormat)
  17447. {
  17448. jassert (newFormat != 0);
  17449. if (newFormat != 0)
  17450. {
  17451. #if JUCE_DEBUG
  17452. for (int i = getNumKnownFormats(); --i >= 0;)
  17453. {
  17454. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17455. {
  17456. jassertfalse; // trying to add the same format twice!
  17457. }
  17458. }
  17459. #endif
  17460. if (makeThisTheDefaultFormat)
  17461. defaultFormatIndex = getNumKnownFormats();
  17462. knownFormats.add (newFormat);
  17463. }
  17464. }
  17465. void AudioFormatManager::registerBasicFormats()
  17466. {
  17467. #if JUCE_MAC
  17468. registerFormat (new AiffAudioFormat(), true);
  17469. registerFormat (new WavAudioFormat(), false);
  17470. #else
  17471. registerFormat (new WavAudioFormat(), true);
  17472. registerFormat (new AiffAudioFormat(), false);
  17473. #endif
  17474. #if JUCE_USE_FLAC
  17475. registerFormat (new FlacAudioFormat(), false);
  17476. #endif
  17477. #if JUCE_USE_OGGVORBIS
  17478. registerFormat (new OggVorbisAudioFormat(), false);
  17479. #endif
  17480. }
  17481. void AudioFormatManager::clearFormats()
  17482. {
  17483. knownFormats.clear();
  17484. defaultFormatIndex = 0;
  17485. }
  17486. int AudioFormatManager::getNumKnownFormats() const
  17487. {
  17488. return knownFormats.size();
  17489. }
  17490. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17491. {
  17492. return knownFormats [index];
  17493. }
  17494. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17495. {
  17496. return getKnownFormat (defaultFormatIndex);
  17497. }
  17498. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17499. {
  17500. String e (fileExtension);
  17501. if (! e.startsWithChar ('.'))
  17502. e = "." + e;
  17503. for (int i = 0; i < getNumKnownFormats(); ++i)
  17504. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17505. return getKnownFormat(i);
  17506. return 0;
  17507. }
  17508. const String AudioFormatManager::getWildcardForAllFormats() const
  17509. {
  17510. StringArray allExtensions;
  17511. int i;
  17512. for (i = 0; i < getNumKnownFormats(); ++i)
  17513. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17514. allExtensions.trim();
  17515. allExtensions.removeEmptyStrings();
  17516. String s;
  17517. for (i = 0; i < allExtensions.size(); ++i)
  17518. {
  17519. s << '*';
  17520. if (! allExtensions[i].startsWithChar ('.'))
  17521. s << '.';
  17522. s << allExtensions[i];
  17523. if (i < allExtensions.size() - 1)
  17524. s << ';';
  17525. }
  17526. return s;
  17527. }
  17528. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17529. {
  17530. // you need to actually register some formats before the manager can
  17531. // use them to open a file!
  17532. jassert (getNumKnownFormats() > 0);
  17533. for (int i = 0; i < getNumKnownFormats(); ++i)
  17534. {
  17535. AudioFormat* const af = getKnownFormat(i);
  17536. if (af->canHandleFile (file))
  17537. {
  17538. InputStream* const in = file.createInputStream();
  17539. if (in != 0)
  17540. {
  17541. AudioFormatReader* const r = af->createReaderFor (in, true);
  17542. if (r != 0)
  17543. return r;
  17544. }
  17545. }
  17546. }
  17547. return 0;
  17548. }
  17549. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17550. {
  17551. // you need to actually register some formats before the manager can
  17552. // use them to open a file!
  17553. jassert (getNumKnownFormats() > 0);
  17554. ScopedPointer <InputStream> in (audioFileStream);
  17555. if (in != 0)
  17556. {
  17557. const int64 originalStreamPos = in->getPosition();
  17558. for (int i = 0; i < getNumKnownFormats(); ++i)
  17559. {
  17560. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17561. if (r != 0)
  17562. {
  17563. in.release();
  17564. return r;
  17565. }
  17566. in->setPosition (originalStreamPos);
  17567. // the stream that is passed-in must be capable of being repositioned so
  17568. // that all the formats can have a go at opening it.
  17569. jassert (in->getPosition() == originalStreamPos);
  17570. }
  17571. }
  17572. return 0;
  17573. }
  17574. END_JUCE_NAMESPACE
  17575. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17576. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17577. BEGIN_JUCE_NAMESPACE
  17578. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17579. const int64 startSample_,
  17580. const int64 length_,
  17581. const bool deleteSourceWhenDeleted_)
  17582. : AudioFormatReader (0, source_->getFormatName()),
  17583. source (source_),
  17584. startSample (startSample_),
  17585. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17586. {
  17587. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17588. sampleRate = source->sampleRate;
  17589. bitsPerSample = source->bitsPerSample;
  17590. lengthInSamples = length;
  17591. numChannels = source->numChannels;
  17592. usesFloatingPointData = source->usesFloatingPointData;
  17593. }
  17594. AudioSubsectionReader::~AudioSubsectionReader()
  17595. {
  17596. if (deleteSourceWhenDeleted)
  17597. delete source;
  17598. }
  17599. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17600. int64 startSampleInFile, int numSamples)
  17601. {
  17602. if (startSampleInFile + numSamples > length)
  17603. {
  17604. for (int i = numDestChannels; --i >= 0;)
  17605. if (destSamples[i] != 0)
  17606. zeromem (destSamples[i], sizeof (int) * numSamples);
  17607. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17608. if (numSamples <= 0)
  17609. return true;
  17610. }
  17611. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17612. startSampleInFile + startSample, numSamples);
  17613. }
  17614. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17615. int64 numSamples,
  17616. float& lowestLeft,
  17617. float& highestLeft,
  17618. float& lowestRight,
  17619. float& highestRight)
  17620. {
  17621. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17622. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17623. source->readMaxLevels (startSampleInFile + startSample,
  17624. numSamples,
  17625. lowestLeft,
  17626. highestLeft,
  17627. lowestRight,
  17628. highestRight);
  17629. }
  17630. END_JUCE_NAMESPACE
  17631. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17632. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17633. BEGIN_JUCE_NAMESPACE
  17634. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  17635. AudioFormatManager& formatManagerToUse_,
  17636. AudioThumbnailCache& cacheToUse)
  17637. : formatManagerToUse (formatManagerToUse_),
  17638. cache (cacheToUse),
  17639. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_),
  17640. timeBeforeDeletingReader (2000)
  17641. {
  17642. clear();
  17643. }
  17644. AudioThumbnail::~AudioThumbnail()
  17645. {
  17646. cache.removeThumbnail (this);
  17647. const ScopedLock sl (readerLock);
  17648. reader = 0;
  17649. }
  17650. AudioThumbnail::DataFormat* AudioThumbnail::getData() const throw()
  17651. {
  17652. jassert (data.getData() != 0);
  17653. return static_cast <DataFormat*> (data.getData());
  17654. }
  17655. void AudioThumbnail::setSource (InputSource* const newSource)
  17656. {
  17657. cache.removeThumbnail (this);
  17658. timerCallback(); // stops the timer and deletes the reader
  17659. source = newSource;
  17660. clear();
  17661. if (newSource != 0
  17662. && ! (cache.loadThumb (*this, newSource->hashCode())
  17663. && isFullyLoaded()))
  17664. {
  17665. {
  17666. const ScopedLock sl (readerLock);
  17667. reader = createReader();
  17668. }
  17669. if (reader != 0)
  17670. {
  17671. initialiseFromAudioFile (*reader);
  17672. cache.addThumbnail (this);
  17673. }
  17674. }
  17675. sendChangeMessage (this);
  17676. }
  17677. bool AudioThumbnail::useTimeSlice()
  17678. {
  17679. const ScopedLock sl (readerLock);
  17680. if (isFullyLoaded())
  17681. {
  17682. if (reader != 0)
  17683. startTimer (timeBeforeDeletingReader);
  17684. cache.removeThumbnail (this);
  17685. return false;
  17686. }
  17687. if (reader == 0)
  17688. reader = createReader();
  17689. if (reader != 0)
  17690. {
  17691. readNextBlockFromAudioFile (*reader);
  17692. stopTimer();
  17693. sendChangeMessage (this);
  17694. const bool justFinished = isFullyLoaded();
  17695. if (justFinished)
  17696. cache.storeThumb (*this, source->hashCode());
  17697. return ! justFinished;
  17698. }
  17699. return false;
  17700. }
  17701. AudioFormatReader* AudioThumbnail::createReader() const
  17702. {
  17703. if (source != 0)
  17704. {
  17705. InputStream* const audioFileStream = source->createInputStream();
  17706. if (audioFileStream != 0)
  17707. return formatManagerToUse.createReaderFor (audioFileStream);
  17708. }
  17709. return 0;
  17710. }
  17711. void AudioThumbnail::timerCallback()
  17712. {
  17713. stopTimer();
  17714. const ScopedLock sl (readerLock);
  17715. reader = 0;
  17716. }
  17717. void AudioThumbnail::clear()
  17718. {
  17719. data.setSize (sizeof (DataFormat) + 3);
  17720. DataFormat* const d = getData();
  17721. d->thumbnailMagic[0] = 'j';
  17722. d->thumbnailMagic[1] = 'a';
  17723. d->thumbnailMagic[2] = 't';
  17724. d->thumbnailMagic[3] = 'm';
  17725. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  17726. d->totalSamples = 0;
  17727. d->numFinishedSamples = 0;
  17728. d->numThumbnailSamples = 0;
  17729. d->numChannels = 0;
  17730. d->sampleRate = 0;
  17731. numSamplesCached = 0;
  17732. cacheNeedsRefilling = true;
  17733. }
  17734. void AudioThumbnail::loadFrom (InputStream& input)
  17735. {
  17736. const ScopedLock sl (readerLock);
  17737. data.setSize (0);
  17738. input.readIntoMemoryBlock (data);
  17739. DataFormat* const d = getData();
  17740. d->flipEndiannessIfBigEndian();
  17741. if (! (d->thumbnailMagic[0] == 'j'
  17742. && d->thumbnailMagic[1] == 'a'
  17743. && d->thumbnailMagic[2] == 't'
  17744. && d->thumbnailMagic[3] == 'm'))
  17745. {
  17746. clear();
  17747. }
  17748. numSamplesCached = 0;
  17749. cacheNeedsRefilling = true;
  17750. }
  17751. void AudioThumbnail::saveTo (OutputStream& output) const
  17752. {
  17753. const ScopedLock sl (readerLock);
  17754. DataFormat* const d = getData();
  17755. d->flipEndiannessIfBigEndian();
  17756. output.write (d, (int) data.getSize());
  17757. d->flipEndiannessIfBigEndian();
  17758. }
  17759. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  17760. {
  17761. DataFormat* d = getData();
  17762. d->totalSamples = fileReader.lengthInSamples;
  17763. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  17764. d->numFinishedSamples = 0;
  17765. d->sampleRate = roundToInt (fileReader.sampleRate);
  17766. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  17767. data.setSize (sizeof (DataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  17768. d = getData();
  17769. zeromem (d->data, d->numThumbnailSamples * d->numChannels * 2);
  17770. return d->totalSamples > 0;
  17771. }
  17772. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  17773. {
  17774. DataFormat* const d = getData();
  17775. if (d->numFinishedSamples < d->totalSamples)
  17776. {
  17777. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  17778. generateSection (fileReader,
  17779. d->numFinishedSamples,
  17780. numToDo);
  17781. d->numFinishedSamples += numToDo;
  17782. }
  17783. cacheNeedsRefilling = true;
  17784. return d->numFinishedSamples < d->totalSamples;
  17785. }
  17786. int AudioThumbnail::getNumChannels() const throw()
  17787. {
  17788. return getData()->numChannels;
  17789. }
  17790. double AudioThumbnail::getTotalLength() const throw()
  17791. {
  17792. const DataFormat* const d = getData();
  17793. if (d->sampleRate > 0)
  17794. return d->totalSamples / (double) d->sampleRate;
  17795. else
  17796. return 0.0;
  17797. }
  17798. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  17799. int64 startSample,
  17800. int numSamples)
  17801. {
  17802. DataFormat* const d = getData();
  17803. const int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  17804. const int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  17805. char* const l = getChannelData (0);
  17806. char* const r = getChannelData (1);
  17807. for (int i = firstDataPos; i < lastDataPos; ++i)
  17808. {
  17809. const int sourceStart = i * d->samplesPerThumbSample;
  17810. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  17811. float lowestLeft, highestLeft, lowestRight, highestRight;
  17812. fileReader.readMaxLevels (sourceStart,
  17813. sourceEnd - sourceStart,
  17814. lowestLeft,
  17815. highestLeft,
  17816. lowestRight,
  17817. highestRight);
  17818. int n = i * 2;
  17819. if (r != 0)
  17820. {
  17821. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17822. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  17823. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17824. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  17825. }
  17826. else
  17827. {
  17828. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17829. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17830. }
  17831. }
  17832. }
  17833. char* AudioThumbnail::getChannelData (int channel) const
  17834. {
  17835. DataFormat* const d = getData();
  17836. if (channel >= 0 && channel < d->numChannels)
  17837. return d->data + (channel * 2 * d->numThumbnailSamples);
  17838. return 0;
  17839. }
  17840. bool AudioThumbnail::isFullyLoaded() const throw()
  17841. {
  17842. const DataFormat* const d = getData();
  17843. return d->numFinishedSamples >= d->totalSamples;
  17844. }
  17845. void AudioThumbnail::refillCache (const int numSamples,
  17846. double startTime,
  17847. const double timePerPixel)
  17848. {
  17849. const DataFormat* const d = getData();
  17850. if (numSamples <= 0
  17851. || timePerPixel <= 0.0
  17852. || d->sampleRate <= 0)
  17853. {
  17854. numSamplesCached = 0;
  17855. cacheNeedsRefilling = true;
  17856. return;
  17857. }
  17858. if (numSamples == numSamplesCached
  17859. && numChannelsCached == d->numChannels
  17860. && startTime == cachedStart
  17861. && timePerPixel == cachedTimePerPixel
  17862. && ! cacheNeedsRefilling)
  17863. {
  17864. return;
  17865. }
  17866. numSamplesCached = numSamples;
  17867. numChannelsCached = d->numChannels;
  17868. cachedStart = startTime;
  17869. cachedTimePerPixel = timePerPixel;
  17870. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  17871. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  17872. const ScopedLock sl (readerLock);
  17873. cacheNeedsRefilling = false;
  17874. if (needExtraDetail && reader == 0)
  17875. reader = createReader();
  17876. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  17877. {
  17878. startTimer (timeBeforeDeletingReader);
  17879. char* cacheData = static_cast <char*> (cachedLevels.getData());
  17880. int sample = roundToInt (startTime * d->sampleRate);
  17881. for (int i = numSamples; --i >= 0;)
  17882. {
  17883. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  17884. if (sample >= 0)
  17885. {
  17886. if (sample >= reader->lengthInSamples)
  17887. break;
  17888. float lmin, lmax, rmin, rmax;
  17889. reader->readMaxLevels (sample,
  17890. jmax (1, nextSample - sample),
  17891. lmin, lmax, rmin, rmax);
  17892. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  17893. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  17894. if (numChannelsCached > 1)
  17895. {
  17896. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  17897. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  17898. }
  17899. cacheData += 2 * numChannelsCached;
  17900. }
  17901. startTime += timePerPixel;
  17902. sample = nextSample;
  17903. }
  17904. }
  17905. else
  17906. {
  17907. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17908. {
  17909. char* const channelData = getChannelData (channelNum);
  17910. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  17911. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  17912. startTime = cachedStart;
  17913. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17914. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  17915. for (int i = numSamples; --i >= 0;)
  17916. {
  17917. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17918. if (sample >= 0 && channelData != 0)
  17919. {
  17920. char mx = -128;
  17921. char mn = 127;
  17922. while (sample <= nextSample)
  17923. {
  17924. if (sample >= numFinished)
  17925. break;
  17926. const int n = sample << 1;
  17927. const char sampMin = channelData [n];
  17928. const char sampMax = channelData [n + 1];
  17929. if (sampMin < mn)
  17930. mn = sampMin;
  17931. if (sampMax > mx)
  17932. mx = sampMax;
  17933. ++sample;
  17934. }
  17935. if (mn <= mx)
  17936. {
  17937. cacheData[0] = mn;
  17938. cacheData[1] = mx;
  17939. }
  17940. else
  17941. {
  17942. cacheData[0] = 1;
  17943. cacheData[1] = 0;
  17944. }
  17945. }
  17946. else
  17947. {
  17948. cacheData[0] = 1;
  17949. cacheData[1] = 0;
  17950. }
  17951. cacheData += numChannelsCached * 2;
  17952. startTime += timePerPixel;
  17953. sample = nextSample;
  17954. }
  17955. }
  17956. }
  17957. }
  17958. void AudioThumbnail::drawChannel (Graphics& g,
  17959. int x, int y, int w, int h,
  17960. double startTime,
  17961. double endTime,
  17962. int channelNum,
  17963. const float verticalZoomFactor)
  17964. {
  17965. refillCache (w, startTime, (endTime - startTime) / w);
  17966. if (numSamplesCached >= w
  17967. && channelNum >= 0
  17968. && channelNum < numChannelsCached)
  17969. {
  17970. const float topY = (float) y;
  17971. const float bottomY = topY + h;
  17972. const float midY = topY + h * 0.5f;
  17973. const float vscale = verticalZoomFactor * h / 256.0f;
  17974. const Rectangle<int> clip (g.getClipBounds());
  17975. const int skipLeft = jlimit (0, w, clip.getX() - x);
  17976. w -= skipLeft;
  17977. x += skipLeft;
  17978. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  17979. + (channelNum << 1)
  17980. + skipLeft * (numChannelsCached << 1);
  17981. while (--w >= 0)
  17982. {
  17983. const char mn = cacheData[0];
  17984. const char mx = cacheData[1];
  17985. cacheData += numChannelsCached << 1;
  17986. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  17987. g.drawVerticalLine (x, jmax (midY - mx * vscale - 0.3f, topY),
  17988. jmin (midY - mn * vscale + 0.3f, bottomY));
  17989. if (++x >= clip.getRight())
  17990. break;
  17991. }
  17992. }
  17993. }
  17994. void AudioThumbnail::DataFormat::flipEndiannessIfBigEndian() throw()
  17995. {
  17996. #if JUCE_BIG_ENDIAN
  17997. struct Flipper
  17998. {
  17999. static void flip (int32& n) { n = (int32) ByteOrder::swap ((uint32) n); }
  18000. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  18001. };
  18002. Flipper::flip (samplesPerThumbSample);
  18003. Flipper::flip (totalSamples);
  18004. Flipper::flip (numFinishedSamples);
  18005. Flipper::flip (numThumbnailSamples);
  18006. Flipper::flip (numChannels);
  18007. Flipper::flip (sampleRate);
  18008. #endif
  18009. }
  18010. END_JUCE_NAMESPACE
  18011. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  18012. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  18013. BEGIN_JUCE_NAMESPACE
  18014. struct ThumbnailCacheEntry
  18015. {
  18016. int64 hash;
  18017. uint32 lastUsed;
  18018. MemoryBlock data;
  18019. juce_UseDebuggingNewOperator
  18020. };
  18021. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18022. : TimeSliceThread ("thumb cache"),
  18023. maxNumThumbsToStore (maxNumThumbsToStore_)
  18024. {
  18025. startThread (2);
  18026. }
  18027. AudioThumbnailCache::~AudioThumbnailCache()
  18028. {
  18029. }
  18030. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18031. {
  18032. for (int i = thumbs.size(); --i >= 0;)
  18033. {
  18034. if (thumbs[i]->hash == hashCode)
  18035. {
  18036. MemoryInputStream in (thumbs[i]->data, false);
  18037. thumb.loadFrom (in);
  18038. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  18039. return true;
  18040. }
  18041. }
  18042. return false;
  18043. }
  18044. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18045. const int64 hashCode)
  18046. {
  18047. MemoryOutputStream out;
  18048. thumb.saveTo (out);
  18049. ThumbnailCacheEntry* te = 0;
  18050. for (int i = thumbs.size(); --i >= 0;)
  18051. {
  18052. if (thumbs[i]->hash == hashCode)
  18053. {
  18054. te = thumbs[i];
  18055. break;
  18056. }
  18057. }
  18058. if (te == 0)
  18059. {
  18060. te = new ThumbnailCacheEntry();
  18061. te->hash = hashCode;
  18062. if (thumbs.size() < maxNumThumbsToStore)
  18063. {
  18064. thumbs.add (te);
  18065. }
  18066. else
  18067. {
  18068. int oldest = 0;
  18069. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  18070. int i;
  18071. for (i = thumbs.size(); --i >= 0;)
  18072. if (thumbs[i]->lastUsed < oldestTime)
  18073. oldest = i;
  18074. thumbs.set (i, te);
  18075. }
  18076. }
  18077. te->lastUsed = Time::getMillisecondCounter();
  18078. te->data.setSize (0);
  18079. te->data.append (out.getData(), out.getDataSize());
  18080. }
  18081. void AudioThumbnailCache::clear()
  18082. {
  18083. thumbs.clear();
  18084. }
  18085. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  18086. {
  18087. addTimeSliceClient (thumb);
  18088. }
  18089. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  18090. {
  18091. removeTimeSliceClient (thumb);
  18092. }
  18093. END_JUCE_NAMESPACE
  18094. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18095. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18096. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18097. #if ! JUCE_WINDOWS
  18098. #include <QuickTime/Movies.h>
  18099. #include <QuickTime/QTML.h>
  18100. #include <QuickTime/QuickTimeComponents.h>
  18101. #include <QuickTime/MediaHandlers.h>
  18102. #include <QuickTime/ImageCodec.h>
  18103. #else
  18104. #if JUCE_MSVC
  18105. #pragma warning (push)
  18106. #pragma warning (disable : 4100)
  18107. #endif
  18108. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18109. add its header directory to your include path.
  18110. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  18111. flag in juce_Config.h
  18112. */
  18113. #include <Movies.h>
  18114. #include <QTML.h>
  18115. #include <QuickTimeComponents.h>
  18116. #include <MediaHandlers.h>
  18117. #include <ImageCodec.h>
  18118. #if JUCE_MSVC
  18119. #pragma warning (pop)
  18120. #endif
  18121. #endif
  18122. BEGIN_JUCE_NAMESPACE
  18123. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18124. static const char* const quickTimeFormatName = "QuickTime file";
  18125. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  18126. class QTAudioReader : public AudioFormatReader
  18127. {
  18128. public:
  18129. QTAudioReader (InputStream* const input_, const int trackNum_)
  18130. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18131. ok (false),
  18132. movie (0),
  18133. trackNum (trackNum_),
  18134. lastSampleRead (0),
  18135. lastThreadId (0),
  18136. extractor (0),
  18137. dataHandle (0)
  18138. {
  18139. bufferList.calloc (256, 1);
  18140. #if JUCE_WINDOWS
  18141. if (InitializeQTML (0) != noErr)
  18142. return;
  18143. #endif
  18144. if (EnterMovies() != noErr)
  18145. return;
  18146. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18147. if (! opened)
  18148. return;
  18149. {
  18150. const int numTracks = GetMovieTrackCount (movie);
  18151. int trackCount = 0;
  18152. for (int i = 1; i <= numTracks; ++i)
  18153. {
  18154. track = GetMovieIndTrack (movie, i);
  18155. media = GetTrackMedia (track);
  18156. OSType mediaType;
  18157. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18158. if (mediaType == SoundMediaType
  18159. && trackCount++ == trackNum_)
  18160. {
  18161. ok = true;
  18162. break;
  18163. }
  18164. }
  18165. }
  18166. if (! ok)
  18167. return;
  18168. ok = false;
  18169. lengthInSamples = GetMediaDecodeDuration (media);
  18170. usesFloatingPointData = false;
  18171. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18172. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18173. / GetMediaTimeScale (media);
  18174. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18175. unsigned long output_layout_size;
  18176. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18177. kQTPropertyClass_MovieAudioExtraction_Audio,
  18178. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18179. 0, &output_layout_size, 0);
  18180. if (err != noErr)
  18181. return;
  18182. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18183. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18184. err = MovieAudioExtractionGetProperty (extractor,
  18185. kQTPropertyClass_MovieAudioExtraction_Audio,
  18186. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18187. output_layout_size, qt_audio_channel_layout, 0);
  18188. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18189. err = MovieAudioExtractionSetProperty (extractor,
  18190. kQTPropertyClass_MovieAudioExtraction_Audio,
  18191. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18192. output_layout_size,
  18193. qt_audio_channel_layout);
  18194. err = MovieAudioExtractionGetProperty (extractor,
  18195. kQTPropertyClass_MovieAudioExtraction_Audio,
  18196. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18197. sizeof (inputStreamDesc),
  18198. &inputStreamDesc, 0);
  18199. if (err != noErr)
  18200. return;
  18201. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18202. | kAudioFormatFlagIsPacked
  18203. | kAudioFormatFlagsNativeEndian;
  18204. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18205. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18206. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18207. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18208. err = MovieAudioExtractionSetProperty (extractor,
  18209. kQTPropertyClass_MovieAudioExtraction_Audio,
  18210. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18211. sizeof (inputStreamDesc),
  18212. &inputStreamDesc);
  18213. if (err != noErr)
  18214. return;
  18215. Boolean allChannelsDiscrete = false;
  18216. err = MovieAudioExtractionSetProperty (extractor,
  18217. kQTPropertyClass_MovieAudioExtraction_Movie,
  18218. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18219. sizeof (allChannelsDiscrete),
  18220. &allChannelsDiscrete);
  18221. if (err != noErr)
  18222. return;
  18223. bufferList->mNumberBuffers = 1;
  18224. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18225. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18226. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18227. bufferList->mBuffers[0].mData = dataBuffer;
  18228. sampleRate = inputStreamDesc.mSampleRate;
  18229. bitsPerSample = 16;
  18230. numChannels = inputStreamDesc.mChannelsPerFrame;
  18231. detachThread();
  18232. ok = true;
  18233. }
  18234. ~QTAudioReader()
  18235. {
  18236. if (dataHandle != 0)
  18237. DisposeHandle (dataHandle);
  18238. if (extractor != 0)
  18239. {
  18240. MovieAudioExtractionEnd (extractor);
  18241. extractor = 0;
  18242. }
  18243. checkThreadIsAttached();
  18244. DisposeMovie (movie);
  18245. #if JUCE_MAC
  18246. ExitMoviesOnThread ();
  18247. #endif
  18248. }
  18249. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18250. int64 startSampleInFile, int numSamples)
  18251. {
  18252. checkThreadIsAttached();
  18253. bool ok = true;
  18254. while (numSamples > 0)
  18255. {
  18256. if (lastSampleRead != startSampleInFile)
  18257. {
  18258. TimeRecord time;
  18259. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18260. time.base = 0;
  18261. time.value.hi = 0;
  18262. time.value.lo = (UInt32) startSampleInFile;
  18263. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18264. kQTPropertyClass_MovieAudioExtraction_Movie,
  18265. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18266. sizeof (time), &time);
  18267. if (err != noErr)
  18268. {
  18269. ok = false;
  18270. break;
  18271. }
  18272. }
  18273. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18274. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18275. UInt32 outFlags = 0;
  18276. UInt32 actualNumFrames = framesToDo;
  18277. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18278. if (err != noErr)
  18279. {
  18280. ok = false;
  18281. break;
  18282. }
  18283. lastSampleRead = startSampleInFile + actualNumFrames;
  18284. const int samplesReceived = actualNumFrames;
  18285. for (int j = numDestChannels; --j >= 0;)
  18286. {
  18287. if (destSamples[j] != 0)
  18288. {
  18289. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18290. for (int i = 0; i < samplesReceived; ++i)
  18291. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18292. }
  18293. }
  18294. startOffsetInDestBuffer += samplesReceived;
  18295. startSampleInFile += samplesReceived;
  18296. numSamples -= samplesReceived;
  18297. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18298. {
  18299. for (int j = numDestChannels; --j >= 0;)
  18300. if (destSamples[j] != 0)
  18301. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18302. break;
  18303. }
  18304. }
  18305. detachThread();
  18306. return ok;
  18307. }
  18308. juce_UseDebuggingNewOperator
  18309. bool ok;
  18310. private:
  18311. Movie movie;
  18312. Media media;
  18313. Track track;
  18314. const int trackNum;
  18315. double trackUnitsPerFrame;
  18316. int samplesPerFrame;
  18317. int64 lastSampleRead;
  18318. Thread::ThreadID lastThreadId;
  18319. MovieAudioExtractionRef extractor;
  18320. AudioStreamBasicDescription inputStreamDesc;
  18321. HeapBlock <AudioBufferList> bufferList;
  18322. HeapBlock <char> dataBuffer;
  18323. Handle dataHandle;
  18324. void checkThreadIsAttached()
  18325. {
  18326. #if JUCE_MAC
  18327. if (Thread::getCurrentThreadId() != lastThreadId)
  18328. EnterMoviesOnThread (0);
  18329. AttachMovieToCurrentThread (movie);
  18330. #endif
  18331. }
  18332. void detachThread()
  18333. {
  18334. #if JUCE_MAC
  18335. DetachMovieFromCurrentThread (movie);
  18336. #endif
  18337. }
  18338. QTAudioReader (const QTAudioReader&);
  18339. QTAudioReader& operator= (const QTAudioReader&);
  18340. };
  18341. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18342. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18343. {
  18344. }
  18345. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18346. {
  18347. }
  18348. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18349. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18350. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18351. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18352. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18353. const bool deleteStreamIfOpeningFails)
  18354. {
  18355. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18356. if (r->ok)
  18357. return r.release();
  18358. if (! deleteStreamIfOpeningFails)
  18359. r->input = 0;
  18360. return 0;
  18361. }
  18362. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18363. double /*sampleRateToUse*/,
  18364. unsigned int /*numberOfChannels*/,
  18365. int /*bitsPerSample*/,
  18366. const StringPairArray& /*metadataValues*/,
  18367. int /*qualityOptionIndex*/)
  18368. {
  18369. jassertfalse; // not yet implemented!
  18370. return 0;
  18371. }
  18372. END_JUCE_NAMESPACE
  18373. #endif
  18374. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18375. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18376. BEGIN_JUCE_NAMESPACE
  18377. static const char* const wavFormatName = "WAV file";
  18378. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18379. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18380. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18381. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18382. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18383. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18384. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18385. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18386. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18387. const String& originator,
  18388. const String& originatorRef,
  18389. const Time& date,
  18390. const int64 timeReferenceSamples,
  18391. const String& codingHistory)
  18392. {
  18393. StringPairArray m;
  18394. m.set (bwavDescription, description);
  18395. m.set (bwavOriginator, originator);
  18396. m.set (bwavOriginatorRef, originatorRef);
  18397. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18398. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18399. m.set (bwavTimeReference, String (timeReferenceSamples));
  18400. m.set (bwavCodingHistory, codingHistory);
  18401. return m;
  18402. }
  18403. #if JUCE_MSVC
  18404. #pragma pack (push, 1)
  18405. #define PACKED
  18406. #elif JUCE_GCC
  18407. #define PACKED __attribute__((packed))
  18408. #else
  18409. #define PACKED
  18410. #endif
  18411. struct BWAVChunk
  18412. {
  18413. char description [256];
  18414. char originator [32];
  18415. char originatorRef [32];
  18416. char originationDate [10];
  18417. char originationTime [8];
  18418. uint32 timeRefLow;
  18419. uint32 timeRefHigh;
  18420. uint16 version;
  18421. uint8 umid[64];
  18422. uint8 reserved[190];
  18423. char codingHistory[1];
  18424. void copyTo (StringPairArray& values) const
  18425. {
  18426. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18427. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18428. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18429. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18430. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18431. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18432. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18433. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18434. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18435. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18436. }
  18437. static MemoryBlock createFrom (const StringPairArray& values)
  18438. {
  18439. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18440. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18441. data.fillWith (0);
  18442. BWAVChunk* b = (BWAVChunk*) data.getData();
  18443. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18444. // as they get called in the right order..
  18445. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18446. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18447. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18448. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18449. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18450. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18451. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18452. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18453. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18454. if (b->description[0] != 0
  18455. || b->originator[0] != 0
  18456. || b->originationDate[0] != 0
  18457. || b->originationTime[0] != 0
  18458. || b->codingHistory[0] != 0
  18459. || time != 0)
  18460. {
  18461. return data;
  18462. }
  18463. return MemoryBlock();
  18464. }
  18465. } PACKED;
  18466. struct SMPLChunk
  18467. {
  18468. struct SampleLoop
  18469. {
  18470. uint32 identifier;
  18471. uint32 type;
  18472. uint32 start;
  18473. uint32 end;
  18474. uint32 fraction;
  18475. uint32 playCount;
  18476. } PACKED;
  18477. uint32 manufacturer;
  18478. uint32 product;
  18479. uint32 samplePeriod;
  18480. uint32 midiUnityNote;
  18481. uint32 midiPitchFraction;
  18482. uint32 smpteFormat;
  18483. uint32 smpteOffset;
  18484. uint32 numSampleLoops;
  18485. uint32 samplerData;
  18486. SampleLoop loops[1];
  18487. void copyTo (StringPairArray& values, const int totalSize) const
  18488. {
  18489. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18490. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18491. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18492. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18493. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18494. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18495. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18496. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18497. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18498. for (uint32 i = 0; i < numSampleLoops; ++i)
  18499. {
  18500. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18501. break;
  18502. const String prefix ("Loop" + String(i));
  18503. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18504. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18505. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18506. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18507. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18508. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18509. }
  18510. }
  18511. static MemoryBlock createFrom (const StringPairArray& values)
  18512. {
  18513. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18514. if (numLoops <= 0)
  18515. return MemoryBlock();
  18516. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18517. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18518. data.fillWith (0);
  18519. SMPLChunk* s = (SMPLChunk*) data.getData();
  18520. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18521. // as they get called in the right order..
  18522. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18523. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18524. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18525. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18526. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18527. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18528. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18529. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18530. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18531. for (int i = 0; i < numLoops; ++i)
  18532. {
  18533. const String prefix ("Loop" + String(i));
  18534. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18535. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18536. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18537. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18538. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18539. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18540. }
  18541. return data;
  18542. }
  18543. } PACKED;
  18544. struct ExtensibleWavSubFormat
  18545. {
  18546. uint32 data1;
  18547. uint16 data2;
  18548. uint16 data3;
  18549. uint8 data4[8];
  18550. } PACKED;
  18551. #if JUCE_MSVC
  18552. #pragma pack (pop)
  18553. #endif
  18554. #undef PACKED
  18555. class WavAudioFormatReader : public AudioFormatReader
  18556. {
  18557. public:
  18558. WavAudioFormatReader (InputStream* const in)
  18559. : AudioFormatReader (in, TRANS (wavFormatName)),
  18560. dataLength (0),
  18561. bwavChunkStart (0),
  18562. bwavSize (0)
  18563. {
  18564. if (input->readInt() == chunkName ("RIFF"))
  18565. {
  18566. const uint32 len = (uint32) input->readInt();
  18567. const int64 end = input->getPosition() + len;
  18568. bool hasGotType = false;
  18569. bool hasGotData = false;
  18570. if (input->readInt() == chunkName ("WAVE"))
  18571. {
  18572. while (input->getPosition() < end
  18573. && ! input->isExhausted())
  18574. {
  18575. const int chunkType = input->readInt();
  18576. uint32 length = (uint32) input->readInt();
  18577. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18578. if (chunkType == chunkName ("fmt "))
  18579. {
  18580. // read the format chunk
  18581. const unsigned short format = input->readShort();
  18582. const short numChans = input->readShort();
  18583. sampleRate = input->readInt();
  18584. const int bytesPerSec = input->readInt();
  18585. numChannels = numChans;
  18586. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18587. bitsPerSample = 8 * bytesPerFrame / numChans;
  18588. if (format == 3)
  18589. {
  18590. usesFloatingPointData = true;
  18591. }
  18592. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18593. {
  18594. if (length < 40) // too short
  18595. {
  18596. bytesPerFrame = 0;
  18597. }
  18598. else
  18599. {
  18600. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18601. ExtensibleWavSubFormat subFormat;
  18602. subFormat.data1 = input->readInt();
  18603. subFormat.data2 = input->readShort();
  18604. subFormat.data3 = input->readShort();
  18605. input->read (subFormat.data4, sizeof (subFormat.data4));
  18606. const ExtensibleWavSubFormat pcmFormat
  18607. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18608. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18609. {
  18610. const ExtensibleWavSubFormat ambisonicFormat
  18611. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18612. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18613. bytesPerFrame = 0;
  18614. }
  18615. }
  18616. }
  18617. else if (format != 1)
  18618. {
  18619. bytesPerFrame = 0;
  18620. }
  18621. hasGotType = true;
  18622. }
  18623. else if (chunkType == chunkName ("data"))
  18624. {
  18625. // get the data chunk's position
  18626. dataLength = length;
  18627. dataChunkStart = input->getPosition();
  18628. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18629. hasGotData = true;
  18630. }
  18631. else if (chunkType == chunkName ("bext"))
  18632. {
  18633. bwavChunkStart = input->getPosition();
  18634. bwavSize = length;
  18635. // Broadcast-wav extension chunk..
  18636. HeapBlock <BWAVChunk> bwav;
  18637. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18638. input->read (bwav, length);
  18639. bwav->copyTo (metadataValues);
  18640. }
  18641. else if (chunkType == chunkName ("smpl"))
  18642. {
  18643. HeapBlock <SMPLChunk> smpl;
  18644. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18645. input->read (smpl, length);
  18646. smpl->copyTo (metadataValues, length);
  18647. }
  18648. else if (chunkEnd <= input->getPosition())
  18649. {
  18650. break;
  18651. }
  18652. input->setPosition (chunkEnd);
  18653. }
  18654. }
  18655. }
  18656. }
  18657. ~WavAudioFormatReader()
  18658. {
  18659. }
  18660. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18661. int64 startSampleInFile, int numSamples)
  18662. {
  18663. jassert (destSamples != 0);
  18664. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18665. if (samplesAvailable < numSamples)
  18666. {
  18667. for (int i = numDestChannels; --i >= 0;)
  18668. if (destSamples[i] != 0)
  18669. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18670. numSamples = (int) samplesAvailable;
  18671. }
  18672. if (numSamples <= 0)
  18673. return true;
  18674. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18675. while (numSamples > 0)
  18676. {
  18677. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18678. char tempBuffer [tempBufSize];
  18679. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18680. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18681. if (bytesRead < numThisTime * bytesPerFrame)
  18682. {
  18683. jassert (bytesRead >= 0);
  18684. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18685. }
  18686. switch (bitsPerSample)
  18687. {
  18688. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18689. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18690. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18691. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18692. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18693. default: jassertfalse; break;
  18694. }
  18695. startOffsetInDestBuffer += numThisTime;
  18696. numSamples -= numThisTime;
  18697. }
  18698. return true;
  18699. }
  18700. int64 bwavChunkStart, bwavSize;
  18701. juce_UseDebuggingNewOperator
  18702. private:
  18703. ScopedPointer<AudioData::Converter> converter;
  18704. int bytesPerFrame;
  18705. int64 dataChunkStart, dataLength;
  18706. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18707. WavAudioFormatReader (const WavAudioFormatReader&);
  18708. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  18709. };
  18710. class WavAudioFormatWriter : public AudioFormatWriter
  18711. {
  18712. public:
  18713. WavAudioFormatWriter (OutputStream* const out,
  18714. const double sampleRate_,
  18715. const unsigned int numChannels_,
  18716. const int bits,
  18717. const StringPairArray& metadataValues)
  18718. : AudioFormatWriter (out,
  18719. TRANS (wavFormatName),
  18720. sampleRate_,
  18721. numChannels_,
  18722. bits),
  18723. lengthInSamples (0),
  18724. bytesWritten (0),
  18725. writeFailed (false)
  18726. {
  18727. if (metadataValues.size() > 0)
  18728. {
  18729. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18730. smplChunk = SMPLChunk::createFrom (metadataValues);
  18731. }
  18732. headerPosition = out->getPosition();
  18733. writeHeader();
  18734. }
  18735. ~WavAudioFormatWriter()
  18736. {
  18737. writeHeader();
  18738. }
  18739. bool write (const int** data, int numSamples)
  18740. {
  18741. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18742. if (writeFailed)
  18743. return false;
  18744. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18745. tempBlock.ensureSize (bytes, false);
  18746. switch (bitsPerSample)
  18747. {
  18748. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18749. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18750. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18751. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18752. default: jassertfalse; break;
  18753. }
  18754. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18755. || ! output->write (tempBlock.getData(), bytes))
  18756. {
  18757. // failed to write to disk, so let's try writing the header.
  18758. // If it's just run out of disk space, then if it does manage
  18759. // to write the header, we'll still have a useable file..
  18760. writeHeader();
  18761. writeFailed = true;
  18762. return false;
  18763. }
  18764. else
  18765. {
  18766. bytesWritten += bytes;
  18767. lengthInSamples += numSamples;
  18768. return true;
  18769. }
  18770. }
  18771. juce_UseDebuggingNewOperator
  18772. private:
  18773. ScopedPointer<AudioData::Converter> converter;
  18774. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18775. uint32 lengthInSamples, bytesWritten;
  18776. int64 headerPosition;
  18777. bool writeFailed;
  18778. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18779. void writeHeader()
  18780. {
  18781. const bool seekedOk = output->setPosition (headerPosition);
  18782. (void) seekedOk;
  18783. // if this fails, you've given it an output stream that can't seek! It needs
  18784. // to be able to seek back to write the header
  18785. jassert (seekedOk);
  18786. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18787. output->writeInt (chunkName ("RIFF"));
  18788. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18789. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18790. output->writeInt (chunkName ("WAVE"));
  18791. output->writeInt (chunkName ("fmt "));
  18792. output->writeInt (16);
  18793. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18794. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18795. output->writeShort ((short) numChannels);
  18796. output->writeInt ((int) sampleRate);
  18797. output->writeInt (bytesPerFrame * (int) sampleRate);
  18798. output->writeShort ((short) bytesPerFrame);
  18799. output->writeShort ((short) bitsPerSample);
  18800. if (bwavChunk.getSize() > 0)
  18801. {
  18802. output->writeInt (chunkName ("bext"));
  18803. output->writeInt ((int) bwavChunk.getSize());
  18804. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18805. }
  18806. if (smplChunk.getSize() > 0)
  18807. {
  18808. output->writeInt (chunkName ("smpl"));
  18809. output->writeInt ((int) smplChunk.getSize());
  18810. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18811. }
  18812. output->writeInt (chunkName ("data"));
  18813. output->writeInt (lengthInSamples * bytesPerFrame);
  18814. usesFloatingPointData = (bitsPerSample == 32);
  18815. }
  18816. WavAudioFormatWriter (const WavAudioFormatWriter&);
  18817. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  18818. };
  18819. WavAudioFormat::WavAudioFormat()
  18820. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18821. {
  18822. }
  18823. WavAudioFormat::~WavAudioFormat()
  18824. {
  18825. }
  18826. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18827. {
  18828. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18829. return Array <int> (rates);
  18830. }
  18831. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18832. {
  18833. const int depths[] = { 8, 16, 24, 32, 0 };
  18834. return Array <int> (depths);
  18835. }
  18836. bool WavAudioFormat::canDoStereo() { return true; }
  18837. bool WavAudioFormat::canDoMono() { return true; }
  18838. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18839. const bool deleteStreamIfOpeningFails)
  18840. {
  18841. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18842. if (r->sampleRate != 0)
  18843. return r.release();
  18844. if (! deleteStreamIfOpeningFails)
  18845. r->input = 0;
  18846. return 0;
  18847. }
  18848. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18849. double sampleRate,
  18850. unsigned int numChannels,
  18851. int bitsPerSample,
  18852. const StringPairArray& metadataValues,
  18853. int /*qualityOptionIndex*/)
  18854. {
  18855. if (getPossibleBitDepths().contains (bitsPerSample))
  18856. {
  18857. return new WavAudioFormatWriter (out,
  18858. sampleRate,
  18859. numChannels,
  18860. bitsPerSample,
  18861. metadataValues);
  18862. }
  18863. return 0;
  18864. }
  18865. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18866. {
  18867. TemporaryFile tempFile (file);
  18868. WavAudioFormat wav;
  18869. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18870. if (reader != 0)
  18871. {
  18872. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18873. if (outStream != 0)
  18874. {
  18875. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18876. reader->numChannels, reader->bitsPerSample,
  18877. metadata, 0));
  18878. if (writer != 0)
  18879. {
  18880. outStream.release();
  18881. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18882. writer = 0;
  18883. reader = 0;
  18884. return ok && tempFile.overwriteTargetFileWithTemporary();
  18885. }
  18886. }
  18887. }
  18888. return false;
  18889. }
  18890. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18891. {
  18892. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18893. if (reader != 0)
  18894. {
  18895. const int64 bwavPos = reader->bwavChunkStart;
  18896. const int64 bwavSize = reader->bwavSize;
  18897. reader = 0;
  18898. if (bwavSize > 0)
  18899. {
  18900. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18901. if (chunk.getSize() <= (size_t) bwavSize)
  18902. {
  18903. // the new one will fit in the space available, so write it directly..
  18904. const int64 oldSize = wavFile.getSize();
  18905. {
  18906. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18907. out->setPosition (bwavPos);
  18908. out->write (chunk.getData(), (int) chunk.getSize());
  18909. out->setPosition (oldSize);
  18910. }
  18911. jassert (wavFile.getSize() == oldSize);
  18912. return true;
  18913. }
  18914. }
  18915. }
  18916. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18917. }
  18918. END_JUCE_NAMESPACE
  18919. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18920. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18921. #if JUCE_USE_CDREADER
  18922. BEGIN_JUCE_NAMESPACE
  18923. int AudioCDReader::getNumTracks() const
  18924. {
  18925. return trackStartSamples.size() - 1;
  18926. }
  18927. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18928. {
  18929. return trackStartSamples [trackNum];
  18930. }
  18931. const Array<int>& AudioCDReader::getTrackOffsets() const
  18932. {
  18933. return trackStartSamples;
  18934. }
  18935. int AudioCDReader::getCDDBId()
  18936. {
  18937. int checksum = 0;
  18938. const int numTracks = getNumTracks();
  18939. for (int i = 0; i < numTracks; ++i)
  18940. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18941. checksum += offset % 10;
  18942. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18943. // CCLLLLTT: checksum, length, tracks
  18944. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18945. }
  18946. END_JUCE_NAMESPACE
  18947. #endif
  18948. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18949. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18950. BEGIN_JUCE_NAMESPACE
  18951. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18952. const bool deleteReaderWhenThisIsDeleted)
  18953. : reader (reader_),
  18954. deleteReader (deleteReaderWhenThisIsDeleted),
  18955. nextPlayPos (0),
  18956. looping (false)
  18957. {
  18958. jassert (reader != 0);
  18959. }
  18960. AudioFormatReaderSource::~AudioFormatReaderSource()
  18961. {
  18962. releaseResources();
  18963. if (deleteReader)
  18964. delete reader;
  18965. }
  18966. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18967. {
  18968. nextPlayPos = newPosition;
  18969. }
  18970. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  18971. {
  18972. looping = shouldLoop;
  18973. }
  18974. int AudioFormatReaderSource::getNextReadPosition() const
  18975. {
  18976. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18977. : nextPlayPos;
  18978. }
  18979. int AudioFormatReaderSource::getTotalLength() const
  18980. {
  18981. return (int) reader->lengthInSamples;
  18982. }
  18983. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18984. double /*sampleRate*/)
  18985. {
  18986. }
  18987. void AudioFormatReaderSource::releaseResources()
  18988. {
  18989. }
  18990. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18991. {
  18992. if (info.numSamples > 0)
  18993. {
  18994. const int start = nextPlayPos;
  18995. if (looping)
  18996. {
  18997. const int newStart = start % (int) reader->lengthInSamples;
  18998. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18999. if (newEnd > newStart)
  19000. {
  19001. info.buffer->readFromAudioReader (reader,
  19002. info.startSample,
  19003. newEnd - newStart,
  19004. newStart,
  19005. true, true);
  19006. }
  19007. else
  19008. {
  19009. const int endSamps = (int) reader->lengthInSamples - newStart;
  19010. info.buffer->readFromAudioReader (reader,
  19011. info.startSample,
  19012. endSamps,
  19013. newStart,
  19014. true, true);
  19015. info.buffer->readFromAudioReader (reader,
  19016. info.startSample + endSamps,
  19017. newEnd,
  19018. 0,
  19019. true, true);
  19020. }
  19021. nextPlayPos = newEnd;
  19022. }
  19023. else
  19024. {
  19025. info.buffer->readFromAudioReader (reader,
  19026. info.startSample,
  19027. info.numSamples,
  19028. start,
  19029. true, true);
  19030. nextPlayPos += info.numSamples;
  19031. }
  19032. }
  19033. }
  19034. END_JUCE_NAMESPACE
  19035. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19036. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19037. BEGIN_JUCE_NAMESPACE
  19038. AudioSourcePlayer::AudioSourcePlayer()
  19039. : source (0),
  19040. sampleRate (0),
  19041. bufferSize (0),
  19042. tempBuffer (2, 8),
  19043. lastGain (1.0f),
  19044. gain (1.0f)
  19045. {
  19046. }
  19047. AudioSourcePlayer::~AudioSourcePlayer()
  19048. {
  19049. setSource (0);
  19050. }
  19051. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19052. {
  19053. if (source != newSource)
  19054. {
  19055. AudioSource* const oldSource = source;
  19056. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19057. newSource->prepareToPlay (bufferSize, sampleRate);
  19058. {
  19059. const ScopedLock sl (readLock);
  19060. source = newSource;
  19061. }
  19062. if (oldSource != 0)
  19063. oldSource->releaseResources();
  19064. }
  19065. }
  19066. void AudioSourcePlayer::setGain (const float newGain) throw()
  19067. {
  19068. gain = newGain;
  19069. }
  19070. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19071. int totalNumInputChannels,
  19072. float** outputChannelData,
  19073. int totalNumOutputChannels,
  19074. int numSamples)
  19075. {
  19076. // these should have been prepared by audioDeviceAboutToStart()...
  19077. jassert (sampleRate > 0 && bufferSize > 0);
  19078. const ScopedLock sl (readLock);
  19079. if (source != 0)
  19080. {
  19081. AudioSourceChannelInfo info;
  19082. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19083. // messy stuff needed to compact the channels down into an array
  19084. // of non-zero pointers..
  19085. for (i = 0; i < totalNumInputChannels; ++i)
  19086. {
  19087. if (inputChannelData[i] != 0)
  19088. {
  19089. inputChans [numInputs++] = inputChannelData[i];
  19090. if (numInputs >= numElementsInArray (inputChans))
  19091. break;
  19092. }
  19093. }
  19094. for (i = 0; i < totalNumOutputChannels; ++i)
  19095. {
  19096. if (outputChannelData[i] != 0)
  19097. {
  19098. outputChans [numOutputs++] = outputChannelData[i];
  19099. if (numOutputs >= numElementsInArray (outputChans))
  19100. break;
  19101. }
  19102. }
  19103. if (numInputs > numOutputs)
  19104. {
  19105. // if there aren't enough output channels for the number of
  19106. // inputs, we need to create some temporary extra ones (can't
  19107. // use the input data in case it gets written to)
  19108. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19109. false, false, true);
  19110. for (i = 0; i < numOutputs; ++i)
  19111. {
  19112. channels[numActiveChans] = outputChans[i];
  19113. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19114. ++numActiveChans;
  19115. }
  19116. for (i = numOutputs; i < numInputs; ++i)
  19117. {
  19118. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19119. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19120. ++numActiveChans;
  19121. }
  19122. }
  19123. else
  19124. {
  19125. for (i = 0; i < numInputs; ++i)
  19126. {
  19127. channels[numActiveChans] = outputChans[i];
  19128. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19129. ++numActiveChans;
  19130. }
  19131. for (i = numInputs; i < numOutputs; ++i)
  19132. {
  19133. channels[numActiveChans] = outputChans[i];
  19134. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19135. ++numActiveChans;
  19136. }
  19137. }
  19138. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19139. info.buffer = &buffer;
  19140. info.startSample = 0;
  19141. info.numSamples = numSamples;
  19142. source->getNextAudioBlock (info);
  19143. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19144. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19145. lastGain = gain;
  19146. }
  19147. else
  19148. {
  19149. for (int i = 0; i < totalNumOutputChannels; ++i)
  19150. if (outputChannelData[i] != 0)
  19151. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19152. }
  19153. }
  19154. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19155. {
  19156. sampleRate = device->getCurrentSampleRate();
  19157. bufferSize = device->getCurrentBufferSizeSamples();
  19158. zeromem (channels, sizeof (channels));
  19159. if (source != 0)
  19160. source->prepareToPlay (bufferSize, sampleRate);
  19161. }
  19162. void AudioSourcePlayer::audioDeviceStopped()
  19163. {
  19164. if (source != 0)
  19165. source->releaseResources();
  19166. sampleRate = 0.0;
  19167. bufferSize = 0;
  19168. tempBuffer.setSize (2, 8);
  19169. }
  19170. END_JUCE_NAMESPACE
  19171. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19172. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19173. BEGIN_JUCE_NAMESPACE
  19174. AudioTransportSource::AudioTransportSource()
  19175. : source (0),
  19176. resamplerSource (0),
  19177. bufferingSource (0),
  19178. positionableSource (0),
  19179. masterSource (0),
  19180. gain (1.0f),
  19181. lastGain (1.0f),
  19182. playing (false),
  19183. stopped (true),
  19184. sampleRate (44100.0),
  19185. sourceSampleRate (0.0),
  19186. blockSize (128),
  19187. readAheadBufferSize (0),
  19188. isPrepared (false),
  19189. inputStreamEOF (false)
  19190. {
  19191. }
  19192. AudioTransportSource::~AudioTransportSource()
  19193. {
  19194. setSource (0);
  19195. releaseResources();
  19196. }
  19197. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19198. int readAheadBufferSize_,
  19199. double sourceSampleRateToCorrectFor)
  19200. {
  19201. if (source == newSource)
  19202. {
  19203. if (source == 0)
  19204. return;
  19205. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19206. }
  19207. readAheadBufferSize = readAheadBufferSize_;
  19208. sourceSampleRate = sourceSampleRateToCorrectFor;
  19209. ResamplingAudioSource* newResamplerSource = 0;
  19210. BufferingAudioSource* newBufferingSource = 0;
  19211. PositionableAudioSource* newPositionableSource = 0;
  19212. AudioSource* newMasterSource = 0;
  19213. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19214. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19215. AudioSource* oldMasterSource = masterSource;
  19216. if (newSource != 0)
  19217. {
  19218. newPositionableSource = newSource;
  19219. if (readAheadBufferSize_ > 0)
  19220. newPositionableSource = newBufferingSource
  19221. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19222. newPositionableSource->setNextReadPosition (0);
  19223. if (sourceSampleRateToCorrectFor != 0)
  19224. newMasterSource = newResamplerSource
  19225. = new ResamplingAudioSource (newPositionableSource, false);
  19226. else
  19227. newMasterSource = newPositionableSource;
  19228. if (isPrepared)
  19229. {
  19230. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19231. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19232. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19233. }
  19234. }
  19235. {
  19236. const ScopedLock sl (callbackLock);
  19237. source = newSource;
  19238. resamplerSource = newResamplerSource;
  19239. bufferingSource = newBufferingSource;
  19240. masterSource = newMasterSource;
  19241. positionableSource = newPositionableSource;
  19242. playing = false;
  19243. }
  19244. if (oldMasterSource != 0)
  19245. oldMasterSource->releaseResources();
  19246. }
  19247. void AudioTransportSource::start()
  19248. {
  19249. if ((! playing) && masterSource != 0)
  19250. {
  19251. {
  19252. const ScopedLock sl (callbackLock);
  19253. playing = true;
  19254. stopped = false;
  19255. inputStreamEOF = false;
  19256. }
  19257. sendChangeMessage (this);
  19258. }
  19259. }
  19260. void AudioTransportSource::stop()
  19261. {
  19262. if (playing)
  19263. {
  19264. {
  19265. const ScopedLock sl (callbackLock);
  19266. playing = false;
  19267. }
  19268. int n = 500;
  19269. while (--n >= 0 && ! stopped)
  19270. Thread::sleep (2);
  19271. sendChangeMessage (this);
  19272. }
  19273. }
  19274. void AudioTransportSource::setPosition (double newPosition)
  19275. {
  19276. if (sampleRate > 0.0)
  19277. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19278. }
  19279. double AudioTransportSource::getCurrentPosition() const
  19280. {
  19281. if (sampleRate > 0.0)
  19282. return getNextReadPosition() / sampleRate;
  19283. else
  19284. return 0.0;
  19285. }
  19286. void AudioTransportSource::setNextReadPosition (int newPosition)
  19287. {
  19288. if (positionableSource != 0)
  19289. {
  19290. if (sampleRate > 0 && sourceSampleRate > 0)
  19291. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19292. positionableSource->setNextReadPosition (newPosition);
  19293. }
  19294. }
  19295. int AudioTransportSource::getNextReadPosition() const
  19296. {
  19297. if (positionableSource != 0)
  19298. {
  19299. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19300. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19301. }
  19302. return 0;
  19303. }
  19304. int AudioTransportSource::getTotalLength() const
  19305. {
  19306. const ScopedLock sl (callbackLock);
  19307. if (positionableSource != 0)
  19308. {
  19309. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19310. return roundToInt (positionableSource->getTotalLength() * ratio);
  19311. }
  19312. return 0;
  19313. }
  19314. bool AudioTransportSource::isLooping() const
  19315. {
  19316. const ScopedLock sl (callbackLock);
  19317. return positionableSource != 0
  19318. && positionableSource->isLooping();
  19319. }
  19320. void AudioTransportSource::setGain (const float newGain) throw()
  19321. {
  19322. gain = newGain;
  19323. }
  19324. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19325. double sampleRate_)
  19326. {
  19327. const ScopedLock sl (callbackLock);
  19328. sampleRate = sampleRate_;
  19329. blockSize = samplesPerBlockExpected;
  19330. if (masterSource != 0)
  19331. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19332. if (resamplerSource != 0 && sourceSampleRate != 0)
  19333. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19334. isPrepared = true;
  19335. }
  19336. void AudioTransportSource::releaseResources()
  19337. {
  19338. const ScopedLock sl (callbackLock);
  19339. if (masterSource != 0)
  19340. masterSource->releaseResources();
  19341. isPrepared = false;
  19342. }
  19343. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19344. {
  19345. const ScopedLock sl (callbackLock);
  19346. inputStreamEOF = false;
  19347. if (masterSource != 0 && ! stopped)
  19348. {
  19349. masterSource->getNextAudioBlock (info);
  19350. if (! playing)
  19351. {
  19352. // just stopped playing, so fade out the last block..
  19353. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19354. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19355. if (info.numSamples > 256)
  19356. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19357. }
  19358. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19359. && ! positionableSource->isLooping())
  19360. {
  19361. playing = false;
  19362. inputStreamEOF = true;
  19363. sendChangeMessage (this);
  19364. }
  19365. stopped = ! playing;
  19366. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19367. {
  19368. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19369. lastGain, gain);
  19370. }
  19371. }
  19372. else
  19373. {
  19374. info.clearActiveBufferRegion();
  19375. stopped = true;
  19376. }
  19377. lastGain = gain;
  19378. }
  19379. END_JUCE_NAMESPACE
  19380. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19381. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19382. BEGIN_JUCE_NAMESPACE
  19383. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19384. public Thread,
  19385. private Timer
  19386. {
  19387. public:
  19388. SharedBufferingAudioSourceThread()
  19389. : Thread ("Audio Buffer")
  19390. {
  19391. }
  19392. ~SharedBufferingAudioSourceThread()
  19393. {
  19394. stopThread (10000);
  19395. clearSingletonInstance();
  19396. }
  19397. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19398. void addSource (BufferingAudioSource* source)
  19399. {
  19400. const ScopedLock sl (lock);
  19401. if (! sources.contains (source))
  19402. {
  19403. sources.add (source);
  19404. startThread();
  19405. stopTimer();
  19406. }
  19407. notify();
  19408. }
  19409. void removeSource (BufferingAudioSource* source)
  19410. {
  19411. const ScopedLock sl (lock);
  19412. sources.removeValue (source);
  19413. if (sources.size() == 0)
  19414. startTimer (5000);
  19415. }
  19416. private:
  19417. Array <BufferingAudioSource*> sources;
  19418. CriticalSection lock;
  19419. void run()
  19420. {
  19421. while (! threadShouldExit())
  19422. {
  19423. bool busy = false;
  19424. for (int i = sources.size(); --i >= 0;)
  19425. {
  19426. if (threadShouldExit())
  19427. return;
  19428. const ScopedLock sl (lock);
  19429. BufferingAudioSource* const b = sources[i];
  19430. if (b != 0 && b->readNextBufferChunk())
  19431. busy = true;
  19432. }
  19433. if (! busy)
  19434. wait (500);
  19435. }
  19436. }
  19437. void timerCallback()
  19438. {
  19439. stopTimer();
  19440. if (sources.size() == 0)
  19441. deleteInstance();
  19442. }
  19443. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  19444. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  19445. };
  19446. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19447. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19448. const bool deleteSourceWhenDeleted_,
  19449. int numberOfSamplesToBuffer_)
  19450. : source (source_),
  19451. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19452. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19453. buffer (2, 0),
  19454. bufferValidStart (0),
  19455. bufferValidEnd (0),
  19456. nextPlayPos (0),
  19457. wasSourceLooping (false)
  19458. {
  19459. jassert (source_ != 0);
  19460. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19461. // not using a larger buffer..
  19462. }
  19463. BufferingAudioSource::~BufferingAudioSource()
  19464. {
  19465. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19466. if (thread != 0)
  19467. thread->removeSource (this);
  19468. if (deleteSourceWhenDeleted)
  19469. delete source;
  19470. }
  19471. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19472. {
  19473. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19474. sampleRate = sampleRate_;
  19475. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19476. buffer.clear();
  19477. bufferValidStart = 0;
  19478. bufferValidEnd = 0;
  19479. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19480. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19481. buffer.getNumSamples() / 2))
  19482. {
  19483. SharedBufferingAudioSourceThread::getInstance()->notify();
  19484. Thread::sleep (5);
  19485. }
  19486. }
  19487. void BufferingAudioSource::releaseResources()
  19488. {
  19489. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19490. if (thread != 0)
  19491. thread->removeSource (this);
  19492. buffer.setSize (2, 0);
  19493. source->releaseResources();
  19494. }
  19495. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19496. {
  19497. const ScopedLock sl (bufferStartPosLock);
  19498. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19499. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19500. if (validStart == validEnd)
  19501. {
  19502. // total cache miss
  19503. info.clearActiveBufferRegion();
  19504. }
  19505. else
  19506. {
  19507. if (validStart > 0)
  19508. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19509. if (validEnd < info.numSamples)
  19510. info.buffer->clear (info.startSample + validEnd,
  19511. info.numSamples - validEnd); // partial cache miss at end
  19512. if (validStart < validEnd)
  19513. {
  19514. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19515. {
  19516. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19517. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19518. if (startBufferIndex < endBufferIndex)
  19519. {
  19520. info.buffer->copyFrom (chan, info.startSample + validStart,
  19521. buffer,
  19522. chan, startBufferIndex,
  19523. validEnd - validStart);
  19524. }
  19525. else
  19526. {
  19527. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19528. info.buffer->copyFrom (chan, info.startSample + validStart,
  19529. buffer,
  19530. chan, startBufferIndex,
  19531. initialSize);
  19532. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19533. buffer,
  19534. chan, 0,
  19535. (validEnd - validStart) - initialSize);
  19536. }
  19537. }
  19538. }
  19539. nextPlayPos += info.numSamples;
  19540. if (source->isLooping() && nextPlayPos > 0)
  19541. nextPlayPos %= source->getTotalLength();
  19542. }
  19543. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19544. if (thread != 0)
  19545. thread->notify();
  19546. }
  19547. int BufferingAudioSource::getNextReadPosition() const
  19548. {
  19549. return (source->isLooping() && nextPlayPos > 0)
  19550. ? nextPlayPos % source->getTotalLength()
  19551. : nextPlayPos;
  19552. }
  19553. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19554. {
  19555. const ScopedLock sl (bufferStartPosLock);
  19556. nextPlayPos = newPosition;
  19557. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19558. if (thread != 0)
  19559. thread->notify();
  19560. }
  19561. bool BufferingAudioSource::readNextBufferChunk()
  19562. {
  19563. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19564. {
  19565. const ScopedLock sl (bufferStartPosLock);
  19566. if (wasSourceLooping != isLooping())
  19567. {
  19568. wasSourceLooping = isLooping();
  19569. bufferValidStart = 0;
  19570. bufferValidEnd = 0;
  19571. }
  19572. newBVS = jmax (0, nextPlayPos);
  19573. newBVE = newBVS + buffer.getNumSamples() - 4;
  19574. sectionToReadStart = 0;
  19575. sectionToReadEnd = 0;
  19576. const int maxChunkSize = 2048;
  19577. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19578. {
  19579. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19580. sectionToReadStart = newBVS;
  19581. sectionToReadEnd = newBVE;
  19582. bufferValidStart = 0;
  19583. bufferValidEnd = 0;
  19584. }
  19585. else if (abs (newBVS - bufferValidStart) > 512
  19586. || abs (newBVE - bufferValidEnd) > 512)
  19587. {
  19588. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19589. sectionToReadStart = bufferValidEnd;
  19590. sectionToReadEnd = newBVE;
  19591. bufferValidStart = newBVS;
  19592. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19593. }
  19594. }
  19595. if (sectionToReadStart != sectionToReadEnd)
  19596. {
  19597. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19598. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19599. if (bufferIndexStart < bufferIndexEnd)
  19600. {
  19601. readBufferSection (sectionToReadStart,
  19602. sectionToReadEnd - sectionToReadStart,
  19603. bufferIndexStart);
  19604. }
  19605. else
  19606. {
  19607. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19608. readBufferSection (sectionToReadStart,
  19609. initialSize,
  19610. bufferIndexStart);
  19611. readBufferSection (sectionToReadStart + initialSize,
  19612. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19613. 0);
  19614. }
  19615. const ScopedLock sl2 (bufferStartPosLock);
  19616. bufferValidStart = newBVS;
  19617. bufferValidEnd = newBVE;
  19618. return true;
  19619. }
  19620. else
  19621. {
  19622. return false;
  19623. }
  19624. }
  19625. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19626. {
  19627. if (source->getNextReadPosition() != start)
  19628. source->setNextReadPosition (start);
  19629. AudioSourceChannelInfo info;
  19630. info.buffer = &buffer;
  19631. info.startSample = bufferOffset;
  19632. info.numSamples = length;
  19633. source->getNextAudioBlock (info);
  19634. }
  19635. END_JUCE_NAMESPACE
  19636. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19637. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19638. BEGIN_JUCE_NAMESPACE
  19639. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19640. const bool deleteSourceWhenDeleted_)
  19641. : requiredNumberOfChannels (2),
  19642. source (source_),
  19643. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19644. buffer (2, 16)
  19645. {
  19646. remappedInfo.buffer = &buffer;
  19647. remappedInfo.startSample = 0;
  19648. }
  19649. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19650. {
  19651. if (deleteSourceWhenDeleted)
  19652. delete source;
  19653. }
  19654. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19655. {
  19656. const ScopedLock sl (lock);
  19657. requiredNumberOfChannels = requiredNumberOfChannels_;
  19658. }
  19659. void ChannelRemappingAudioSource::clearAllMappings()
  19660. {
  19661. const ScopedLock sl (lock);
  19662. remappedInputs.clear();
  19663. remappedOutputs.clear();
  19664. }
  19665. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19666. {
  19667. const ScopedLock sl (lock);
  19668. while (remappedInputs.size() < destIndex)
  19669. remappedInputs.add (-1);
  19670. remappedInputs.set (destIndex, sourceIndex);
  19671. }
  19672. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19673. {
  19674. const ScopedLock sl (lock);
  19675. while (remappedOutputs.size() < sourceIndex)
  19676. remappedOutputs.add (-1);
  19677. remappedOutputs.set (sourceIndex, destIndex);
  19678. }
  19679. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19680. {
  19681. const ScopedLock sl (lock);
  19682. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19683. return remappedInputs.getUnchecked (inputChannelIndex);
  19684. return -1;
  19685. }
  19686. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19687. {
  19688. const ScopedLock sl (lock);
  19689. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19690. return remappedOutputs .getUnchecked (outputChannelIndex);
  19691. return -1;
  19692. }
  19693. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19694. {
  19695. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19696. }
  19697. void ChannelRemappingAudioSource::releaseResources()
  19698. {
  19699. source->releaseResources();
  19700. }
  19701. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19702. {
  19703. const ScopedLock sl (lock);
  19704. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19705. const int numChans = bufferToFill.buffer->getNumChannels();
  19706. int i;
  19707. for (i = 0; i < buffer.getNumChannels(); ++i)
  19708. {
  19709. const int remappedChan = getRemappedInputChannel (i);
  19710. if (remappedChan >= 0 && remappedChan < numChans)
  19711. {
  19712. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19713. remappedChan,
  19714. bufferToFill.startSample,
  19715. bufferToFill.numSamples);
  19716. }
  19717. else
  19718. {
  19719. buffer.clear (i, 0, bufferToFill.numSamples);
  19720. }
  19721. }
  19722. remappedInfo.numSamples = bufferToFill.numSamples;
  19723. source->getNextAudioBlock (remappedInfo);
  19724. bufferToFill.clearActiveBufferRegion();
  19725. for (i = 0; i < requiredNumberOfChannels; ++i)
  19726. {
  19727. const int remappedChan = getRemappedOutputChannel (i);
  19728. if (remappedChan >= 0 && remappedChan < numChans)
  19729. {
  19730. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19731. buffer, i, 0, bufferToFill.numSamples);
  19732. }
  19733. }
  19734. }
  19735. XmlElement* ChannelRemappingAudioSource::createXml() const
  19736. {
  19737. XmlElement* e = new XmlElement ("MAPPINGS");
  19738. String ins, outs;
  19739. int i;
  19740. const ScopedLock sl (lock);
  19741. for (i = 0; i < remappedInputs.size(); ++i)
  19742. ins << remappedInputs.getUnchecked(i) << ' ';
  19743. for (i = 0; i < remappedOutputs.size(); ++i)
  19744. outs << remappedOutputs.getUnchecked(i) << ' ';
  19745. e->setAttribute ("inputs", ins.trimEnd());
  19746. e->setAttribute ("outputs", outs.trimEnd());
  19747. return e;
  19748. }
  19749. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19750. {
  19751. if (e.hasTagName ("MAPPINGS"))
  19752. {
  19753. const ScopedLock sl (lock);
  19754. clearAllMappings();
  19755. StringArray ins, outs;
  19756. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19757. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19758. int i;
  19759. for (i = 0; i < ins.size(); ++i)
  19760. remappedInputs.add (ins[i].getIntValue());
  19761. for (i = 0; i < outs.size(); ++i)
  19762. remappedOutputs.add (outs[i].getIntValue());
  19763. }
  19764. }
  19765. END_JUCE_NAMESPACE
  19766. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19767. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19768. BEGIN_JUCE_NAMESPACE
  19769. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19770. const bool deleteInputWhenDeleted_)
  19771. : input (inputSource),
  19772. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19773. {
  19774. jassert (inputSource != 0);
  19775. for (int i = 2; --i >= 0;)
  19776. iirFilters.add (new IIRFilter());
  19777. }
  19778. IIRFilterAudioSource::~IIRFilterAudioSource()
  19779. {
  19780. if (deleteInputWhenDeleted)
  19781. delete input;
  19782. }
  19783. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19784. {
  19785. for (int i = iirFilters.size(); --i >= 0;)
  19786. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19787. }
  19788. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19789. {
  19790. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19791. for (int i = iirFilters.size(); --i >= 0;)
  19792. iirFilters.getUnchecked(i)->reset();
  19793. }
  19794. void IIRFilterAudioSource::releaseResources()
  19795. {
  19796. input->releaseResources();
  19797. }
  19798. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19799. {
  19800. input->getNextAudioBlock (bufferToFill);
  19801. const int numChannels = bufferToFill.buffer->getNumChannels();
  19802. while (numChannels > iirFilters.size())
  19803. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19804. for (int i = 0; i < numChannels; ++i)
  19805. iirFilters.getUnchecked(i)
  19806. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19807. bufferToFill.numSamples);
  19808. }
  19809. END_JUCE_NAMESPACE
  19810. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19811. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19812. BEGIN_JUCE_NAMESPACE
  19813. MixerAudioSource::MixerAudioSource()
  19814. : tempBuffer (2, 0),
  19815. currentSampleRate (0.0),
  19816. bufferSizeExpected (0)
  19817. {
  19818. }
  19819. MixerAudioSource::~MixerAudioSource()
  19820. {
  19821. removeAllInputs();
  19822. }
  19823. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19824. {
  19825. if (input != 0 && ! inputs.contains (input))
  19826. {
  19827. double localRate;
  19828. int localBufferSize;
  19829. {
  19830. const ScopedLock sl (lock);
  19831. localRate = currentSampleRate;
  19832. localBufferSize = bufferSizeExpected;
  19833. }
  19834. if (localRate != 0.0)
  19835. input->prepareToPlay (localBufferSize, localRate);
  19836. const ScopedLock sl (lock);
  19837. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19838. inputs.add (input);
  19839. }
  19840. }
  19841. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19842. {
  19843. if (input != 0)
  19844. {
  19845. int index;
  19846. {
  19847. const ScopedLock sl (lock);
  19848. index = inputs.indexOf (input);
  19849. if (index >= 0)
  19850. {
  19851. inputsToDelete.shiftBits (index, 1);
  19852. inputs.remove (index);
  19853. }
  19854. }
  19855. if (index >= 0)
  19856. {
  19857. input->releaseResources();
  19858. if (deleteInput)
  19859. delete input;
  19860. }
  19861. }
  19862. }
  19863. void MixerAudioSource::removeAllInputs()
  19864. {
  19865. OwnedArray<AudioSource> toDelete;
  19866. {
  19867. const ScopedLock sl (lock);
  19868. for (int i = inputs.size(); --i >= 0;)
  19869. if (inputsToDelete[i])
  19870. toDelete.add (inputs.getUnchecked(i));
  19871. }
  19872. }
  19873. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19874. {
  19875. tempBuffer.setSize (2, samplesPerBlockExpected);
  19876. const ScopedLock sl (lock);
  19877. currentSampleRate = sampleRate;
  19878. bufferSizeExpected = samplesPerBlockExpected;
  19879. for (int i = inputs.size(); --i >= 0;)
  19880. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19881. }
  19882. void MixerAudioSource::releaseResources()
  19883. {
  19884. const ScopedLock sl (lock);
  19885. for (int i = inputs.size(); --i >= 0;)
  19886. inputs.getUnchecked(i)->releaseResources();
  19887. tempBuffer.setSize (2, 0);
  19888. currentSampleRate = 0;
  19889. bufferSizeExpected = 0;
  19890. }
  19891. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19892. {
  19893. const ScopedLock sl (lock);
  19894. if (inputs.size() > 0)
  19895. {
  19896. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19897. if (inputs.size() > 1)
  19898. {
  19899. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19900. info.buffer->getNumSamples());
  19901. AudioSourceChannelInfo info2;
  19902. info2.buffer = &tempBuffer;
  19903. info2.numSamples = info.numSamples;
  19904. info2.startSample = 0;
  19905. for (int i = 1; i < inputs.size(); ++i)
  19906. {
  19907. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19908. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19909. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19910. }
  19911. }
  19912. }
  19913. else
  19914. {
  19915. info.clearActiveBufferRegion();
  19916. }
  19917. }
  19918. END_JUCE_NAMESPACE
  19919. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19920. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19921. BEGIN_JUCE_NAMESPACE
  19922. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19923. const bool deleteInputWhenDeleted_,
  19924. const int numChannels_)
  19925. : input (inputSource),
  19926. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19927. ratio (1.0),
  19928. lastRatio (1.0),
  19929. buffer (numChannels_, 0),
  19930. sampsInBuffer (0),
  19931. numChannels (numChannels_)
  19932. {
  19933. jassert (input != 0);
  19934. }
  19935. ResamplingAudioSource::~ResamplingAudioSource()
  19936. {
  19937. if (deleteInputWhenDeleted)
  19938. delete input;
  19939. }
  19940. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19941. {
  19942. jassert (samplesInPerOutputSample > 0);
  19943. const ScopedLock sl (ratioLock);
  19944. ratio = jmax (0.0, samplesInPerOutputSample);
  19945. }
  19946. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19947. double sampleRate)
  19948. {
  19949. const ScopedLock sl (ratioLock);
  19950. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19951. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19952. buffer.clear();
  19953. sampsInBuffer = 0;
  19954. bufferPos = 0;
  19955. subSampleOffset = 0.0;
  19956. filterStates.calloc (numChannels);
  19957. srcBuffers.calloc (numChannels);
  19958. destBuffers.calloc (numChannels);
  19959. createLowPass (ratio);
  19960. resetFilters();
  19961. }
  19962. void ResamplingAudioSource::releaseResources()
  19963. {
  19964. input->releaseResources();
  19965. buffer.setSize (numChannels, 0);
  19966. }
  19967. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19968. {
  19969. const ScopedLock sl (ratioLock);
  19970. if (lastRatio != ratio)
  19971. {
  19972. createLowPass (ratio);
  19973. lastRatio = ratio;
  19974. }
  19975. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19976. int bufferSize = buffer.getNumSamples();
  19977. if (bufferSize < sampsNeeded + 8)
  19978. {
  19979. bufferPos %= bufferSize;
  19980. bufferSize = sampsNeeded + 32;
  19981. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19982. }
  19983. bufferPos %= bufferSize;
  19984. int endOfBufferPos = bufferPos + sampsInBuffer;
  19985. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19986. while (sampsNeeded > sampsInBuffer)
  19987. {
  19988. endOfBufferPos %= bufferSize;
  19989. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19990. bufferSize - endOfBufferPos);
  19991. AudioSourceChannelInfo readInfo;
  19992. readInfo.buffer = &buffer;
  19993. readInfo.numSamples = numToDo;
  19994. readInfo.startSample = endOfBufferPos;
  19995. input->getNextAudioBlock (readInfo);
  19996. if (ratio > 1.0001)
  19997. {
  19998. // for down-sampling, pre-apply the filter..
  19999. for (int i = channelsToProcess; --i >= 0;)
  20000. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  20001. }
  20002. sampsInBuffer += numToDo;
  20003. endOfBufferPos += numToDo;
  20004. }
  20005. for (int channel = 0; channel < channelsToProcess; ++channel)
  20006. {
  20007. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  20008. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  20009. }
  20010. int nextPos = (bufferPos + 1) % bufferSize;
  20011. for (int m = info.numSamples; --m >= 0;)
  20012. {
  20013. const float alpha = (float) subSampleOffset;
  20014. const float invAlpha = 1.0f - alpha;
  20015. for (int channel = 0; channel < channelsToProcess; ++channel)
  20016. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20017. subSampleOffset += ratio;
  20018. jassert (sampsInBuffer > 0);
  20019. while (subSampleOffset >= 1.0)
  20020. {
  20021. if (++bufferPos >= bufferSize)
  20022. bufferPos = 0;
  20023. --sampsInBuffer;
  20024. nextPos = (bufferPos + 1) % bufferSize;
  20025. subSampleOffset -= 1.0;
  20026. }
  20027. }
  20028. if (ratio < 0.9999)
  20029. {
  20030. // for up-sampling, apply the filter after transposing..
  20031. for (int i = channelsToProcess; --i >= 0;)
  20032. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20033. }
  20034. else if (ratio <= 1.0001)
  20035. {
  20036. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20037. for (int i = channelsToProcess; --i >= 0;)
  20038. {
  20039. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20040. FilterState& fs = filterStates[i];
  20041. if (info.numSamples > 1)
  20042. {
  20043. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20044. }
  20045. else
  20046. {
  20047. fs.y2 = fs.y1;
  20048. fs.x2 = fs.x1;
  20049. }
  20050. fs.y1 = fs.x1 = *endOfBuffer;
  20051. }
  20052. }
  20053. jassert (sampsInBuffer >= 0);
  20054. }
  20055. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20056. {
  20057. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20058. : 0.5 * frequencyRatio;
  20059. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  20060. const double nSquared = n * n;
  20061. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20062. setFilterCoefficients (c1,
  20063. c1 * 2.0f,
  20064. c1,
  20065. 1.0,
  20066. c1 * 2.0 * (1.0 - nSquared),
  20067. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20068. }
  20069. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20070. {
  20071. const double a = 1.0 / c4;
  20072. c1 *= a;
  20073. c2 *= a;
  20074. c3 *= a;
  20075. c5 *= a;
  20076. c6 *= a;
  20077. coefficients[0] = c1;
  20078. coefficients[1] = c2;
  20079. coefficients[2] = c3;
  20080. coefficients[3] = c4;
  20081. coefficients[4] = c5;
  20082. coefficients[5] = c6;
  20083. }
  20084. void ResamplingAudioSource::resetFilters()
  20085. {
  20086. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20087. }
  20088. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20089. {
  20090. while (--num >= 0)
  20091. {
  20092. const double in = *samples;
  20093. double out = coefficients[0] * in
  20094. + coefficients[1] * fs.x1
  20095. + coefficients[2] * fs.x2
  20096. - coefficients[4] * fs.y1
  20097. - coefficients[5] * fs.y2;
  20098. #if JUCE_INTEL
  20099. if (! (out < -1.0e-8 || out > 1.0e-8))
  20100. out = 0;
  20101. #endif
  20102. fs.x2 = fs.x1;
  20103. fs.x1 = in;
  20104. fs.y2 = fs.y1;
  20105. fs.y1 = out;
  20106. *samples++ = (float) out;
  20107. }
  20108. }
  20109. END_JUCE_NAMESPACE
  20110. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20111. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20112. BEGIN_JUCE_NAMESPACE
  20113. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20114. : frequency (1000.0),
  20115. sampleRate (44100.0),
  20116. currentPhase (0.0),
  20117. phasePerSample (0.0),
  20118. amplitude (0.5f)
  20119. {
  20120. }
  20121. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20122. {
  20123. }
  20124. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20125. {
  20126. amplitude = newAmplitude;
  20127. }
  20128. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20129. {
  20130. frequency = newFrequencyHz;
  20131. phasePerSample = 0.0;
  20132. }
  20133. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20134. double sampleRate_)
  20135. {
  20136. currentPhase = 0.0;
  20137. phasePerSample = 0.0;
  20138. sampleRate = sampleRate_;
  20139. }
  20140. void ToneGeneratorAudioSource::releaseResources()
  20141. {
  20142. }
  20143. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20144. {
  20145. if (phasePerSample == 0.0)
  20146. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20147. for (int i = 0; i < info.numSamples; ++i)
  20148. {
  20149. const float sample = amplitude * (float) std::sin (currentPhase);
  20150. currentPhase += phasePerSample;
  20151. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20152. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20153. }
  20154. }
  20155. END_JUCE_NAMESPACE
  20156. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20157. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20158. BEGIN_JUCE_NAMESPACE
  20159. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20160. : sampleRate (0),
  20161. bufferSize (0),
  20162. useDefaultInputChannels (true),
  20163. useDefaultOutputChannels (true)
  20164. {
  20165. }
  20166. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20167. {
  20168. return outputDeviceName == other.outputDeviceName
  20169. && inputDeviceName == other.inputDeviceName
  20170. && sampleRate == other.sampleRate
  20171. && bufferSize == other.bufferSize
  20172. && inputChannels == other.inputChannels
  20173. && useDefaultInputChannels == other.useDefaultInputChannels
  20174. && outputChannels == other.outputChannels
  20175. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20176. }
  20177. AudioDeviceManager::AudioDeviceManager()
  20178. : currentAudioDevice (0),
  20179. numInputChansNeeded (0),
  20180. numOutputChansNeeded (2),
  20181. listNeedsScanning (true),
  20182. useInputNames (false),
  20183. inputLevelMeasurementEnabledCount (0),
  20184. inputLevel (0),
  20185. tempBuffer (2, 2),
  20186. defaultMidiOutput (0),
  20187. cpuUsageMs (0),
  20188. timeToCpuScale (0)
  20189. {
  20190. callbackHandler.owner = this;
  20191. }
  20192. AudioDeviceManager::~AudioDeviceManager()
  20193. {
  20194. currentAudioDevice = 0;
  20195. defaultMidiOutput = 0;
  20196. }
  20197. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20198. {
  20199. if (availableDeviceTypes.size() == 0)
  20200. {
  20201. createAudioDeviceTypes (availableDeviceTypes);
  20202. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20203. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20204. if (availableDeviceTypes.size() > 0)
  20205. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20206. }
  20207. }
  20208. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20209. {
  20210. scanDevicesIfNeeded();
  20211. return availableDeviceTypes;
  20212. }
  20213. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20214. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20215. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20216. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20217. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20218. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20219. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20220. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20221. {
  20222. (void) list; // (to avoid 'unused param' warnings)
  20223. #if JUCE_WINDOWS
  20224. #if JUCE_WASAPI
  20225. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20226. list.add (juce_createAudioIODeviceType_WASAPI());
  20227. #endif
  20228. #if JUCE_DIRECTSOUND
  20229. list.add (juce_createAudioIODeviceType_DirectSound());
  20230. #endif
  20231. #if JUCE_ASIO
  20232. list.add (juce_createAudioIODeviceType_ASIO());
  20233. #endif
  20234. #endif
  20235. #if JUCE_MAC
  20236. list.add (juce_createAudioIODeviceType_CoreAudio());
  20237. #endif
  20238. #if JUCE_IOS
  20239. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20240. #endif
  20241. #if JUCE_LINUX && JUCE_ALSA
  20242. list.add (juce_createAudioIODeviceType_ALSA());
  20243. #endif
  20244. #if JUCE_LINUX && JUCE_JACK
  20245. list.add (juce_createAudioIODeviceType_JACK());
  20246. #endif
  20247. }
  20248. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20249. const int numOutputChannelsNeeded,
  20250. const XmlElement* const e,
  20251. const bool selectDefaultDeviceOnFailure,
  20252. const String& preferredDefaultDeviceName,
  20253. const AudioDeviceSetup* preferredSetupOptions)
  20254. {
  20255. scanDevicesIfNeeded();
  20256. numInputChansNeeded = numInputChannelsNeeded;
  20257. numOutputChansNeeded = numOutputChannelsNeeded;
  20258. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20259. {
  20260. lastExplicitSettings = new XmlElement (*e);
  20261. String error;
  20262. AudioDeviceSetup setup;
  20263. if (preferredSetupOptions != 0)
  20264. setup = *preferredSetupOptions;
  20265. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20266. {
  20267. setup.inputDeviceName = setup.outputDeviceName
  20268. = e->getStringAttribute ("audioDeviceName");
  20269. }
  20270. else
  20271. {
  20272. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20273. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20274. }
  20275. currentDeviceType = e->getStringAttribute ("deviceType");
  20276. if (currentDeviceType.isEmpty())
  20277. {
  20278. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20279. if (type != 0)
  20280. currentDeviceType = type->getTypeName();
  20281. else if (availableDeviceTypes.size() > 0)
  20282. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20283. }
  20284. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20285. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20286. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20287. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20288. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20289. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20290. error = setAudioDeviceSetup (setup, true);
  20291. midiInsFromXml.clear();
  20292. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20293. midiInsFromXml.add (c->getStringAttribute ("name"));
  20294. const StringArray allMidiIns (MidiInput::getDevices());
  20295. for (int i = allMidiIns.size(); --i >= 0;)
  20296. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20297. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20298. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20299. false, preferredDefaultDeviceName);
  20300. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20301. return error;
  20302. }
  20303. else
  20304. {
  20305. AudioDeviceSetup setup;
  20306. if (preferredSetupOptions != 0)
  20307. {
  20308. setup = *preferredSetupOptions;
  20309. }
  20310. else if (preferredDefaultDeviceName.isNotEmpty())
  20311. {
  20312. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20313. {
  20314. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20315. StringArray outs (type->getDeviceNames (false));
  20316. int i;
  20317. for (i = 0; i < outs.size(); ++i)
  20318. {
  20319. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20320. {
  20321. setup.outputDeviceName = outs[i];
  20322. break;
  20323. }
  20324. }
  20325. StringArray ins (type->getDeviceNames (true));
  20326. for (i = 0; i < ins.size(); ++i)
  20327. {
  20328. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20329. {
  20330. setup.inputDeviceName = ins[i];
  20331. break;
  20332. }
  20333. }
  20334. }
  20335. }
  20336. insertDefaultDeviceNames (setup);
  20337. return setAudioDeviceSetup (setup, false);
  20338. }
  20339. }
  20340. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20341. {
  20342. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20343. if (type != 0)
  20344. {
  20345. if (setup.outputDeviceName.isEmpty())
  20346. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20347. if (setup.inputDeviceName.isEmpty())
  20348. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20349. }
  20350. }
  20351. XmlElement* AudioDeviceManager::createStateXml() const
  20352. {
  20353. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20354. }
  20355. void AudioDeviceManager::scanDevicesIfNeeded()
  20356. {
  20357. if (listNeedsScanning)
  20358. {
  20359. listNeedsScanning = false;
  20360. createDeviceTypesIfNeeded();
  20361. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20362. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20363. }
  20364. }
  20365. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20366. {
  20367. scanDevicesIfNeeded();
  20368. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20369. {
  20370. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20371. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20372. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20373. {
  20374. return type;
  20375. }
  20376. }
  20377. return 0;
  20378. }
  20379. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20380. {
  20381. setup = currentSetup;
  20382. }
  20383. void AudioDeviceManager::deleteCurrentDevice()
  20384. {
  20385. currentAudioDevice = 0;
  20386. currentSetup.inputDeviceName = String::empty;
  20387. currentSetup.outputDeviceName = String::empty;
  20388. }
  20389. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20390. const bool treatAsChosenDevice)
  20391. {
  20392. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20393. {
  20394. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20395. && currentDeviceType != type)
  20396. {
  20397. currentDeviceType = type;
  20398. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20399. insertDefaultDeviceNames (s);
  20400. setAudioDeviceSetup (s, treatAsChosenDevice);
  20401. sendChangeMessage (this);
  20402. break;
  20403. }
  20404. }
  20405. }
  20406. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20407. {
  20408. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20409. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20410. return availableDeviceTypes[i];
  20411. return availableDeviceTypes[0];
  20412. }
  20413. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20414. const bool treatAsChosenDevice)
  20415. {
  20416. jassert (&newSetup != &currentSetup); // this will have no effect
  20417. if (newSetup == currentSetup && currentAudioDevice != 0)
  20418. return String::empty;
  20419. if (! (newSetup == currentSetup))
  20420. sendChangeMessage (this);
  20421. stopDevice();
  20422. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20423. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20424. String error;
  20425. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20426. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20427. {
  20428. deleteCurrentDevice();
  20429. if (treatAsChosenDevice)
  20430. updateXml();
  20431. return String::empty;
  20432. }
  20433. if (currentSetup.inputDeviceName != newInputDeviceName
  20434. || currentSetup.outputDeviceName != newOutputDeviceName
  20435. || currentAudioDevice == 0)
  20436. {
  20437. deleteCurrentDevice();
  20438. scanDevicesIfNeeded();
  20439. if (newOutputDeviceName.isNotEmpty()
  20440. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20441. {
  20442. return "No such device: " + newOutputDeviceName;
  20443. }
  20444. if (newInputDeviceName.isNotEmpty()
  20445. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20446. {
  20447. return "No such device: " + newInputDeviceName;
  20448. }
  20449. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20450. if (currentAudioDevice == 0)
  20451. 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!";
  20452. else
  20453. error = currentAudioDevice->getLastError();
  20454. if (error.isNotEmpty())
  20455. {
  20456. deleteCurrentDevice();
  20457. return error;
  20458. }
  20459. if (newSetup.useDefaultInputChannels)
  20460. {
  20461. inputChannels.clear();
  20462. inputChannels.setRange (0, numInputChansNeeded, true);
  20463. }
  20464. if (newSetup.useDefaultOutputChannels)
  20465. {
  20466. outputChannels.clear();
  20467. outputChannels.setRange (0, numOutputChansNeeded, true);
  20468. }
  20469. if (newInputDeviceName.isEmpty())
  20470. inputChannels.clear();
  20471. if (newOutputDeviceName.isEmpty())
  20472. outputChannels.clear();
  20473. }
  20474. if (! newSetup.useDefaultInputChannels)
  20475. inputChannels = newSetup.inputChannels;
  20476. if (! newSetup.useDefaultOutputChannels)
  20477. outputChannels = newSetup.outputChannels;
  20478. currentSetup = newSetup;
  20479. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20480. error = currentAudioDevice->open (inputChannels,
  20481. outputChannels,
  20482. currentSetup.sampleRate,
  20483. currentSetup.bufferSize);
  20484. if (error.isEmpty())
  20485. {
  20486. currentDeviceType = currentAudioDevice->getTypeName();
  20487. currentAudioDevice->start (&callbackHandler);
  20488. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20489. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20490. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20491. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20492. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20493. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20494. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20495. if (treatAsChosenDevice)
  20496. updateXml();
  20497. }
  20498. else
  20499. {
  20500. deleteCurrentDevice();
  20501. }
  20502. return error;
  20503. }
  20504. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20505. {
  20506. jassert (currentAudioDevice != 0);
  20507. if (rate > 0)
  20508. {
  20509. bool ok = false;
  20510. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20511. {
  20512. const double sr = currentAudioDevice->getSampleRate (i);
  20513. if (sr == rate)
  20514. ok = true;
  20515. }
  20516. if (! ok)
  20517. rate = 0;
  20518. }
  20519. if (rate == 0)
  20520. {
  20521. double lowestAbove44 = 0.0;
  20522. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20523. {
  20524. const double sr = currentAudioDevice->getSampleRate (i);
  20525. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20526. lowestAbove44 = sr;
  20527. }
  20528. if (lowestAbove44 == 0.0)
  20529. rate = currentAudioDevice->getSampleRate (0);
  20530. else
  20531. rate = lowestAbove44;
  20532. }
  20533. return rate;
  20534. }
  20535. void AudioDeviceManager::stopDevice()
  20536. {
  20537. if (currentAudioDevice != 0)
  20538. currentAudioDevice->stop();
  20539. testSound = 0;
  20540. }
  20541. void AudioDeviceManager::closeAudioDevice()
  20542. {
  20543. stopDevice();
  20544. currentAudioDevice = 0;
  20545. }
  20546. void AudioDeviceManager::restartLastAudioDevice()
  20547. {
  20548. if (currentAudioDevice == 0)
  20549. {
  20550. if (currentSetup.inputDeviceName.isEmpty()
  20551. && currentSetup.outputDeviceName.isEmpty())
  20552. {
  20553. // This method will only reload the last device that was running
  20554. // before closeAudioDevice() was called - you need to actually open
  20555. // one first, with setAudioDevice().
  20556. jassertfalse;
  20557. return;
  20558. }
  20559. AudioDeviceSetup s (currentSetup);
  20560. setAudioDeviceSetup (s, false);
  20561. }
  20562. }
  20563. void AudioDeviceManager::updateXml()
  20564. {
  20565. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20566. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20567. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20568. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20569. if (currentAudioDevice != 0)
  20570. {
  20571. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20572. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20573. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20574. if (! currentSetup.useDefaultInputChannels)
  20575. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20576. if (! currentSetup.useDefaultOutputChannels)
  20577. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20578. }
  20579. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20580. {
  20581. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20582. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20583. }
  20584. if (midiInsFromXml.size() > 0)
  20585. {
  20586. // Add any midi devices that have been enabled before, but which aren't currently
  20587. // open because the device has been disconnected.
  20588. const StringArray availableMidiDevices (MidiInput::getDevices());
  20589. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20590. {
  20591. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20592. {
  20593. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20594. m->setAttribute ("name", midiInsFromXml[i]);
  20595. }
  20596. }
  20597. }
  20598. if (defaultMidiOutputName.isNotEmpty())
  20599. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20600. }
  20601. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20602. {
  20603. {
  20604. const ScopedLock sl (audioCallbackLock);
  20605. if (callbacks.contains (newCallback))
  20606. return;
  20607. }
  20608. if (currentAudioDevice != 0 && newCallback != 0)
  20609. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20610. const ScopedLock sl (audioCallbackLock);
  20611. callbacks.add (newCallback);
  20612. }
  20613. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  20614. {
  20615. if (callback != 0)
  20616. {
  20617. bool needsDeinitialising = currentAudioDevice != 0;
  20618. {
  20619. const ScopedLock sl (audioCallbackLock);
  20620. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  20621. callbacks.removeValue (callback);
  20622. }
  20623. if (needsDeinitialising)
  20624. callback->audioDeviceStopped();
  20625. }
  20626. }
  20627. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20628. int numInputChannels,
  20629. float** outputChannelData,
  20630. int numOutputChannels,
  20631. int numSamples)
  20632. {
  20633. const ScopedLock sl (audioCallbackLock);
  20634. if (inputLevelMeasurementEnabledCount > 0)
  20635. {
  20636. for (int j = 0; j < numSamples; ++j)
  20637. {
  20638. float s = 0;
  20639. for (int i = 0; i < numInputChannels; ++i)
  20640. s += std::abs (inputChannelData[i][j]);
  20641. s /= numInputChannels;
  20642. const double decayFactor = 0.99992;
  20643. if (s > inputLevel)
  20644. inputLevel = s;
  20645. else if (inputLevel > 0.001f)
  20646. inputLevel *= decayFactor;
  20647. else
  20648. inputLevel = 0;
  20649. }
  20650. }
  20651. if (callbacks.size() > 0)
  20652. {
  20653. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20654. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20655. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20656. outputChannelData, numOutputChannels, numSamples);
  20657. float** const tempChans = tempBuffer.getArrayOfChannels();
  20658. for (int i = callbacks.size(); --i > 0;)
  20659. {
  20660. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20661. tempChans, numOutputChannels, numSamples);
  20662. for (int chan = 0; chan < numOutputChannels; ++chan)
  20663. {
  20664. const float* const src = tempChans [chan];
  20665. float* const dst = outputChannelData [chan];
  20666. if (src != 0 && dst != 0)
  20667. for (int j = 0; j < numSamples; ++j)
  20668. dst[j] += src[j];
  20669. }
  20670. }
  20671. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20672. const double filterAmount = 0.2;
  20673. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20674. }
  20675. else
  20676. {
  20677. for (int i = 0; i < numOutputChannels; ++i)
  20678. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20679. }
  20680. if (testSound != 0)
  20681. {
  20682. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20683. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20684. for (int i = 0; i < numOutputChannels; ++i)
  20685. for (int j = 0; j < numSamps; ++j)
  20686. outputChannelData [i][j] += src[j];
  20687. testSoundPosition += numSamps;
  20688. if (testSoundPosition >= testSound->getNumSamples())
  20689. testSound = 0;
  20690. }
  20691. }
  20692. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20693. {
  20694. cpuUsageMs = 0;
  20695. const double sampleRate = device->getCurrentSampleRate();
  20696. const int blockSize = device->getCurrentBufferSizeSamples();
  20697. if (sampleRate > 0.0 && blockSize > 0)
  20698. {
  20699. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20700. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20701. }
  20702. {
  20703. const ScopedLock sl (audioCallbackLock);
  20704. for (int i = callbacks.size(); --i >= 0;)
  20705. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20706. }
  20707. sendChangeMessage (this);
  20708. }
  20709. void AudioDeviceManager::audioDeviceStoppedInt()
  20710. {
  20711. cpuUsageMs = 0;
  20712. timeToCpuScale = 0;
  20713. sendChangeMessage (this);
  20714. const ScopedLock sl (audioCallbackLock);
  20715. for (int i = callbacks.size(); --i >= 0;)
  20716. callbacks.getUnchecked(i)->audioDeviceStopped();
  20717. }
  20718. double AudioDeviceManager::getCpuUsage() const
  20719. {
  20720. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20721. }
  20722. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20723. const bool enabled)
  20724. {
  20725. if (enabled != isMidiInputEnabled (name))
  20726. {
  20727. if (enabled)
  20728. {
  20729. const int index = MidiInput::getDevices().indexOf (name);
  20730. if (index >= 0)
  20731. {
  20732. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20733. if (min != 0)
  20734. {
  20735. enabledMidiInputs.add (min);
  20736. min->start();
  20737. }
  20738. }
  20739. }
  20740. else
  20741. {
  20742. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20743. if (enabledMidiInputs[i]->getName() == name)
  20744. enabledMidiInputs.remove (i);
  20745. }
  20746. updateXml();
  20747. sendChangeMessage (this);
  20748. }
  20749. }
  20750. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20751. {
  20752. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20753. if (enabledMidiInputs[i]->getName() == name)
  20754. return true;
  20755. return false;
  20756. }
  20757. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20758. MidiInputCallback* callback)
  20759. {
  20760. removeMidiInputCallback (name, callback);
  20761. if (name.isEmpty())
  20762. {
  20763. midiCallbacks.add (callback);
  20764. midiCallbackDevices.add (0);
  20765. }
  20766. else
  20767. {
  20768. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20769. {
  20770. if (enabledMidiInputs[i]->getName() == name)
  20771. {
  20772. const ScopedLock sl (midiCallbackLock);
  20773. midiCallbacks.add (callback);
  20774. midiCallbackDevices.add (enabledMidiInputs[i]);
  20775. break;
  20776. }
  20777. }
  20778. }
  20779. }
  20780. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  20781. MidiInputCallback* /*callback*/)
  20782. {
  20783. const ScopedLock sl (midiCallbackLock);
  20784. for (int i = midiCallbacks.size(); --i >= 0;)
  20785. {
  20786. String devName;
  20787. if (midiCallbackDevices.getUnchecked(i) != 0)
  20788. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20789. if (devName == name)
  20790. {
  20791. midiCallbacks.remove (i);
  20792. midiCallbackDevices.remove (i);
  20793. }
  20794. }
  20795. }
  20796. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20797. const MidiMessage& message)
  20798. {
  20799. if (! message.isActiveSense())
  20800. {
  20801. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20802. const ScopedLock sl (midiCallbackLock);
  20803. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20804. {
  20805. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20806. if (md == source || (md == 0 && isDefaultSource))
  20807. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20808. }
  20809. }
  20810. }
  20811. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20812. {
  20813. if (defaultMidiOutputName != deviceName)
  20814. {
  20815. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20816. {
  20817. const ScopedLock sl (audioCallbackLock);
  20818. oldCallbacks = callbacks;
  20819. callbacks.clear();
  20820. }
  20821. if (currentAudioDevice != 0)
  20822. for (int i = oldCallbacks.size(); --i >= 0;)
  20823. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20824. defaultMidiOutput = 0;
  20825. defaultMidiOutputName = deviceName;
  20826. if (deviceName.isNotEmpty())
  20827. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20828. if (currentAudioDevice != 0)
  20829. for (int i = oldCallbacks.size(); --i >= 0;)
  20830. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20831. {
  20832. const ScopedLock sl (audioCallbackLock);
  20833. callbacks = oldCallbacks;
  20834. }
  20835. updateXml();
  20836. sendChangeMessage (this);
  20837. }
  20838. }
  20839. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20840. int numInputChannels,
  20841. float** outputChannelData,
  20842. int numOutputChannels,
  20843. int numSamples)
  20844. {
  20845. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20846. }
  20847. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20848. {
  20849. owner->audioDeviceAboutToStartInt (device);
  20850. }
  20851. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20852. {
  20853. owner->audioDeviceStoppedInt();
  20854. }
  20855. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20856. {
  20857. owner->handleIncomingMidiMessageInt (source, message);
  20858. }
  20859. void AudioDeviceManager::playTestSound()
  20860. {
  20861. { // cunningly nested to swap, unlock and delete in that order.
  20862. ScopedPointer <AudioSampleBuffer> oldSound;
  20863. {
  20864. const ScopedLock sl (audioCallbackLock);
  20865. oldSound = testSound;
  20866. }
  20867. }
  20868. testSoundPosition = 0;
  20869. if (currentAudioDevice != 0)
  20870. {
  20871. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20872. const int soundLength = (int) sampleRate;
  20873. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20874. float* samples = newSound->getSampleData (0);
  20875. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20876. const float amplitude = 0.5f;
  20877. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20878. for (int i = 0; i < soundLength; ++i)
  20879. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20880. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20881. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20882. const ScopedLock sl (audioCallbackLock);
  20883. testSound = newSound;
  20884. }
  20885. }
  20886. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20887. {
  20888. const ScopedLock sl (audioCallbackLock);
  20889. if (enableMeasurement)
  20890. ++inputLevelMeasurementEnabledCount;
  20891. else
  20892. --inputLevelMeasurementEnabledCount;
  20893. inputLevel = 0;
  20894. }
  20895. double AudioDeviceManager::getCurrentInputLevel() const
  20896. {
  20897. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20898. return inputLevel;
  20899. }
  20900. END_JUCE_NAMESPACE
  20901. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20902. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20903. BEGIN_JUCE_NAMESPACE
  20904. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20905. : name (deviceName),
  20906. typeName (typeName_)
  20907. {
  20908. }
  20909. AudioIODevice::~AudioIODevice()
  20910. {
  20911. }
  20912. bool AudioIODevice::hasControlPanel() const
  20913. {
  20914. return false;
  20915. }
  20916. bool AudioIODevice::showControlPanel()
  20917. {
  20918. jassertfalse; // this should only be called for devices which return true from
  20919. // their hasControlPanel() method.
  20920. return false;
  20921. }
  20922. END_JUCE_NAMESPACE
  20923. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20924. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20925. BEGIN_JUCE_NAMESPACE
  20926. AudioIODeviceType::AudioIODeviceType (const String& name)
  20927. : typeName (name)
  20928. {
  20929. }
  20930. AudioIODeviceType::~AudioIODeviceType()
  20931. {
  20932. }
  20933. END_JUCE_NAMESPACE
  20934. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20935. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20936. BEGIN_JUCE_NAMESPACE
  20937. MidiOutput::MidiOutput()
  20938. : Thread ("midi out"),
  20939. internal (0),
  20940. firstMessage (0)
  20941. {
  20942. }
  20943. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20944. const double sampleNumber)
  20945. : message (data, len, sampleNumber)
  20946. {
  20947. }
  20948. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20949. const double millisecondCounterToStartAt,
  20950. double samplesPerSecondForBuffer)
  20951. {
  20952. // You've got to call startBackgroundThread() for this to actually work..
  20953. jassert (isThreadRunning());
  20954. // this needs to be a value in the future - RTFM for this method!
  20955. jassert (millisecondCounterToStartAt > 0);
  20956. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20957. MidiBuffer::Iterator i (buffer);
  20958. const uint8* data;
  20959. int len, time;
  20960. while (i.getNextEvent (data, len, time))
  20961. {
  20962. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20963. PendingMessage* const m
  20964. = new PendingMessage (data, len, eventTime);
  20965. const ScopedLock sl (lock);
  20966. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20967. {
  20968. m->next = firstMessage;
  20969. firstMessage = m;
  20970. }
  20971. else
  20972. {
  20973. PendingMessage* mm = firstMessage;
  20974. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20975. mm = mm->next;
  20976. m->next = mm->next;
  20977. mm->next = m;
  20978. }
  20979. }
  20980. notify();
  20981. }
  20982. void MidiOutput::clearAllPendingMessages()
  20983. {
  20984. const ScopedLock sl (lock);
  20985. while (firstMessage != 0)
  20986. {
  20987. PendingMessage* const m = firstMessage;
  20988. firstMessage = firstMessage->next;
  20989. delete m;
  20990. }
  20991. }
  20992. void MidiOutput::startBackgroundThread()
  20993. {
  20994. startThread (9);
  20995. }
  20996. void MidiOutput::stopBackgroundThread()
  20997. {
  20998. stopThread (5000);
  20999. }
  21000. void MidiOutput::run()
  21001. {
  21002. while (! threadShouldExit())
  21003. {
  21004. uint32 now = Time::getMillisecondCounter();
  21005. uint32 eventTime = 0;
  21006. uint32 timeToWait = 500;
  21007. PendingMessage* message;
  21008. {
  21009. const ScopedLock sl (lock);
  21010. message = firstMessage;
  21011. if (message != 0)
  21012. {
  21013. eventTime = roundToInt (message->message.getTimeStamp());
  21014. if (eventTime > now + 20)
  21015. {
  21016. timeToWait = eventTime - (now + 20);
  21017. message = 0;
  21018. }
  21019. else
  21020. {
  21021. firstMessage = message->next;
  21022. }
  21023. }
  21024. }
  21025. if (message != 0)
  21026. {
  21027. if (eventTime > now)
  21028. {
  21029. Time::waitForMillisecondCounter (eventTime);
  21030. if (threadShouldExit())
  21031. break;
  21032. }
  21033. if (eventTime > now - 200)
  21034. sendMessageNow (message->message);
  21035. delete message;
  21036. }
  21037. else
  21038. {
  21039. jassert (timeToWait < 1000 * 30);
  21040. wait (timeToWait);
  21041. }
  21042. }
  21043. clearAllPendingMessages();
  21044. }
  21045. END_JUCE_NAMESPACE
  21046. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21047. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21048. BEGIN_JUCE_NAMESPACE
  21049. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21050. {
  21051. const double maxVal = (double) 0x7fff;
  21052. char* intData = static_cast <char*> (dest);
  21053. if (dest != (void*) source || destBytesPerSample <= 4)
  21054. {
  21055. for (int i = 0; i < numSamples; ++i)
  21056. {
  21057. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21058. intData += destBytesPerSample;
  21059. }
  21060. }
  21061. else
  21062. {
  21063. intData += destBytesPerSample * numSamples;
  21064. for (int i = numSamples; --i >= 0;)
  21065. {
  21066. intData -= destBytesPerSample;
  21067. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21068. }
  21069. }
  21070. }
  21071. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21072. {
  21073. const double maxVal = (double) 0x7fff;
  21074. char* intData = static_cast <char*> (dest);
  21075. if (dest != (void*) source || destBytesPerSample <= 4)
  21076. {
  21077. for (int i = 0; i < numSamples; ++i)
  21078. {
  21079. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21080. intData += destBytesPerSample;
  21081. }
  21082. }
  21083. else
  21084. {
  21085. intData += destBytesPerSample * numSamples;
  21086. for (int i = numSamples; --i >= 0;)
  21087. {
  21088. intData -= destBytesPerSample;
  21089. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21090. }
  21091. }
  21092. }
  21093. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21094. {
  21095. const double maxVal = (double) 0x7fffff;
  21096. char* intData = static_cast <char*> (dest);
  21097. if (dest != (void*) source || destBytesPerSample <= 4)
  21098. {
  21099. for (int i = 0; i < numSamples; ++i)
  21100. {
  21101. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21102. intData += destBytesPerSample;
  21103. }
  21104. }
  21105. else
  21106. {
  21107. intData += destBytesPerSample * numSamples;
  21108. for (int i = numSamples; --i >= 0;)
  21109. {
  21110. intData -= destBytesPerSample;
  21111. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21112. }
  21113. }
  21114. }
  21115. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21116. {
  21117. const double maxVal = (double) 0x7fffff;
  21118. char* intData = static_cast <char*> (dest);
  21119. if (dest != (void*) source || destBytesPerSample <= 4)
  21120. {
  21121. for (int i = 0; i < numSamples; ++i)
  21122. {
  21123. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21124. intData += destBytesPerSample;
  21125. }
  21126. }
  21127. else
  21128. {
  21129. intData += destBytesPerSample * numSamples;
  21130. for (int i = numSamples; --i >= 0;)
  21131. {
  21132. intData -= destBytesPerSample;
  21133. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21134. }
  21135. }
  21136. }
  21137. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21138. {
  21139. const double maxVal = (double) 0x7fffffff;
  21140. char* intData = static_cast <char*> (dest);
  21141. if (dest != (void*) source || destBytesPerSample <= 4)
  21142. {
  21143. for (int i = 0; i < numSamples; ++i)
  21144. {
  21145. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21146. intData += destBytesPerSample;
  21147. }
  21148. }
  21149. else
  21150. {
  21151. intData += destBytesPerSample * numSamples;
  21152. for (int i = numSamples; --i >= 0;)
  21153. {
  21154. intData -= destBytesPerSample;
  21155. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21156. }
  21157. }
  21158. }
  21159. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21160. {
  21161. const double maxVal = (double) 0x7fffffff;
  21162. char* intData = static_cast <char*> (dest);
  21163. if (dest != (void*) source || destBytesPerSample <= 4)
  21164. {
  21165. for (int i = 0; i < numSamples; ++i)
  21166. {
  21167. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21168. intData += destBytesPerSample;
  21169. }
  21170. }
  21171. else
  21172. {
  21173. intData += destBytesPerSample * numSamples;
  21174. for (int i = numSamples; --i >= 0;)
  21175. {
  21176. intData -= destBytesPerSample;
  21177. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21178. }
  21179. }
  21180. }
  21181. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21182. {
  21183. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21184. char* d = static_cast <char*> (dest);
  21185. for (int i = 0; i < numSamples; ++i)
  21186. {
  21187. *(float*) d = source[i];
  21188. #if JUCE_BIG_ENDIAN
  21189. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21190. #endif
  21191. d += destBytesPerSample;
  21192. }
  21193. }
  21194. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21195. {
  21196. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21197. char* d = static_cast <char*> (dest);
  21198. for (int i = 0; i < numSamples; ++i)
  21199. {
  21200. *(float*) d = source[i];
  21201. #if JUCE_LITTLE_ENDIAN
  21202. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21203. #endif
  21204. d += destBytesPerSample;
  21205. }
  21206. }
  21207. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21208. {
  21209. const float scale = 1.0f / 0x7fff;
  21210. const char* intData = static_cast <const char*> (source);
  21211. if (source != (void*) dest || srcBytesPerSample >= 4)
  21212. {
  21213. for (int i = 0; i < numSamples; ++i)
  21214. {
  21215. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21216. intData += srcBytesPerSample;
  21217. }
  21218. }
  21219. else
  21220. {
  21221. intData += srcBytesPerSample * numSamples;
  21222. for (int i = numSamples; --i >= 0;)
  21223. {
  21224. intData -= srcBytesPerSample;
  21225. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21226. }
  21227. }
  21228. }
  21229. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21230. {
  21231. const float scale = 1.0f / 0x7fff;
  21232. const char* intData = static_cast <const char*> (source);
  21233. if (source != (void*) dest || srcBytesPerSample >= 4)
  21234. {
  21235. for (int i = 0; i < numSamples; ++i)
  21236. {
  21237. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21238. intData += srcBytesPerSample;
  21239. }
  21240. }
  21241. else
  21242. {
  21243. intData += srcBytesPerSample * numSamples;
  21244. for (int i = numSamples; --i >= 0;)
  21245. {
  21246. intData -= srcBytesPerSample;
  21247. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21248. }
  21249. }
  21250. }
  21251. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21252. {
  21253. const float scale = 1.0f / 0x7fffff;
  21254. const char* intData = static_cast <const char*> (source);
  21255. if (source != (void*) dest || srcBytesPerSample >= 4)
  21256. {
  21257. for (int i = 0; i < numSamples; ++i)
  21258. {
  21259. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21260. intData += srcBytesPerSample;
  21261. }
  21262. }
  21263. else
  21264. {
  21265. intData += srcBytesPerSample * numSamples;
  21266. for (int i = numSamples; --i >= 0;)
  21267. {
  21268. intData -= srcBytesPerSample;
  21269. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21270. }
  21271. }
  21272. }
  21273. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21274. {
  21275. const float scale = 1.0f / 0x7fffff;
  21276. const char* intData = static_cast <const char*> (source);
  21277. if (source != (void*) dest || srcBytesPerSample >= 4)
  21278. {
  21279. for (int i = 0; i < numSamples; ++i)
  21280. {
  21281. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21282. intData += srcBytesPerSample;
  21283. }
  21284. }
  21285. else
  21286. {
  21287. intData += srcBytesPerSample * numSamples;
  21288. for (int i = numSamples; --i >= 0;)
  21289. {
  21290. intData -= srcBytesPerSample;
  21291. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21292. }
  21293. }
  21294. }
  21295. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21296. {
  21297. const float scale = 1.0f / 0x7fffffff;
  21298. const char* intData = static_cast <const char*> (source);
  21299. if (source != (void*) dest || srcBytesPerSample >= 4)
  21300. {
  21301. for (int i = 0; i < numSamples; ++i)
  21302. {
  21303. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21304. intData += srcBytesPerSample;
  21305. }
  21306. }
  21307. else
  21308. {
  21309. intData += srcBytesPerSample * numSamples;
  21310. for (int i = numSamples; --i >= 0;)
  21311. {
  21312. intData -= srcBytesPerSample;
  21313. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21314. }
  21315. }
  21316. }
  21317. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21318. {
  21319. const float scale = 1.0f / 0x7fffffff;
  21320. const char* intData = static_cast <const char*> (source);
  21321. if (source != (void*) dest || srcBytesPerSample >= 4)
  21322. {
  21323. for (int i = 0; i < numSamples; ++i)
  21324. {
  21325. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21326. intData += srcBytesPerSample;
  21327. }
  21328. }
  21329. else
  21330. {
  21331. intData += srcBytesPerSample * numSamples;
  21332. for (int i = numSamples; --i >= 0;)
  21333. {
  21334. intData -= srcBytesPerSample;
  21335. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21336. }
  21337. }
  21338. }
  21339. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21340. {
  21341. const char* s = static_cast <const char*> (source);
  21342. for (int i = 0; i < numSamples; ++i)
  21343. {
  21344. dest[i] = *(float*)s;
  21345. #if JUCE_BIG_ENDIAN
  21346. uint32* const d = (uint32*) (dest + i);
  21347. *d = ByteOrder::swap (*d);
  21348. #endif
  21349. s += srcBytesPerSample;
  21350. }
  21351. }
  21352. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21353. {
  21354. const char* s = static_cast <const char*> (source);
  21355. for (int i = 0; i < numSamples; ++i)
  21356. {
  21357. dest[i] = *(float*)s;
  21358. #if JUCE_LITTLE_ENDIAN
  21359. uint32* const d = (uint32*) (dest + i);
  21360. *d = ByteOrder::swap (*d);
  21361. #endif
  21362. s += srcBytesPerSample;
  21363. }
  21364. }
  21365. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21366. const float* const source,
  21367. void* const dest,
  21368. const int numSamples)
  21369. {
  21370. switch (destFormat)
  21371. {
  21372. case int16LE:
  21373. convertFloatToInt16LE (source, dest, numSamples);
  21374. break;
  21375. case int16BE:
  21376. convertFloatToInt16BE (source, dest, numSamples);
  21377. break;
  21378. case int24LE:
  21379. convertFloatToInt24LE (source, dest, numSamples);
  21380. break;
  21381. case int24BE:
  21382. convertFloatToInt24BE (source, dest, numSamples);
  21383. break;
  21384. case int32LE:
  21385. convertFloatToInt32LE (source, dest, numSamples);
  21386. break;
  21387. case int32BE:
  21388. convertFloatToInt32BE (source, dest, numSamples);
  21389. break;
  21390. case float32LE:
  21391. convertFloatToFloat32LE (source, dest, numSamples);
  21392. break;
  21393. case float32BE:
  21394. convertFloatToFloat32BE (source, dest, numSamples);
  21395. break;
  21396. default:
  21397. jassertfalse;
  21398. break;
  21399. }
  21400. }
  21401. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21402. const void* const source,
  21403. float* const dest,
  21404. const int numSamples)
  21405. {
  21406. switch (sourceFormat)
  21407. {
  21408. case int16LE:
  21409. convertInt16LEToFloat (source, dest, numSamples);
  21410. break;
  21411. case int16BE:
  21412. convertInt16BEToFloat (source, dest, numSamples);
  21413. break;
  21414. case int24LE:
  21415. convertInt24LEToFloat (source, dest, numSamples);
  21416. break;
  21417. case int24BE:
  21418. convertInt24BEToFloat (source, dest, numSamples);
  21419. break;
  21420. case int32LE:
  21421. convertInt32LEToFloat (source, dest, numSamples);
  21422. break;
  21423. case int32BE:
  21424. convertInt32BEToFloat (source, dest, numSamples);
  21425. break;
  21426. case float32LE:
  21427. convertFloat32LEToFloat (source, dest, numSamples);
  21428. break;
  21429. case float32BE:
  21430. convertFloat32BEToFloat (source, dest, numSamples);
  21431. break;
  21432. default:
  21433. jassertfalse;
  21434. break;
  21435. }
  21436. }
  21437. void AudioDataConverters::interleaveSamples (const float** const source,
  21438. float* const dest,
  21439. const int numSamples,
  21440. const int numChannels)
  21441. {
  21442. for (int chan = 0; chan < numChannels; ++chan)
  21443. {
  21444. int i = chan;
  21445. const float* src = source [chan];
  21446. for (int j = 0; j < numSamples; ++j)
  21447. {
  21448. dest [i] = src [j];
  21449. i += numChannels;
  21450. }
  21451. }
  21452. }
  21453. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21454. float** const dest,
  21455. const int numSamples,
  21456. const int numChannels)
  21457. {
  21458. for (int chan = 0; chan < numChannels; ++chan)
  21459. {
  21460. int i = chan;
  21461. float* dst = dest [chan];
  21462. for (int j = 0; j < numSamples; ++j)
  21463. {
  21464. dst [j] = source [i];
  21465. i += numChannels;
  21466. }
  21467. }
  21468. }
  21469. #if JUCE_UNIT_TESTS
  21470. class AudioConversionTests : public UnitTest
  21471. {
  21472. public:
  21473. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21474. template <class F1, class E1, class F2, class E2>
  21475. struct Test5
  21476. {
  21477. static void test (UnitTest& unitTest)
  21478. {
  21479. test (unitTest, false);
  21480. test (unitTest, true);
  21481. }
  21482. static void test (UnitTest& unitTest, bool inPlace)
  21483. {
  21484. const int numSamples = 2048;
  21485. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21486. {
  21487. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21488. bool clippingFailed = false;
  21489. for (int i = 0; i < numSamples / 2; ++i)
  21490. {
  21491. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21492. if (! d.isFloatingPoint())
  21493. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21494. ++d;
  21495. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21496. ++d;
  21497. }
  21498. unitTest.expect (! clippingFailed);
  21499. }
  21500. // convert data from the source to dest format..
  21501. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21502. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21503. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21504. // ..and back again..
  21505. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21506. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21507. if (! inPlace)
  21508. zerostruct (reversed);
  21509. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21510. {
  21511. int biggestDiff = 0;
  21512. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21513. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21514. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21515. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21516. for (int i = 0; i < numSamples; ++i)
  21517. {
  21518. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21519. ++d1;
  21520. ++d2;
  21521. }
  21522. unitTest.expect (biggestDiff <= errorMargin);
  21523. }
  21524. }
  21525. };
  21526. template <class F1, class E1, class FormatType>
  21527. struct Test3
  21528. {
  21529. static void test (UnitTest& unitTest)
  21530. {
  21531. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21532. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21533. }
  21534. };
  21535. template <class FormatType, class Endianness>
  21536. struct Test2
  21537. {
  21538. static void test (UnitTest& unitTest)
  21539. {
  21540. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21541. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21542. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21543. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21544. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21545. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21546. }
  21547. };
  21548. template <class FormatType>
  21549. struct Test1
  21550. {
  21551. static void test (UnitTest& unitTest)
  21552. {
  21553. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21554. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21555. }
  21556. };
  21557. void runTest()
  21558. {
  21559. beginTest ("Round-trip conversion");
  21560. Test1 <AudioData::Int8>::test (*this);
  21561. Test1 <AudioData::Int16>::test (*this);
  21562. Test1 <AudioData::Int24>::test (*this);
  21563. Test1 <AudioData::Int32>::test (*this);
  21564. Test1 <AudioData::Float32>::test (*this);
  21565. }
  21566. };
  21567. static AudioConversionTests audioConversionUnitTests;
  21568. #endif
  21569. END_JUCE_NAMESPACE
  21570. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21571. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21572. BEGIN_JUCE_NAMESPACE
  21573. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21574. const int numSamples) throw()
  21575. : numChannels (numChannels_),
  21576. size (numSamples)
  21577. {
  21578. jassert (numSamples >= 0);
  21579. jassert (numChannels_ > 0);
  21580. allocateData();
  21581. }
  21582. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21583. : numChannels (other.numChannels),
  21584. size (other.size)
  21585. {
  21586. allocateData();
  21587. const size_t numBytes = size * sizeof (float);
  21588. for (int i = 0; i < numChannels; ++i)
  21589. memcpy (channels[i], other.channels[i], numBytes);
  21590. }
  21591. void AudioSampleBuffer::allocateData()
  21592. {
  21593. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21594. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21595. allocatedData.malloc (allocatedBytes);
  21596. channels = reinterpret_cast <float**> (allocatedData.getData());
  21597. float* chan = (float*) (allocatedData + channelListSize);
  21598. for (int i = 0; i < numChannels; ++i)
  21599. {
  21600. channels[i] = chan;
  21601. chan += size;
  21602. }
  21603. channels [numChannels] = 0;
  21604. }
  21605. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21606. const int numChannels_,
  21607. const int numSamples) throw()
  21608. : numChannels (numChannels_),
  21609. size (numSamples),
  21610. allocatedBytes (0)
  21611. {
  21612. jassert (numChannels_ > 0);
  21613. allocateChannels (dataToReferTo);
  21614. }
  21615. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21616. const int newNumChannels,
  21617. const int newNumSamples) throw()
  21618. {
  21619. jassert (newNumChannels > 0);
  21620. allocatedBytes = 0;
  21621. allocatedData.free();
  21622. numChannels = newNumChannels;
  21623. size = newNumSamples;
  21624. allocateChannels (dataToReferTo);
  21625. }
  21626. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21627. {
  21628. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21629. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21630. {
  21631. channels = static_cast <float**> (preallocatedChannelSpace);
  21632. }
  21633. else
  21634. {
  21635. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21636. channels = reinterpret_cast <float**> (allocatedData.getData());
  21637. }
  21638. for (int i = 0; i < numChannels; ++i)
  21639. {
  21640. // you have to pass in the same number of valid pointers as numChannels
  21641. jassert (dataToReferTo[i] != 0);
  21642. channels[i] = dataToReferTo[i];
  21643. }
  21644. channels [numChannels] = 0;
  21645. }
  21646. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21647. {
  21648. if (this != &other)
  21649. {
  21650. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21651. const size_t numBytes = size * sizeof (float);
  21652. for (int i = 0; i < numChannels; ++i)
  21653. memcpy (channels[i], other.channels[i], numBytes);
  21654. }
  21655. return *this;
  21656. }
  21657. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21658. {
  21659. }
  21660. void AudioSampleBuffer::setSize (const int newNumChannels,
  21661. const int newNumSamples,
  21662. const bool keepExistingContent,
  21663. const bool clearExtraSpace,
  21664. const bool avoidReallocating) throw()
  21665. {
  21666. jassert (newNumChannels > 0);
  21667. if (newNumSamples != size || newNumChannels != numChannels)
  21668. {
  21669. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21670. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21671. if (keepExistingContent)
  21672. {
  21673. HeapBlock <char> newData;
  21674. newData.allocate (newTotalBytes, clearExtraSpace);
  21675. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21676. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21677. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21678. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21679. for (int i = 0; i < numChansToCopy; ++i)
  21680. {
  21681. memcpy (newChan, channels[i], numBytesToCopy);
  21682. newChannels[i] = newChan;
  21683. newChan += newNumSamples;
  21684. }
  21685. allocatedData.swapWith (newData);
  21686. allocatedBytes = (int) newTotalBytes;
  21687. channels = newChannels;
  21688. }
  21689. else
  21690. {
  21691. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21692. {
  21693. if (clearExtraSpace)
  21694. zeromem (allocatedData, newTotalBytes);
  21695. }
  21696. else
  21697. {
  21698. allocatedBytes = newTotalBytes;
  21699. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21700. channels = reinterpret_cast <float**> (allocatedData.getData());
  21701. }
  21702. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21703. for (int i = 0; i < newNumChannels; ++i)
  21704. {
  21705. channels[i] = chan;
  21706. chan += newNumSamples;
  21707. }
  21708. }
  21709. channels [newNumChannels] = 0;
  21710. size = newNumSamples;
  21711. numChannels = newNumChannels;
  21712. }
  21713. }
  21714. void AudioSampleBuffer::clear() throw()
  21715. {
  21716. for (int i = 0; i < numChannels; ++i)
  21717. zeromem (channels[i], size * sizeof (float));
  21718. }
  21719. void AudioSampleBuffer::clear (const int startSample,
  21720. const int numSamples) throw()
  21721. {
  21722. jassert (startSample >= 0 && startSample + numSamples <= size);
  21723. for (int i = 0; i < numChannels; ++i)
  21724. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21725. }
  21726. void AudioSampleBuffer::clear (const int channel,
  21727. const int startSample,
  21728. const int numSamples) throw()
  21729. {
  21730. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21731. jassert (startSample >= 0 && startSample + numSamples <= size);
  21732. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21733. }
  21734. void AudioSampleBuffer::applyGain (const int channel,
  21735. const int startSample,
  21736. int numSamples,
  21737. const float gain) throw()
  21738. {
  21739. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21740. jassert (startSample >= 0 && startSample + numSamples <= size);
  21741. if (gain != 1.0f)
  21742. {
  21743. float* d = channels [channel] + startSample;
  21744. if (gain == 0.0f)
  21745. {
  21746. zeromem (d, sizeof (float) * numSamples);
  21747. }
  21748. else
  21749. {
  21750. while (--numSamples >= 0)
  21751. *d++ *= gain;
  21752. }
  21753. }
  21754. }
  21755. void AudioSampleBuffer::applyGainRamp (const int channel,
  21756. const int startSample,
  21757. int numSamples,
  21758. float startGain,
  21759. float endGain) throw()
  21760. {
  21761. if (startGain == endGain)
  21762. {
  21763. applyGain (channel, startSample, numSamples, startGain);
  21764. }
  21765. else
  21766. {
  21767. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21768. jassert (startSample >= 0 && startSample + numSamples <= size);
  21769. const float increment = (endGain - startGain) / numSamples;
  21770. float* d = channels [channel] + startSample;
  21771. while (--numSamples >= 0)
  21772. {
  21773. *d++ *= startGain;
  21774. startGain += increment;
  21775. }
  21776. }
  21777. }
  21778. void AudioSampleBuffer::applyGain (const int startSample,
  21779. const int numSamples,
  21780. const float gain) throw()
  21781. {
  21782. for (int i = 0; i < numChannels; ++i)
  21783. applyGain (i, startSample, numSamples, gain);
  21784. }
  21785. void AudioSampleBuffer::addFrom (const int destChannel,
  21786. const int destStartSample,
  21787. const AudioSampleBuffer& source,
  21788. const int sourceChannel,
  21789. const int sourceStartSample,
  21790. int numSamples,
  21791. const float gain) throw()
  21792. {
  21793. jassert (&source != this || sourceChannel != destChannel);
  21794. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21795. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21796. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21797. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21798. if (gain != 0.0f && numSamples > 0)
  21799. {
  21800. float* d = channels [destChannel] + destStartSample;
  21801. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21802. if (gain != 1.0f)
  21803. {
  21804. while (--numSamples >= 0)
  21805. *d++ += gain * *s++;
  21806. }
  21807. else
  21808. {
  21809. while (--numSamples >= 0)
  21810. *d++ += *s++;
  21811. }
  21812. }
  21813. }
  21814. void AudioSampleBuffer::addFrom (const int destChannel,
  21815. const int destStartSample,
  21816. const float* source,
  21817. int numSamples,
  21818. const float gain) throw()
  21819. {
  21820. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21821. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21822. jassert (source != 0);
  21823. if (gain != 0.0f && numSamples > 0)
  21824. {
  21825. float* d = channels [destChannel] + destStartSample;
  21826. if (gain != 1.0f)
  21827. {
  21828. while (--numSamples >= 0)
  21829. *d++ += gain * *source++;
  21830. }
  21831. else
  21832. {
  21833. while (--numSamples >= 0)
  21834. *d++ += *source++;
  21835. }
  21836. }
  21837. }
  21838. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21839. const int destStartSample,
  21840. const float* source,
  21841. int numSamples,
  21842. float startGain,
  21843. const float endGain) throw()
  21844. {
  21845. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21846. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21847. jassert (source != 0);
  21848. if (startGain == endGain)
  21849. {
  21850. addFrom (destChannel,
  21851. destStartSample,
  21852. source,
  21853. numSamples,
  21854. startGain);
  21855. }
  21856. else
  21857. {
  21858. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21859. {
  21860. const float increment = (endGain - startGain) / numSamples;
  21861. float* d = channels [destChannel] + destStartSample;
  21862. while (--numSamples >= 0)
  21863. {
  21864. *d++ += startGain * *source++;
  21865. startGain += increment;
  21866. }
  21867. }
  21868. }
  21869. }
  21870. void AudioSampleBuffer::copyFrom (const int destChannel,
  21871. const int destStartSample,
  21872. const AudioSampleBuffer& source,
  21873. const int sourceChannel,
  21874. const int sourceStartSample,
  21875. int numSamples) throw()
  21876. {
  21877. jassert (&source != this || sourceChannel != destChannel);
  21878. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21879. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21880. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21881. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21882. if (numSamples > 0)
  21883. {
  21884. memcpy (channels [destChannel] + destStartSample,
  21885. source.channels [sourceChannel] + sourceStartSample,
  21886. sizeof (float) * numSamples);
  21887. }
  21888. }
  21889. void AudioSampleBuffer::copyFrom (const int destChannel,
  21890. const int destStartSample,
  21891. const float* source,
  21892. int numSamples) throw()
  21893. {
  21894. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21895. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21896. jassert (source != 0);
  21897. if (numSamples > 0)
  21898. {
  21899. memcpy (channels [destChannel] + destStartSample,
  21900. source,
  21901. sizeof (float) * numSamples);
  21902. }
  21903. }
  21904. void AudioSampleBuffer::copyFrom (const int destChannel,
  21905. const int destStartSample,
  21906. const float* source,
  21907. int numSamples,
  21908. const float gain) throw()
  21909. {
  21910. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21911. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21912. jassert (source != 0);
  21913. if (numSamples > 0)
  21914. {
  21915. float* d = channels [destChannel] + destStartSample;
  21916. if (gain != 1.0f)
  21917. {
  21918. if (gain == 0)
  21919. {
  21920. zeromem (d, sizeof (float) * numSamples);
  21921. }
  21922. else
  21923. {
  21924. while (--numSamples >= 0)
  21925. *d++ = gain * *source++;
  21926. }
  21927. }
  21928. else
  21929. {
  21930. memcpy (d, source, sizeof (float) * numSamples);
  21931. }
  21932. }
  21933. }
  21934. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21935. const int destStartSample,
  21936. const float* source,
  21937. int numSamples,
  21938. float startGain,
  21939. float endGain) throw()
  21940. {
  21941. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21942. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21943. jassert (source != 0);
  21944. if (startGain == endGain)
  21945. {
  21946. copyFrom (destChannel,
  21947. destStartSample,
  21948. source,
  21949. numSamples,
  21950. startGain);
  21951. }
  21952. else
  21953. {
  21954. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21955. {
  21956. const float increment = (endGain - startGain) / numSamples;
  21957. float* d = channels [destChannel] + destStartSample;
  21958. while (--numSamples >= 0)
  21959. {
  21960. *d++ = startGain * *source++;
  21961. startGain += increment;
  21962. }
  21963. }
  21964. }
  21965. }
  21966. void AudioSampleBuffer::findMinMax (const int channel,
  21967. const int startSample,
  21968. int numSamples,
  21969. float& minVal,
  21970. float& maxVal) const throw()
  21971. {
  21972. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21973. jassert (startSample >= 0 && startSample + numSamples <= size);
  21974. if (numSamples <= 0)
  21975. {
  21976. minVal = 0.0f;
  21977. maxVal = 0.0f;
  21978. }
  21979. else
  21980. {
  21981. const float* d = channels [channel] + startSample;
  21982. float mn = *d++;
  21983. float mx = mn;
  21984. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21985. {
  21986. const float samp = *d++;
  21987. if (samp > mx)
  21988. mx = samp;
  21989. if (samp < mn)
  21990. mn = samp;
  21991. }
  21992. maxVal = mx;
  21993. minVal = mn;
  21994. }
  21995. }
  21996. float AudioSampleBuffer::getMagnitude (const int channel,
  21997. const int startSample,
  21998. const int numSamples) const throw()
  21999. {
  22000. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22001. jassert (startSample >= 0 && startSample + numSamples <= size);
  22002. float mn, mx;
  22003. findMinMax (channel, startSample, numSamples, mn, mx);
  22004. return jmax (mn, -mn, mx, -mx);
  22005. }
  22006. float AudioSampleBuffer::getMagnitude (const int startSample,
  22007. const int numSamples) const throw()
  22008. {
  22009. float mag = 0.0f;
  22010. for (int i = 0; i < numChannels; ++i)
  22011. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  22012. return mag;
  22013. }
  22014. float AudioSampleBuffer::getRMSLevel (const int channel,
  22015. const int startSample,
  22016. const int numSamples) const throw()
  22017. {
  22018. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22019. jassert (startSample >= 0 && startSample + numSamples <= size);
  22020. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  22021. return 0.0f;
  22022. const float* const data = channels [channel] + startSample;
  22023. double sum = 0.0;
  22024. for (int i = 0; i < numSamples; ++i)
  22025. {
  22026. const float sample = data [i];
  22027. sum += sample * sample;
  22028. }
  22029. return (float) std::sqrt (sum / numSamples);
  22030. }
  22031. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  22032. const int startSample,
  22033. const int numSamples,
  22034. const int readerStartSample,
  22035. const bool useLeftChan,
  22036. const bool useRightChan)
  22037. {
  22038. jassert (reader != 0);
  22039. jassert (startSample >= 0 && startSample + numSamples <= size);
  22040. if (numSamples > 0)
  22041. {
  22042. int* chans[3];
  22043. if (useLeftChan == useRightChan)
  22044. {
  22045. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22046. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22047. }
  22048. else if (useLeftChan || (reader->numChannels == 1))
  22049. {
  22050. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22051. chans[1] = 0;
  22052. }
  22053. else if (useRightChan)
  22054. {
  22055. chans[0] = 0;
  22056. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22057. }
  22058. chans[2] = 0;
  22059. reader->read (chans, 2, readerStartSample, numSamples, true);
  22060. if (! reader->usesFloatingPointData)
  22061. {
  22062. for (int j = 0; j < 2; ++j)
  22063. {
  22064. float* const d = reinterpret_cast <float*> (chans[j]);
  22065. if (d != 0)
  22066. {
  22067. const float multiplier = 1.0f / 0x7fffffff;
  22068. for (int i = 0; i < numSamples; ++i)
  22069. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22070. }
  22071. }
  22072. }
  22073. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22074. {
  22075. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22076. memcpy (getSampleData (1, startSample),
  22077. getSampleData (0, startSample),
  22078. sizeof (float) * numSamples);
  22079. }
  22080. }
  22081. }
  22082. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22083. const int startSample,
  22084. const int numSamples) const
  22085. {
  22086. jassert (writer != 0);
  22087. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22088. }
  22089. END_JUCE_NAMESPACE
  22090. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22091. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22092. BEGIN_JUCE_NAMESPACE
  22093. IIRFilter::IIRFilter()
  22094. : active (false)
  22095. {
  22096. reset();
  22097. }
  22098. IIRFilter::IIRFilter (const IIRFilter& other)
  22099. : active (other.active)
  22100. {
  22101. const ScopedLock sl (other.processLock);
  22102. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22103. reset();
  22104. }
  22105. IIRFilter::~IIRFilter()
  22106. {
  22107. }
  22108. void IIRFilter::reset() throw()
  22109. {
  22110. const ScopedLock sl (processLock);
  22111. x1 = 0;
  22112. x2 = 0;
  22113. y1 = 0;
  22114. y2 = 0;
  22115. }
  22116. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22117. {
  22118. float out = coefficients[0] * in
  22119. + coefficients[1] * x1
  22120. + coefficients[2] * x2
  22121. - coefficients[4] * y1
  22122. - coefficients[5] * y2;
  22123. #if JUCE_INTEL
  22124. if (! (out < -1.0e-8 || out > 1.0e-8))
  22125. out = 0;
  22126. #endif
  22127. x2 = x1;
  22128. x1 = in;
  22129. y2 = y1;
  22130. y1 = out;
  22131. return out;
  22132. }
  22133. void IIRFilter::processSamples (float* const samples,
  22134. const int numSamples) throw()
  22135. {
  22136. const ScopedLock sl (processLock);
  22137. if (active)
  22138. {
  22139. for (int i = 0; i < numSamples; ++i)
  22140. {
  22141. const float in = samples[i];
  22142. float out = coefficients[0] * in
  22143. + coefficients[1] * x1
  22144. + coefficients[2] * x2
  22145. - coefficients[4] * y1
  22146. - coefficients[5] * y2;
  22147. #if JUCE_INTEL
  22148. if (! (out < -1.0e-8 || out > 1.0e-8))
  22149. out = 0;
  22150. #endif
  22151. x2 = x1;
  22152. x1 = in;
  22153. y2 = y1;
  22154. y1 = out;
  22155. samples[i] = out;
  22156. }
  22157. }
  22158. }
  22159. void IIRFilter::makeLowPass (const double sampleRate,
  22160. const double frequency) throw()
  22161. {
  22162. jassert (sampleRate > 0);
  22163. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22164. const double nSquared = n * n;
  22165. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22166. setCoefficients (c1,
  22167. c1 * 2.0f,
  22168. c1,
  22169. 1.0,
  22170. c1 * 2.0 * (1.0 - nSquared),
  22171. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22172. }
  22173. void IIRFilter::makeHighPass (const double sampleRate,
  22174. const double frequency) throw()
  22175. {
  22176. const double n = tan (double_Pi * frequency / sampleRate);
  22177. const double nSquared = n * n;
  22178. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22179. setCoefficients (c1,
  22180. c1 * -2.0f,
  22181. c1,
  22182. 1.0,
  22183. c1 * 2.0 * (nSquared - 1.0),
  22184. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22185. }
  22186. void IIRFilter::makeLowShelf (const double sampleRate,
  22187. const double cutOffFrequency,
  22188. const double Q,
  22189. const float gainFactor) throw()
  22190. {
  22191. jassert (sampleRate > 0);
  22192. jassert (Q > 0);
  22193. const double A = jmax (0.0f, gainFactor);
  22194. const double aminus1 = A - 1.0;
  22195. const double aplus1 = A + 1.0;
  22196. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22197. const double coso = std::cos (omega);
  22198. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22199. const double aminus1TimesCoso = aminus1 * coso;
  22200. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22201. A * 2.0 * (aminus1 - aplus1 * coso),
  22202. A * (aplus1 - aminus1TimesCoso - beta),
  22203. aplus1 + aminus1TimesCoso + beta,
  22204. -2.0 * (aminus1 + aplus1 * coso),
  22205. aplus1 + aminus1TimesCoso - beta);
  22206. }
  22207. void IIRFilter::makeHighShelf (const double sampleRate,
  22208. const double cutOffFrequency,
  22209. const double Q,
  22210. const float gainFactor) throw()
  22211. {
  22212. jassert (sampleRate > 0);
  22213. jassert (Q > 0);
  22214. const double A = jmax (0.0f, gainFactor);
  22215. const double aminus1 = A - 1.0;
  22216. const double aplus1 = A + 1.0;
  22217. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22218. const double coso = std::cos (omega);
  22219. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22220. const double aminus1TimesCoso = aminus1 * coso;
  22221. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22222. A * -2.0 * (aminus1 + aplus1 * coso),
  22223. A * (aplus1 + aminus1TimesCoso - beta),
  22224. aplus1 - aminus1TimesCoso + beta,
  22225. 2.0 * (aminus1 - aplus1 * coso),
  22226. aplus1 - aminus1TimesCoso - beta);
  22227. }
  22228. void IIRFilter::makeBandPass (const double sampleRate,
  22229. const double centreFrequency,
  22230. const double Q,
  22231. const float gainFactor) throw()
  22232. {
  22233. jassert (sampleRate > 0);
  22234. jassert (Q > 0);
  22235. const double A = jmax (0.0f, gainFactor);
  22236. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22237. const double alpha = 0.5 * std::sin (omega) / Q;
  22238. const double c2 = -2.0 * std::cos (omega);
  22239. const double alphaTimesA = alpha * A;
  22240. const double alphaOverA = alpha / A;
  22241. setCoefficients (1.0 + alphaTimesA,
  22242. c2,
  22243. 1.0 - alphaTimesA,
  22244. 1.0 + alphaOverA,
  22245. c2,
  22246. 1.0 - alphaOverA);
  22247. }
  22248. void IIRFilter::makeInactive() throw()
  22249. {
  22250. const ScopedLock sl (processLock);
  22251. active = false;
  22252. }
  22253. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22254. {
  22255. const ScopedLock sl (processLock);
  22256. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22257. active = other.active;
  22258. }
  22259. void IIRFilter::setCoefficients (double c1,
  22260. double c2,
  22261. double c3,
  22262. double c4,
  22263. double c5,
  22264. double c6) throw()
  22265. {
  22266. const double a = 1.0 / c4;
  22267. c1 *= a;
  22268. c2 *= a;
  22269. c3 *= a;
  22270. c5 *= a;
  22271. c6 *= a;
  22272. const ScopedLock sl (processLock);
  22273. coefficients[0] = (float) c1;
  22274. coefficients[1] = (float) c2;
  22275. coefficients[2] = (float) c3;
  22276. coefficients[3] = (float) c4;
  22277. coefficients[4] = (float) c5;
  22278. coefficients[5] = (float) c6;
  22279. active = true;
  22280. }
  22281. END_JUCE_NAMESPACE
  22282. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22283. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22284. BEGIN_JUCE_NAMESPACE
  22285. MidiBuffer::MidiBuffer() throw()
  22286. : bytesUsed (0)
  22287. {
  22288. }
  22289. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22290. : bytesUsed (0)
  22291. {
  22292. addEvent (message, 0);
  22293. }
  22294. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22295. : data (other.data),
  22296. bytesUsed (other.bytesUsed)
  22297. {
  22298. }
  22299. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22300. {
  22301. bytesUsed = other.bytesUsed;
  22302. data = other.data;
  22303. return *this;
  22304. }
  22305. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22306. {
  22307. data.swapWith (other.data);
  22308. swapVariables <int> (bytesUsed, other.bytesUsed);
  22309. }
  22310. MidiBuffer::~MidiBuffer()
  22311. {
  22312. }
  22313. inline uint8* MidiBuffer::getData() const throw()
  22314. {
  22315. return static_cast <uint8*> (data.getData());
  22316. }
  22317. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22318. {
  22319. return *static_cast <const int*> (d);
  22320. }
  22321. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22322. {
  22323. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22324. }
  22325. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22326. {
  22327. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22328. }
  22329. void MidiBuffer::clear() throw()
  22330. {
  22331. bytesUsed = 0;
  22332. }
  22333. void MidiBuffer::clear (const int startSample, const int numSamples)
  22334. {
  22335. uint8* const start = findEventAfter (getData(), startSample - 1);
  22336. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22337. if (end > start)
  22338. {
  22339. const int bytesToMove = bytesUsed - (int) (end - getData());
  22340. if (bytesToMove > 0)
  22341. memmove (start, end, bytesToMove);
  22342. bytesUsed -= (int) (end - start);
  22343. }
  22344. }
  22345. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22346. {
  22347. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22348. }
  22349. static int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22350. {
  22351. unsigned int byte = (unsigned int) *data;
  22352. int size = 0;
  22353. if (byte == 0xf0 || byte == 0xf7)
  22354. {
  22355. const uint8* d = data + 1;
  22356. while (d < data + maxBytes)
  22357. if (*d++ == 0xf7)
  22358. break;
  22359. size = (int) (d - data);
  22360. }
  22361. else if (byte == 0xff)
  22362. {
  22363. int n;
  22364. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22365. size = jmin (maxBytes, n + 2 + bytesLeft);
  22366. }
  22367. else if (byte >= 0x80)
  22368. {
  22369. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22370. }
  22371. return size;
  22372. }
  22373. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22374. {
  22375. const int numBytes = findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22376. if (numBytes > 0)
  22377. {
  22378. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22379. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22380. uint8* d = findEventAfter (getData(), sampleNumber);
  22381. const int bytesToMove = bytesUsed - (int) (d - getData());
  22382. if (bytesToMove > 0)
  22383. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22384. *reinterpret_cast <int*> (d) = sampleNumber;
  22385. d += sizeof (int);
  22386. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22387. d += sizeof (uint16);
  22388. memcpy (d, newData, numBytes);
  22389. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22390. }
  22391. }
  22392. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22393. const int startSample,
  22394. const int numSamples,
  22395. const int sampleDeltaToAdd)
  22396. {
  22397. Iterator i (otherBuffer);
  22398. i.setNextSamplePosition (startSample);
  22399. const uint8* eventData;
  22400. int eventSize, position;
  22401. while (i.getNextEvent (eventData, eventSize, position)
  22402. && (position < startSample + numSamples || numSamples < 0))
  22403. {
  22404. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22405. }
  22406. }
  22407. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22408. {
  22409. data.ensureSize (minimumNumBytes);
  22410. }
  22411. bool MidiBuffer::isEmpty() const throw()
  22412. {
  22413. return bytesUsed == 0;
  22414. }
  22415. int MidiBuffer::getNumEvents() const throw()
  22416. {
  22417. int n = 0;
  22418. const uint8* d = getData();
  22419. const uint8* const end = d + bytesUsed;
  22420. while (d < end)
  22421. {
  22422. d += getEventTotalSize (d);
  22423. ++n;
  22424. }
  22425. return n;
  22426. }
  22427. int MidiBuffer::getFirstEventTime() const throw()
  22428. {
  22429. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22430. }
  22431. int MidiBuffer::getLastEventTime() const throw()
  22432. {
  22433. if (bytesUsed == 0)
  22434. return 0;
  22435. const uint8* d = getData();
  22436. const uint8* const endData = d + bytesUsed;
  22437. for (;;)
  22438. {
  22439. const uint8* const nextOne = d + getEventTotalSize (d);
  22440. if (nextOne >= endData)
  22441. return getEventTime (d);
  22442. d = nextOne;
  22443. }
  22444. }
  22445. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22446. {
  22447. const uint8* const endData = getData() + bytesUsed;
  22448. while (d < endData && getEventTime (d) <= samplePosition)
  22449. d += getEventTotalSize (d);
  22450. return d;
  22451. }
  22452. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22453. : buffer (buffer_),
  22454. data (buffer_.getData())
  22455. {
  22456. }
  22457. MidiBuffer::Iterator::~Iterator() throw()
  22458. {
  22459. }
  22460. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22461. {
  22462. data = buffer.getData();
  22463. const uint8* dataEnd = data + buffer.bytesUsed;
  22464. while (data < dataEnd && getEventTime (data) < samplePosition)
  22465. data += getEventTotalSize (data);
  22466. }
  22467. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22468. {
  22469. if (data >= buffer.getData() + buffer.bytesUsed)
  22470. return false;
  22471. samplePosition = getEventTime (data);
  22472. numBytes = getEventDataSize (data);
  22473. data += sizeof (int) + sizeof (uint16);
  22474. midiData = data;
  22475. data += numBytes;
  22476. return true;
  22477. }
  22478. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22479. {
  22480. if (data >= buffer.getData() + buffer.bytesUsed)
  22481. return false;
  22482. samplePosition = getEventTime (data);
  22483. const int numBytes = getEventDataSize (data);
  22484. data += sizeof (int) + sizeof (uint16);
  22485. result = MidiMessage (data, numBytes, samplePosition);
  22486. data += numBytes;
  22487. return true;
  22488. }
  22489. END_JUCE_NAMESPACE
  22490. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22491. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22492. BEGIN_JUCE_NAMESPACE
  22493. namespace MidiFileHelpers
  22494. {
  22495. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22496. {
  22497. unsigned int buffer = v & 0x7F;
  22498. while ((v >>= 7) != 0)
  22499. {
  22500. buffer <<= 8;
  22501. buffer |= ((v & 0x7F) | 0x80);
  22502. }
  22503. for (;;)
  22504. {
  22505. out.writeByte ((char) buffer);
  22506. if (buffer & 0x80)
  22507. buffer >>= 8;
  22508. else
  22509. break;
  22510. }
  22511. }
  22512. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22513. {
  22514. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22515. data += 4;
  22516. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22517. {
  22518. bool ok = false;
  22519. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22520. {
  22521. for (int i = 0; i < 8; ++i)
  22522. {
  22523. ch = ByteOrder::bigEndianInt (data);
  22524. data += 4;
  22525. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22526. {
  22527. ok = true;
  22528. break;
  22529. }
  22530. }
  22531. }
  22532. if (! ok)
  22533. return false;
  22534. }
  22535. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22536. data += 4;
  22537. fileType = (short) ByteOrder::bigEndianShort (data);
  22538. data += 2;
  22539. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22540. data += 2;
  22541. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22542. data += 2;
  22543. bytesRemaining -= 6;
  22544. data += bytesRemaining;
  22545. return true;
  22546. }
  22547. static double convertTicksToSeconds (const double time,
  22548. const MidiMessageSequence& tempoEvents,
  22549. const int timeFormat)
  22550. {
  22551. if (timeFormat > 0)
  22552. {
  22553. int numer = 4, denom = 4;
  22554. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22555. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22556. double secsPerTick = 0.5 * tickLen;
  22557. const int numEvents = tempoEvents.getNumEvents();
  22558. for (int i = 0; i < numEvents; ++i)
  22559. {
  22560. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22561. if (time <= m.getTimeStamp())
  22562. break;
  22563. if (timeFormat > 0)
  22564. {
  22565. correctedTempoTime = correctedTempoTime
  22566. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22567. }
  22568. else
  22569. {
  22570. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22571. }
  22572. tempoTime = m.getTimeStamp();
  22573. if (m.isTempoMetaEvent())
  22574. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22575. else if (m.isTimeSignatureMetaEvent())
  22576. m.getTimeSignatureInfo (numer, denom);
  22577. while (i + 1 < numEvents)
  22578. {
  22579. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22580. if (m2.getTimeStamp() == tempoTime)
  22581. {
  22582. ++i;
  22583. if (m2.isTempoMetaEvent())
  22584. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22585. else if (m2.isTimeSignatureMetaEvent())
  22586. m2.getTimeSignatureInfo (numer, denom);
  22587. }
  22588. else
  22589. {
  22590. break;
  22591. }
  22592. }
  22593. }
  22594. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22595. }
  22596. else
  22597. {
  22598. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22599. }
  22600. }
  22601. // a comparator that puts all the note-offs before note-ons that have the same time
  22602. struct Sorter
  22603. {
  22604. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22605. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22606. {
  22607. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22608. if (diff == 0)
  22609. {
  22610. if (first->message.isNoteOff() && second->message.isNoteOn())
  22611. return -1;
  22612. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22613. return 1;
  22614. else
  22615. return 0;
  22616. }
  22617. else
  22618. {
  22619. return (diff > 0) ? 1 : -1;
  22620. }
  22621. }
  22622. };
  22623. }
  22624. MidiFile::MidiFile()
  22625. : timeFormat ((short) (unsigned short) 0xe728)
  22626. {
  22627. }
  22628. MidiFile::~MidiFile()
  22629. {
  22630. clear();
  22631. }
  22632. void MidiFile::clear()
  22633. {
  22634. tracks.clear();
  22635. }
  22636. int MidiFile::getNumTracks() const throw()
  22637. {
  22638. return tracks.size();
  22639. }
  22640. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22641. {
  22642. return tracks [index];
  22643. }
  22644. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22645. {
  22646. tracks.add (new MidiMessageSequence (trackSequence));
  22647. }
  22648. short MidiFile::getTimeFormat() const throw()
  22649. {
  22650. return timeFormat;
  22651. }
  22652. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22653. {
  22654. timeFormat = (short) ticks;
  22655. }
  22656. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22657. const int subframeResolution) throw()
  22658. {
  22659. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22660. }
  22661. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22662. {
  22663. for (int i = tracks.size(); --i >= 0;)
  22664. {
  22665. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22666. for (int j = 0; j < numEvents; ++j)
  22667. {
  22668. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22669. if (m.isTempoMetaEvent())
  22670. tempoChangeEvents.addEvent (m);
  22671. }
  22672. }
  22673. }
  22674. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22675. {
  22676. for (int i = tracks.size(); --i >= 0;)
  22677. {
  22678. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22679. for (int j = 0; j < numEvents; ++j)
  22680. {
  22681. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22682. if (m.isTimeSignatureMetaEvent())
  22683. timeSigEvents.addEvent (m);
  22684. }
  22685. }
  22686. }
  22687. double MidiFile::getLastTimestamp() const
  22688. {
  22689. double t = 0.0;
  22690. for (int i = tracks.size(); --i >= 0;)
  22691. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22692. return t;
  22693. }
  22694. bool MidiFile::readFrom (InputStream& sourceStream)
  22695. {
  22696. clear();
  22697. MemoryBlock data;
  22698. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22699. // (put a sanity-check on the file size, as midi files are generally small)
  22700. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22701. {
  22702. size_t size = data.getSize();
  22703. const uint8* d = static_cast <const uint8*> (data.getData());
  22704. short fileType, expectedTracks;
  22705. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22706. {
  22707. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22708. int track = 0;
  22709. while (size > 0 && track < expectedTracks)
  22710. {
  22711. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22712. d += 4;
  22713. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22714. d += 4;
  22715. if (chunkSize <= 0)
  22716. break;
  22717. if (size < 0)
  22718. return false;
  22719. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22720. {
  22721. readNextTrack (d, chunkSize);
  22722. }
  22723. size -= chunkSize + 8;
  22724. d += chunkSize;
  22725. ++track;
  22726. }
  22727. return true;
  22728. }
  22729. }
  22730. return false;
  22731. }
  22732. void MidiFile::readNextTrack (const uint8* data, int size)
  22733. {
  22734. double time = 0;
  22735. char lastStatusByte = 0;
  22736. MidiMessageSequence result;
  22737. while (size > 0)
  22738. {
  22739. int bytesUsed;
  22740. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22741. data += bytesUsed;
  22742. size -= bytesUsed;
  22743. time += delay;
  22744. int messSize = 0;
  22745. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22746. if (messSize <= 0)
  22747. break;
  22748. size -= messSize;
  22749. data += messSize;
  22750. result.addEvent (mm);
  22751. const char firstByte = *(mm.getRawData());
  22752. if ((firstByte & 0xf0) != 0xf0)
  22753. lastStatusByte = firstByte;
  22754. }
  22755. // use a sort that puts all the note-offs before note-ons that have the same time
  22756. MidiFileHelpers::Sorter sorter;
  22757. result.list.sort (sorter, true);
  22758. result.updateMatchedPairs();
  22759. addTrack (result);
  22760. }
  22761. void MidiFile::convertTimestampTicksToSeconds()
  22762. {
  22763. MidiMessageSequence tempoEvents;
  22764. findAllTempoEvents (tempoEvents);
  22765. findAllTimeSigEvents (tempoEvents);
  22766. for (int i = 0; i < tracks.size(); ++i)
  22767. {
  22768. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22769. for (int j = ms.getNumEvents(); --j >= 0;)
  22770. {
  22771. MidiMessage& m = ms.getEventPointer(j)->message;
  22772. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22773. tempoEvents,
  22774. timeFormat));
  22775. }
  22776. }
  22777. }
  22778. bool MidiFile::writeTo (OutputStream& out)
  22779. {
  22780. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22781. out.writeIntBigEndian (6);
  22782. out.writeShortBigEndian (1); // type
  22783. out.writeShortBigEndian ((short) tracks.size());
  22784. out.writeShortBigEndian (timeFormat);
  22785. for (int i = 0; i < tracks.size(); ++i)
  22786. writeTrack (out, i);
  22787. out.flush();
  22788. return true;
  22789. }
  22790. void MidiFile::writeTrack (OutputStream& mainOut,
  22791. const int trackNum)
  22792. {
  22793. MemoryOutputStream out;
  22794. const MidiMessageSequence& ms = *tracks[trackNum];
  22795. int lastTick = 0;
  22796. char lastStatusByte = 0;
  22797. for (int i = 0; i < ms.getNumEvents(); ++i)
  22798. {
  22799. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22800. const int tick = roundToInt (mm.getTimeStamp());
  22801. const int delta = jmax (0, tick - lastTick);
  22802. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22803. lastTick = tick;
  22804. const char statusByte = *(mm.getRawData());
  22805. if ((statusByte == lastStatusByte)
  22806. && ((statusByte & 0xf0) != 0xf0)
  22807. && i > 0
  22808. && mm.getRawDataSize() > 1)
  22809. {
  22810. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22811. }
  22812. else
  22813. {
  22814. out.write (mm.getRawData(), mm.getRawDataSize());
  22815. }
  22816. lastStatusByte = statusByte;
  22817. }
  22818. out.writeByte (0);
  22819. const MidiMessage m (MidiMessage::endOfTrack());
  22820. out.write (m.getRawData(),
  22821. m.getRawDataSize());
  22822. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22823. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22824. mainOut.write (out.getData(), (int) out.getDataSize());
  22825. }
  22826. END_JUCE_NAMESPACE
  22827. /*** End of inlined file: juce_MidiFile.cpp ***/
  22828. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22829. BEGIN_JUCE_NAMESPACE
  22830. MidiKeyboardState::MidiKeyboardState()
  22831. {
  22832. zerostruct (noteStates);
  22833. }
  22834. MidiKeyboardState::~MidiKeyboardState()
  22835. {
  22836. }
  22837. void MidiKeyboardState::reset()
  22838. {
  22839. const ScopedLock sl (lock);
  22840. zerostruct (noteStates);
  22841. eventsToAdd.clear();
  22842. }
  22843. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22844. {
  22845. jassert (midiChannel >= 0 && midiChannel <= 16);
  22846. return ((unsigned int) n) < 128
  22847. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22848. }
  22849. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22850. {
  22851. return ((unsigned int) n) < 128
  22852. && (noteStates[n] & midiChannelMask) != 0;
  22853. }
  22854. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22855. {
  22856. jassert (midiChannel >= 0 && midiChannel <= 16);
  22857. jassert (((unsigned int) midiNoteNumber) < 128);
  22858. const ScopedLock sl (lock);
  22859. if (((unsigned int) midiNoteNumber) < 128)
  22860. {
  22861. const int timeNow = (int) Time::getMillisecondCounter();
  22862. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22863. eventsToAdd.clear (0, timeNow - 500);
  22864. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22865. }
  22866. }
  22867. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22868. {
  22869. if (((unsigned int) midiNoteNumber) < 128)
  22870. {
  22871. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22872. for (int i = listeners.size(); --i >= 0;)
  22873. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22874. }
  22875. }
  22876. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22877. {
  22878. const ScopedLock sl (lock);
  22879. if (isNoteOn (midiChannel, midiNoteNumber))
  22880. {
  22881. const int timeNow = (int) Time::getMillisecondCounter();
  22882. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22883. eventsToAdd.clear (0, timeNow - 500);
  22884. noteOffInternal (midiChannel, midiNoteNumber);
  22885. }
  22886. }
  22887. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22888. {
  22889. if (isNoteOn (midiChannel, midiNoteNumber))
  22890. {
  22891. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22892. for (int i = listeners.size(); --i >= 0;)
  22893. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22894. }
  22895. }
  22896. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22897. {
  22898. const ScopedLock sl (lock);
  22899. if (midiChannel <= 0)
  22900. {
  22901. for (int i = 1; i <= 16; ++i)
  22902. allNotesOff (i);
  22903. }
  22904. else
  22905. {
  22906. for (int i = 0; i < 128; ++i)
  22907. noteOff (midiChannel, i);
  22908. }
  22909. }
  22910. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22911. {
  22912. if (message.isNoteOn())
  22913. {
  22914. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22915. }
  22916. else if (message.isNoteOff())
  22917. {
  22918. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22919. }
  22920. else if (message.isAllNotesOff())
  22921. {
  22922. for (int i = 0; i < 128; ++i)
  22923. noteOffInternal (message.getChannel(), i);
  22924. }
  22925. }
  22926. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22927. const int startSample,
  22928. const int numSamples,
  22929. const bool injectIndirectEvents)
  22930. {
  22931. MidiBuffer::Iterator i (buffer);
  22932. MidiMessage message (0xf4, 0.0);
  22933. int time;
  22934. const ScopedLock sl (lock);
  22935. while (i.getNextEvent (message, time))
  22936. processNextMidiEvent (message);
  22937. if (injectIndirectEvents)
  22938. {
  22939. MidiBuffer::Iterator i2 (eventsToAdd);
  22940. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22941. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22942. while (i2.getNextEvent (message, time))
  22943. {
  22944. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22945. buffer.addEvent (message, startSample + pos);
  22946. }
  22947. }
  22948. eventsToAdd.clear();
  22949. }
  22950. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22951. {
  22952. const ScopedLock sl (lock);
  22953. listeners.addIfNotAlreadyThere (listener);
  22954. }
  22955. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22956. {
  22957. const ScopedLock sl (lock);
  22958. listeners.removeValue (listener);
  22959. }
  22960. END_JUCE_NAMESPACE
  22961. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22962. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22963. BEGIN_JUCE_NAMESPACE
  22964. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  22965. {
  22966. numBytesUsed = 0;
  22967. int v = 0;
  22968. int i;
  22969. do
  22970. {
  22971. i = (int) *data++;
  22972. if (++numBytesUsed > 6)
  22973. break;
  22974. v = (v << 7) + (i & 0x7f);
  22975. } while (i & 0x80);
  22976. return v;
  22977. }
  22978. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22979. {
  22980. // this method only works for valid starting bytes of a short midi message
  22981. jassert (firstByte >= 0x80
  22982. && firstByte != 0xf0
  22983. && firstByte != 0xf7);
  22984. static const char messageLengths[] =
  22985. {
  22986. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22987. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22988. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22989. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22990. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22991. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22992. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22993. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22994. };
  22995. return messageLengths [firstByte & 0x7f];
  22996. }
  22997. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22998. : timeStamp (t),
  22999. size (dataSize)
  23000. {
  23001. jassert (dataSize > 0);
  23002. if (dataSize <= 4)
  23003. data = static_cast<uint8*> (preallocatedData.asBytes);
  23004. else
  23005. data = new uint8 [dataSize];
  23006. memcpy (data, d, dataSize);
  23007. // check that the length matches the data..
  23008. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  23009. }
  23010. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  23011. : timeStamp (t),
  23012. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23013. size (1)
  23014. {
  23015. data[0] = (uint8) byte1;
  23016. // check that the length matches the data..
  23017. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  23018. }
  23019. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  23020. : timeStamp (t),
  23021. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23022. size (2)
  23023. {
  23024. data[0] = (uint8) byte1;
  23025. data[1] = (uint8) byte2;
  23026. // check that the length matches the data..
  23027. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  23028. }
  23029. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  23030. : timeStamp (t),
  23031. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23032. size (3)
  23033. {
  23034. data[0] = (uint8) byte1;
  23035. data[1] = (uint8) byte2;
  23036. data[2] = (uint8) byte3;
  23037. // check that the length matches the data..
  23038. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23039. }
  23040. MidiMessage::MidiMessage (const MidiMessage& other)
  23041. : timeStamp (other.timeStamp),
  23042. size (other.size)
  23043. {
  23044. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23045. {
  23046. data = new uint8 [size];
  23047. memcpy (data, other.data, size);
  23048. }
  23049. else
  23050. {
  23051. data = static_cast<uint8*> (preallocatedData.asBytes);
  23052. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23053. }
  23054. }
  23055. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23056. : timeStamp (newTimeStamp),
  23057. size (other.size)
  23058. {
  23059. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23060. {
  23061. data = new uint8 [size];
  23062. memcpy (data, other.data, size);
  23063. }
  23064. else
  23065. {
  23066. data = static_cast<uint8*> (preallocatedData.asBytes);
  23067. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23068. }
  23069. }
  23070. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23071. : timeStamp (t),
  23072. data (static_cast<uint8*> (preallocatedData.asBytes))
  23073. {
  23074. const uint8* src = static_cast <const uint8*> (src_);
  23075. unsigned int byte = (unsigned int) *src;
  23076. if (byte < 0x80)
  23077. {
  23078. byte = (unsigned int) (uint8) lastStatusByte;
  23079. numBytesUsed = -1;
  23080. }
  23081. else
  23082. {
  23083. numBytesUsed = 0;
  23084. --sz;
  23085. ++src;
  23086. }
  23087. if (byte >= 0x80)
  23088. {
  23089. if (byte == 0xf0)
  23090. {
  23091. const uint8* d = src;
  23092. while (d < src + sz)
  23093. {
  23094. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  23095. {
  23096. if (*d == 0xf7) // include an 0xf7 if we hit one
  23097. ++d;
  23098. break;
  23099. }
  23100. ++d;
  23101. }
  23102. size = 1 + (int) (d - src);
  23103. data = new uint8 [size];
  23104. *data = (uint8) byte;
  23105. memcpy (data + 1, src, size - 1);
  23106. }
  23107. else if (byte == 0xff)
  23108. {
  23109. int n;
  23110. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23111. size = jmin (sz + 1, n + 2 + bytesLeft);
  23112. data = new uint8 [size];
  23113. *data = (uint8) byte;
  23114. memcpy (data + 1, src, size - 1);
  23115. }
  23116. else
  23117. {
  23118. preallocatedData.asInt32 = 0;
  23119. size = getMessageLengthFromFirstByte ((uint8) byte);
  23120. data[0] = (uint8) byte;
  23121. if (size > 1)
  23122. {
  23123. data[1] = src[0];
  23124. if (size > 2)
  23125. data[2] = src[1];
  23126. }
  23127. }
  23128. numBytesUsed += size;
  23129. }
  23130. else
  23131. {
  23132. preallocatedData.asInt32 = 0;
  23133. size = 0;
  23134. }
  23135. }
  23136. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23137. {
  23138. if (this != &other)
  23139. {
  23140. timeStamp = other.timeStamp;
  23141. size = other.size;
  23142. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23143. delete[] data;
  23144. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23145. {
  23146. data = new uint8 [size];
  23147. memcpy (data, other.data, size);
  23148. }
  23149. else
  23150. {
  23151. data = static_cast<uint8*> (preallocatedData.asBytes);
  23152. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23153. }
  23154. }
  23155. return *this;
  23156. }
  23157. MidiMessage::~MidiMessage()
  23158. {
  23159. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23160. delete[] data;
  23161. }
  23162. int MidiMessage::getChannel() const throw()
  23163. {
  23164. if ((data[0] & 0xf0) != 0xf0)
  23165. return (data[0] & 0xf) + 1;
  23166. else
  23167. return 0;
  23168. }
  23169. bool MidiMessage::isForChannel (const int channel) const throw()
  23170. {
  23171. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23172. return ((data[0] & 0xf) == channel - 1)
  23173. && ((data[0] & 0xf0) != 0xf0);
  23174. }
  23175. void MidiMessage::setChannel (const int channel) throw()
  23176. {
  23177. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23178. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23179. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  23180. | (uint8)(channel - 1));
  23181. }
  23182. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23183. {
  23184. return ((data[0] & 0xf0) == 0x90)
  23185. && (returnTrueForVelocity0 || data[2] != 0);
  23186. }
  23187. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23188. {
  23189. return ((data[0] & 0xf0) == 0x80)
  23190. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23191. }
  23192. bool MidiMessage::isNoteOnOrOff() const throw()
  23193. {
  23194. const int d = data[0] & 0xf0;
  23195. return (d == 0x90) || (d == 0x80);
  23196. }
  23197. int MidiMessage::getNoteNumber() const throw()
  23198. {
  23199. return data[1];
  23200. }
  23201. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23202. {
  23203. if (isNoteOnOrOff())
  23204. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23205. }
  23206. uint8 MidiMessage::getVelocity() const throw()
  23207. {
  23208. if (isNoteOnOrOff())
  23209. return data[2];
  23210. else
  23211. return 0;
  23212. }
  23213. float MidiMessage::getFloatVelocity() const throw()
  23214. {
  23215. return getVelocity() * (1.0f / 127.0f);
  23216. }
  23217. void MidiMessage::setVelocity (const float newVelocity) throw()
  23218. {
  23219. if (isNoteOnOrOff())
  23220. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23221. }
  23222. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23223. {
  23224. if (isNoteOnOrOff())
  23225. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23226. }
  23227. bool MidiMessage::isAftertouch() const throw()
  23228. {
  23229. return (data[0] & 0xf0) == 0xa0;
  23230. }
  23231. int MidiMessage::getAfterTouchValue() const throw()
  23232. {
  23233. return data[2];
  23234. }
  23235. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23236. const int noteNum,
  23237. const int aftertouchValue) throw()
  23238. {
  23239. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23240. jassert (((unsigned int) noteNum) <= 127);
  23241. jassert (((unsigned int) aftertouchValue) <= 127);
  23242. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23243. noteNum & 0x7f,
  23244. aftertouchValue & 0x7f);
  23245. }
  23246. bool MidiMessage::isChannelPressure() const throw()
  23247. {
  23248. return (data[0] & 0xf0) == 0xd0;
  23249. }
  23250. int MidiMessage::getChannelPressureValue() const throw()
  23251. {
  23252. jassert (isChannelPressure());
  23253. return data[1];
  23254. }
  23255. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23256. const int pressure) throw()
  23257. {
  23258. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23259. jassert (((unsigned int) pressure) <= 127);
  23260. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23261. pressure & 0x7f);
  23262. }
  23263. bool MidiMessage::isProgramChange() const throw()
  23264. {
  23265. return (data[0] & 0xf0) == 0xc0;
  23266. }
  23267. int MidiMessage::getProgramChangeNumber() const throw()
  23268. {
  23269. return data[1];
  23270. }
  23271. const MidiMessage MidiMessage::programChange (const int channel,
  23272. const int programNumber) throw()
  23273. {
  23274. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23275. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23276. programNumber & 0x7f);
  23277. }
  23278. bool MidiMessage::isPitchWheel() const throw()
  23279. {
  23280. return (data[0] & 0xf0) == 0xe0;
  23281. }
  23282. int MidiMessage::getPitchWheelValue() const throw()
  23283. {
  23284. return data[1] | (data[2] << 7);
  23285. }
  23286. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23287. const int position) throw()
  23288. {
  23289. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23290. jassert (((unsigned int) position) <= 0x3fff);
  23291. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23292. position & 127,
  23293. (position >> 7) & 127);
  23294. }
  23295. bool MidiMessage::isController() const throw()
  23296. {
  23297. return (data[0] & 0xf0) == 0xb0;
  23298. }
  23299. int MidiMessage::getControllerNumber() const throw()
  23300. {
  23301. jassert (isController());
  23302. return data[1];
  23303. }
  23304. int MidiMessage::getControllerValue() const throw()
  23305. {
  23306. jassert (isController());
  23307. return data[2];
  23308. }
  23309. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23310. const int controllerType,
  23311. const int value) throw()
  23312. {
  23313. // the channel must be between 1 and 16 inclusive
  23314. jassert (channel > 0 && channel <= 16);
  23315. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23316. controllerType & 127,
  23317. value & 127);
  23318. }
  23319. const MidiMessage MidiMessage::noteOn (const int channel,
  23320. const int noteNumber,
  23321. const float velocity) throw()
  23322. {
  23323. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23324. }
  23325. const MidiMessage MidiMessage::noteOn (const int channel,
  23326. const int noteNumber,
  23327. const uint8 velocity) throw()
  23328. {
  23329. jassert (channel > 0 && channel <= 16);
  23330. jassert (((unsigned int) noteNumber) <= 127);
  23331. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23332. noteNumber & 127,
  23333. jlimit (0, 127, roundToInt (velocity)));
  23334. }
  23335. const MidiMessage MidiMessage::noteOff (const int channel,
  23336. const int noteNumber) throw()
  23337. {
  23338. jassert (channel > 0 && channel <= 16);
  23339. jassert (((unsigned int) noteNumber) <= 127);
  23340. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23341. }
  23342. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23343. {
  23344. return controllerEvent (channel, 123, 0);
  23345. }
  23346. bool MidiMessage::isAllNotesOff() const throw()
  23347. {
  23348. return (data[0] & 0xf0) == 0xb0
  23349. && data[1] == 123;
  23350. }
  23351. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23352. {
  23353. return controllerEvent (channel, 120, 0);
  23354. }
  23355. bool MidiMessage::isAllSoundOff() const throw()
  23356. {
  23357. return (data[0] & 0xf0) == 0xb0
  23358. && data[1] == 120;
  23359. }
  23360. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23361. {
  23362. return controllerEvent (channel, 121, 0);
  23363. }
  23364. const MidiMessage MidiMessage::masterVolume (const float volume)
  23365. {
  23366. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23367. uint8 buf[8];
  23368. buf[0] = 0xf0;
  23369. buf[1] = 0x7f;
  23370. buf[2] = 0x7f;
  23371. buf[3] = 0x04;
  23372. buf[4] = 0x01;
  23373. buf[5] = (uint8) (vol & 0x7f);
  23374. buf[6] = (uint8) (vol >> 7);
  23375. buf[7] = 0xf7;
  23376. return MidiMessage (buf, 8);
  23377. }
  23378. bool MidiMessage::isSysEx() const throw()
  23379. {
  23380. return *data == 0xf0;
  23381. }
  23382. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23383. {
  23384. MemoryBlock mm (dataSize + 2);
  23385. uint8* const m = static_cast <uint8*> (mm.getData());
  23386. m[0] = 0xf0;
  23387. memcpy (m + 1, sysexData, dataSize);
  23388. m[dataSize + 1] = 0xf7;
  23389. return MidiMessage (m, dataSize + 2);
  23390. }
  23391. const uint8* MidiMessage::getSysExData() const throw()
  23392. {
  23393. return (isSysEx()) ? getRawData() + 1 : 0;
  23394. }
  23395. int MidiMessage::getSysExDataSize() const throw()
  23396. {
  23397. return (isSysEx()) ? size - 2 : 0;
  23398. }
  23399. bool MidiMessage::isMetaEvent() const throw()
  23400. {
  23401. return *data == 0xff;
  23402. }
  23403. bool MidiMessage::isActiveSense() const throw()
  23404. {
  23405. return *data == 0xfe;
  23406. }
  23407. int MidiMessage::getMetaEventType() const throw()
  23408. {
  23409. if (*data != 0xff)
  23410. return -1;
  23411. else
  23412. return data[1];
  23413. }
  23414. int MidiMessage::getMetaEventLength() const throw()
  23415. {
  23416. if (*data == 0xff)
  23417. {
  23418. int n;
  23419. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23420. }
  23421. return 0;
  23422. }
  23423. const uint8* MidiMessage::getMetaEventData() const throw()
  23424. {
  23425. int n;
  23426. const uint8* d = data + 2;
  23427. readVariableLengthVal (d, n);
  23428. return d + n;
  23429. }
  23430. bool MidiMessage::isTrackMetaEvent() const throw()
  23431. {
  23432. return getMetaEventType() == 0;
  23433. }
  23434. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23435. {
  23436. return getMetaEventType() == 47;
  23437. }
  23438. bool MidiMessage::isTextMetaEvent() const throw()
  23439. {
  23440. const int t = getMetaEventType();
  23441. return t > 0 && t < 16;
  23442. }
  23443. const String MidiMessage::getTextFromTextMetaEvent() const
  23444. {
  23445. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23446. }
  23447. bool MidiMessage::isTrackNameEvent() const throw()
  23448. {
  23449. return (data[1] == 3)
  23450. && (*data == 0xff);
  23451. }
  23452. bool MidiMessage::isTempoMetaEvent() const throw()
  23453. {
  23454. return (data[1] == 81)
  23455. && (*data == 0xff);
  23456. }
  23457. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23458. {
  23459. return (data[1] == 0x20)
  23460. && (*data == 0xff)
  23461. && (data[2] == 1);
  23462. }
  23463. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23464. {
  23465. return data[3] + 1;
  23466. }
  23467. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23468. {
  23469. if (! isTempoMetaEvent())
  23470. return 0.0;
  23471. const uint8* const d = getMetaEventData();
  23472. return (((unsigned int) d[0] << 16)
  23473. | ((unsigned int) d[1] << 8)
  23474. | d[2])
  23475. / 1000000.0;
  23476. }
  23477. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23478. {
  23479. if (timeFormat > 0)
  23480. {
  23481. if (! isTempoMetaEvent())
  23482. return 0.5 / timeFormat;
  23483. return getTempoSecondsPerQuarterNote() / timeFormat;
  23484. }
  23485. else
  23486. {
  23487. const int frameCode = (-timeFormat) >> 8;
  23488. double framesPerSecond;
  23489. switch (frameCode)
  23490. {
  23491. case 24: framesPerSecond = 24.0; break;
  23492. case 25: framesPerSecond = 25.0; break;
  23493. case 29: framesPerSecond = 29.97; break;
  23494. case 30: framesPerSecond = 30.0; break;
  23495. default: framesPerSecond = 30.0; break;
  23496. }
  23497. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23498. }
  23499. }
  23500. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23501. {
  23502. uint8 d[8];
  23503. d[0] = 0xff;
  23504. d[1] = 81;
  23505. d[2] = 3;
  23506. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23507. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23508. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23509. return MidiMessage (d, 6, 0.0);
  23510. }
  23511. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23512. {
  23513. return (data[1] == 0x58)
  23514. && (*data == (uint8) 0xff);
  23515. }
  23516. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23517. {
  23518. if (isTimeSignatureMetaEvent())
  23519. {
  23520. const uint8* const d = getMetaEventData();
  23521. numerator = d[0];
  23522. denominator = 1 << d[1];
  23523. }
  23524. else
  23525. {
  23526. numerator = 4;
  23527. denominator = 4;
  23528. }
  23529. }
  23530. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23531. {
  23532. uint8 d[8];
  23533. d[0] = 0xff;
  23534. d[1] = 0x58;
  23535. d[2] = 0x04;
  23536. d[3] = (uint8) numerator;
  23537. int n = 1;
  23538. int powerOfTwo = 0;
  23539. while (n < denominator)
  23540. {
  23541. n <<= 1;
  23542. ++powerOfTwo;
  23543. }
  23544. d[4] = (uint8) powerOfTwo;
  23545. d[5] = 0x01;
  23546. d[6] = 96;
  23547. return MidiMessage (d, 7, 0.0);
  23548. }
  23549. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23550. {
  23551. uint8 d[8];
  23552. d[0] = 0xff;
  23553. d[1] = 0x20;
  23554. d[2] = 0x01;
  23555. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23556. return MidiMessage (d, 4, 0.0);
  23557. }
  23558. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23559. {
  23560. return getMetaEventType() == 89;
  23561. }
  23562. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23563. {
  23564. return (int) *getMetaEventData();
  23565. }
  23566. const MidiMessage MidiMessage::endOfTrack() throw()
  23567. {
  23568. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23569. }
  23570. bool MidiMessage::isSongPositionPointer() const throw()
  23571. {
  23572. return *data == 0xf2;
  23573. }
  23574. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23575. {
  23576. return data[1] | (data[2] << 7);
  23577. }
  23578. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23579. {
  23580. return MidiMessage (0xf2,
  23581. positionInMidiBeats & 127,
  23582. (positionInMidiBeats >> 7) & 127);
  23583. }
  23584. bool MidiMessage::isMidiStart() const throw()
  23585. {
  23586. return *data == 0xfa;
  23587. }
  23588. const MidiMessage MidiMessage::midiStart() throw()
  23589. {
  23590. return MidiMessage (0xfa);
  23591. }
  23592. bool MidiMessage::isMidiContinue() const throw()
  23593. {
  23594. return *data == 0xfb;
  23595. }
  23596. const MidiMessage MidiMessage::midiContinue() throw()
  23597. {
  23598. return MidiMessage (0xfb);
  23599. }
  23600. bool MidiMessage::isMidiStop() const throw()
  23601. {
  23602. return *data == 0xfc;
  23603. }
  23604. const MidiMessage MidiMessage::midiStop() throw()
  23605. {
  23606. return MidiMessage (0xfc);
  23607. }
  23608. bool MidiMessage::isMidiClock() const throw()
  23609. {
  23610. return *data == 0xf8;
  23611. }
  23612. const MidiMessage MidiMessage::midiClock() throw()
  23613. {
  23614. return MidiMessage (0xf8);
  23615. }
  23616. bool MidiMessage::isQuarterFrame() const throw()
  23617. {
  23618. return *data == 0xf1;
  23619. }
  23620. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23621. {
  23622. return ((int) data[1]) >> 4;
  23623. }
  23624. int MidiMessage::getQuarterFrameValue() const throw()
  23625. {
  23626. return ((int) data[1]) & 0x0f;
  23627. }
  23628. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23629. const int value) throw()
  23630. {
  23631. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23632. }
  23633. bool MidiMessage::isFullFrame() const throw()
  23634. {
  23635. return data[0] == 0xf0
  23636. && data[1] == 0x7f
  23637. && size >= 10
  23638. && data[3] == 0x01
  23639. && data[4] == 0x01;
  23640. }
  23641. void MidiMessage::getFullFrameParameters (int& hours,
  23642. int& minutes,
  23643. int& seconds,
  23644. int& frames,
  23645. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23646. {
  23647. jassert (isFullFrame());
  23648. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23649. hours = data[5] & 0x1f;
  23650. minutes = data[6];
  23651. seconds = data[7];
  23652. frames = data[8];
  23653. }
  23654. const MidiMessage MidiMessage::fullFrame (const int hours,
  23655. const int minutes,
  23656. const int seconds,
  23657. const int frames,
  23658. MidiMessage::SmpteTimecodeType timecodeType)
  23659. {
  23660. uint8 d[10];
  23661. d[0] = 0xf0;
  23662. d[1] = 0x7f;
  23663. d[2] = 0x7f;
  23664. d[3] = 0x01;
  23665. d[4] = 0x01;
  23666. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23667. d[6] = (uint8) minutes;
  23668. d[7] = (uint8) seconds;
  23669. d[8] = (uint8) frames;
  23670. d[9] = 0xf7;
  23671. return MidiMessage (d, 10, 0.0);
  23672. }
  23673. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23674. {
  23675. return data[0] == 0xf0
  23676. && data[1] == 0x7f
  23677. && data[3] == 0x06
  23678. && size > 5;
  23679. }
  23680. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23681. {
  23682. jassert (isMidiMachineControlMessage());
  23683. return (MidiMachineControlCommand) data[4];
  23684. }
  23685. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23686. {
  23687. uint8 d[6];
  23688. d[0] = 0xf0;
  23689. d[1] = 0x7f;
  23690. d[2] = 0x00;
  23691. d[3] = 0x06;
  23692. d[4] = (uint8) command;
  23693. d[5] = 0xf7;
  23694. return MidiMessage (d, 6, 0.0);
  23695. }
  23696. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23697. int& minutes,
  23698. int& seconds,
  23699. int& frames) const throw()
  23700. {
  23701. if (size >= 12
  23702. && data[0] == 0xf0
  23703. && data[1] == 0x7f
  23704. && data[3] == 0x06
  23705. && data[4] == 0x44
  23706. && data[5] == 0x06
  23707. && data[6] == 0x01)
  23708. {
  23709. hours = data[7] % 24; // (that some machines send out hours > 24)
  23710. minutes = data[8];
  23711. seconds = data[9];
  23712. frames = data[10];
  23713. return true;
  23714. }
  23715. return false;
  23716. }
  23717. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23718. int minutes,
  23719. int seconds,
  23720. int frames)
  23721. {
  23722. uint8 d[12];
  23723. d[0] = 0xf0;
  23724. d[1] = 0x7f;
  23725. d[2] = 0x00;
  23726. d[3] = 0x06;
  23727. d[4] = 0x44;
  23728. d[5] = 0x06;
  23729. d[6] = 0x01;
  23730. d[7] = (uint8) hours;
  23731. d[8] = (uint8) minutes;
  23732. d[9] = (uint8) seconds;
  23733. d[10] = (uint8) frames;
  23734. d[11] = 0xf7;
  23735. return MidiMessage (d, 12, 0.0);
  23736. }
  23737. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23738. {
  23739. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23740. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23741. if (((unsigned int) note) < 128)
  23742. {
  23743. String s (useSharps ? sharpNoteNames [note % 12]
  23744. : flatNoteNames [note % 12]);
  23745. if (includeOctaveNumber)
  23746. s << (note / 12 + (octaveNumForMiddleC - 5));
  23747. return s;
  23748. }
  23749. return String::empty;
  23750. }
  23751. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23752. {
  23753. noteNumber -= 12 * 6 + 9; // now 0 = A
  23754. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23755. }
  23756. const String MidiMessage::getGMInstrumentName (const int n)
  23757. {
  23758. const char* names[] =
  23759. {
  23760. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23761. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23762. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23763. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23764. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23765. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23766. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23767. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23768. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23769. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23770. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23771. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23772. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23773. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23774. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23775. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23776. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23777. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23778. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23779. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23780. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23781. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23782. "Applause", "Gunshot"
  23783. };
  23784. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23785. }
  23786. const String MidiMessage::getGMInstrumentBankName (const int n)
  23787. {
  23788. const char* names[] =
  23789. {
  23790. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23791. "Bass", "Strings", "Ensemble", "Brass",
  23792. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23793. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23794. };
  23795. return (((unsigned int) n) <= 15) ? names[n] : (const char*) 0;
  23796. }
  23797. const String MidiMessage::getRhythmInstrumentName (const int n)
  23798. {
  23799. const char* names[] =
  23800. {
  23801. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23802. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23803. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23804. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23805. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23806. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23807. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23808. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23809. "Mute Triangle", "Open Triangle"
  23810. };
  23811. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23812. }
  23813. const String MidiMessage::getControllerName (const int n)
  23814. {
  23815. const char* names[] =
  23816. {
  23817. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23818. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23819. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23820. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23821. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23822. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23823. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23824. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23825. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23826. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23827. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23828. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23829. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23830. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23831. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23832. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23833. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23834. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23835. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23837. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23838. "Poly Operation"
  23839. };
  23840. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23841. }
  23842. END_JUCE_NAMESPACE
  23843. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23844. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23845. BEGIN_JUCE_NAMESPACE
  23846. MidiMessageCollector::MidiMessageCollector()
  23847. : lastCallbackTime (0),
  23848. sampleRate (44100.0001)
  23849. {
  23850. }
  23851. MidiMessageCollector::~MidiMessageCollector()
  23852. {
  23853. }
  23854. void MidiMessageCollector::reset (const double sampleRate_)
  23855. {
  23856. jassert (sampleRate_ > 0);
  23857. const ScopedLock sl (midiCallbackLock);
  23858. sampleRate = sampleRate_;
  23859. incomingMessages.clear();
  23860. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23861. }
  23862. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23863. {
  23864. // you need to call reset() to set the correct sample rate before using this object
  23865. jassert (sampleRate != 44100.0001);
  23866. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23867. // for details of what the number should be.
  23868. jassert (message.getTimeStamp() != 0);
  23869. const ScopedLock sl (midiCallbackLock);
  23870. const int sampleNumber
  23871. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23872. incomingMessages.addEvent (message, sampleNumber);
  23873. // if the messages don't get used for over a second, we'd better
  23874. // get rid of any old ones to avoid the queue getting too big
  23875. if (sampleNumber > sampleRate)
  23876. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23877. }
  23878. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23879. const int numSamples)
  23880. {
  23881. // you need to call reset() to set the correct sample rate before using this object
  23882. jassert (sampleRate != 44100.0001);
  23883. const double timeNow = Time::getMillisecondCounterHiRes();
  23884. const double msElapsed = timeNow - lastCallbackTime;
  23885. const ScopedLock sl (midiCallbackLock);
  23886. lastCallbackTime = timeNow;
  23887. if (! incomingMessages.isEmpty())
  23888. {
  23889. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23890. int startSample = 0;
  23891. int scale = 1 << 16;
  23892. const uint8* midiData;
  23893. int numBytes, samplePosition;
  23894. MidiBuffer::Iterator iter (incomingMessages);
  23895. if (numSourceSamples > numSamples)
  23896. {
  23897. // if our list of events is longer than the buffer we're being
  23898. // asked for, scale them down to squeeze them all in..
  23899. const int maxBlockLengthToUse = numSamples << 5;
  23900. if (numSourceSamples > maxBlockLengthToUse)
  23901. {
  23902. startSample = numSourceSamples - maxBlockLengthToUse;
  23903. numSourceSamples = maxBlockLengthToUse;
  23904. iter.setNextSamplePosition (startSample);
  23905. }
  23906. scale = (numSamples << 10) / numSourceSamples;
  23907. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23908. {
  23909. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23910. destBuffer.addEvent (midiData, numBytes,
  23911. jlimit (0, numSamples - 1, samplePosition));
  23912. }
  23913. }
  23914. else
  23915. {
  23916. // if our event list is shorter than the number we need, put them
  23917. // towards the end of the buffer
  23918. startSample = numSamples - numSourceSamples;
  23919. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23920. {
  23921. destBuffer.addEvent (midiData, numBytes,
  23922. jlimit (0, numSamples - 1, samplePosition + startSample));
  23923. }
  23924. }
  23925. incomingMessages.clear();
  23926. }
  23927. }
  23928. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23929. {
  23930. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23931. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23932. addMessageToQueue (m);
  23933. }
  23934. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23935. {
  23936. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23937. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23938. addMessageToQueue (m);
  23939. }
  23940. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23941. {
  23942. addMessageToQueue (message);
  23943. }
  23944. END_JUCE_NAMESPACE
  23945. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23946. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23947. BEGIN_JUCE_NAMESPACE
  23948. MidiMessageSequence::MidiMessageSequence()
  23949. {
  23950. }
  23951. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23952. {
  23953. list.ensureStorageAllocated (other.list.size());
  23954. for (int i = 0; i < other.list.size(); ++i)
  23955. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23956. }
  23957. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23958. {
  23959. MidiMessageSequence otherCopy (other);
  23960. swapWith (otherCopy);
  23961. return *this;
  23962. }
  23963. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23964. {
  23965. list.swapWithArray (other.list);
  23966. }
  23967. MidiMessageSequence::~MidiMessageSequence()
  23968. {
  23969. }
  23970. void MidiMessageSequence::clear()
  23971. {
  23972. list.clear();
  23973. }
  23974. int MidiMessageSequence::getNumEvents() const
  23975. {
  23976. return list.size();
  23977. }
  23978. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23979. {
  23980. return list [index];
  23981. }
  23982. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23983. {
  23984. const MidiEventHolder* const meh = list [index];
  23985. if (meh != 0 && meh->noteOffObject != 0)
  23986. return meh->noteOffObject->message.getTimeStamp();
  23987. else
  23988. return 0.0;
  23989. }
  23990. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23991. {
  23992. const MidiEventHolder* const meh = list [index];
  23993. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23994. }
  23995. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23996. {
  23997. return list.indexOf (event);
  23998. }
  23999. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  24000. {
  24001. const int numEvents = list.size();
  24002. int i;
  24003. for (i = 0; i < numEvents; ++i)
  24004. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  24005. break;
  24006. return i;
  24007. }
  24008. double MidiMessageSequence::getStartTime() const
  24009. {
  24010. if (list.size() > 0)
  24011. return list.getUnchecked(0)->message.getTimeStamp();
  24012. else
  24013. return 0;
  24014. }
  24015. double MidiMessageSequence::getEndTime() const
  24016. {
  24017. if (list.size() > 0)
  24018. return list.getLast()->message.getTimeStamp();
  24019. else
  24020. return 0;
  24021. }
  24022. double MidiMessageSequence::getEventTime (const int index) const
  24023. {
  24024. if (((unsigned int) index) < (unsigned int) list.size())
  24025. return list.getUnchecked (index)->message.getTimeStamp();
  24026. return 0.0;
  24027. }
  24028. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  24029. double timeAdjustment)
  24030. {
  24031. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  24032. timeAdjustment += newMessage.getTimeStamp();
  24033. newOne->message.setTimeStamp (timeAdjustment);
  24034. int i;
  24035. for (i = list.size(); --i >= 0;)
  24036. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24037. break;
  24038. list.insert (i + 1, newOne);
  24039. }
  24040. void MidiMessageSequence::deleteEvent (const int index,
  24041. const bool deleteMatchingNoteUp)
  24042. {
  24043. if (((unsigned int) index) < (unsigned int) list.size())
  24044. {
  24045. if (deleteMatchingNoteUp)
  24046. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24047. list.remove (index);
  24048. }
  24049. }
  24050. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24051. double timeAdjustment,
  24052. double firstAllowableTime,
  24053. double endOfAllowableDestTimes)
  24054. {
  24055. firstAllowableTime -= timeAdjustment;
  24056. endOfAllowableDestTimes -= timeAdjustment;
  24057. for (int i = 0; i < other.list.size(); ++i)
  24058. {
  24059. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24060. const double t = m.getTimeStamp();
  24061. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24062. {
  24063. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24064. newOne->message.setTimeStamp (timeAdjustment + t);
  24065. list.add (newOne);
  24066. }
  24067. }
  24068. sort();
  24069. }
  24070. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24071. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24072. {
  24073. const double diff = first->message.getTimeStamp()
  24074. - second->message.getTimeStamp();
  24075. return (diff > 0) - (diff < 0);
  24076. }
  24077. void MidiMessageSequence::sort()
  24078. {
  24079. list.sort (*this, true);
  24080. }
  24081. void MidiMessageSequence::updateMatchedPairs()
  24082. {
  24083. for (int i = 0; i < list.size(); ++i)
  24084. {
  24085. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24086. if (m1.isNoteOn())
  24087. {
  24088. list.getUnchecked(i)->noteOffObject = 0;
  24089. const int note = m1.getNoteNumber();
  24090. const int chan = m1.getChannel();
  24091. const int len = list.size();
  24092. for (int j = i + 1; j < len; ++j)
  24093. {
  24094. const MidiMessage& m = list.getUnchecked(j)->message;
  24095. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24096. {
  24097. if (m.isNoteOff())
  24098. {
  24099. list.getUnchecked(i)->noteOffObject = list[j];
  24100. break;
  24101. }
  24102. else if (m.isNoteOn())
  24103. {
  24104. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24105. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24106. list.getUnchecked(i)->noteOffObject = list[j];
  24107. break;
  24108. }
  24109. }
  24110. }
  24111. }
  24112. }
  24113. }
  24114. void MidiMessageSequence::addTimeToMessages (const double delta)
  24115. {
  24116. for (int i = list.size(); --i >= 0;)
  24117. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24118. + delta);
  24119. }
  24120. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24121. MidiMessageSequence& destSequence,
  24122. const bool alsoIncludeMetaEvents) const
  24123. {
  24124. for (int i = 0; i < list.size(); ++i)
  24125. {
  24126. const MidiMessage& mm = list.getUnchecked(i)->message;
  24127. if (mm.isForChannel (channelNumberToExtract)
  24128. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24129. {
  24130. destSequence.addEvent (mm);
  24131. }
  24132. }
  24133. }
  24134. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24135. {
  24136. for (int i = 0; i < list.size(); ++i)
  24137. {
  24138. const MidiMessage& mm = list.getUnchecked(i)->message;
  24139. if (mm.isSysEx())
  24140. destSequence.addEvent (mm);
  24141. }
  24142. }
  24143. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24144. {
  24145. for (int i = list.size(); --i >= 0;)
  24146. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24147. list.remove(i);
  24148. }
  24149. void MidiMessageSequence::deleteSysExMessages()
  24150. {
  24151. for (int i = list.size(); --i >= 0;)
  24152. if (list.getUnchecked(i)->message.isSysEx())
  24153. list.remove(i);
  24154. }
  24155. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24156. const double time,
  24157. OwnedArray<MidiMessage>& dest)
  24158. {
  24159. bool doneProg = false;
  24160. bool donePitchWheel = false;
  24161. Array <int> doneControllers;
  24162. doneControllers.ensureStorageAllocated (32);
  24163. for (int i = list.size(); --i >= 0;)
  24164. {
  24165. const MidiMessage& mm = list.getUnchecked(i)->message;
  24166. if (mm.isForChannel (channelNumber)
  24167. && mm.getTimeStamp() <= time)
  24168. {
  24169. if (mm.isProgramChange())
  24170. {
  24171. if (! doneProg)
  24172. {
  24173. dest.add (new MidiMessage (mm, 0.0));
  24174. doneProg = true;
  24175. }
  24176. }
  24177. else if (mm.isController())
  24178. {
  24179. if (! doneControllers.contains (mm.getControllerNumber()))
  24180. {
  24181. dest.add (new MidiMessage (mm, 0.0));
  24182. doneControllers.add (mm.getControllerNumber());
  24183. }
  24184. }
  24185. else if (mm.isPitchWheel())
  24186. {
  24187. if (! donePitchWheel)
  24188. {
  24189. dest.add (new MidiMessage (mm, 0.0));
  24190. donePitchWheel = true;
  24191. }
  24192. }
  24193. }
  24194. }
  24195. }
  24196. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24197. : message (message_),
  24198. noteOffObject (0)
  24199. {
  24200. }
  24201. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24202. {
  24203. }
  24204. END_JUCE_NAMESPACE
  24205. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24206. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24207. BEGIN_JUCE_NAMESPACE
  24208. AudioPluginFormat::AudioPluginFormat() throw()
  24209. {
  24210. }
  24211. AudioPluginFormat::~AudioPluginFormat()
  24212. {
  24213. }
  24214. END_JUCE_NAMESPACE
  24215. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24216. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24217. BEGIN_JUCE_NAMESPACE
  24218. AudioPluginFormatManager::AudioPluginFormatManager()
  24219. {
  24220. }
  24221. AudioPluginFormatManager::~AudioPluginFormatManager()
  24222. {
  24223. clearSingletonInstance();
  24224. }
  24225. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24226. void AudioPluginFormatManager::addDefaultFormats()
  24227. {
  24228. #if JUCE_DEBUG
  24229. // you should only call this method once!
  24230. for (int i = formats.size(); --i >= 0;)
  24231. {
  24232. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24233. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24234. #endif
  24235. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24236. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24237. #endif
  24238. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24239. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24240. #endif
  24241. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24242. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24243. #endif
  24244. }
  24245. #endif
  24246. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24247. formats.add (new AudioUnitPluginFormat());
  24248. #endif
  24249. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24250. formats.add (new VSTPluginFormat());
  24251. #endif
  24252. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24253. formats.add (new DirectXPluginFormat());
  24254. #endif
  24255. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24256. formats.add (new LADSPAPluginFormat());
  24257. #endif
  24258. }
  24259. int AudioPluginFormatManager::getNumFormats()
  24260. {
  24261. return formats.size();
  24262. }
  24263. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24264. {
  24265. return formats [index];
  24266. }
  24267. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24268. {
  24269. formats.add (format);
  24270. }
  24271. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24272. String& errorMessage) const
  24273. {
  24274. AudioPluginInstance* result = 0;
  24275. for (int i = 0; i < formats.size(); ++i)
  24276. {
  24277. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24278. if (result != 0)
  24279. break;
  24280. }
  24281. if (result == 0)
  24282. {
  24283. if (! doesPluginStillExist (description))
  24284. errorMessage = TRANS ("This plug-in file no longer exists");
  24285. else
  24286. errorMessage = TRANS ("This plug-in failed to load correctly");
  24287. }
  24288. return result;
  24289. }
  24290. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24291. {
  24292. for (int i = 0; i < formats.size(); ++i)
  24293. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24294. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24295. return false;
  24296. }
  24297. END_JUCE_NAMESPACE
  24298. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24299. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24300. #define JUCE_PLUGIN_HOST 1
  24301. BEGIN_JUCE_NAMESPACE
  24302. AudioPluginInstance::AudioPluginInstance()
  24303. {
  24304. }
  24305. AudioPluginInstance::~AudioPluginInstance()
  24306. {
  24307. }
  24308. END_JUCE_NAMESPACE
  24309. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24310. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24311. BEGIN_JUCE_NAMESPACE
  24312. KnownPluginList::KnownPluginList()
  24313. {
  24314. }
  24315. KnownPluginList::~KnownPluginList()
  24316. {
  24317. }
  24318. void KnownPluginList::clear()
  24319. {
  24320. if (types.size() > 0)
  24321. {
  24322. types.clear();
  24323. sendChangeMessage (this);
  24324. }
  24325. }
  24326. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24327. {
  24328. for (int i = 0; i < types.size(); ++i)
  24329. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24330. return types.getUnchecked(i);
  24331. return 0;
  24332. }
  24333. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24334. {
  24335. for (int i = 0; i < types.size(); ++i)
  24336. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24337. return types.getUnchecked(i);
  24338. return 0;
  24339. }
  24340. bool KnownPluginList::addType (const PluginDescription& type)
  24341. {
  24342. for (int i = types.size(); --i >= 0;)
  24343. {
  24344. if (types.getUnchecked(i)->isDuplicateOf (type))
  24345. {
  24346. // strange - found a duplicate plugin with different info..
  24347. jassert (types.getUnchecked(i)->name == type.name);
  24348. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24349. *types.getUnchecked(i) = type;
  24350. return false;
  24351. }
  24352. }
  24353. types.add (new PluginDescription (type));
  24354. sendChangeMessage (this);
  24355. return true;
  24356. }
  24357. void KnownPluginList::removeType (const int index)
  24358. {
  24359. types.remove (index);
  24360. sendChangeMessage (this);
  24361. }
  24362. static const Time getPluginFileModTime (const String& fileOrIdentifier)
  24363. {
  24364. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24365. return File (fileOrIdentifier).getLastModificationTime();
  24366. return Time (0);
  24367. }
  24368. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24369. {
  24370. return t1 != t2 || t1 == Time (0);
  24371. }
  24372. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24373. {
  24374. if (getTypeForFile (fileOrIdentifier) == 0)
  24375. return false;
  24376. for (int i = types.size(); --i >= 0;)
  24377. {
  24378. const PluginDescription* const d = types.getUnchecked(i);
  24379. if (d->fileOrIdentifier == fileOrIdentifier
  24380. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24381. {
  24382. return false;
  24383. }
  24384. }
  24385. return true;
  24386. }
  24387. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24388. const bool dontRescanIfAlreadyInList,
  24389. OwnedArray <PluginDescription>& typesFound,
  24390. AudioPluginFormat& format)
  24391. {
  24392. bool addedOne = false;
  24393. if (dontRescanIfAlreadyInList
  24394. && getTypeForFile (fileOrIdentifier) != 0)
  24395. {
  24396. bool needsRescanning = false;
  24397. for (int i = types.size(); --i >= 0;)
  24398. {
  24399. const PluginDescription* const d = types.getUnchecked(i);
  24400. if (d->fileOrIdentifier == fileOrIdentifier)
  24401. {
  24402. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24403. needsRescanning = true;
  24404. else
  24405. typesFound.add (new PluginDescription (*d));
  24406. }
  24407. }
  24408. if (! needsRescanning)
  24409. return false;
  24410. }
  24411. OwnedArray <PluginDescription> found;
  24412. format.findAllTypesForFile (found, fileOrIdentifier);
  24413. for (int i = 0; i < found.size(); ++i)
  24414. {
  24415. PluginDescription* const desc = found.getUnchecked(i);
  24416. jassert (desc != 0);
  24417. if (addType (*desc))
  24418. addedOne = true;
  24419. typesFound.add (new PluginDescription (*desc));
  24420. }
  24421. return addedOne;
  24422. }
  24423. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24424. OwnedArray <PluginDescription>& typesFound)
  24425. {
  24426. for (int i = 0; i < files.size(); ++i)
  24427. {
  24428. bool loaded = false;
  24429. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24430. {
  24431. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24432. if (scanAndAddFile (files[i], true, typesFound, *format))
  24433. loaded = true;
  24434. }
  24435. if (! loaded)
  24436. {
  24437. const File f (files[i]);
  24438. if (f.isDirectory())
  24439. {
  24440. StringArray s;
  24441. {
  24442. Array<File> subFiles;
  24443. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24444. for (int j = 0; j < subFiles.size(); ++j)
  24445. s.add (subFiles.getReference(j).getFullPathName());
  24446. }
  24447. scanAndAddDragAndDroppedFiles (s, typesFound);
  24448. }
  24449. }
  24450. }
  24451. }
  24452. class PluginSorter
  24453. {
  24454. public:
  24455. KnownPluginList::SortMethod method;
  24456. PluginSorter() throw() {}
  24457. int compareElements (const PluginDescription* const first,
  24458. const PluginDescription* const second) const
  24459. {
  24460. int diff = 0;
  24461. if (method == KnownPluginList::sortByCategory)
  24462. diff = first->category.compareLexicographically (second->category);
  24463. else if (method == KnownPluginList::sortByManufacturer)
  24464. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24465. else if (method == KnownPluginList::sortByFileSystemLocation)
  24466. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24467. .upToLastOccurrenceOf ("/", false, false)
  24468. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24469. .upToLastOccurrenceOf ("/", false, false));
  24470. if (diff == 0)
  24471. diff = first->name.compareLexicographically (second->name);
  24472. return diff;
  24473. }
  24474. };
  24475. void KnownPluginList::sort (const SortMethod method)
  24476. {
  24477. if (method != defaultOrder)
  24478. {
  24479. PluginSorter sorter;
  24480. sorter.method = method;
  24481. types.sort (sorter, true);
  24482. sendChangeMessage (this);
  24483. }
  24484. }
  24485. XmlElement* KnownPluginList::createXml() const
  24486. {
  24487. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24488. for (int i = 0; i < types.size(); ++i)
  24489. e->addChildElement (types.getUnchecked(i)->createXml());
  24490. return e;
  24491. }
  24492. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24493. {
  24494. clear();
  24495. if (xml.hasTagName ("KNOWNPLUGINS"))
  24496. {
  24497. forEachXmlChildElement (xml, e)
  24498. {
  24499. PluginDescription info;
  24500. if (info.loadFromXml (*e))
  24501. addType (info);
  24502. }
  24503. }
  24504. }
  24505. const int menuIdBase = 0x324503f4;
  24506. // This is used to turn a bunch of paths into a nested menu structure.
  24507. struct PluginFilesystemTree
  24508. {
  24509. private:
  24510. String folder;
  24511. OwnedArray <PluginFilesystemTree> subFolders;
  24512. Array <PluginDescription*> plugins;
  24513. void addPlugin (PluginDescription* const pd, const String& path)
  24514. {
  24515. if (path.isEmpty())
  24516. {
  24517. plugins.add (pd);
  24518. }
  24519. else
  24520. {
  24521. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24522. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24523. for (int i = subFolders.size(); --i >= 0;)
  24524. {
  24525. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24526. {
  24527. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24528. return;
  24529. }
  24530. }
  24531. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24532. newFolder->folder = firstSubFolder;
  24533. subFolders.add (newFolder);
  24534. newFolder->addPlugin (pd, remainingPath);
  24535. }
  24536. }
  24537. // removes any deeply nested folders that don't contain any actual plugins
  24538. void optimise()
  24539. {
  24540. for (int i = subFolders.size(); --i >= 0;)
  24541. {
  24542. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24543. sub->optimise();
  24544. if (sub->plugins.size() == 0)
  24545. {
  24546. for (int j = 0; j < sub->subFolders.size(); ++j)
  24547. subFolders.add (sub->subFolders.getUnchecked(j));
  24548. sub->subFolders.clear (false);
  24549. subFolders.remove (i);
  24550. }
  24551. }
  24552. }
  24553. public:
  24554. void buildTree (const Array <PluginDescription*>& allPlugins)
  24555. {
  24556. for (int i = 0; i < allPlugins.size(); ++i)
  24557. {
  24558. String path (allPlugins.getUnchecked(i)
  24559. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24560. .upToLastOccurrenceOf ("/", false, false));
  24561. if (path.substring (1, 2) == ":")
  24562. path = path.substring (2);
  24563. addPlugin (allPlugins.getUnchecked(i), path);
  24564. }
  24565. optimise();
  24566. }
  24567. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24568. {
  24569. int i;
  24570. for (i = 0; i < subFolders.size(); ++i)
  24571. {
  24572. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24573. PopupMenu subMenu;
  24574. sub->addToMenu (subMenu, allPlugins);
  24575. #if JUCE_MAC
  24576. // avoid the special AU formatting nonsense on Mac..
  24577. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24578. #else
  24579. m.addSubMenu (sub->folder, subMenu);
  24580. #endif
  24581. }
  24582. for (i = 0; i < plugins.size(); ++i)
  24583. {
  24584. PluginDescription* const plugin = plugins.getUnchecked(i);
  24585. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24586. plugin->name, true, false);
  24587. }
  24588. }
  24589. };
  24590. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24591. {
  24592. Array <PluginDescription*> sorted;
  24593. {
  24594. PluginSorter sorter;
  24595. sorter.method = sortMethod;
  24596. for (int i = 0; i < types.size(); ++i)
  24597. sorted.addSorted (sorter, types.getUnchecked(i));
  24598. }
  24599. if (sortMethod == sortByCategory
  24600. || sortMethod == sortByManufacturer)
  24601. {
  24602. String lastSubMenuName;
  24603. PopupMenu sub;
  24604. for (int i = 0; i < sorted.size(); ++i)
  24605. {
  24606. const PluginDescription* const pd = sorted.getUnchecked(i);
  24607. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24608. : pd->manufacturerName);
  24609. if (! thisSubMenuName.containsNonWhitespaceChars())
  24610. thisSubMenuName = "Other";
  24611. if (thisSubMenuName != lastSubMenuName)
  24612. {
  24613. if (sub.getNumItems() > 0)
  24614. {
  24615. menu.addSubMenu (lastSubMenuName, sub);
  24616. sub.clear();
  24617. }
  24618. lastSubMenuName = thisSubMenuName;
  24619. }
  24620. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24621. }
  24622. if (sub.getNumItems() > 0)
  24623. menu.addSubMenu (lastSubMenuName, sub);
  24624. }
  24625. else if (sortMethod == sortByFileSystemLocation)
  24626. {
  24627. PluginFilesystemTree root;
  24628. root.buildTree (sorted);
  24629. root.addToMenu (menu, types);
  24630. }
  24631. else
  24632. {
  24633. for (int i = 0; i < sorted.size(); ++i)
  24634. {
  24635. const PluginDescription* const pd = sorted.getUnchecked(i);
  24636. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24637. }
  24638. }
  24639. }
  24640. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24641. {
  24642. const int i = menuResultCode - menuIdBase;
  24643. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  24644. }
  24645. END_JUCE_NAMESPACE
  24646. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24647. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24648. BEGIN_JUCE_NAMESPACE
  24649. PluginDescription::PluginDescription()
  24650. : uid (0),
  24651. isInstrument (false),
  24652. numInputChannels (0),
  24653. numOutputChannels (0)
  24654. {
  24655. }
  24656. PluginDescription::~PluginDescription()
  24657. {
  24658. }
  24659. PluginDescription::PluginDescription (const PluginDescription& other)
  24660. : name (other.name),
  24661. pluginFormatName (other.pluginFormatName),
  24662. category (other.category),
  24663. manufacturerName (other.manufacturerName),
  24664. version (other.version),
  24665. fileOrIdentifier (other.fileOrIdentifier),
  24666. lastFileModTime (other.lastFileModTime),
  24667. uid (other.uid),
  24668. isInstrument (other.isInstrument),
  24669. numInputChannels (other.numInputChannels),
  24670. numOutputChannels (other.numOutputChannels)
  24671. {
  24672. }
  24673. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24674. {
  24675. name = other.name;
  24676. pluginFormatName = other.pluginFormatName;
  24677. category = other.category;
  24678. manufacturerName = other.manufacturerName;
  24679. version = other.version;
  24680. fileOrIdentifier = other.fileOrIdentifier;
  24681. uid = other.uid;
  24682. isInstrument = other.isInstrument;
  24683. lastFileModTime = other.lastFileModTime;
  24684. numInputChannels = other.numInputChannels;
  24685. numOutputChannels = other.numOutputChannels;
  24686. return *this;
  24687. }
  24688. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24689. {
  24690. return fileOrIdentifier == other.fileOrIdentifier
  24691. && uid == other.uid;
  24692. }
  24693. const String PluginDescription::createIdentifierString() const
  24694. {
  24695. return pluginFormatName
  24696. + "-" + name
  24697. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24698. + "-" + String::toHexString (uid);
  24699. }
  24700. XmlElement* PluginDescription::createXml() const
  24701. {
  24702. XmlElement* const e = new XmlElement ("PLUGIN");
  24703. e->setAttribute ("name", name);
  24704. e->setAttribute ("format", pluginFormatName);
  24705. e->setAttribute ("category", category);
  24706. e->setAttribute ("manufacturer", manufacturerName);
  24707. e->setAttribute ("version", version);
  24708. e->setAttribute ("file", fileOrIdentifier);
  24709. e->setAttribute ("uid", String::toHexString (uid));
  24710. e->setAttribute ("isInstrument", isInstrument);
  24711. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24712. e->setAttribute ("numInputs", numInputChannels);
  24713. e->setAttribute ("numOutputs", numOutputChannels);
  24714. return e;
  24715. }
  24716. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24717. {
  24718. if (xml.hasTagName ("PLUGIN"))
  24719. {
  24720. name = xml.getStringAttribute ("name");
  24721. pluginFormatName = xml.getStringAttribute ("format");
  24722. category = xml.getStringAttribute ("category");
  24723. manufacturerName = xml.getStringAttribute ("manufacturer");
  24724. version = xml.getStringAttribute ("version");
  24725. fileOrIdentifier = xml.getStringAttribute ("file");
  24726. uid = xml.getStringAttribute ("uid").getHexValue32();
  24727. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24728. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24729. numInputChannels = xml.getIntAttribute ("numInputs");
  24730. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24731. return true;
  24732. }
  24733. return false;
  24734. }
  24735. END_JUCE_NAMESPACE
  24736. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24737. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24738. BEGIN_JUCE_NAMESPACE
  24739. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24740. AudioPluginFormat& formatToLookFor,
  24741. FileSearchPath directoriesToSearch,
  24742. const bool recursive,
  24743. const File& deadMansPedalFile_)
  24744. : list (listToAddTo),
  24745. format (formatToLookFor),
  24746. deadMansPedalFile (deadMansPedalFile_),
  24747. nextIndex (0),
  24748. progress (0)
  24749. {
  24750. directoriesToSearch.removeRedundantPaths();
  24751. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24752. // If any plugins have crashed recently when being loaded, move them to the
  24753. // end of the list to give the others a chance to load correctly..
  24754. const StringArray crashedPlugins (getDeadMansPedalFile());
  24755. for (int i = 0; i < crashedPlugins.size(); ++i)
  24756. {
  24757. const String f = crashedPlugins[i];
  24758. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24759. if (f == filesOrIdentifiersToScan[j])
  24760. filesOrIdentifiersToScan.move (j, -1);
  24761. }
  24762. }
  24763. PluginDirectoryScanner::~PluginDirectoryScanner()
  24764. {
  24765. }
  24766. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24767. {
  24768. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24769. }
  24770. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24771. {
  24772. String file (filesOrIdentifiersToScan [nextIndex]);
  24773. if (file.isNotEmpty())
  24774. {
  24775. if (! list.isListingUpToDate (file))
  24776. {
  24777. OwnedArray <PluginDescription> typesFound;
  24778. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24779. StringArray crashedPlugins (getDeadMansPedalFile());
  24780. crashedPlugins.removeString (file);
  24781. crashedPlugins.add (file);
  24782. setDeadMansPedalFile (crashedPlugins);
  24783. list.scanAndAddFile (file,
  24784. dontRescanIfAlreadyInList,
  24785. typesFound,
  24786. format);
  24787. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24788. crashedPlugins.removeString (file);
  24789. setDeadMansPedalFile (crashedPlugins);
  24790. if (typesFound.size() == 0)
  24791. failedFiles.add (file);
  24792. }
  24793. ++nextIndex;
  24794. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  24795. }
  24796. return nextIndex < filesOrIdentifiersToScan.size();
  24797. }
  24798. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24799. {
  24800. StringArray lines;
  24801. if (deadMansPedalFile != File::nonexistent)
  24802. {
  24803. lines.addLines (deadMansPedalFile.loadFileAsString());
  24804. lines.removeEmptyStrings();
  24805. }
  24806. return lines;
  24807. }
  24808. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24809. {
  24810. if (deadMansPedalFile != File::nonexistent)
  24811. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24812. }
  24813. END_JUCE_NAMESPACE
  24814. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24815. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24816. BEGIN_JUCE_NAMESPACE
  24817. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24818. const File& deadMansPedalFile_,
  24819. PropertiesFile* const propertiesToUse_)
  24820. : list (listToEdit),
  24821. deadMansPedalFile (deadMansPedalFile_),
  24822. propertiesToUse (propertiesToUse_)
  24823. {
  24824. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  24825. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  24826. optionsButton->addButtonListener (this);
  24827. optionsButton->setTriggeredOnMouseDown (true);
  24828. setSize (400, 600);
  24829. list.addChangeListener (this);
  24830. changeListenerCallback (0);
  24831. }
  24832. PluginListComponent::~PluginListComponent()
  24833. {
  24834. list.removeChangeListener (this);
  24835. deleteAllChildren();
  24836. }
  24837. void PluginListComponent::resized()
  24838. {
  24839. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  24840. optionsButton->changeWidthToFitText (24);
  24841. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  24842. }
  24843. void PluginListComponent::changeListenerCallback (void*)
  24844. {
  24845. listBox->updateContent();
  24846. listBox->repaint();
  24847. }
  24848. int PluginListComponent::getNumRows()
  24849. {
  24850. return list.getNumTypes();
  24851. }
  24852. void PluginListComponent::paintListBoxItem (int row,
  24853. Graphics& g,
  24854. int width, int height,
  24855. bool rowIsSelected)
  24856. {
  24857. if (rowIsSelected)
  24858. g.fillAll (findColour (TextEditor::highlightColourId));
  24859. const PluginDescription* const pd = list.getType (row);
  24860. if (pd != 0)
  24861. {
  24862. GlyphArrangement ga;
  24863. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24864. g.setColour (Colours::black);
  24865. ga.draw (g);
  24866. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24867. String desc;
  24868. desc << pd->pluginFormatName
  24869. << (pd->isInstrument ? " instrument" : " effect")
  24870. << " - "
  24871. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24872. << " / "
  24873. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24874. if (pd->manufacturerName.isNotEmpty())
  24875. desc << " - " << pd->manufacturerName;
  24876. if (pd->version.isNotEmpty())
  24877. desc << " - " << pd->version;
  24878. if (pd->category.isNotEmpty())
  24879. desc << " - category: '" << pd->category << '\'';
  24880. g.setColour (Colours::grey);
  24881. ga.clear();
  24882. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24883. ga.draw (g);
  24884. }
  24885. }
  24886. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24887. {
  24888. list.removeType (lastRowSelected);
  24889. }
  24890. void PluginListComponent::buttonClicked (Button* b)
  24891. {
  24892. if (optionsButton == b)
  24893. {
  24894. PopupMenu menu;
  24895. menu.addItem (1, TRANS("Clear list"));
  24896. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24897. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24898. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24899. menu.addSeparator();
  24900. menu.addItem (2, TRANS("Sort alphabetically"));
  24901. menu.addItem (3, TRANS("Sort by category"));
  24902. menu.addItem (4, TRANS("Sort by manufacturer"));
  24903. menu.addSeparator();
  24904. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24905. {
  24906. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24907. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24908. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24909. }
  24910. const int r = menu.showAt (optionsButton);
  24911. if (r == 1)
  24912. {
  24913. list.clear();
  24914. }
  24915. else if (r == 2)
  24916. {
  24917. list.sort (KnownPluginList::sortAlphabetically);
  24918. }
  24919. else if (r == 3)
  24920. {
  24921. list.sort (KnownPluginList::sortByCategory);
  24922. }
  24923. else if (r == 4)
  24924. {
  24925. list.sort (KnownPluginList::sortByManufacturer);
  24926. }
  24927. else if (r == 5)
  24928. {
  24929. const SparseSet <int> selected (listBox->getSelectedRows());
  24930. for (int i = list.getNumTypes(); --i >= 0;)
  24931. if (selected.contains (i))
  24932. list.removeType (i);
  24933. }
  24934. else if (r == 6)
  24935. {
  24936. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24937. if (desc != 0)
  24938. {
  24939. if (File (desc->fileOrIdentifier).existsAsFile())
  24940. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24941. }
  24942. }
  24943. else if (r == 7)
  24944. {
  24945. for (int i = list.getNumTypes(); --i >= 0;)
  24946. {
  24947. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24948. {
  24949. list.removeType (i);
  24950. }
  24951. }
  24952. }
  24953. else if (r != 0)
  24954. {
  24955. typeToScan = r - 10;
  24956. startTimer (1);
  24957. }
  24958. }
  24959. }
  24960. void PluginListComponent::timerCallback()
  24961. {
  24962. stopTimer();
  24963. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24964. }
  24965. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24966. {
  24967. return true;
  24968. }
  24969. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24970. {
  24971. OwnedArray <PluginDescription> typesFound;
  24972. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24973. }
  24974. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24975. {
  24976. if (format == 0)
  24977. return;
  24978. FileSearchPath path (format->getDefaultLocationsToSearch());
  24979. if (propertiesToUse != 0)
  24980. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24981. {
  24982. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24983. FileSearchPathListComponent pathList;
  24984. pathList.setSize (500, 300);
  24985. pathList.setPath (path);
  24986. aw.addCustomComponent (&pathList);
  24987. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24988. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24989. if (aw.runModalLoop() == 0)
  24990. return;
  24991. path = pathList.getPath();
  24992. }
  24993. if (propertiesToUse != 0)
  24994. {
  24995. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24996. propertiesToUse->saveIfNeeded();
  24997. }
  24998. double progress = 0.0;
  24999. AlertWindow aw (TRANS("Scanning for plugins..."),
  25000. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  25001. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25002. aw.addProgressBarComponent (progress);
  25003. aw.enterModalState();
  25004. MessageManager::getInstance()->runDispatchLoopUntil (300);
  25005. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  25006. for (;;)
  25007. {
  25008. aw.setMessage (TRANS("Testing:\n\n")
  25009. + scanner.getNextPluginFileThatWillBeScanned());
  25010. MessageManager::getInstance()->runDispatchLoopUntil (20);
  25011. if (! scanner.scanNextFile (true))
  25012. break;
  25013. if (! aw.isCurrentlyModal())
  25014. break;
  25015. progress = scanner.getProgress();
  25016. }
  25017. if (scanner.getFailedFiles().size() > 0)
  25018. {
  25019. StringArray shortNames;
  25020. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25021. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25022. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25023. TRANS("Scan complete"),
  25024. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25025. + shortNames.joinIntoString (", "));
  25026. }
  25027. }
  25028. END_JUCE_NAMESPACE
  25029. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25030. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25031. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25032. #include <AudioUnit/AudioUnit.h>
  25033. #include <AudioUnit/AUCocoaUIView.h>
  25034. #include <CoreAudioKit/AUGenericView.h>
  25035. #if JUCE_SUPPORT_CARBON
  25036. #include <AudioToolbox/AudioUnitUtilities.h>
  25037. #include <AudioUnit/AudioUnitCarbonView.h>
  25038. #endif
  25039. BEGIN_JUCE_NAMESPACE
  25040. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25041. #endif
  25042. #if JUCE_MAC
  25043. // Change this to disable logging of various activities
  25044. #ifndef AU_LOGGING
  25045. #define AU_LOGGING 1
  25046. #endif
  25047. #if AU_LOGGING
  25048. #define log(a) Logger::writeToLog(a);
  25049. #else
  25050. #define log(a)
  25051. #endif
  25052. namespace AudioUnitFormatHelpers
  25053. {
  25054. static int insideCallback = 0;
  25055. static const String osTypeToString (OSType type)
  25056. {
  25057. char s[4];
  25058. s[0] = (char) (((uint32) type) >> 24);
  25059. s[1] = (char) (((uint32) type) >> 16);
  25060. s[2] = (char) (((uint32) type) >> 8);
  25061. s[3] = (char) ((uint32) type);
  25062. return String (s, 4);
  25063. }
  25064. static OSType stringToOSType (const String& s1)
  25065. {
  25066. const String s (s1 + " ");
  25067. return (((OSType) (unsigned char) s[0]) << 24)
  25068. | (((OSType) (unsigned char) s[1]) << 16)
  25069. | (((OSType) (unsigned char) s[2]) << 8)
  25070. | ((OSType) (unsigned char) s[3]);
  25071. }
  25072. static const char* auIdentifierPrefix = "AudioUnit:";
  25073. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  25074. {
  25075. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25076. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25077. String s (auIdentifierPrefix);
  25078. if (desc.componentType == kAudioUnitType_MusicDevice)
  25079. s << "Synths/";
  25080. else if (desc.componentType == kAudioUnitType_MusicEffect
  25081. || desc.componentType == kAudioUnitType_Effect)
  25082. s << "Effects/";
  25083. else if (desc.componentType == kAudioUnitType_Generator)
  25084. s << "Generators/";
  25085. else if (desc.componentType == kAudioUnitType_Panner)
  25086. s << "Panners/";
  25087. s << osTypeToString (desc.componentType) << ","
  25088. << osTypeToString (desc.componentSubType) << ","
  25089. << osTypeToString (desc.componentManufacturer);
  25090. return s;
  25091. }
  25092. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25093. {
  25094. Handle componentNameHandle = NewHandle (sizeof (void*));
  25095. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25096. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25097. {
  25098. ComponentDescription desc;
  25099. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25100. {
  25101. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25102. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25103. if (nameString != 0 && nameString[0] != 0)
  25104. {
  25105. const String all ((const char*) nameString + 1, nameString[0]);
  25106. DBG ("name: "+ all);
  25107. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25108. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25109. }
  25110. if (infoString != 0 && infoString[0] != 0)
  25111. {
  25112. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25113. }
  25114. if (name.isEmpty())
  25115. name = "<Unknown>";
  25116. }
  25117. DisposeHandle (componentNameHandle);
  25118. DisposeHandle (componentInfoHandle);
  25119. }
  25120. }
  25121. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25122. String& name, String& version, String& manufacturer)
  25123. {
  25124. zerostruct (desc);
  25125. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25126. {
  25127. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25128. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25129. StringArray tokens;
  25130. tokens.addTokens (s, ",", String::empty);
  25131. tokens.trim();
  25132. tokens.removeEmptyStrings();
  25133. if (tokens.size() == 3)
  25134. {
  25135. desc.componentType = stringToOSType (tokens[0]);
  25136. desc.componentSubType = stringToOSType (tokens[1]);
  25137. desc.componentManufacturer = stringToOSType (tokens[2]);
  25138. ComponentRecord* comp = FindNextComponent (0, &desc);
  25139. if (comp != 0)
  25140. {
  25141. getAUDetails (comp, name, manufacturer);
  25142. return true;
  25143. }
  25144. }
  25145. }
  25146. return false;
  25147. }
  25148. }
  25149. class AudioUnitPluginWindowCarbon;
  25150. class AudioUnitPluginWindowCocoa;
  25151. class AudioUnitPluginInstance : public AudioPluginInstance
  25152. {
  25153. public:
  25154. ~AudioUnitPluginInstance();
  25155. void initialise();
  25156. // AudioPluginInstance methods:
  25157. void fillInPluginDescription (PluginDescription& desc) const
  25158. {
  25159. desc.name = pluginName;
  25160. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25161. desc.uid = ((int) componentDesc.componentType)
  25162. ^ ((int) componentDesc.componentSubType)
  25163. ^ ((int) componentDesc.componentManufacturer);
  25164. desc.lastFileModTime = 0;
  25165. desc.pluginFormatName = "AudioUnit";
  25166. desc.category = getCategory();
  25167. desc.manufacturerName = manufacturer;
  25168. desc.version = version;
  25169. desc.numInputChannels = getNumInputChannels();
  25170. desc.numOutputChannels = getNumOutputChannels();
  25171. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25172. }
  25173. const String getName() const { return pluginName; }
  25174. bool acceptsMidi() const { return wantsMidiMessages; }
  25175. bool producesMidi() const { return false; }
  25176. // AudioProcessor methods:
  25177. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25178. void releaseResources();
  25179. void processBlock (AudioSampleBuffer& buffer,
  25180. MidiBuffer& midiMessages);
  25181. bool hasEditor() const;
  25182. AudioProcessorEditor* createEditor();
  25183. const String getInputChannelName (int index) const;
  25184. bool isInputChannelStereoPair (int index) const;
  25185. const String getOutputChannelName (int index) const;
  25186. bool isOutputChannelStereoPair (int index) const;
  25187. int getNumParameters();
  25188. float getParameter (int index);
  25189. void setParameter (int index, float newValue);
  25190. const String getParameterName (int index);
  25191. const String getParameterText (int index);
  25192. bool isParameterAutomatable (int index) const;
  25193. int getNumPrograms();
  25194. int getCurrentProgram();
  25195. void setCurrentProgram (int index);
  25196. const String getProgramName (int index);
  25197. void changeProgramName (int index, const String& newName);
  25198. void getStateInformation (MemoryBlock& destData);
  25199. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25200. void setStateInformation (const void* data, int sizeInBytes);
  25201. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25202. juce_UseDebuggingNewOperator
  25203. private:
  25204. friend class AudioUnitPluginWindowCarbon;
  25205. friend class AudioUnitPluginWindowCocoa;
  25206. friend class AudioUnitPluginFormat;
  25207. ComponentDescription componentDesc;
  25208. String pluginName, manufacturer, version;
  25209. String fileOrIdentifier;
  25210. CriticalSection lock;
  25211. bool wantsMidiMessages, wasPlaying, prepared;
  25212. HeapBlock <AudioBufferList> outputBufferList;
  25213. AudioTimeStamp timeStamp;
  25214. AudioSampleBuffer* currentBuffer;
  25215. AudioUnit audioUnit;
  25216. Array <int> parameterIds;
  25217. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25218. void setPluginCallbacks();
  25219. void getParameterListFromPlugin();
  25220. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25221. const AudioTimeStamp* inTimeStamp,
  25222. UInt32 inBusNumber,
  25223. UInt32 inNumberFrames,
  25224. AudioBufferList* ioData) const;
  25225. static OSStatus renderGetInputCallback (void* inRefCon,
  25226. AudioUnitRenderActionFlags* ioActionFlags,
  25227. const AudioTimeStamp* inTimeStamp,
  25228. UInt32 inBusNumber,
  25229. UInt32 inNumberFrames,
  25230. AudioBufferList* ioData)
  25231. {
  25232. return ((AudioUnitPluginInstance*) inRefCon)
  25233. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25234. }
  25235. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25236. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25237. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25238. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25239. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25240. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25241. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25242. {
  25243. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25244. }
  25245. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25246. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25247. Float64* outCurrentMeasureDownBeat)
  25248. {
  25249. return ((AudioUnitPluginInstance*) inHostUserData)
  25250. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25251. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25252. }
  25253. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25254. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25255. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25256. {
  25257. return ((AudioUnitPluginInstance*) inHostUserData)
  25258. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25259. outCurrentSampleInTimeLine, outIsCycling,
  25260. outCycleStartBeat, outCycleEndBeat);
  25261. }
  25262. void getNumChannels (int& numIns, int& numOuts)
  25263. {
  25264. numIns = 0;
  25265. numOuts = 0;
  25266. AUChannelInfo supportedChannels [128];
  25267. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25268. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25269. 0, supportedChannels, &supportedChannelsSize) == noErr
  25270. && supportedChannelsSize > 0)
  25271. {
  25272. int explicitNumIns = 0;
  25273. int explicitNumOuts = 0;
  25274. int maximumNumIns = 0;
  25275. int maximumNumOuts = 0;
  25276. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25277. {
  25278. const int inChannels = (int) supportedChannels[i].inChannels;
  25279. const int outChannels = (int) supportedChannels[i].outChannels;
  25280. if (inChannels < 0)
  25281. maximumNumIns = jmin (maximumNumIns, inChannels);
  25282. else
  25283. explicitNumIns = jmax (explicitNumIns, inChannels);
  25284. if (outChannels < 0)
  25285. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25286. else
  25287. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25288. }
  25289. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25290. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25291. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25292. {
  25293. numIns = numOuts = 2;
  25294. }
  25295. else
  25296. {
  25297. numIns = explicitNumIns;
  25298. numOuts = explicitNumOuts;
  25299. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25300. numIns = 2;
  25301. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25302. numOuts = 2;
  25303. }
  25304. }
  25305. else
  25306. {
  25307. // (this really means the plugin will take any number of ins/outs as long
  25308. // as they are the same)
  25309. numIns = numOuts = 2;
  25310. }
  25311. }
  25312. const String getCategory() const;
  25313. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25314. };
  25315. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25316. : fileOrIdentifier (fileOrIdentifier),
  25317. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25318. audioUnit (0),
  25319. currentBuffer (0)
  25320. {
  25321. using namespace AudioUnitFormatHelpers;
  25322. try
  25323. {
  25324. ++insideCallback;
  25325. log ("Opening AU: " + fileOrIdentifier);
  25326. if (getComponentDescFromFile (fileOrIdentifier))
  25327. {
  25328. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25329. if (comp != 0)
  25330. {
  25331. audioUnit = (AudioUnit) OpenComponent (comp);
  25332. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25333. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25334. }
  25335. }
  25336. --insideCallback;
  25337. }
  25338. catch (...)
  25339. {
  25340. --insideCallback;
  25341. }
  25342. }
  25343. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25344. {
  25345. const ScopedLock sl (lock);
  25346. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25347. if (audioUnit != 0)
  25348. {
  25349. AudioUnitUninitialize (audioUnit);
  25350. CloseComponent (audioUnit);
  25351. audioUnit = 0;
  25352. }
  25353. }
  25354. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25355. {
  25356. zerostruct (componentDesc);
  25357. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25358. return true;
  25359. const File file (fileOrIdentifier);
  25360. if (! file.hasFileExtension (".component"))
  25361. return false;
  25362. const char* const utf8 = fileOrIdentifier.toUTF8();
  25363. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25364. strlen (utf8), file.isDirectory());
  25365. if (url != 0)
  25366. {
  25367. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25368. CFRelease (url);
  25369. if (bundleRef != 0)
  25370. {
  25371. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25372. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25373. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25374. if (pluginName.isEmpty())
  25375. pluginName = file.getFileNameWithoutExtension();
  25376. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25377. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25378. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25379. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25380. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25381. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25382. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25383. UseResFile (resFileId);
  25384. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25385. {
  25386. Handle h = Get1IndResource ('thng', i);
  25387. if (h != 0)
  25388. {
  25389. HLock (h);
  25390. const uint32* const types = (const uint32*) *h;
  25391. if (types[0] == kAudioUnitType_MusicDevice
  25392. || types[0] == kAudioUnitType_MusicEffect
  25393. || types[0] == kAudioUnitType_Effect
  25394. || types[0] == kAudioUnitType_Generator
  25395. || types[0] == kAudioUnitType_Panner)
  25396. {
  25397. componentDesc.componentType = types[0];
  25398. componentDesc.componentSubType = types[1];
  25399. componentDesc.componentManufacturer = types[2];
  25400. break;
  25401. }
  25402. HUnlock (h);
  25403. ReleaseResource (h);
  25404. }
  25405. }
  25406. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25407. CFRelease (bundleRef);
  25408. }
  25409. }
  25410. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25411. }
  25412. void AudioUnitPluginInstance::initialise()
  25413. {
  25414. getParameterListFromPlugin();
  25415. setPluginCallbacks();
  25416. int numIns, numOuts;
  25417. getNumChannels (numIns, numOuts);
  25418. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25419. setLatencySamples (0);
  25420. }
  25421. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25422. {
  25423. parameterIds.clear();
  25424. if (audioUnit != 0)
  25425. {
  25426. UInt32 paramListSize = 0;
  25427. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25428. 0, 0, &paramListSize);
  25429. if (paramListSize > 0)
  25430. {
  25431. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25432. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25433. 0, &parameterIds.getReference(0), &paramListSize);
  25434. }
  25435. }
  25436. }
  25437. void AudioUnitPluginInstance::setPluginCallbacks()
  25438. {
  25439. if (audioUnit != 0)
  25440. {
  25441. {
  25442. AURenderCallbackStruct info;
  25443. zerostruct (info);
  25444. info.inputProcRefCon = this;
  25445. info.inputProc = renderGetInputCallback;
  25446. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25447. 0, &info, sizeof (info));
  25448. }
  25449. {
  25450. HostCallbackInfo info;
  25451. zerostruct (info);
  25452. info.hostUserData = this;
  25453. info.beatAndTempoProc = getBeatAndTempoCallback;
  25454. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25455. info.transportStateProc = getTransportStateCallback;
  25456. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25457. 0, &info, sizeof (info));
  25458. }
  25459. }
  25460. }
  25461. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25462. int samplesPerBlockExpected)
  25463. {
  25464. if (audioUnit != 0)
  25465. {
  25466. releaseResources();
  25467. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25468. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25469. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25470. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25471. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25472. {
  25473. Float64 sr = sampleRate_;
  25474. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25475. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25476. }
  25477. int numIns, numOuts;
  25478. getNumChannels (numIns, numOuts);
  25479. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25480. Float64 latencySecs = 0.0;
  25481. UInt32 latencySize = sizeof (latencySecs);
  25482. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25483. 0, &latencySecs, &latencySize);
  25484. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25485. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25486. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25487. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25488. {
  25489. AudioStreamBasicDescription stream;
  25490. zerostruct (stream);
  25491. stream.mSampleRate = sampleRate_;
  25492. stream.mFormatID = kAudioFormatLinearPCM;
  25493. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25494. stream.mFramesPerPacket = 1;
  25495. stream.mBytesPerPacket = 4;
  25496. stream.mBytesPerFrame = 4;
  25497. stream.mBitsPerChannel = 32;
  25498. stream.mChannelsPerFrame = numIns;
  25499. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25500. 0, &stream, sizeof (stream));
  25501. stream.mChannelsPerFrame = numOuts;
  25502. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25503. 0, &stream, sizeof (stream));
  25504. }
  25505. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25506. outputBufferList->mNumberBuffers = numOuts;
  25507. for (int i = numOuts; --i >= 0;)
  25508. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25509. zerostruct (timeStamp);
  25510. timeStamp.mSampleTime = 0;
  25511. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25512. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25513. currentBuffer = 0;
  25514. wasPlaying = false;
  25515. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25516. }
  25517. }
  25518. void AudioUnitPluginInstance::releaseResources()
  25519. {
  25520. if (prepared)
  25521. {
  25522. AudioUnitUninitialize (audioUnit);
  25523. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25524. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25525. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25526. outputBufferList.free();
  25527. currentBuffer = 0;
  25528. prepared = false;
  25529. }
  25530. }
  25531. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25532. const AudioTimeStamp* inTimeStamp,
  25533. UInt32 inBusNumber,
  25534. UInt32 inNumberFrames,
  25535. AudioBufferList* ioData) const
  25536. {
  25537. if (inBusNumber == 0
  25538. && currentBuffer != 0)
  25539. {
  25540. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25541. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25542. {
  25543. if (i < currentBuffer->getNumChannels())
  25544. {
  25545. memcpy (ioData->mBuffers[i].mData,
  25546. currentBuffer->getSampleData (i, 0),
  25547. sizeof (float) * inNumberFrames);
  25548. }
  25549. else
  25550. {
  25551. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25552. }
  25553. }
  25554. }
  25555. return noErr;
  25556. }
  25557. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25558. MidiBuffer& midiMessages)
  25559. {
  25560. const int numSamples = buffer.getNumSamples();
  25561. if (prepared)
  25562. {
  25563. AudioUnitRenderActionFlags flags = 0;
  25564. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25565. for (int i = getNumOutputChannels(); --i >= 0;)
  25566. {
  25567. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25568. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25569. }
  25570. currentBuffer = &buffer;
  25571. if (wantsMidiMessages)
  25572. {
  25573. const uint8* midiEventData;
  25574. int midiEventSize, midiEventPosition;
  25575. MidiBuffer::Iterator i (midiMessages);
  25576. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25577. {
  25578. if (midiEventSize <= 3)
  25579. MusicDeviceMIDIEvent (audioUnit,
  25580. midiEventData[0], midiEventData[1], midiEventData[2],
  25581. midiEventPosition);
  25582. else
  25583. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25584. }
  25585. midiMessages.clear();
  25586. }
  25587. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25588. 0, numSamples, outputBufferList);
  25589. timeStamp.mSampleTime += numSamples;
  25590. }
  25591. else
  25592. {
  25593. // Plugin not working correctly, so just bypass..
  25594. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25595. buffer.clear (i, 0, buffer.getNumSamples());
  25596. }
  25597. }
  25598. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25599. {
  25600. AudioPlayHead* const ph = getPlayHead();
  25601. AudioPlayHead::CurrentPositionInfo result;
  25602. if (ph != 0 && ph->getCurrentPosition (result))
  25603. {
  25604. if (outCurrentBeat != 0)
  25605. *outCurrentBeat = result.ppqPosition;
  25606. if (outCurrentTempo != 0)
  25607. *outCurrentTempo = result.bpm;
  25608. }
  25609. else
  25610. {
  25611. if (outCurrentBeat != 0)
  25612. *outCurrentBeat = 0;
  25613. if (outCurrentTempo != 0)
  25614. *outCurrentTempo = 120.0;
  25615. }
  25616. return noErr;
  25617. }
  25618. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25619. Float32* outTimeSig_Numerator,
  25620. UInt32* outTimeSig_Denominator,
  25621. Float64* outCurrentMeasureDownBeat) const
  25622. {
  25623. AudioPlayHead* const ph = getPlayHead();
  25624. AudioPlayHead::CurrentPositionInfo result;
  25625. if (ph != 0 && ph->getCurrentPosition (result))
  25626. {
  25627. if (outTimeSig_Numerator != 0)
  25628. *outTimeSig_Numerator = result.timeSigNumerator;
  25629. if (outTimeSig_Denominator != 0)
  25630. *outTimeSig_Denominator = result.timeSigDenominator;
  25631. if (outDeltaSampleOffsetToNextBeat != 0)
  25632. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25633. if (outCurrentMeasureDownBeat != 0)
  25634. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25635. }
  25636. else
  25637. {
  25638. if (outDeltaSampleOffsetToNextBeat != 0)
  25639. *outDeltaSampleOffsetToNextBeat = 0;
  25640. if (outTimeSig_Numerator != 0)
  25641. *outTimeSig_Numerator = 4;
  25642. if (outTimeSig_Denominator != 0)
  25643. *outTimeSig_Denominator = 4;
  25644. if (outCurrentMeasureDownBeat != 0)
  25645. *outCurrentMeasureDownBeat = 0;
  25646. }
  25647. return noErr;
  25648. }
  25649. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25650. Boolean* outTransportStateChanged,
  25651. Float64* outCurrentSampleInTimeLine,
  25652. Boolean* outIsCycling,
  25653. Float64* outCycleStartBeat,
  25654. Float64* outCycleEndBeat)
  25655. {
  25656. AudioPlayHead* const ph = getPlayHead();
  25657. AudioPlayHead::CurrentPositionInfo result;
  25658. if (ph != 0 && ph->getCurrentPosition (result))
  25659. {
  25660. if (outIsPlaying != 0)
  25661. *outIsPlaying = result.isPlaying;
  25662. if (outTransportStateChanged != 0)
  25663. {
  25664. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25665. wasPlaying = result.isPlaying;
  25666. }
  25667. if (outCurrentSampleInTimeLine != 0)
  25668. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25669. if (outIsCycling != 0)
  25670. *outIsCycling = false;
  25671. if (outCycleStartBeat != 0)
  25672. *outCycleStartBeat = 0;
  25673. if (outCycleEndBeat != 0)
  25674. *outCycleEndBeat = 0;
  25675. }
  25676. else
  25677. {
  25678. if (outIsPlaying != 0)
  25679. *outIsPlaying = false;
  25680. if (outTransportStateChanged != 0)
  25681. *outTransportStateChanged = false;
  25682. if (outCurrentSampleInTimeLine != 0)
  25683. *outCurrentSampleInTimeLine = 0;
  25684. if (outIsCycling != 0)
  25685. *outIsCycling = false;
  25686. if (outCycleStartBeat != 0)
  25687. *outCycleStartBeat = 0;
  25688. if (outCycleEndBeat != 0)
  25689. *outCycleEndBeat = 0;
  25690. }
  25691. return noErr;
  25692. }
  25693. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  25694. {
  25695. public:
  25696. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25697. : AudioProcessorEditor (&plugin_),
  25698. plugin (plugin_)
  25699. {
  25700. addAndMakeVisible (&wrapper);
  25701. setOpaque (true);
  25702. setVisible (true);
  25703. setSize (100, 100);
  25704. createView (createGenericViewIfNeeded);
  25705. }
  25706. ~AudioUnitPluginWindowCocoa()
  25707. {
  25708. const bool wasValid = isValid();
  25709. wrapper.setView (0);
  25710. if (wasValid)
  25711. plugin.editorBeingDeleted (this);
  25712. }
  25713. bool isValid() const { return wrapper.getView() != 0; }
  25714. void paint (Graphics& g)
  25715. {
  25716. g.fillAll (Colours::white);
  25717. }
  25718. void resized()
  25719. {
  25720. wrapper.setSize (getWidth(), getHeight());
  25721. }
  25722. private:
  25723. AudioUnitPluginInstance& plugin;
  25724. NSViewComponent wrapper;
  25725. bool createView (const bool createGenericViewIfNeeded)
  25726. {
  25727. NSView* pluginView = 0;
  25728. UInt32 dataSize = 0;
  25729. Boolean isWritable = false;
  25730. AudioUnitInitialize (plugin.audioUnit);
  25731. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25732. 0, &dataSize, &isWritable) == noErr
  25733. && dataSize != 0
  25734. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25735. 0, &dataSize, &isWritable) == noErr)
  25736. {
  25737. HeapBlock <AudioUnitCocoaViewInfo> info;
  25738. info.calloc (dataSize, 1);
  25739. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25740. 0, info, &dataSize) == noErr)
  25741. {
  25742. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25743. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25744. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25745. Class viewClass = [viewBundle classNamed: viewClassName];
  25746. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25747. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25748. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25749. {
  25750. id factory = [[[viewClass alloc] init] autorelease];
  25751. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25752. withSize: NSMakeSize (getWidth(), getHeight())];
  25753. }
  25754. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25755. {
  25756. CFRelease (info->mCocoaAUViewClass[i]);
  25757. CFRelease (info->mCocoaAUViewBundleLocation);
  25758. }
  25759. }
  25760. }
  25761. if (createGenericViewIfNeeded && (pluginView == 0))
  25762. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25763. wrapper.setView (pluginView);
  25764. if (pluginView != 0)
  25765. setSize ([pluginView frame].size.width,
  25766. [pluginView frame].size.height);
  25767. return pluginView != 0;
  25768. }
  25769. };
  25770. #if JUCE_SUPPORT_CARBON
  25771. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25772. {
  25773. public:
  25774. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25775. : AudioProcessorEditor (&plugin_),
  25776. plugin (plugin_),
  25777. viewComponent (0)
  25778. {
  25779. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25780. setOpaque (true);
  25781. setVisible (true);
  25782. setSize (400, 300);
  25783. ComponentDescription viewList [16];
  25784. UInt32 viewListSize = sizeof (viewList);
  25785. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25786. 0, &viewList, &viewListSize);
  25787. componentRecord = FindNextComponent (0, &viewList[0]);
  25788. }
  25789. ~AudioUnitPluginWindowCarbon()
  25790. {
  25791. innerWrapper = 0;
  25792. if (isValid())
  25793. plugin.editorBeingDeleted (this);
  25794. }
  25795. bool isValid() const throw() { return componentRecord != 0; }
  25796. void paint (Graphics& g)
  25797. {
  25798. g.fillAll (Colours::black);
  25799. }
  25800. void resized()
  25801. {
  25802. innerWrapper->setSize (getWidth(), getHeight());
  25803. }
  25804. bool keyStateChanged (bool)
  25805. {
  25806. return false;
  25807. }
  25808. bool keyPressed (const KeyPress&)
  25809. {
  25810. return false;
  25811. }
  25812. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25813. AudioUnitCarbonView getViewComponent()
  25814. {
  25815. if (viewComponent == 0 && componentRecord != 0)
  25816. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25817. return viewComponent;
  25818. }
  25819. void closeViewComponent()
  25820. {
  25821. if (viewComponent != 0)
  25822. {
  25823. log ("Closing AU GUI: " + plugin.getName());
  25824. CloseComponent (viewComponent);
  25825. viewComponent = 0;
  25826. }
  25827. }
  25828. juce_UseDebuggingNewOperator
  25829. private:
  25830. AudioUnitPluginInstance& plugin;
  25831. ComponentRecord* componentRecord;
  25832. AudioUnitCarbonView viewComponent;
  25833. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25834. {
  25835. public:
  25836. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25837. : owner (owner_)
  25838. {
  25839. }
  25840. ~InnerWrapperComponent()
  25841. {
  25842. deleteWindow();
  25843. }
  25844. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25845. {
  25846. log ("Opening AU GUI: " + owner->plugin.getName());
  25847. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25848. if (viewComponent == 0)
  25849. return 0;
  25850. Float32Point pos = { 0, 0 };
  25851. Float32Point size = { 250, 200 };
  25852. HIViewRef pluginView = 0;
  25853. AudioUnitCarbonViewCreate (viewComponent,
  25854. owner->getAudioUnit(),
  25855. windowRef,
  25856. rootView,
  25857. &pos,
  25858. &size,
  25859. (ControlRef*) &pluginView);
  25860. return pluginView;
  25861. }
  25862. void removeView (HIViewRef)
  25863. {
  25864. owner->closeViewComponent();
  25865. }
  25866. private:
  25867. AudioUnitPluginWindowCarbon* const owner;
  25868. };
  25869. friend class InnerWrapperComponent;
  25870. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25871. };
  25872. #endif
  25873. bool AudioUnitPluginInstance::hasEditor() const
  25874. {
  25875. return true;
  25876. }
  25877. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25878. {
  25879. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25880. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25881. w = 0;
  25882. #if JUCE_SUPPORT_CARBON
  25883. if (w == 0)
  25884. {
  25885. w = new AudioUnitPluginWindowCarbon (*this);
  25886. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25887. w = 0;
  25888. }
  25889. #endif
  25890. if (w == 0)
  25891. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25892. return w.release();
  25893. }
  25894. const String AudioUnitPluginInstance::getCategory() const
  25895. {
  25896. const char* result = 0;
  25897. switch (componentDesc.componentType)
  25898. {
  25899. case kAudioUnitType_Effect:
  25900. case kAudioUnitType_MusicEffect:
  25901. result = "Effect";
  25902. break;
  25903. case kAudioUnitType_MusicDevice:
  25904. result = "Synth";
  25905. break;
  25906. case kAudioUnitType_Generator:
  25907. result = "Generator";
  25908. break;
  25909. case kAudioUnitType_Panner:
  25910. result = "Panner";
  25911. break;
  25912. default:
  25913. break;
  25914. }
  25915. return result;
  25916. }
  25917. int AudioUnitPluginInstance::getNumParameters()
  25918. {
  25919. return parameterIds.size();
  25920. }
  25921. float AudioUnitPluginInstance::getParameter (int index)
  25922. {
  25923. const ScopedLock sl (lock);
  25924. Float32 value = 0.0f;
  25925. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25926. {
  25927. AudioUnitGetParameter (audioUnit,
  25928. (UInt32) parameterIds.getUnchecked (index),
  25929. kAudioUnitScope_Global, 0,
  25930. &value);
  25931. }
  25932. return value;
  25933. }
  25934. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25935. {
  25936. const ScopedLock sl (lock);
  25937. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25938. {
  25939. AudioUnitSetParameter (audioUnit,
  25940. (UInt32) parameterIds.getUnchecked (index),
  25941. kAudioUnitScope_Global, 0,
  25942. newValue, 0);
  25943. }
  25944. }
  25945. const String AudioUnitPluginInstance::getParameterName (int index)
  25946. {
  25947. AudioUnitParameterInfo info;
  25948. zerostruct (info);
  25949. UInt32 sz = sizeof (info);
  25950. String name;
  25951. if (AudioUnitGetProperty (audioUnit,
  25952. kAudioUnitProperty_ParameterInfo,
  25953. kAudioUnitScope_Global,
  25954. parameterIds [index], &info, &sz) == noErr)
  25955. {
  25956. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25957. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25958. else
  25959. name = String (info.name, sizeof (info.name));
  25960. }
  25961. return name;
  25962. }
  25963. const String AudioUnitPluginInstance::getParameterText (int index)
  25964. {
  25965. return String (getParameter (index));
  25966. }
  25967. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25968. {
  25969. AudioUnitParameterInfo info;
  25970. UInt32 sz = sizeof (info);
  25971. if (AudioUnitGetProperty (audioUnit,
  25972. kAudioUnitProperty_ParameterInfo,
  25973. kAudioUnitScope_Global,
  25974. parameterIds [index], &info, &sz) == noErr)
  25975. {
  25976. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25977. }
  25978. return true;
  25979. }
  25980. int AudioUnitPluginInstance::getNumPrograms()
  25981. {
  25982. CFArrayRef presets;
  25983. UInt32 sz = sizeof (CFArrayRef);
  25984. int num = 0;
  25985. if (AudioUnitGetProperty (audioUnit,
  25986. kAudioUnitProperty_FactoryPresets,
  25987. kAudioUnitScope_Global,
  25988. 0, &presets, &sz) == noErr)
  25989. {
  25990. num = (int) CFArrayGetCount (presets);
  25991. CFRelease (presets);
  25992. }
  25993. return num;
  25994. }
  25995. int AudioUnitPluginInstance::getCurrentProgram()
  25996. {
  25997. AUPreset current;
  25998. current.presetNumber = 0;
  25999. UInt32 sz = sizeof (AUPreset);
  26000. AudioUnitGetProperty (audioUnit,
  26001. kAudioUnitProperty_FactoryPresets,
  26002. kAudioUnitScope_Global,
  26003. 0, &current, &sz);
  26004. return current.presetNumber;
  26005. }
  26006. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  26007. {
  26008. AUPreset current;
  26009. current.presetNumber = newIndex;
  26010. current.presetName = 0;
  26011. AudioUnitSetProperty (audioUnit,
  26012. kAudioUnitProperty_FactoryPresets,
  26013. kAudioUnitScope_Global,
  26014. 0, &current, sizeof (AUPreset));
  26015. }
  26016. const String AudioUnitPluginInstance::getProgramName (int index)
  26017. {
  26018. String s;
  26019. CFArrayRef presets;
  26020. UInt32 sz = sizeof (CFArrayRef);
  26021. if (AudioUnitGetProperty (audioUnit,
  26022. kAudioUnitProperty_FactoryPresets,
  26023. kAudioUnitScope_Global,
  26024. 0, &presets, &sz) == noErr)
  26025. {
  26026. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26027. {
  26028. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26029. if (p != 0 && p->presetNumber == index)
  26030. {
  26031. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26032. break;
  26033. }
  26034. }
  26035. CFRelease (presets);
  26036. }
  26037. return s;
  26038. }
  26039. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26040. {
  26041. jassertfalse; // xxx not implemented!
  26042. }
  26043. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26044. {
  26045. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  26046. return "Input " + String (index + 1);
  26047. return String::empty;
  26048. }
  26049. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26050. {
  26051. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  26052. return false;
  26053. return true;
  26054. }
  26055. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26056. {
  26057. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  26058. return "Output " + String (index + 1);
  26059. return String::empty;
  26060. }
  26061. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26062. {
  26063. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  26064. return false;
  26065. return true;
  26066. }
  26067. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26068. {
  26069. getCurrentProgramStateInformation (destData);
  26070. }
  26071. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26072. {
  26073. CFPropertyListRef propertyList = 0;
  26074. UInt32 sz = sizeof (CFPropertyListRef);
  26075. if (AudioUnitGetProperty (audioUnit,
  26076. kAudioUnitProperty_ClassInfo,
  26077. kAudioUnitScope_Global,
  26078. 0, &propertyList, &sz) == noErr)
  26079. {
  26080. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26081. CFWriteStreamOpen (stream);
  26082. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26083. CFWriteStreamClose (stream);
  26084. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26085. destData.setSize (bytesWritten);
  26086. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26087. CFRelease (data);
  26088. CFRelease (stream);
  26089. CFRelease (propertyList);
  26090. }
  26091. }
  26092. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26093. {
  26094. setCurrentProgramStateInformation (data, sizeInBytes);
  26095. }
  26096. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26097. {
  26098. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26099. (const UInt8*) data,
  26100. sizeInBytes,
  26101. kCFAllocatorNull);
  26102. CFReadStreamOpen (stream);
  26103. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26104. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26105. stream,
  26106. 0,
  26107. kCFPropertyListImmutable,
  26108. &format,
  26109. 0);
  26110. CFRelease (stream);
  26111. if (propertyList != 0)
  26112. AudioUnitSetProperty (audioUnit,
  26113. kAudioUnitProperty_ClassInfo,
  26114. kAudioUnitScope_Global,
  26115. 0, &propertyList, sizeof (propertyList));
  26116. }
  26117. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26118. {
  26119. }
  26120. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26121. {
  26122. }
  26123. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26124. const String& fileOrIdentifier)
  26125. {
  26126. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26127. return;
  26128. PluginDescription desc;
  26129. desc.fileOrIdentifier = fileOrIdentifier;
  26130. desc.uid = 0;
  26131. try
  26132. {
  26133. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26134. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26135. if (auInstance != 0)
  26136. {
  26137. auInstance->fillInPluginDescription (desc);
  26138. results.add (new PluginDescription (desc));
  26139. }
  26140. }
  26141. catch (...)
  26142. {
  26143. // crashed while loading...
  26144. }
  26145. }
  26146. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26147. {
  26148. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26149. {
  26150. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26151. if (result->audioUnit != 0)
  26152. {
  26153. result->initialise();
  26154. return result.release();
  26155. }
  26156. }
  26157. return 0;
  26158. }
  26159. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26160. const bool /*recursive*/)
  26161. {
  26162. StringArray result;
  26163. ComponentRecord* comp = 0;
  26164. ComponentDescription desc;
  26165. zerostruct (desc);
  26166. for (;;)
  26167. {
  26168. zerostruct (desc);
  26169. comp = FindNextComponent (comp, &desc);
  26170. if (comp == 0)
  26171. break;
  26172. GetComponentInfo (comp, &desc, 0, 0, 0);
  26173. if (desc.componentType == kAudioUnitType_MusicDevice
  26174. || desc.componentType == kAudioUnitType_MusicEffect
  26175. || desc.componentType == kAudioUnitType_Effect
  26176. || desc.componentType == kAudioUnitType_Generator
  26177. || desc.componentType == kAudioUnitType_Panner)
  26178. {
  26179. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26180. DBG (s);
  26181. result.add (s);
  26182. }
  26183. }
  26184. return result;
  26185. }
  26186. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26187. {
  26188. ComponentDescription desc;
  26189. String name, version, manufacturer;
  26190. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26191. return FindNextComponent (0, &desc) != 0;
  26192. const File f (fileOrIdentifier);
  26193. return f.hasFileExtension (".component")
  26194. && f.isDirectory();
  26195. }
  26196. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26197. {
  26198. ComponentDescription desc;
  26199. String name, version, manufacturer;
  26200. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26201. if (name.isEmpty())
  26202. name = fileOrIdentifier;
  26203. return name;
  26204. }
  26205. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26206. {
  26207. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26208. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26209. else
  26210. return File (desc.fileOrIdentifier).exists();
  26211. }
  26212. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26213. {
  26214. return FileSearchPath ("/(Default AudioUnit locations)");
  26215. }
  26216. #endif
  26217. END_JUCE_NAMESPACE
  26218. #undef log
  26219. #endif
  26220. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26221. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26222. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26223. #define JUCE_MAC_VST_INCLUDED 1
  26224. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26225. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26226. #if JUCE_WINDOWS
  26227. #undef _WIN32_WINNT
  26228. #define _WIN32_WINNT 0x500
  26229. #undef STRICT
  26230. #define STRICT
  26231. #include <windows.h>
  26232. #include <float.h>
  26233. #pragma warning (disable : 4312 4355)
  26234. #elif JUCE_LINUX
  26235. #include <float.h>
  26236. #include <sys/time.h>
  26237. #include <X11/Xlib.h>
  26238. #include <X11/Xutil.h>
  26239. #include <X11/Xatom.h>
  26240. #undef Font
  26241. #undef KeyPress
  26242. #undef Drawable
  26243. #undef Time
  26244. #else
  26245. #include <Cocoa/Cocoa.h>
  26246. #include <Carbon/Carbon.h>
  26247. #endif
  26248. #if ! (JUCE_MAC && JUCE_64BIT)
  26249. BEGIN_JUCE_NAMESPACE
  26250. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26251. #endif
  26252. #undef PRAGMA_ALIGN_SUPPORTED
  26253. #define VST_FORCE_DEPRECATED 0
  26254. #if JUCE_MSVC
  26255. #pragma warning (push)
  26256. #pragma warning (disable: 4996)
  26257. #endif
  26258. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26259. your include path if you want to add VST support.
  26260. If you're not interested in VSTs, you can disable them by changing the
  26261. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26262. */
  26263. #include "pluginterfaces/vst2.x/aeffectx.h"
  26264. #if JUCE_MSVC
  26265. #pragma warning (pop)
  26266. #endif
  26267. #if JUCE_LINUX
  26268. #define Font JUCE_NAMESPACE::Font
  26269. #define KeyPress JUCE_NAMESPACE::KeyPress
  26270. #define Drawable JUCE_NAMESPACE::Drawable
  26271. #define Time JUCE_NAMESPACE::Time
  26272. #endif
  26273. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26274. #ifdef __aeffect__
  26275. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26276. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26277. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26278. events to the list.
  26279. This is used by both the VST hosting code and the plugin wrapper.
  26280. */
  26281. class VSTMidiEventList
  26282. {
  26283. public:
  26284. VSTMidiEventList()
  26285. : numEventsUsed (0), numEventsAllocated (0)
  26286. {
  26287. }
  26288. ~VSTMidiEventList()
  26289. {
  26290. freeEvents();
  26291. }
  26292. void clear()
  26293. {
  26294. numEventsUsed = 0;
  26295. if (events != 0)
  26296. events->numEvents = 0;
  26297. }
  26298. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26299. {
  26300. ensureSize (numEventsUsed + 1);
  26301. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26302. events->numEvents = ++numEventsUsed;
  26303. if (numBytes <= 4)
  26304. {
  26305. if (e->type == kVstSysExType)
  26306. {
  26307. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26308. e->type = kVstMidiType;
  26309. e->byteSize = sizeof (VstMidiEvent);
  26310. e->noteLength = 0;
  26311. e->noteOffset = 0;
  26312. e->detune = 0;
  26313. e->noteOffVelocity = 0;
  26314. }
  26315. e->deltaFrames = frameOffset;
  26316. memcpy (e->midiData, midiData, numBytes);
  26317. }
  26318. else
  26319. {
  26320. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26321. if (se->type == kVstSysExType)
  26322. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26323. else
  26324. se->sysexDump = (char*) juce_malloc (numBytes);
  26325. memcpy (se->sysexDump, midiData, numBytes);
  26326. se->type = kVstSysExType;
  26327. se->byteSize = sizeof (VstMidiSysexEvent);
  26328. se->deltaFrames = frameOffset;
  26329. se->flags = 0;
  26330. se->dumpBytes = numBytes;
  26331. se->resvd1 = 0;
  26332. se->resvd2 = 0;
  26333. }
  26334. }
  26335. // Handy method to pull the events out of an event buffer supplied by the host
  26336. // or plugin.
  26337. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26338. {
  26339. for (int i = 0; i < events->numEvents; ++i)
  26340. {
  26341. const VstEvent* const e = events->events[i];
  26342. if (e != 0)
  26343. {
  26344. if (e->type == kVstMidiType)
  26345. {
  26346. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26347. 4, e->deltaFrames);
  26348. }
  26349. else if (e->type == kVstSysExType)
  26350. {
  26351. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26352. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26353. e->deltaFrames);
  26354. }
  26355. }
  26356. }
  26357. }
  26358. void ensureSize (int numEventsNeeded)
  26359. {
  26360. if (numEventsNeeded > numEventsAllocated)
  26361. {
  26362. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26363. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26364. if (events == 0)
  26365. events.calloc (size, 1);
  26366. else
  26367. events.realloc (size, 1);
  26368. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26369. {
  26370. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26371. (int) sizeof (VstMidiSysexEvent)));
  26372. e->type = kVstMidiType;
  26373. e->byteSize = sizeof (VstMidiEvent);
  26374. events->events[i] = (VstEvent*) e;
  26375. }
  26376. numEventsAllocated = numEventsNeeded;
  26377. }
  26378. }
  26379. void freeEvents()
  26380. {
  26381. if (events != 0)
  26382. {
  26383. for (int i = numEventsAllocated; --i >= 0;)
  26384. {
  26385. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26386. if (e->type == kVstSysExType)
  26387. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26388. juce_free (e);
  26389. }
  26390. events.free();
  26391. numEventsUsed = 0;
  26392. numEventsAllocated = 0;
  26393. }
  26394. }
  26395. HeapBlock <VstEvents> events;
  26396. private:
  26397. int numEventsUsed, numEventsAllocated;
  26398. };
  26399. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26400. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26401. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26402. #if ! JUCE_WINDOWS
  26403. static void _fpreset() {}
  26404. static void _clearfp() {}
  26405. #endif
  26406. extern void juce_callAnyTimersSynchronously();
  26407. const int fxbVersionNum = 1;
  26408. struct fxProgram
  26409. {
  26410. long chunkMagic; // 'CcnK'
  26411. long byteSize; // of this chunk, excl. magic + byteSize
  26412. long fxMagic; // 'FxCk'
  26413. long version;
  26414. long fxID; // fx unique id
  26415. long fxVersion;
  26416. long numParams;
  26417. char prgName[28];
  26418. float params[1]; // variable no. of parameters
  26419. };
  26420. struct fxSet
  26421. {
  26422. long chunkMagic; // 'CcnK'
  26423. long byteSize; // of this chunk, excl. magic + byteSize
  26424. long fxMagic; // 'FxBk'
  26425. long version;
  26426. long fxID; // fx unique id
  26427. long fxVersion;
  26428. long numPrograms;
  26429. char future[128];
  26430. fxProgram programs[1]; // variable no. of programs
  26431. };
  26432. struct fxChunkSet
  26433. {
  26434. long chunkMagic; // 'CcnK'
  26435. long byteSize; // of this chunk, excl. magic + byteSize
  26436. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26437. long version;
  26438. long fxID; // fx unique id
  26439. long fxVersion;
  26440. long numPrograms;
  26441. char future[128];
  26442. long chunkSize;
  26443. char chunk[8]; // variable
  26444. };
  26445. struct fxProgramSet
  26446. {
  26447. long chunkMagic; // 'CcnK'
  26448. long byteSize; // of this chunk, excl. magic + byteSize
  26449. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26450. long version;
  26451. long fxID; // fx unique id
  26452. long fxVersion;
  26453. long numPrograms;
  26454. char name[28];
  26455. long chunkSize;
  26456. char chunk[8]; // variable
  26457. };
  26458. static long vst_swap (const long x) throw()
  26459. {
  26460. #ifdef JUCE_LITTLE_ENDIAN
  26461. return (long) ByteOrder::swap ((uint32) x);
  26462. #else
  26463. return x;
  26464. #endif
  26465. }
  26466. static float vst_swapFloat (const float x) throw()
  26467. {
  26468. #ifdef JUCE_LITTLE_ENDIAN
  26469. union { uint32 asInt; float asFloat; } n;
  26470. n.asFloat = x;
  26471. n.asInt = ByteOrder::swap (n.asInt);
  26472. return n.asFloat;
  26473. #else
  26474. return x;
  26475. #endif
  26476. }
  26477. static double getVSTHostTimeNanoseconds()
  26478. {
  26479. #if JUCE_WINDOWS
  26480. return timeGetTime() * 1000000.0;
  26481. #elif JUCE_LINUX
  26482. timeval micro;
  26483. gettimeofday (&micro, 0);
  26484. return micro.tv_usec * 1000.0;
  26485. #elif JUCE_MAC
  26486. UnsignedWide micro;
  26487. Microseconds (&micro);
  26488. return micro.lo * 1000.0;
  26489. #endif
  26490. }
  26491. typedef AEffect* (*MainCall) (audioMasterCallback);
  26492. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26493. static int shellUIDToCreate = 0;
  26494. static int insideVSTCallback = 0;
  26495. class VSTPluginWindow;
  26496. // Change this to disable logging of various VST activities
  26497. #ifndef VST_LOGGING
  26498. #define VST_LOGGING 1
  26499. #endif
  26500. #if VST_LOGGING
  26501. #define log(a) Logger::writeToLog(a);
  26502. #else
  26503. #define log(a)
  26504. #endif
  26505. #if JUCE_MAC && JUCE_PPC
  26506. static void* NewCFMFromMachO (void* const machofp) throw()
  26507. {
  26508. void* result = juce_malloc (8);
  26509. ((void**) result)[0] = machofp;
  26510. ((void**) result)[1] = result;
  26511. return result;
  26512. }
  26513. #endif
  26514. #if JUCE_LINUX
  26515. extern Display* display;
  26516. extern XContext windowHandleXContext;
  26517. typedef void (*EventProcPtr) (XEvent* ev);
  26518. static bool xErrorTriggered;
  26519. static int temporaryErrorHandler (Display*, XErrorEvent*)
  26520. {
  26521. xErrorTriggered = true;
  26522. return 0;
  26523. }
  26524. static int getPropertyFromXWindow (Window handle, Atom atom)
  26525. {
  26526. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26527. xErrorTriggered = false;
  26528. int userSize;
  26529. unsigned long bytes, userCount;
  26530. unsigned char* data;
  26531. Atom userType;
  26532. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26533. &userType, &userSize, &userCount, &bytes, &data);
  26534. XSetErrorHandler (oldErrorHandler);
  26535. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26536. : 0;
  26537. }
  26538. static Window getChildWindow (Window windowToCheck)
  26539. {
  26540. Window rootWindow, parentWindow;
  26541. Window* childWindows;
  26542. unsigned int numChildren;
  26543. XQueryTree (display,
  26544. windowToCheck,
  26545. &rootWindow,
  26546. &parentWindow,
  26547. &childWindows,
  26548. &numChildren);
  26549. if (numChildren > 0)
  26550. return childWindows [0];
  26551. return 0;
  26552. }
  26553. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26554. {
  26555. if (e.mods.isLeftButtonDown())
  26556. {
  26557. ev.xbutton.button = Button1;
  26558. ev.xbutton.state |= Button1Mask;
  26559. }
  26560. else if (e.mods.isRightButtonDown())
  26561. {
  26562. ev.xbutton.button = Button3;
  26563. ev.xbutton.state |= Button3Mask;
  26564. }
  26565. else if (e.mods.isMiddleButtonDown())
  26566. {
  26567. ev.xbutton.button = Button2;
  26568. ev.xbutton.state |= Button2Mask;
  26569. }
  26570. }
  26571. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26572. {
  26573. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26574. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26575. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26576. }
  26577. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26578. {
  26579. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26580. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26581. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26582. }
  26583. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26584. {
  26585. if (increment < 0)
  26586. {
  26587. ev.xbutton.button = Button5;
  26588. ev.xbutton.state |= Button5Mask;
  26589. }
  26590. else if (increment > 0)
  26591. {
  26592. ev.xbutton.button = Button4;
  26593. ev.xbutton.state |= Button4Mask;
  26594. }
  26595. }
  26596. #endif
  26597. class ModuleHandle : public ReferenceCountedObject
  26598. {
  26599. public:
  26600. File file;
  26601. MainCall moduleMain;
  26602. String pluginName;
  26603. static Array <ModuleHandle*>& getActiveModules()
  26604. {
  26605. static Array <ModuleHandle*> activeModules;
  26606. return activeModules;
  26607. }
  26608. static ModuleHandle* findOrCreateModule (const File& file)
  26609. {
  26610. for (int i = getActiveModules().size(); --i >= 0;)
  26611. {
  26612. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26613. if (module->file == file)
  26614. return module;
  26615. }
  26616. _fpreset(); // (doesn't do any harm)
  26617. ++insideVSTCallback;
  26618. shellUIDToCreate = 0;
  26619. log ("Attempting to load VST: " + file.getFullPathName());
  26620. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26621. if (! m->open())
  26622. m = 0;
  26623. --insideVSTCallback;
  26624. _fpreset(); // (doesn't do any harm)
  26625. return m.release();
  26626. }
  26627. ModuleHandle (const File& file_)
  26628. : file (file_),
  26629. moduleMain (0),
  26630. #if JUCE_WINDOWS || JUCE_LINUX
  26631. hModule (0)
  26632. #elif JUCE_MAC
  26633. fragId (0),
  26634. resHandle (0),
  26635. bundleRef (0),
  26636. resFileId (0)
  26637. #endif
  26638. {
  26639. getActiveModules().add (this);
  26640. #if JUCE_WINDOWS || JUCE_LINUX
  26641. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26642. #elif JUCE_MAC
  26643. FSRef ref;
  26644. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26645. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26646. #endif
  26647. }
  26648. ~ModuleHandle()
  26649. {
  26650. getActiveModules().removeValue (this);
  26651. close();
  26652. }
  26653. juce_UseDebuggingNewOperator
  26654. #if JUCE_WINDOWS || JUCE_LINUX
  26655. void* hModule;
  26656. String fullParentDirectoryPathName;
  26657. bool open()
  26658. {
  26659. #if JUCE_WINDOWS
  26660. static bool timePeriodSet = false;
  26661. if (! timePeriodSet)
  26662. {
  26663. timePeriodSet = true;
  26664. timeBeginPeriod (2);
  26665. }
  26666. #endif
  26667. pluginName = file.getFileNameWithoutExtension();
  26668. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26669. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26670. if (moduleMain == 0)
  26671. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26672. return moduleMain != 0;
  26673. }
  26674. void close()
  26675. {
  26676. _fpreset(); // (doesn't do any harm)
  26677. PlatformUtilities::freeDynamicLibrary (hModule);
  26678. }
  26679. void closeEffect (AEffect* eff)
  26680. {
  26681. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26682. }
  26683. #else
  26684. CFragConnectionID fragId;
  26685. Handle resHandle;
  26686. CFBundleRef bundleRef;
  26687. FSSpec parentDirFSSpec;
  26688. short resFileId;
  26689. bool open()
  26690. {
  26691. bool ok = false;
  26692. const String filename (file.getFullPathName());
  26693. if (file.hasFileExtension (".vst"))
  26694. {
  26695. const char* const utf8 = filename.toUTF8();
  26696. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26697. strlen (utf8), file.isDirectory());
  26698. if (url != 0)
  26699. {
  26700. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26701. CFRelease (url);
  26702. if (bundleRef != 0)
  26703. {
  26704. if (CFBundleLoadExecutable (bundleRef))
  26705. {
  26706. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26707. if (moduleMain == 0)
  26708. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26709. if (moduleMain != 0)
  26710. {
  26711. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26712. if (name != 0)
  26713. {
  26714. if (CFGetTypeID (name) == CFStringGetTypeID())
  26715. {
  26716. char buffer[1024];
  26717. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26718. pluginName = buffer;
  26719. }
  26720. }
  26721. if (pluginName.isEmpty())
  26722. pluginName = file.getFileNameWithoutExtension();
  26723. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26724. ok = true;
  26725. }
  26726. }
  26727. if (! ok)
  26728. {
  26729. CFBundleUnloadExecutable (bundleRef);
  26730. CFRelease (bundleRef);
  26731. bundleRef = 0;
  26732. }
  26733. }
  26734. }
  26735. }
  26736. #if JUCE_PPC
  26737. else
  26738. {
  26739. FSRef fn;
  26740. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26741. {
  26742. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26743. if (resFileId != -1)
  26744. {
  26745. const int numEffs = Count1Resources ('aEff');
  26746. for (int i = 0; i < numEffs; ++i)
  26747. {
  26748. resHandle = Get1IndResource ('aEff', i + 1);
  26749. if (resHandle != 0)
  26750. {
  26751. OSType type;
  26752. Str255 name;
  26753. SInt16 id;
  26754. GetResInfo (resHandle, &id, &type, name);
  26755. pluginName = String ((const char*) name + 1, name[0]);
  26756. DetachResource (resHandle);
  26757. HLock (resHandle);
  26758. Ptr ptr;
  26759. Str255 errorText;
  26760. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26761. name, kPrivateCFragCopy,
  26762. &fragId, &ptr, errorText);
  26763. if (err == noErr)
  26764. {
  26765. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26766. ok = true;
  26767. }
  26768. else
  26769. {
  26770. HUnlock (resHandle);
  26771. }
  26772. break;
  26773. }
  26774. }
  26775. if (! ok)
  26776. CloseResFile (resFileId);
  26777. }
  26778. }
  26779. }
  26780. #endif
  26781. return ok;
  26782. }
  26783. void close()
  26784. {
  26785. #if JUCE_PPC
  26786. if (fragId != 0)
  26787. {
  26788. if (moduleMain != 0)
  26789. disposeMachOFromCFM ((void*) moduleMain);
  26790. CloseConnection (&fragId);
  26791. HUnlock (resHandle);
  26792. if (resFileId != 0)
  26793. CloseResFile (resFileId);
  26794. }
  26795. else
  26796. #endif
  26797. if (bundleRef != 0)
  26798. {
  26799. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26800. if (CFGetRetainCount (bundleRef) == 1)
  26801. CFBundleUnloadExecutable (bundleRef);
  26802. if (CFGetRetainCount (bundleRef) > 0)
  26803. CFRelease (bundleRef);
  26804. }
  26805. }
  26806. void closeEffect (AEffect* eff)
  26807. {
  26808. #if JUCE_PPC
  26809. if (fragId != 0)
  26810. {
  26811. Array<void*> thingsToDelete;
  26812. thingsToDelete.add ((void*) eff->dispatcher);
  26813. thingsToDelete.add ((void*) eff->process);
  26814. thingsToDelete.add ((void*) eff->setParameter);
  26815. thingsToDelete.add ((void*) eff->getParameter);
  26816. thingsToDelete.add ((void*) eff->processReplacing);
  26817. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26818. for (int i = thingsToDelete.size(); --i >= 0;)
  26819. disposeMachOFromCFM (thingsToDelete[i]);
  26820. }
  26821. else
  26822. #endif
  26823. {
  26824. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26825. }
  26826. }
  26827. #if JUCE_PPC
  26828. static void* newMachOFromCFM (void* cfmfp)
  26829. {
  26830. if (cfmfp == 0)
  26831. return 0;
  26832. UInt32* const mfp = new UInt32[6];
  26833. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26834. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26835. mfp[2] = 0x800c0000;
  26836. mfp[3] = 0x804c0004;
  26837. mfp[4] = 0x7c0903a6;
  26838. mfp[5] = 0x4e800420;
  26839. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26840. return mfp;
  26841. }
  26842. static void disposeMachOFromCFM (void* ptr)
  26843. {
  26844. delete[] static_cast <UInt32*> (ptr);
  26845. }
  26846. void coerceAEffectFunctionCalls (AEffect* eff)
  26847. {
  26848. if (fragId != 0)
  26849. {
  26850. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26851. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26852. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26853. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26854. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26855. }
  26856. }
  26857. #endif
  26858. #endif
  26859. };
  26860. /**
  26861. An instance of a plugin, created by a VSTPluginFormat.
  26862. */
  26863. class VSTPluginInstance : public AudioPluginInstance,
  26864. private Timer,
  26865. private AsyncUpdater
  26866. {
  26867. public:
  26868. ~VSTPluginInstance();
  26869. // AudioPluginInstance methods:
  26870. void fillInPluginDescription (PluginDescription& desc) const
  26871. {
  26872. desc.name = name;
  26873. desc.fileOrIdentifier = module->file.getFullPathName();
  26874. desc.uid = getUID();
  26875. desc.lastFileModTime = module->file.getLastModificationTime();
  26876. desc.pluginFormatName = "VST";
  26877. desc.category = getCategory();
  26878. {
  26879. char buffer [kVstMaxVendorStrLen + 8];
  26880. zerostruct (buffer);
  26881. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26882. desc.manufacturerName = buffer;
  26883. }
  26884. desc.version = getVersion();
  26885. desc.numInputChannels = getNumInputChannels();
  26886. desc.numOutputChannels = getNumOutputChannels();
  26887. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26888. }
  26889. const String getName() const { return name; }
  26890. int getUID() const;
  26891. bool acceptsMidi() const { return wantsMidiMessages; }
  26892. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26893. // AudioProcessor methods:
  26894. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26895. void releaseResources();
  26896. void processBlock (AudioSampleBuffer& buffer,
  26897. MidiBuffer& midiMessages);
  26898. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26899. AudioProcessorEditor* createEditor();
  26900. const String getInputChannelName (int index) const;
  26901. bool isInputChannelStereoPair (int index) const;
  26902. const String getOutputChannelName (int index) const;
  26903. bool isOutputChannelStereoPair (int index) const;
  26904. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26905. float getParameter (int index);
  26906. void setParameter (int index, float newValue);
  26907. const String getParameterName (int index);
  26908. const String getParameterText (int index);
  26909. bool isParameterAutomatable (int index) const;
  26910. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26911. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26912. void setCurrentProgram (int index);
  26913. const String getProgramName (int index);
  26914. void changeProgramName (int index, const String& newName);
  26915. void getStateInformation (MemoryBlock& destData);
  26916. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26917. void setStateInformation (const void* data, int sizeInBytes);
  26918. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26919. void timerCallback();
  26920. void handleAsyncUpdate();
  26921. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26922. juce_UseDebuggingNewOperator
  26923. private:
  26924. friend class VSTPluginWindow;
  26925. friend class VSTPluginFormat;
  26926. AEffect* effect;
  26927. String name;
  26928. CriticalSection lock;
  26929. bool wantsMidiMessages, initialised, isPowerOn;
  26930. mutable StringArray programNames;
  26931. AudioSampleBuffer tempBuffer;
  26932. CriticalSection midiInLock;
  26933. MidiBuffer incomingMidi;
  26934. VSTMidiEventList midiEventsToSend;
  26935. VstTimeInfo vstHostTime;
  26936. ReferenceCountedObjectPtr <ModuleHandle> module;
  26937. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26938. bool restoreProgramSettings (const fxProgram* const prog);
  26939. const String getCurrentProgramName();
  26940. void setParamsInProgramBlock (fxProgram* const prog);
  26941. void updateStoredProgramNames();
  26942. void initialise();
  26943. void handleMidiFromPlugin (const VstEvents* const events);
  26944. void createTempParameterStore (MemoryBlock& dest);
  26945. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26946. const String getParameterLabel (int index) const;
  26947. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26948. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26949. void setChunkData (const char* data, int size, bool isPreset);
  26950. bool loadFromFXBFile (const void* data, int numBytes);
  26951. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26952. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26953. const String getVersion() const;
  26954. const String getCategory() const;
  26955. void setPower (const bool on);
  26956. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26957. };
  26958. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26959. : effect (0),
  26960. wantsMidiMessages (false),
  26961. initialised (false),
  26962. isPowerOn (false),
  26963. tempBuffer (1, 1),
  26964. module (module_)
  26965. {
  26966. try
  26967. {
  26968. _fpreset();
  26969. ++insideVSTCallback;
  26970. name = module->pluginName;
  26971. log ("Creating VST instance: " + name);
  26972. #if JUCE_MAC
  26973. if (module->resFileId != 0)
  26974. UseResFile (module->resFileId);
  26975. #if JUCE_PPC
  26976. if (module->fragId != 0)
  26977. {
  26978. static void* audioMasterCoerced = 0;
  26979. if (audioMasterCoerced == 0)
  26980. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26981. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26982. }
  26983. else
  26984. #endif
  26985. #endif
  26986. {
  26987. effect = module->moduleMain (&audioMaster);
  26988. }
  26989. --insideVSTCallback;
  26990. if (effect != 0 && effect->magic == kEffectMagic)
  26991. {
  26992. #if JUCE_PPC
  26993. module->coerceAEffectFunctionCalls (effect);
  26994. #endif
  26995. jassert (effect->resvd2 == 0);
  26996. jassert (effect->object != 0);
  26997. _fpreset(); // some dodgy plugs fuck around with this
  26998. }
  26999. else
  27000. {
  27001. effect = 0;
  27002. }
  27003. }
  27004. catch (...)
  27005. {
  27006. --insideVSTCallback;
  27007. }
  27008. }
  27009. VSTPluginInstance::~VSTPluginInstance()
  27010. {
  27011. const ScopedLock sl (lock);
  27012. jassert (insideVSTCallback == 0);
  27013. if (effect != 0 && effect->magic == kEffectMagic)
  27014. {
  27015. try
  27016. {
  27017. #if JUCE_MAC
  27018. if (module->resFileId != 0)
  27019. UseResFile (module->resFileId);
  27020. #endif
  27021. // Must delete any editors before deleting the plugin instance!
  27022. jassert (getActiveEditor() == 0);
  27023. _fpreset(); // some dodgy plugs fuck around with this
  27024. module->closeEffect (effect);
  27025. }
  27026. catch (...)
  27027. {}
  27028. }
  27029. module = 0;
  27030. effect = 0;
  27031. }
  27032. void VSTPluginInstance::initialise()
  27033. {
  27034. if (initialised || effect == 0)
  27035. return;
  27036. log ("Initialising VST: " + module->pluginName);
  27037. initialised = true;
  27038. dispatch (effIdentify, 0, 0, 0, 0);
  27039. // this code would ask the plugin for its name, but so few plugins
  27040. // actually bother implementing this correctly, that it's better to
  27041. // just ignore it and use the file name instead.
  27042. /* {
  27043. char buffer [256];
  27044. zerostruct (buffer);
  27045. dispatch (effGetEffectName, 0, 0, buffer, 0);
  27046. name = String (buffer).trim();
  27047. if (name.isEmpty())
  27048. name = module->pluginName;
  27049. }
  27050. */
  27051. if (getSampleRate() > 0)
  27052. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27053. if (getBlockSize() > 0)
  27054. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27055. dispatch (effOpen, 0, 0, 0, 0);
  27056. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27057. getSampleRate(), getBlockSize());
  27058. if (getNumPrograms() > 1)
  27059. setCurrentProgram (0);
  27060. else
  27061. dispatch (effSetProgram, 0, 0, 0, 0);
  27062. int i;
  27063. for (i = effect->numInputs; --i >= 0;)
  27064. dispatch (effConnectInput, i, 1, 0, 0);
  27065. for (i = effect->numOutputs; --i >= 0;)
  27066. dispatch (effConnectOutput, i, 1, 0, 0);
  27067. updateStoredProgramNames();
  27068. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27069. setLatencySamples (effect->initialDelay);
  27070. }
  27071. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27072. int samplesPerBlockExpected)
  27073. {
  27074. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27075. sampleRate_, samplesPerBlockExpected);
  27076. setLatencySamples (effect->initialDelay);
  27077. vstHostTime.tempo = 120.0;
  27078. vstHostTime.timeSigNumerator = 4;
  27079. vstHostTime.timeSigDenominator = 4;
  27080. vstHostTime.sampleRate = sampleRate_;
  27081. vstHostTime.samplePos = 0;
  27082. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27083. initialise();
  27084. if (initialised)
  27085. {
  27086. wantsMidiMessages = wantsMidiMessages
  27087. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27088. if (wantsMidiMessages)
  27089. midiEventsToSend.ensureSize (256);
  27090. else
  27091. midiEventsToSend.freeEvents();
  27092. incomingMidi.clear();
  27093. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27094. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27095. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27096. if (! isPowerOn)
  27097. setPower (true);
  27098. // dodgy hack to force some plugins to initialise the sample rate..
  27099. if ((! hasEditor()) && getNumParameters() > 0)
  27100. {
  27101. const float old = getParameter (0);
  27102. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27103. setParameter (0, old);
  27104. }
  27105. dispatch (effStartProcess, 0, 0, 0, 0);
  27106. }
  27107. }
  27108. void VSTPluginInstance::releaseResources()
  27109. {
  27110. if (initialised)
  27111. {
  27112. dispatch (effStopProcess, 0, 0, 0, 0);
  27113. setPower (false);
  27114. }
  27115. tempBuffer.setSize (1, 1);
  27116. incomingMidi.clear();
  27117. midiEventsToSend.freeEvents();
  27118. }
  27119. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27120. MidiBuffer& midiMessages)
  27121. {
  27122. const int numSamples = buffer.getNumSamples();
  27123. if (initialised)
  27124. {
  27125. AudioPlayHead* playHead = getPlayHead();
  27126. if (playHead != 0)
  27127. {
  27128. AudioPlayHead::CurrentPositionInfo position;
  27129. playHead->getCurrentPosition (position);
  27130. vstHostTime.tempo = position.bpm;
  27131. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27132. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27133. vstHostTime.ppqPos = position.ppqPosition;
  27134. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27135. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27136. if (position.isPlaying)
  27137. vstHostTime.flags |= kVstTransportPlaying;
  27138. else
  27139. vstHostTime.flags &= ~kVstTransportPlaying;
  27140. }
  27141. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27142. if (wantsMidiMessages)
  27143. {
  27144. midiEventsToSend.clear();
  27145. midiEventsToSend.ensureSize (1);
  27146. MidiBuffer::Iterator iter (midiMessages);
  27147. const uint8* midiData;
  27148. int numBytesOfMidiData, samplePosition;
  27149. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27150. {
  27151. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27152. jlimit (0, numSamples - 1, samplePosition));
  27153. }
  27154. try
  27155. {
  27156. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27157. }
  27158. catch (...)
  27159. {}
  27160. }
  27161. _clearfp();
  27162. if ((effect->flags & effFlagsCanReplacing) != 0)
  27163. {
  27164. try
  27165. {
  27166. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27167. }
  27168. catch (...)
  27169. {}
  27170. }
  27171. else
  27172. {
  27173. tempBuffer.setSize (effect->numOutputs, numSamples);
  27174. tempBuffer.clear();
  27175. try
  27176. {
  27177. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27178. }
  27179. catch (...)
  27180. {}
  27181. for (int i = effect->numOutputs; --i >= 0;)
  27182. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27183. }
  27184. }
  27185. else
  27186. {
  27187. // Not initialised, so just bypass..
  27188. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27189. buffer.clear (i, 0, buffer.getNumSamples());
  27190. }
  27191. {
  27192. // copy any incoming midi..
  27193. const ScopedLock sl (midiInLock);
  27194. midiMessages.swapWith (incomingMidi);
  27195. incomingMidi.clear();
  27196. }
  27197. }
  27198. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27199. {
  27200. if (events != 0)
  27201. {
  27202. const ScopedLock sl (midiInLock);
  27203. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27204. }
  27205. }
  27206. static Array <VSTPluginWindow*> activeVSTWindows;
  27207. class VSTPluginWindow : public AudioProcessorEditor,
  27208. #if ! JUCE_MAC
  27209. public ComponentMovementWatcher,
  27210. #endif
  27211. public Timer
  27212. {
  27213. public:
  27214. VSTPluginWindow (VSTPluginInstance& plugin_)
  27215. : AudioProcessorEditor (&plugin_),
  27216. #if ! JUCE_MAC
  27217. ComponentMovementWatcher (this),
  27218. #endif
  27219. plugin (plugin_),
  27220. isOpen (false),
  27221. wasShowing (false),
  27222. pluginRefusesToResize (false),
  27223. pluginWantsKeys (false),
  27224. alreadyInside (false),
  27225. recursiveResize (false)
  27226. {
  27227. #if JUCE_WINDOWS
  27228. sizeCheckCount = 0;
  27229. pluginHWND = 0;
  27230. #elif JUCE_LINUX
  27231. pluginWindow = None;
  27232. pluginProc = None;
  27233. #else
  27234. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27235. #endif
  27236. activeVSTWindows.add (this);
  27237. setSize (1, 1);
  27238. setOpaque (true);
  27239. setVisible (true);
  27240. }
  27241. ~VSTPluginWindow()
  27242. {
  27243. #if JUCE_MAC
  27244. innerWrapper = 0;
  27245. #else
  27246. closePluginWindow();
  27247. #endif
  27248. activeVSTWindows.removeValue (this);
  27249. plugin.editorBeingDeleted (this);
  27250. }
  27251. #if ! JUCE_MAC
  27252. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27253. {
  27254. if (recursiveResize)
  27255. return;
  27256. Component* const topComp = getTopLevelComponent();
  27257. if (topComp->getPeer() != 0)
  27258. {
  27259. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  27260. recursiveResize = true;
  27261. #if JUCE_WINDOWS
  27262. if (pluginHWND != 0)
  27263. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27264. #elif JUCE_LINUX
  27265. if (pluginWindow != 0)
  27266. {
  27267. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27268. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27269. XMapRaised (display, pluginWindow);
  27270. }
  27271. #endif
  27272. recursiveResize = false;
  27273. }
  27274. }
  27275. void componentVisibilityChanged (Component&)
  27276. {
  27277. const bool isShowingNow = isShowing();
  27278. if (wasShowing != isShowingNow)
  27279. {
  27280. wasShowing = isShowingNow;
  27281. if (isShowingNow)
  27282. openPluginWindow();
  27283. else
  27284. closePluginWindow();
  27285. }
  27286. componentMovedOrResized (true, true);
  27287. }
  27288. void componentPeerChanged()
  27289. {
  27290. closePluginWindow();
  27291. openPluginWindow();
  27292. }
  27293. #endif
  27294. bool keyStateChanged (bool)
  27295. {
  27296. return pluginWantsKeys;
  27297. }
  27298. bool keyPressed (const KeyPress&)
  27299. {
  27300. return pluginWantsKeys;
  27301. }
  27302. #if JUCE_MAC
  27303. void paint (Graphics& g)
  27304. {
  27305. g.fillAll (Colours::black);
  27306. }
  27307. #else
  27308. void paint (Graphics& g)
  27309. {
  27310. if (isOpen)
  27311. {
  27312. ComponentPeer* const peer = getPeer();
  27313. if (peer != 0)
  27314. {
  27315. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27316. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27317. #if JUCE_LINUX
  27318. if (pluginWindow != 0)
  27319. {
  27320. const Rectangle<int> clip (g.getClipBounds());
  27321. XEvent ev;
  27322. zerostruct (ev);
  27323. ev.xexpose.type = Expose;
  27324. ev.xexpose.display = display;
  27325. ev.xexpose.window = pluginWindow;
  27326. ev.xexpose.x = clip.getX();
  27327. ev.xexpose.y = clip.getY();
  27328. ev.xexpose.width = clip.getWidth();
  27329. ev.xexpose.height = clip.getHeight();
  27330. sendEventToChild (&ev);
  27331. }
  27332. #endif
  27333. }
  27334. }
  27335. else
  27336. {
  27337. g.fillAll (Colours::black);
  27338. }
  27339. }
  27340. #endif
  27341. void timerCallback()
  27342. {
  27343. #if JUCE_WINDOWS
  27344. if (--sizeCheckCount <= 0)
  27345. {
  27346. sizeCheckCount = 10;
  27347. checkPluginWindowSize();
  27348. }
  27349. #endif
  27350. try
  27351. {
  27352. static bool reentrant = false;
  27353. if (! reentrant)
  27354. {
  27355. reentrant = true;
  27356. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27357. reentrant = false;
  27358. }
  27359. }
  27360. catch (...)
  27361. {}
  27362. }
  27363. void mouseDown (const MouseEvent& e)
  27364. {
  27365. #if JUCE_LINUX
  27366. if (pluginWindow == 0)
  27367. return;
  27368. toFront (true);
  27369. XEvent ev;
  27370. zerostruct (ev);
  27371. ev.xbutton.display = display;
  27372. ev.xbutton.type = ButtonPress;
  27373. ev.xbutton.window = pluginWindow;
  27374. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27375. ev.xbutton.time = CurrentTime;
  27376. ev.xbutton.x = e.x;
  27377. ev.xbutton.y = e.y;
  27378. ev.xbutton.x_root = e.getScreenX();
  27379. ev.xbutton.y_root = e.getScreenY();
  27380. translateJuceToXButtonModifiers (e, ev);
  27381. sendEventToChild (&ev);
  27382. #elif JUCE_WINDOWS
  27383. (void) e;
  27384. toFront (true);
  27385. #endif
  27386. }
  27387. void broughtToFront()
  27388. {
  27389. activeVSTWindows.removeValue (this);
  27390. activeVSTWindows.add (this);
  27391. #if JUCE_MAC
  27392. dispatch (effEditTop, 0, 0, 0, 0);
  27393. #endif
  27394. }
  27395. juce_UseDebuggingNewOperator
  27396. private:
  27397. VSTPluginInstance& plugin;
  27398. bool isOpen, wasShowing, recursiveResize;
  27399. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27400. #if JUCE_WINDOWS
  27401. HWND pluginHWND;
  27402. void* originalWndProc;
  27403. int sizeCheckCount;
  27404. #elif JUCE_LINUX
  27405. Window pluginWindow;
  27406. EventProcPtr pluginProc;
  27407. #endif
  27408. #if JUCE_MAC
  27409. void openPluginWindow (WindowRef parentWindow)
  27410. {
  27411. if (isOpen || parentWindow == 0)
  27412. return;
  27413. isOpen = true;
  27414. ERect* rect = 0;
  27415. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27416. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27417. // do this before and after like in the steinberg example
  27418. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27419. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27420. // Install keyboard hooks
  27421. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27422. // double-check it's not too tiny
  27423. int w = 250, h = 150;
  27424. if (rect != 0)
  27425. {
  27426. w = rect->right - rect->left;
  27427. h = rect->bottom - rect->top;
  27428. if (w == 0 || h == 0)
  27429. {
  27430. w = 250;
  27431. h = 150;
  27432. }
  27433. }
  27434. w = jmax (w, 32);
  27435. h = jmax (h, 32);
  27436. setSize (w, h);
  27437. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27438. repaint();
  27439. }
  27440. #else
  27441. void openPluginWindow()
  27442. {
  27443. if (isOpen || getWindowHandle() == 0)
  27444. return;
  27445. log ("Opening VST UI: " + plugin.name);
  27446. isOpen = true;
  27447. ERect* rect = 0;
  27448. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27449. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27450. // do this before and after like in the steinberg example
  27451. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27452. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27453. // Install keyboard hooks
  27454. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27455. #if JUCE_WINDOWS
  27456. originalWndProc = 0;
  27457. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27458. if (pluginHWND == 0)
  27459. {
  27460. isOpen = false;
  27461. setSize (300, 150);
  27462. return;
  27463. }
  27464. #pragma warning (push)
  27465. #pragma warning (disable: 4244)
  27466. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27467. if (! pluginWantsKeys)
  27468. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27469. #pragma warning (pop)
  27470. int w, h;
  27471. RECT r;
  27472. GetWindowRect (pluginHWND, &r);
  27473. w = r.right - r.left;
  27474. h = r.bottom - r.top;
  27475. if (rect != 0)
  27476. {
  27477. const int rw = rect->right - rect->left;
  27478. const int rh = rect->bottom - rect->top;
  27479. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27480. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27481. {
  27482. // very dodgy logic to decide which size is right.
  27483. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27484. {
  27485. SetWindowPos (pluginHWND, 0,
  27486. 0, 0, rw, rh,
  27487. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27488. GetWindowRect (pluginHWND, &r);
  27489. w = r.right - r.left;
  27490. h = r.bottom - r.top;
  27491. pluginRefusesToResize = (w != rw) || (h != rh);
  27492. w = rw;
  27493. h = rh;
  27494. }
  27495. }
  27496. }
  27497. #elif JUCE_LINUX
  27498. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27499. if (pluginWindow != 0)
  27500. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27501. XInternAtom (display, "_XEventProc", False));
  27502. int w = 250, h = 150;
  27503. if (rect != 0)
  27504. {
  27505. w = rect->right - rect->left;
  27506. h = rect->bottom - rect->top;
  27507. if (w == 0 || h == 0)
  27508. {
  27509. w = 250;
  27510. h = 150;
  27511. }
  27512. }
  27513. if (pluginWindow != 0)
  27514. XMapRaised (display, pluginWindow);
  27515. #endif
  27516. // double-check it's not too tiny
  27517. w = jmax (w, 32);
  27518. h = jmax (h, 32);
  27519. setSize (w, h);
  27520. #if JUCE_WINDOWS
  27521. checkPluginWindowSize();
  27522. #endif
  27523. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27524. repaint();
  27525. }
  27526. #endif
  27527. #if ! JUCE_MAC
  27528. void closePluginWindow()
  27529. {
  27530. if (isOpen)
  27531. {
  27532. log ("Closing VST UI: " + plugin.getName());
  27533. isOpen = false;
  27534. dispatch (effEditClose, 0, 0, 0, 0);
  27535. #if JUCE_WINDOWS
  27536. #pragma warning (push)
  27537. #pragma warning (disable: 4244)
  27538. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27539. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27540. #pragma warning (pop)
  27541. stopTimer();
  27542. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27543. DestroyWindow (pluginHWND);
  27544. pluginHWND = 0;
  27545. #elif JUCE_LINUX
  27546. stopTimer();
  27547. pluginWindow = 0;
  27548. pluginProc = 0;
  27549. #endif
  27550. }
  27551. }
  27552. #endif
  27553. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27554. {
  27555. return plugin.dispatch (opcode, index, value, ptr, opt);
  27556. }
  27557. #if JUCE_WINDOWS
  27558. void checkPluginWindowSize()
  27559. {
  27560. RECT r;
  27561. GetWindowRect (pluginHWND, &r);
  27562. const int w = r.right - r.left;
  27563. const int h = r.bottom - r.top;
  27564. if (isShowing() && w > 0 && h > 0
  27565. && (w != getWidth() || h != getHeight())
  27566. && ! pluginRefusesToResize)
  27567. {
  27568. setSize (w, h);
  27569. sizeCheckCount = 0;
  27570. }
  27571. }
  27572. // hooks to get keyboard events from VST windows..
  27573. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27574. {
  27575. for (int i = activeVSTWindows.size(); --i >= 0;)
  27576. {
  27577. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27578. if (w->pluginHWND == hW)
  27579. {
  27580. if (message == WM_CHAR
  27581. || message == WM_KEYDOWN
  27582. || message == WM_SYSKEYDOWN
  27583. || message == WM_KEYUP
  27584. || message == WM_SYSKEYUP
  27585. || message == WM_APPCOMMAND)
  27586. {
  27587. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27588. message, wParam, lParam);
  27589. }
  27590. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27591. (HWND) w->pluginHWND,
  27592. message,
  27593. wParam,
  27594. lParam);
  27595. }
  27596. }
  27597. return DefWindowProc (hW, message, wParam, lParam);
  27598. }
  27599. #endif
  27600. #if JUCE_LINUX
  27601. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27602. void sendEventToChild (XEvent* event)
  27603. {
  27604. if (pluginProc != 0)
  27605. {
  27606. // if the plugin publishes an event procedure, pass the event directly..
  27607. pluginProc (event);
  27608. }
  27609. else if (pluginWindow != 0)
  27610. {
  27611. // if the plugin has a window, then send the event to the window so that
  27612. // its message thread will pick it up..
  27613. XSendEvent (display, pluginWindow, False, 0L, event);
  27614. XFlush (display);
  27615. }
  27616. }
  27617. void mouseEnter (const MouseEvent& e)
  27618. {
  27619. if (pluginWindow != 0)
  27620. {
  27621. XEvent ev;
  27622. zerostruct (ev);
  27623. ev.xcrossing.display = display;
  27624. ev.xcrossing.type = EnterNotify;
  27625. ev.xcrossing.window = pluginWindow;
  27626. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27627. ev.xcrossing.time = CurrentTime;
  27628. ev.xcrossing.x = e.x;
  27629. ev.xcrossing.y = e.y;
  27630. ev.xcrossing.x_root = e.getScreenX();
  27631. ev.xcrossing.y_root = e.getScreenY();
  27632. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27633. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27634. translateJuceToXCrossingModifiers (e, ev);
  27635. sendEventToChild (&ev);
  27636. }
  27637. }
  27638. void mouseExit (const MouseEvent& e)
  27639. {
  27640. if (pluginWindow != 0)
  27641. {
  27642. XEvent ev;
  27643. zerostruct (ev);
  27644. ev.xcrossing.display = display;
  27645. ev.xcrossing.type = LeaveNotify;
  27646. ev.xcrossing.window = pluginWindow;
  27647. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27648. ev.xcrossing.time = CurrentTime;
  27649. ev.xcrossing.x = e.x;
  27650. ev.xcrossing.y = e.y;
  27651. ev.xcrossing.x_root = e.getScreenX();
  27652. ev.xcrossing.y_root = e.getScreenY();
  27653. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27654. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27655. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27656. translateJuceToXCrossingModifiers (e, ev);
  27657. sendEventToChild (&ev);
  27658. }
  27659. }
  27660. void mouseMove (const MouseEvent& e)
  27661. {
  27662. if (pluginWindow != 0)
  27663. {
  27664. XEvent ev;
  27665. zerostruct (ev);
  27666. ev.xmotion.display = display;
  27667. ev.xmotion.type = MotionNotify;
  27668. ev.xmotion.window = pluginWindow;
  27669. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27670. ev.xmotion.time = CurrentTime;
  27671. ev.xmotion.is_hint = NotifyNormal;
  27672. ev.xmotion.x = e.x;
  27673. ev.xmotion.y = e.y;
  27674. ev.xmotion.x_root = e.getScreenX();
  27675. ev.xmotion.y_root = e.getScreenY();
  27676. sendEventToChild (&ev);
  27677. }
  27678. }
  27679. void mouseDrag (const MouseEvent& e)
  27680. {
  27681. if (pluginWindow != 0)
  27682. {
  27683. XEvent ev;
  27684. zerostruct (ev);
  27685. ev.xmotion.display = display;
  27686. ev.xmotion.type = MotionNotify;
  27687. ev.xmotion.window = pluginWindow;
  27688. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27689. ev.xmotion.time = CurrentTime;
  27690. ev.xmotion.x = e.x ;
  27691. ev.xmotion.y = e.y;
  27692. ev.xmotion.x_root = e.getScreenX();
  27693. ev.xmotion.y_root = e.getScreenY();
  27694. ev.xmotion.is_hint = NotifyNormal;
  27695. translateJuceToXMotionModifiers (e, ev);
  27696. sendEventToChild (&ev);
  27697. }
  27698. }
  27699. void mouseUp (const MouseEvent& e)
  27700. {
  27701. if (pluginWindow != 0)
  27702. {
  27703. XEvent ev;
  27704. zerostruct (ev);
  27705. ev.xbutton.display = display;
  27706. ev.xbutton.type = ButtonRelease;
  27707. ev.xbutton.window = pluginWindow;
  27708. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27709. ev.xbutton.time = CurrentTime;
  27710. ev.xbutton.x = e.x;
  27711. ev.xbutton.y = e.y;
  27712. ev.xbutton.x_root = e.getScreenX();
  27713. ev.xbutton.y_root = e.getScreenY();
  27714. translateJuceToXButtonModifiers (e, ev);
  27715. sendEventToChild (&ev);
  27716. }
  27717. }
  27718. void mouseWheelMove (const MouseEvent& e,
  27719. float incrementX,
  27720. float incrementY)
  27721. {
  27722. if (pluginWindow != 0)
  27723. {
  27724. XEvent ev;
  27725. zerostruct (ev);
  27726. ev.xbutton.display = display;
  27727. ev.xbutton.type = ButtonPress;
  27728. ev.xbutton.window = pluginWindow;
  27729. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27730. ev.xbutton.time = CurrentTime;
  27731. ev.xbutton.x = e.x;
  27732. ev.xbutton.y = e.y;
  27733. ev.xbutton.x_root = e.getScreenX();
  27734. ev.xbutton.y_root = e.getScreenY();
  27735. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27736. sendEventToChild (&ev);
  27737. // TODO - put a usleep here ?
  27738. ev.xbutton.type = ButtonRelease;
  27739. sendEventToChild (&ev);
  27740. }
  27741. }
  27742. #endif
  27743. #if JUCE_MAC
  27744. #if ! JUCE_SUPPORT_CARBON
  27745. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27746. #endif
  27747. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27748. {
  27749. public:
  27750. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27751. : owner (owner_),
  27752. alreadyInside (false)
  27753. {
  27754. }
  27755. ~InnerWrapperComponent()
  27756. {
  27757. deleteWindow();
  27758. }
  27759. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27760. {
  27761. owner->openPluginWindow (windowRef);
  27762. return 0;
  27763. }
  27764. void removeView (HIViewRef)
  27765. {
  27766. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27767. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27768. }
  27769. bool getEmbeddedViewSize (int& w, int& h)
  27770. {
  27771. ERect* rect = 0;
  27772. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27773. w = rect->right - rect->left;
  27774. h = rect->bottom - rect->top;
  27775. return true;
  27776. }
  27777. void mouseDown (int x, int y)
  27778. {
  27779. if (! alreadyInside)
  27780. {
  27781. alreadyInside = true;
  27782. getTopLevelComponent()->toFront (true);
  27783. owner->dispatch (effEditMouse, x, y, 0, 0);
  27784. alreadyInside = false;
  27785. }
  27786. else
  27787. {
  27788. PostEvent (::mouseDown, 0);
  27789. }
  27790. }
  27791. void paint()
  27792. {
  27793. ComponentPeer* const peer = getPeer();
  27794. if (peer != 0)
  27795. {
  27796. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27797. ERect r;
  27798. r.left = pos.getX();
  27799. r.right = r.left + getWidth();
  27800. r.top = pos.getY();
  27801. r.bottom = r.top + getHeight();
  27802. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27803. }
  27804. }
  27805. private:
  27806. VSTPluginWindow* const owner;
  27807. bool alreadyInside;
  27808. };
  27809. friend class InnerWrapperComponent;
  27810. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27811. void resized()
  27812. {
  27813. innerWrapper->setSize (getWidth(), getHeight());
  27814. }
  27815. #endif
  27816. };
  27817. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27818. {
  27819. if (hasEditor())
  27820. return new VSTPluginWindow (*this);
  27821. return 0;
  27822. }
  27823. void VSTPluginInstance::handleAsyncUpdate()
  27824. {
  27825. // indicates that something about the plugin has changed..
  27826. updateHostDisplay();
  27827. }
  27828. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27829. {
  27830. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27831. {
  27832. changeProgramName (getCurrentProgram(), prog->prgName);
  27833. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27834. setParameter (i, vst_swapFloat (prog->params[i]));
  27835. return true;
  27836. }
  27837. return false;
  27838. }
  27839. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27840. const int dataSize)
  27841. {
  27842. if (dataSize < 28)
  27843. return false;
  27844. const fxSet* const set = (const fxSet*) data;
  27845. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27846. || vst_swap (set->version) > fxbVersionNum)
  27847. return false;
  27848. if (vst_swap (set->fxMagic) == 'FxBk')
  27849. {
  27850. // bank of programs
  27851. if (vst_swap (set->numPrograms) >= 0)
  27852. {
  27853. const int oldProg = getCurrentProgram();
  27854. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27855. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27856. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27857. {
  27858. if (i != oldProg)
  27859. {
  27860. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27861. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27862. return false;
  27863. if (vst_swap (set->numPrograms) > 0)
  27864. setCurrentProgram (i);
  27865. if (! restoreProgramSettings (prog))
  27866. return false;
  27867. }
  27868. }
  27869. if (vst_swap (set->numPrograms) > 0)
  27870. setCurrentProgram (oldProg);
  27871. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27872. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27873. return false;
  27874. if (! restoreProgramSettings (prog))
  27875. return false;
  27876. }
  27877. }
  27878. else if (vst_swap (set->fxMagic) == 'FxCk')
  27879. {
  27880. // single program
  27881. const fxProgram* const prog = (const fxProgram*) data;
  27882. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27883. return false;
  27884. changeProgramName (getCurrentProgram(), prog->prgName);
  27885. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27886. setParameter (i, vst_swapFloat (prog->params[i]));
  27887. }
  27888. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27889. {
  27890. // non-preset chunk
  27891. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27892. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27893. return false;
  27894. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27895. }
  27896. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27897. {
  27898. // preset chunk
  27899. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27900. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27901. return false;
  27902. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27903. changeProgramName (getCurrentProgram(), cset->name);
  27904. }
  27905. else
  27906. {
  27907. return false;
  27908. }
  27909. return true;
  27910. }
  27911. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  27912. {
  27913. const int numParams = getNumParameters();
  27914. prog->chunkMagic = vst_swap ('CcnK');
  27915. prog->byteSize = 0;
  27916. prog->fxMagic = vst_swap ('FxCk');
  27917. prog->version = vst_swap (fxbVersionNum);
  27918. prog->fxID = vst_swap (getUID());
  27919. prog->fxVersion = vst_swap (getVersionNumber());
  27920. prog->numParams = vst_swap (numParams);
  27921. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27922. for (int i = 0; i < numParams; ++i)
  27923. prog->params[i] = vst_swapFloat (getParameter (i));
  27924. }
  27925. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27926. {
  27927. const int numPrograms = getNumPrograms();
  27928. const int numParams = getNumParameters();
  27929. if (usesChunks())
  27930. {
  27931. if (isFXB)
  27932. {
  27933. MemoryBlock chunk;
  27934. getChunkData (chunk, false, maxSizeMB);
  27935. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27936. dest.setSize (totalLen, true);
  27937. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27938. set->chunkMagic = vst_swap ('CcnK');
  27939. set->byteSize = 0;
  27940. set->fxMagic = vst_swap ('FBCh');
  27941. set->version = vst_swap (fxbVersionNum);
  27942. set->fxID = vst_swap (getUID());
  27943. set->fxVersion = vst_swap (getVersionNumber());
  27944. set->numPrograms = vst_swap (numPrograms);
  27945. set->chunkSize = vst_swap ((long) chunk.getSize());
  27946. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27947. }
  27948. else
  27949. {
  27950. MemoryBlock chunk;
  27951. getChunkData (chunk, true, maxSizeMB);
  27952. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27953. dest.setSize (totalLen, true);
  27954. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27955. set->chunkMagic = vst_swap ('CcnK');
  27956. set->byteSize = 0;
  27957. set->fxMagic = vst_swap ('FPCh');
  27958. set->version = vst_swap (fxbVersionNum);
  27959. set->fxID = vst_swap (getUID());
  27960. set->fxVersion = vst_swap (getVersionNumber());
  27961. set->numPrograms = vst_swap (numPrograms);
  27962. set->chunkSize = vst_swap ((long) chunk.getSize());
  27963. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27964. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27965. }
  27966. }
  27967. else
  27968. {
  27969. if (isFXB)
  27970. {
  27971. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27972. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27973. dest.setSize (len, true);
  27974. fxSet* const set = (fxSet*) dest.getData();
  27975. set->chunkMagic = vst_swap ('CcnK');
  27976. set->byteSize = 0;
  27977. set->fxMagic = vst_swap ('FxBk');
  27978. set->version = vst_swap (fxbVersionNum);
  27979. set->fxID = vst_swap (getUID());
  27980. set->fxVersion = vst_swap (getVersionNumber());
  27981. set->numPrograms = vst_swap (numPrograms);
  27982. const int oldProgram = getCurrentProgram();
  27983. MemoryBlock oldSettings;
  27984. createTempParameterStore (oldSettings);
  27985. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27986. for (int i = 0; i < numPrograms; ++i)
  27987. {
  27988. if (i != oldProgram)
  27989. {
  27990. setCurrentProgram (i);
  27991. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27992. }
  27993. }
  27994. setCurrentProgram (oldProgram);
  27995. restoreFromTempParameterStore (oldSettings);
  27996. }
  27997. else
  27998. {
  27999. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28000. dest.setSize (totalLen, true);
  28001. setParamsInProgramBlock ((fxProgram*) dest.getData());
  28002. }
  28003. }
  28004. return true;
  28005. }
  28006. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  28007. {
  28008. if (usesChunks())
  28009. {
  28010. void* data = 0;
  28011. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  28012. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  28013. {
  28014. mb.setSize (bytes);
  28015. mb.copyFrom (data, 0, bytes);
  28016. }
  28017. }
  28018. }
  28019. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28020. {
  28021. if (size > 0 && usesChunks())
  28022. {
  28023. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28024. if (! isPreset)
  28025. updateStoredProgramNames();
  28026. }
  28027. }
  28028. void VSTPluginInstance::timerCallback()
  28029. {
  28030. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28031. stopTimer();
  28032. }
  28033. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28034. {
  28035. const ScopedLock sl (lock);
  28036. ++insideVSTCallback;
  28037. int result = 0;
  28038. try
  28039. {
  28040. if (effect != 0)
  28041. {
  28042. #if JUCE_MAC
  28043. if (module->resFileId != 0)
  28044. UseResFile (module->resFileId);
  28045. #endif
  28046. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28047. #if JUCE_MAC
  28048. module->resFileId = CurResFile();
  28049. #endif
  28050. --insideVSTCallback;
  28051. return result;
  28052. }
  28053. }
  28054. catch (...)
  28055. {
  28056. }
  28057. --insideVSTCallback;
  28058. return result;
  28059. }
  28060. // handles non plugin-specific callbacks..
  28061. static const int defaultVSTSampleRateValue = 16384;
  28062. static const int defaultVSTBlockSizeValue = 512;
  28063. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28064. {
  28065. (void) index;
  28066. (void) value;
  28067. (void) opt;
  28068. switch (opcode)
  28069. {
  28070. case audioMasterCanDo:
  28071. {
  28072. static const char* canDos[] = { "supplyIdle",
  28073. "sendVstEvents",
  28074. "sendVstMidiEvent",
  28075. "sendVstTimeInfo",
  28076. "receiveVstEvents",
  28077. "receiveVstMidiEvent",
  28078. "supportShell",
  28079. "shellCategory" };
  28080. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28081. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28082. return 1;
  28083. return 0;
  28084. }
  28085. case audioMasterVersion: return 0x2400;
  28086. case audioMasterCurrentId: return shellUIDToCreate;
  28087. case audioMasterGetNumAutomatableParameters: return 0;
  28088. case audioMasterGetAutomationState: return 1;
  28089. case audioMasterGetVendorVersion: return 0x0101;
  28090. case audioMasterGetVendorString:
  28091. case audioMasterGetProductString:
  28092. {
  28093. String hostName ("Juce VST Host");
  28094. if (JUCEApplication::getInstance() != 0)
  28095. hostName = JUCEApplication::getInstance()->getApplicationName();
  28096. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28097. break;
  28098. }
  28099. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28100. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28101. case audioMasterSetOutputSampleRate: return 0;
  28102. default:
  28103. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28104. break;
  28105. }
  28106. return 0;
  28107. }
  28108. // handles callbacks for a specific plugin
  28109. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28110. {
  28111. switch (opcode)
  28112. {
  28113. case audioMasterAutomate:
  28114. sendParamChangeMessageToListeners (index, opt);
  28115. break;
  28116. case audioMasterProcessEvents:
  28117. handleMidiFromPlugin ((const VstEvents*) ptr);
  28118. break;
  28119. case audioMasterGetTime:
  28120. #if JUCE_MSVC
  28121. #pragma warning (push)
  28122. #pragma warning (disable: 4311)
  28123. #endif
  28124. return (VstIntPtr) &vstHostTime;
  28125. #if JUCE_MSVC
  28126. #pragma warning (pop)
  28127. #endif
  28128. break;
  28129. case audioMasterIdle:
  28130. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28131. {
  28132. ++insideVSTCallback;
  28133. #if JUCE_MAC
  28134. if (getActiveEditor() != 0)
  28135. dispatch (effEditIdle, 0, 0, 0, 0);
  28136. #endif
  28137. juce_callAnyTimersSynchronously();
  28138. handleUpdateNowIfNeeded();
  28139. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28140. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28141. --insideVSTCallback;
  28142. }
  28143. break;
  28144. case audioMasterUpdateDisplay:
  28145. triggerAsyncUpdate();
  28146. break;
  28147. case audioMasterTempoAt:
  28148. // returns (10000 * bpm)
  28149. break;
  28150. case audioMasterNeedIdle:
  28151. startTimer (50);
  28152. break;
  28153. case audioMasterSizeWindow:
  28154. if (getActiveEditor() != 0)
  28155. getActiveEditor()->setSize (index, value);
  28156. return 1;
  28157. case audioMasterGetSampleRate:
  28158. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28159. case audioMasterGetBlockSize:
  28160. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28161. case audioMasterWantMidi:
  28162. wantsMidiMessages = true;
  28163. break;
  28164. case audioMasterGetDirectory:
  28165. #if JUCE_MAC
  28166. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28167. #else
  28168. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28169. #endif
  28170. case audioMasterGetAutomationState:
  28171. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28172. break;
  28173. // none of these are handled (yet)..
  28174. case audioMasterBeginEdit:
  28175. case audioMasterEndEdit:
  28176. case audioMasterSetTime:
  28177. case audioMasterPinConnected:
  28178. case audioMasterGetParameterQuantization:
  28179. case audioMasterIOChanged:
  28180. case audioMasterGetInputLatency:
  28181. case audioMasterGetOutputLatency:
  28182. case audioMasterGetPreviousPlug:
  28183. case audioMasterGetNextPlug:
  28184. case audioMasterWillReplaceOrAccumulate:
  28185. case audioMasterGetCurrentProcessLevel:
  28186. case audioMasterOfflineStart:
  28187. case audioMasterOfflineRead:
  28188. case audioMasterOfflineWrite:
  28189. case audioMasterOfflineGetCurrentPass:
  28190. case audioMasterOfflineGetCurrentMetaPass:
  28191. case audioMasterVendorSpecific:
  28192. case audioMasterSetIcon:
  28193. case audioMasterGetLanguage:
  28194. case audioMasterOpenWindow:
  28195. case audioMasterCloseWindow:
  28196. break;
  28197. default:
  28198. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28199. }
  28200. return 0;
  28201. }
  28202. // entry point for all callbacks from the plugin
  28203. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28204. {
  28205. try
  28206. {
  28207. if (effect != 0 && effect->resvd2 != 0)
  28208. {
  28209. return ((VSTPluginInstance*)(effect->resvd2))
  28210. ->handleCallback (opcode, index, value, ptr, opt);
  28211. }
  28212. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28213. }
  28214. catch (...)
  28215. {
  28216. return 0;
  28217. }
  28218. }
  28219. const String VSTPluginInstance::getVersion() const
  28220. {
  28221. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28222. String s;
  28223. if (v == 0 || v == -1)
  28224. v = getVersionNumber();
  28225. if (v != 0)
  28226. {
  28227. int versionBits[4];
  28228. int n = 0;
  28229. while (v != 0)
  28230. {
  28231. versionBits [n++] = (v & 0xff);
  28232. v >>= 8;
  28233. }
  28234. s << 'V';
  28235. while (n > 0)
  28236. {
  28237. s << versionBits [--n];
  28238. if (n > 0)
  28239. s << '.';
  28240. }
  28241. }
  28242. return s;
  28243. }
  28244. int VSTPluginInstance::getUID() const
  28245. {
  28246. int uid = effect != 0 ? effect->uniqueID : 0;
  28247. if (uid == 0)
  28248. uid = module->file.hashCode();
  28249. return uid;
  28250. }
  28251. const String VSTPluginInstance::getCategory() const
  28252. {
  28253. const char* result = 0;
  28254. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28255. {
  28256. case kPlugCategEffect: result = "Effect"; break;
  28257. case kPlugCategSynth: result = "Synth"; break;
  28258. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28259. case kPlugCategMastering: result = "Mastering"; break;
  28260. case kPlugCategSpacializer: result = "Spacial"; break;
  28261. case kPlugCategRoomFx: result = "Reverb"; break;
  28262. case kPlugSurroundFx: result = "Surround"; break;
  28263. case kPlugCategRestoration: result = "Restoration"; break;
  28264. case kPlugCategGenerator: result = "Tone generation"; break;
  28265. default: break;
  28266. }
  28267. return result;
  28268. }
  28269. float VSTPluginInstance::getParameter (int index)
  28270. {
  28271. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28272. {
  28273. try
  28274. {
  28275. const ScopedLock sl (lock);
  28276. return effect->getParameter (effect, index);
  28277. }
  28278. catch (...)
  28279. {
  28280. }
  28281. }
  28282. return 0.0f;
  28283. }
  28284. void VSTPluginInstance::setParameter (int index, float newValue)
  28285. {
  28286. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28287. {
  28288. try
  28289. {
  28290. const ScopedLock sl (lock);
  28291. if (effect->getParameter (effect, index) != newValue)
  28292. effect->setParameter (effect, index, newValue);
  28293. }
  28294. catch (...)
  28295. {
  28296. }
  28297. }
  28298. }
  28299. const String VSTPluginInstance::getParameterName (int index)
  28300. {
  28301. if (effect != 0)
  28302. {
  28303. jassert (index >= 0 && index < effect->numParams);
  28304. char nm [256];
  28305. zerostruct (nm);
  28306. dispatch (effGetParamName, index, 0, nm, 0);
  28307. return String (nm).trim();
  28308. }
  28309. return String::empty;
  28310. }
  28311. const String VSTPluginInstance::getParameterLabel (int index) const
  28312. {
  28313. if (effect != 0)
  28314. {
  28315. jassert (index >= 0 && index < effect->numParams);
  28316. char nm [256];
  28317. zerostruct (nm);
  28318. dispatch (effGetParamLabel, index, 0, nm, 0);
  28319. return String (nm).trim();
  28320. }
  28321. return String::empty;
  28322. }
  28323. const String VSTPluginInstance::getParameterText (int index)
  28324. {
  28325. if (effect != 0)
  28326. {
  28327. jassert (index >= 0 && index < effect->numParams);
  28328. char nm [256];
  28329. zerostruct (nm);
  28330. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28331. return String (nm).trim();
  28332. }
  28333. return String::empty;
  28334. }
  28335. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28336. {
  28337. if (effect != 0)
  28338. {
  28339. jassert (index >= 0 && index < effect->numParams);
  28340. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28341. }
  28342. return false;
  28343. }
  28344. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28345. {
  28346. dest.setSize (64 + 4 * getNumParameters());
  28347. dest.fillWith (0);
  28348. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28349. float* const p = (float*) (((char*) dest.getData()) + 64);
  28350. for (int i = 0; i < getNumParameters(); ++i)
  28351. p[i] = getParameter(i);
  28352. }
  28353. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28354. {
  28355. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28356. float* p = (float*) (((char*) m.getData()) + 64);
  28357. for (int i = 0; i < getNumParameters(); ++i)
  28358. setParameter (i, p[i]);
  28359. }
  28360. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28361. {
  28362. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28363. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28364. }
  28365. const String VSTPluginInstance::getProgramName (int index)
  28366. {
  28367. if (index == getCurrentProgram())
  28368. {
  28369. return getCurrentProgramName();
  28370. }
  28371. else if (effect != 0)
  28372. {
  28373. char nm [256];
  28374. zerostruct (nm);
  28375. if (dispatch (effGetProgramNameIndexed,
  28376. jlimit (0, getNumPrograms(), index),
  28377. -1, nm, 0) != 0)
  28378. {
  28379. return String (nm).trim();
  28380. }
  28381. }
  28382. return programNames [index];
  28383. }
  28384. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28385. {
  28386. if (index == getCurrentProgram())
  28387. {
  28388. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28389. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28390. }
  28391. else
  28392. {
  28393. jassertfalse; // xxx not implemented!
  28394. }
  28395. }
  28396. void VSTPluginInstance::updateStoredProgramNames()
  28397. {
  28398. if (effect != 0 && getNumPrograms() > 0)
  28399. {
  28400. char nm [256];
  28401. zerostruct (nm);
  28402. // only do this if the plugin can't use indexed names..
  28403. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28404. {
  28405. const int oldProgram = getCurrentProgram();
  28406. MemoryBlock oldSettings;
  28407. createTempParameterStore (oldSettings);
  28408. for (int i = 0; i < getNumPrograms(); ++i)
  28409. {
  28410. setCurrentProgram (i);
  28411. getCurrentProgramName(); // (this updates the list)
  28412. }
  28413. setCurrentProgram (oldProgram);
  28414. restoreFromTempParameterStore (oldSettings);
  28415. }
  28416. }
  28417. }
  28418. const String VSTPluginInstance::getCurrentProgramName()
  28419. {
  28420. if (effect != 0)
  28421. {
  28422. char nm [256];
  28423. zerostruct (nm);
  28424. dispatch (effGetProgramName, 0, 0, nm, 0);
  28425. const int index = getCurrentProgram();
  28426. if (programNames[index].isEmpty())
  28427. {
  28428. while (programNames.size() < index)
  28429. programNames.add (String::empty);
  28430. programNames.set (index, String (nm).trim());
  28431. }
  28432. return String (nm).trim();
  28433. }
  28434. return String::empty;
  28435. }
  28436. const String VSTPluginInstance::getInputChannelName (int index) const
  28437. {
  28438. if (index >= 0 && index < getNumInputChannels())
  28439. {
  28440. VstPinProperties pinProps;
  28441. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28442. return String (pinProps.label, sizeof (pinProps.label));
  28443. }
  28444. return String::empty;
  28445. }
  28446. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28447. {
  28448. if (index < 0 || index >= getNumInputChannels())
  28449. return false;
  28450. VstPinProperties pinProps;
  28451. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28452. return (pinProps.flags & kVstPinIsStereo) != 0;
  28453. return true;
  28454. }
  28455. const String VSTPluginInstance::getOutputChannelName (int index) const
  28456. {
  28457. if (index >= 0 && index < getNumOutputChannels())
  28458. {
  28459. VstPinProperties pinProps;
  28460. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28461. return String (pinProps.label, sizeof (pinProps.label));
  28462. }
  28463. return String::empty;
  28464. }
  28465. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28466. {
  28467. if (index < 0 || index >= getNumOutputChannels())
  28468. return false;
  28469. VstPinProperties pinProps;
  28470. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28471. return (pinProps.flags & kVstPinIsStereo) != 0;
  28472. return true;
  28473. }
  28474. void VSTPluginInstance::setPower (const bool on)
  28475. {
  28476. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28477. isPowerOn = on;
  28478. }
  28479. const int defaultMaxSizeMB = 64;
  28480. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28481. {
  28482. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28483. }
  28484. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28485. {
  28486. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28487. }
  28488. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28489. {
  28490. loadFromFXBFile (data, sizeInBytes);
  28491. }
  28492. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28493. {
  28494. loadFromFXBFile (data, sizeInBytes);
  28495. }
  28496. VSTPluginFormat::VSTPluginFormat()
  28497. {
  28498. }
  28499. VSTPluginFormat::~VSTPluginFormat()
  28500. {
  28501. }
  28502. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28503. const String& fileOrIdentifier)
  28504. {
  28505. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28506. return;
  28507. PluginDescription desc;
  28508. desc.fileOrIdentifier = fileOrIdentifier;
  28509. desc.uid = 0;
  28510. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28511. if (instance == 0)
  28512. return;
  28513. try
  28514. {
  28515. #if JUCE_MAC
  28516. if (instance->module->resFileId != 0)
  28517. UseResFile (instance->module->resFileId);
  28518. #endif
  28519. instance->fillInPluginDescription (desc);
  28520. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28521. if (category != kPlugCategShell)
  28522. {
  28523. // Normal plugin...
  28524. results.add (new PluginDescription (desc));
  28525. ++insideVSTCallback;
  28526. instance->dispatch (effOpen, 0, 0, 0, 0);
  28527. --insideVSTCallback;
  28528. }
  28529. else
  28530. {
  28531. // It's a shell plugin, so iterate all the subtypes...
  28532. char shellEffectName [64];
  28533. for (;;)
  28534. {
  28535. zerostruct (shellEffectName);
  28536. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28537. if (uid == 0)
  28538. {
  28539. break;
  28540. }
  28541. else
  28542. {
  28543. desc.uid = uid;
  28544. desc.name = shellEffectName;
  28545. bool alreadyThere = false;
  28546. for (int i = results.size(); --i >= 0;)
  28547. {
  28548. PluginDescription* const d = results.getUnchecked(i);
  28549. if (d->isDuplicateOf (desc))
  28550. {
  28551. alreadyThere = true;
  28552. break;
  28553. }
  28554. }
  28555. if (! alreadyThere)
  28556. results.add (new PluginDescription (desc));
  28557. }
  28558. }
  28559. }
  28560. }
  28561. catch (...)
  28562. {
  28563. // crashed while loading...
  28564. }
  28565. }
  28566. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28567. {
  28568. ScopedPointer <VSTPluginInstance> result;
  28569. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28570. {
  28571. File file (desc.fileOrIdentifier);
  28572. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28573. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28574. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28575. if (module != 0)
  28576. {
  28577. shellUIDToCreate = desc.uid;
  28578. result = new VSTPluginInstance (module);
  28579. if (result->effect != 0)
  28580. {
  28581. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28582. result->initialise();
  28583. }
  28584. else
  28585. {
  28586. result = 0;
  28587. }
  28588. }
  28589. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28590. }
  28591. return result.release();
  28592. }
  28593. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28594. {
  28595. const File f (fileOrIdentifier);
  28596. #if JUCE_MAC
  28597. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28598. return true;
  28599. #if JUCE_PPC
  28600. FSRef fileRef;
  28601. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28602. {
  28603. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28604. if (resFileId != -1)
  28605. {
  28606. const int numEffects = Count1Resources ('aEff');
  28607. CloseResFile (resFileId);
  28608. if (numEffects > 0)
  28609. return true;
  28610. }
  28611. }
  28612. #endif
  28613. return false;
  28614. #elif JUCE_WINDOWS
  28615. return f.existsAsFile() && f.hasFileExtension (".dll");
  28616. #elif JUCE_LINUX
  28617. return f.existsAsFile() && f.hasFileExtension (".so");
  28618. #endif
  28619. }
  28620. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28621. {
  28622. return fileOrIdentifier;
  28623. }
  28624. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28625. {
  28626. return File (desc.fileOrIdentifier).exists();
  28627. }
  28628. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28629. {
  28630. StringArray results;
  28631. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28632. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28633. return results;
  28634. }
  28635. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28636. {
  28637. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28638. // .component or .vst directories.
  28639. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28640. while (iter.next())
  28641. {
  28642. const File f (iter.getFile());
  28643. bool isPlugin = false;
  28644. if (fileMightContainThisPluginType (f.getFullPathName()))
  28645. {
  28646. isPlugin = true;
  28647. results.add (f.getFullPathName());
  28648. }
  28649. if (recursive && (! isPlugin) && f.isDirectory())
  28650. recursiveFileSearch (results, f, true);
  28651. }
  28652. }
  28653. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28654. {
  28655. #if JUCE_MAC
  28656. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28657. #elif JUCE_WINDOWS
  28658. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28659. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28660. #elif JUCE_LINUX
  28661. return FileSearchPath ("/usr/lib/vst");
  28662. #endif
  28663. }
  28664. END_JUCE_NAMESPACE
  28665. #endif
  28666. #undef log
  28667. #endif
  28668. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28669. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28670. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28671. BEGIN_JUCE_NAMESPACE
  28672. AudioProcessor::AudioProcessor()
  28673. : playHead (0),
  28674. activeEditor (0),
  28675. sampleRate (0),
  28676. blockSize (0),
  28677. numInputChannels (0),
  28678. numOutputChannels (0),
  28679. latencySamples (0),
  28680. suspended (false),
  28681. nonRealtime (false)
  28682. {
  28683. }
  28684. AudioProcessor::~AudioProcessor()
  28685. {
  28686. // ooh, nasty - the editor should have been deleted before the filter
  28687. // that it refers to is deleted..
  28688. jassert (activeEditor == 0);
  28689. #if JUCE_DEBUG
  28690. // This will fail if you've called beginParameterChangeGesture() for one
  28691. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28692. jassert (changingParams.countNumberOfSetBits() == 0);
  28693. #endif
  28694. }
  28695. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28696. {
  28697. playHead = newPlayHead;
  28698. }
  28699. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28700. {
  28701. const ScopedLock sl (listenerLock);
  28702. listeners.addIfNotAlreadyThere (newListener);
  28703. }
  28704. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28705. {
  28706. const ScopedLock sl (listenerLock);
  28707. listeners.removeValue (listenerToRemove);
  28708. }
  28709. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28710. const int numOuts,
  28711. const double sampleRate_,
  28712. const int blockSize_) throw()
  28713. {
  28714. numInputChannels = numIns;
  28715. numOutputChannels = numOuts;
  28716. sampleRate = sampleRate_;
  28717. blockSize = blockSize_;
  28718. }
  28719. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28720. {
  28721. nonRealtime = nonRealtime_;
  28722. }
  28723. void AudioProcessor::setLatencySamples (const int newLatency)
  28724. {
  28725. if (latencySamples != newLatency)
  28726. {
  28727. latencySamples = newLatency;
  28728. updateHostDisplay();
  28729. }
  28730. }
  28731. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28732. const float newValue)
  28733. {
  28734. setParameter (parameterIndex, newValue);
  28735. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28736. }
  28737. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28738. {
  28739. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28740. for (int i = listeners.size(); --i >= 0;)
  28741. {
  28742. AudioProcessorListener* l;
  28743. {
  28744. const ScopedLock sl (listenerLock);
  28745. l = listeners [i];
  28746. }
  28747. if (l != 0)
  28748. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28749. }
  28750. }
  28751. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28752. {
  28753. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28754. #if JUCE_DEBUG
  28755. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28756. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28757. jassert (! changingParams [parameterIndex]);
  28758. changingParams.setBit (parameterIndex);
  28759. #endif
  28760. for (int i = listeners.size(); --i >= 0;)
  28761. {
  28762. AudioProcessorListener* l;
  28763. {
  28764. const ScopedLock sl (listenerLock);
  28765. l = listeners [i];
  28766. }
  28767. if (l != 0)
  28768. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28769. }
  28770. }
  28771. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28772. {
  28773. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28774. #if JUCE_DEBUG
  28775. // This means you've called endParameterChangeGesture without having previously called
  28776. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28777. // calls matched correctly.
  28778. jassert (changingParams [parameterIndex]);
  28779. changingParams.clearBit (parameterIndex);
  28780. #endif
  28781. for (int i = listeners.size(); --i >= 0;)
  28782. {
  28783. AudioProcessorListener* l;
  28784. {
  28785. const ScopedLock sl (listenerLock);
  28786. l = listeners [i];
  28787. }
  28788. if (l != 0)
  28789. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28790. }
  28791. }
  28792. void AudioProcessor::updateHostDisplay()
  28793. {
  28794. for (int i = listeners.size(); --i >= 0;)
  28795. {
  28796. AudioProcessorListener* l;
  28797. {
  28798. const ScopedLock sl (listenerLock);
  28799. l = listeners [i];
  28800. }
  28801. if (l != 0)
  28802. l->audioProcessorChanged (this);
  28803. }
  28804. }
  28805. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28806. {
  28807. return true;
  28808. }
  28809. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28810. {
  28811. return false;
  28812. }
  28813. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28814. {
  28815. const ScopedLock sl (callbackLock);
  28816. suspended = shouldBeSuspended;
  28817. }
  28818. void AudioProcessor::reset()
  28819. {
  28820. }
  28821. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28822. {
  28823. const ScopedLock sl (callbackLock);
  28824. jassert (activeEditor == editor);
  28825. if (activeEditor == editor)
  28826. activeEditor = 0;
  28827. }
  28828. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28829. {
  28830. if (activeEditor != 0)
  28831. return activeEditor;
  28832. AudioProcessorEditor* const ed = createEditor();
  28833. // You must make your hasEditor() method return a consistent result!
  28834. jassert (hasEditor() == (ed != 0));
  28835. if (ed != 0)
  28836. {
  28837. // you must give your editor comp a size before returning it..
  28838. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28839. const ScopedLock sl (callbackLock);
  28840. activeEditor = ed;
  28841. }
  28842. return ed;
  28843. }
  28844. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28845. {
  28846. getStateInformation (destData);
  28847. }
  28848. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28849. {
  28850. setStateInformation (data, sizeInBytes);
  28851. }
  28852. // magic number to identify memory blocks that we've stored as XML
  28853. const uint32 magicXmlNumber = 0x21324356;
  28854. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28855. JUCE_NAMESPACE::MemoryBlock& destData)
  28856. {
  28857. const String xmlString (xml.createDocument (String::empty, true, false));
  28858. const int stringLength = xmlString.getNumBytesAsUTF8();
  28859. destData.setSize (stringLength + 10);
  28860. char* const d = static_cast<char*> (destData.getData());
  28861. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28862. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28863. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28864. }
  28865. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28866. const int sizeInBytes)
  28867. {
  28868. if (sizeInBytes > 8
  28869. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28870. {
  28871. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28872. if (stringLength > 0)
  28873. {
  28874. XmlDocument doc (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28875. jmin ((sizeInBytes - 8), stringLength)));
  28876. return doc.getDocumentElement();
  28877. }
  28878. }
  28879. return 0;
  28880. }
  28881. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28882. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28883. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28884. {
  28885. return timeInSeconds == other.timeInSeconds
  28886. && ppqPosition == other.ppqPosition
  28887. && editOriginTime == other.editOriginTime
  28888. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28889. && frameRate == other.frameRate
  28890. && isPlaying == other.isPlaying
  28891. && isRecording == other.isRecording
  28892. && bpm == other.bpm
  28893. && timeSigNumerator == other.timeSigNumerator
  28894. && timeSigDenominator == other.timeSigDenominator;
  28895. }
  28896. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28897. {
  28898. return ! operator== (other);
  28899. }
  28900. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28901. {
  28902. zerostruct (*this);
  28903. timeSigNumerator = 4;
  28904. timeSigDenominator = 4;
  28905. bpm = 120;
  28906. }
  28907. END_JUCE_NAMESPACE
  28908. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28909. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28910. BEGIN_JUCE_NAMESPACE
  28911. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28912. : owner (owner_)
  28913. {
  28914. // the filter must be valid..
  28915. jassert (owner != 0);
  28916. }
  28917. AudioProcessorEditor::~AudioProcessorEditor()
  28918. {
  28919. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28920. // filter for some reason..
  28921. jassert (owner->getActiveEditor() != this);
  28922. }
  28923. END_JUCE_NAMESPACE
  28924. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28925. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28926. BEGIN_JUCE_NAMESPACE
  28927. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28928. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28929. : id (id_),
  28930. processor (processor_),
  28931. isPrepared (false)
  28932. {
  28933. jassert (processor_ != 0);
  28934. }
  28935. AudioProcessorGraph::Node::~Node()
  28936. {
  28937. }
  28938. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28939. AudioProcessorGraph* const graph)
  28940. {
  28941. if (! isPrepared)
  28942. {
  28943. isPrepared = true;
  28944. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28945. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28946. if (ioProc != 0)
  28947. ioProc->setParentGraph (graph);
  28948. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28949. processor->getNumOutputChannels(),
  28950. sampleRate, blockSize);
  28951. processor->prepareToPlay (sampleRate, blockSize);
  28952. }
  28953. }
  28954. void AudioProcessorGraph::Node::unprepare()
  28955. {
  28956. if (isPrepared)
  28957. {
  28958. isPrepared = false;
  28959. processor->releaseResources();
  28960. }
  28961. }
  28962. AudioProcessorGraph::AudioProcessorGraph()
  28963. : lastNodeId (0),
  28964. renderingBuffers (1, 1),
  28965. currentAudioOutputBuffer (1, 1)
  28966. {
  28967. }
  28968. AudioProcessorGraph::~AudioProcessorGraph()
  28969. {
  28970. clearRenderingSequence();
  28971. clear();
  28972. }
  28973. const String AudioProcessorGraph::getName() const
  28974. {
  28975. return "Audio Graph";
  28976. }
  28977. void AudioProcessorGraph::clear()
  28978. {
  28979. nodes.clear();
  28980. connections.clear();
  28981. triggerAsyncUpdate();
  28982. }
  28983. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28984. {
  28985. for (int i = nodes.size(); --i >= 0;)
  28986. if (nodes.getUnchecked(i)->id == nodeId)
  28987. return nodes.getUnchecked(i);
  28988. return 0;
  28989. }
  28990. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28991. uint32 nodeId)
  28992. {
  28993. if (newProcessor == 0)
  28994. {
  28995. jassertfalse;
  28996. return 0;
  28997. }
  28998. if (nodeId == 0)
  28999. {
  29000. nodeId = ++lastNodeId;
  29001. }
  29002. else
  29003. {
  29004. // you can't add a node with an id that already exists in the graph..
  29005. jassert (getNodeForId (nodeId) == 0);
  29006. removeNode (nodeId);
  29007. }
  29008. lastNodeId = nodeId;
  29009. Node* const n = new Node (nodeId, newProcessor);
  29010. nodes.add (n);
  29011. triggerAsyncUpdate();
  29012. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29013. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  29014. if (ioProc != 0)
  29015. ioProc->setParentGraph (this);
  29016. return n;
  29017. }
  29018. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29019. {
  29020. disconnectNode (nodeId);
  29021. for (int i = nodes.size(); --i >= 0;)
  29022. {
  29023. if (nodes.getUnchecked(i)->id == nodeId)
  29024. {
  29025. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29026. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29027. if (ioProc != 0)
  29028. ioProc->setParentGraph (0);
  29029. nodes.remove (i);
  29030. triggerAsyncUpdate();
  29031. return true;
  29032. }
  29033. }
  29034. return false;
  29035. }
  29036. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29037. const int sourceChannelIndex,
  29038. const uint32 destNodeId,
  29039. const int destChannelIndex) const
  29040. {
  29041. for (int i = connections.size(); --i >= 0;)
  29042. {
  29043. const Connection* const c = connections.getUnchecked(i);
  29044. if (c->sourceNodeId == sourceNodeId
  29045. && c->destNodeId == destNodeId
  29046. && c->sourceChannelIndex == sourceChannelIndex
  29047. && c->destChannelIndex == destChannelIndex)
  29048. {
  29049. return c;
  29050. }
  29051. }
  29052. return 0;
  29053. }
  29054. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29055. const uint32 possibleDestNodeId) const
  29056. {
  29057. for (int i = connections.size(); --i >= 0;)
  29058. {
  29059. const Connection* const c = connections.getUnchecked(i);
  29060. if (c->sourceNodeId == possibleSourceNodeId
  29061. && c->destNodeId == possibleDestNodeId)
  29062. {
  29063. return true;
  29064. }
  29065. }
  29066. return false;
  29067. }
  29068. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29069. const int sourceChannelIndex,
  29070. const uint32 destNodeId,
  29071. const int destChannelIndex) const
  29072. {
  29073. if (sourceChannelIndex < 0
  29074. || destChannelIndex < 0
  29075. || sourceNodeId == destNodeId
  29076. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29077. return false;
  29078. const Node* const source = getNodeForId (sourceNodeId);
  29079. if (source == 0
  29080. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29081. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29082. return false;
  29083. const Node* const dest = getNodeForId (destNodeId);
  29084. if (dest == 0
  29085. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29086. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29087. return false;
  29088. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29089. destNodeId, destChannelIndex) == 0;
  29090. }
  29091. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29092. const int sourceChannelIndex,
  29093. const uint32 destNodeId,
  29094. const int destChannelIndex)
  29095. {
  29096. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29097. return false;
  29098. Connection* const c = new Connection();
  29099. c->sourceNodeId = sourceNodeId;
  29100. c->sourceChannelIndex = sourceChannelIndex;
  29101. c->destNodeId = destNodeId;
  29102. c->destChannelIndex = destChannelIndex;
  29103. connections.add (c);
  29104. triggerAsyncUpdate();
  29105. return true;
  29106. }
  29107. void AudioProcessorGraph::removeConnection (const int index)
  29108. {
  29109. connections.remove (index);
  29110. triggerAsyncUpdate();
  29111. }
  29112. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29113. const uint32 destNodeId, const int destChannelIndex)
  29114. {
  29115. bool doneAnything = false;
  29116. for (int i = connections.size(); --i >= 0;)
  29117. {
  29118. const Connection* const c = connections.getUnchecked(i);
  29119. if (c->sourceNodeId == sourceNodeId
  29120. && c->destNodeId == destNodeId
  29121. && c->sourceChannelIndex == sourceChannelIndex
  29122. && c->destChannelIndex == destChannelIndex)
  29123. {
  29124. removeConnection (i);
  29125. doneAnything = true;
  29126. triggerAsyncUpdate();
  29127. }
  29128. }
  29129. return doneAnything;
  29130. }
  29131. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29132. {
  29133. bool doneAnything = false;
  29134. for (int i = connections.size(); --i >= 0;)
  29135. {
  29136. const Connection* const c = connections.getUnchecked(i);
  29137. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29138. {
  29139. removeConnection (i);
  29140. doneAnything = true;
  29141. triggerAsyncUpdate();
  29142. }
  29143. }
  29144. return doneAnything;
  29145. }
  29146. bool AudioProcessorGraph::removeIllegalConnections()
  29147. {
  29148. bool doneAnything = false;
  29149. for (int i = connections.size(); --i >= 0;)
  29150. {
  29151. const Connection* const c = connections.getUnchecked(i);
  29152. const Node* const source = getNodeForId (c->sourceNodeId);
  29153. const Node* const dest = getNodeForId (c->destNodeId);
  29154. if (source == 0 || dest == 0
  29155. || (c->sourceChannelIndex != midiChannelIndex
  29156. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  29157. || (c->sourceChannelIndex == midiChannelIndex
  29158. && ! source->processor->producesMidi())
  29159. || (c->destChannelIndex != midiChannelIndex
  29160. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  29161. || (c->destChannelIndex == midiChannelIndex
  29162. && ! dest->processor->acceptsMidi()))
  29163. {
  29164. removeConnection (i);
  29165. doneAnything = true;
  29166. triggerAsyncUpdate();
  29167. }
  29168. }
  29169. return doneAnything;
  29170. }
  29171. namespace GraphRenderingOps
  29172. {
  29173. class AudioGraphRenderingOp
  29174. {
  29175. public:
  29176. AudioGraphRenderingOp() {}
  29177. virtual ~AudioGraphRenderingOp() {}
  29178. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29179. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29180. const int numSamples) = 0;
  29181. juce_UseDebuggingNewOperator
  29182. };
  29183. class ClearChannelOp : public AudioGraphRenderingOp
  29184. {
  29185. public:
  29186. ClearChannelOp (const int channelNum_)
  29187. : channelNum (channelNum_)
  29188. {}
  29189. ~ClearChannelOp() {}
  29190. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29191. {
  29192. sharedBufferChans.clear (channelNum, 0, numSamples);
  29193. }
  29194. private:
  29195. const int channelNum;
  29196. ClearChannelOp (const ClearChannelOp&);
  29197. ClearChannelOp& operator= (const ClearChannelOp&);
  29198. };
  29199. class CopyChannelOp : public AudioGraphRenderingOp
  29200. {
  29201. public:
  29202. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29203. : srcChannelNum (srcChannelNum_),
  29204. dstChannelNum (dstChannelNum_)
  29205. {}
  29206. ~CopyChannelOp() {}
  29207. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29208. {
  29209. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29210. }
  29211. private:
  29212. const int srcChannelNum, dstChannelNum;
  29213. CopyChannelOp (const CopyChannelOp&);
  29214. CopyChannelOp& operator= (const CopyChannelOp&);
  29215. };
  29216. class AddChannelOp : public AudioGraphRenderingOp
  29217. {
  29218. public:
  29219. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29220. : srcChannelNum (srcChannelNum_),
  29221. dstChannelNum (dstChannelNum_)
  29222. {}
  29223. ~AddChannelOp() {}
  29224. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29225. {
  29226. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29227. }
  29228. private:
  29229. const int srcChannelNum, dstChannelNum;
  29230. AddChannelOp (const AddChannelOp&);
  29231. AddChannelOp& operator= (const AddChannelOp&);
  29232. };
  29233. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29234. {
  29235. public:
  29236. ClearMidiBufferOp (const int bufferNum_)
  29237. : bufferNum (bufferNum_)
  29238. {}
  29239. ~ClearMidiBufferOp() {}
  29240. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29241. {
  29242. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29243. }
  29244. private:
  29245. const int bufferNum;
  29246. ClearMidiBufferOp (const ClearMidiBufferOp&);
  29247. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  29248. };
  29249. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29250. {
  29251. public:
  29252. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29253. : srcBufferNum (srcBufferNum_),
  29254. dstBufferNum (dstBufferNum_)
  29255. {}
  29256. ~CopyMidiBufferOp() {}
  29257. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29258. {
  29259. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29260. }
  29261. private:
  29262. const int srcBufferNum, dstBufferNum;
  29263. CopyMidiBufferOp (const CopyMidiBufferOp&);
  29264. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  29265. };
  29266. class AddMidiBufferOp : public AudioGraphRenderingOp
  29267. {
  29268. public:
  29269. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29270. : srcBufferNum (srcBufferNum_),
  29271. dstBufferNum (dstBufferNum_)
  29272. {}
  29273. ~AddMidiBufferOp() {}
  29274. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29275. {
  29276. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29277. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29278. }
  29279. private:
  29280. const int srcBufferNum, dstBufferNum;
  29281. AddMidiBufferOp (const AddMidiBufferOp&);
  29282. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  29283. };
  29284. class ProcessBufferOp : public AudioGraphRenderingOp
  29285. {
  29286. public:
  29287. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29288. const Array <int>& audioChannelsToUse_,
  29289. const int totalChans_,
  29290. const int midiBufferToUse_)
  29291. : node (node_),
  29292. processor (node_->getProcessor()),
  29293. audioChannelsToUse (audioChannelsToUse_),
  29294. totalChans (jmax (1, totalChans_)),
  29295. midiBufferToUse (midiBufferToUse_)
  29296. {
  29297. channels.calloc (totalChans);
  29298. while (audioChannelsToUse.size() < totalChans)
  29299. audioChannelsToUse.add (0);
  29300. }
  29301. ~ProcessBufferOp()
  29302. {
  29303. }
  29304. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29305. {
  29306. for (int i = totalChans; --i >= 0;)
  29307. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29308. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29309. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29310. }
  29311. const AudioProcessorGraph::Node::Ptr node;
  29312. AudioProcessor* const processor;
  29313. private:
  29314. Array <int> audioChannelsToUse;
  29315. HeapBlock <float*> channels;
  29316. int totalChans;
  29317. int midiBufferToUse;
  29318. ProcessBufferOp (const ProcessBufferOp&);
  29319. ProcessBufferOp& operator= (const ProcessBufferOp&);
  29320. };
  29321. /** Used to calculate the correct sequence of rendering ops needed, based on
  29322. the best re-use of shared buffers at each stage.
  29323. */
  29324. class RenderingOpSequenceCalculator
  29325. {
  29326. public:
  29327. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29328. const Array<void*>& orderedNodes_,
  29329. Array<void*>& renderingOps)
  29330. : graph (graph_),
  29331. orderedNodes (orderedNodes_)
  29332. {
  29333. nodeIds.add (-2); // first buffer is read-only zeros
  29334. channels.add (0);
  29335. midiNodeIds.add (-2);
  29336. for (int i = 0; i < orderedNodes.size(); ++i)
  29337. {
  29338. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29339. renderingOps, i);
  29340. markAnyUnusedBuffersAsFree (i);
  29341. }
  29342. }
  29343. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29344. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29345. juce_UseDebuggingNewOperator
  29346. private:
  29347. AudioProcessorGraph& graph;
  29348. const Array<void*>& orderedNodes;
  29349. Array <int> nodeIds, channels, midiNodeIds;
  29350. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29351. Array<void*>& renderingOps,
  29352. const int ourRenderingIndex)
  29353. {
  29354. const int numIns = node->getProcessor()->getNumInputChannels();
  29355. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29356. const int totalChans = jmax (numIns, numOuts);
  29357. Array <int> audioChannelsToUse;
  29358. int midiBufferToUse = -1;
  29359. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29360. {
  29361. // get a list of all the inputs to this node
  29362. Array <int> sourceNodes, sourceOutputChans;
  29363. for (int i = graph.getNumConnections(); --i >= 0;)
  29364. {
  29365. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29366. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29367. {
  29368. sourceNodes.add (c->sourceNodeId);
  29369. sourceOutputChans.add (c->sourceChannelIndex);
  29370. }
  29371. }
  29372. int bufIndex = -1;
  29373. if (sourceNodes.size() == 0)
  29374. {
  29375. // unconnected input channel
  29376. if (inputChan >= numOuts)
  29377. {
  29378. bufIndex = getReadOnlyEmptyBuffer();
  29379. jassert (bufIndex >= 0);
  29380. }
  29381. else
  29382. {
  29383. bufIndex = getFreeBuffer (false);
  29384. renderingOps.add (new ClearChannelOp (bufIndex));
  29385. }
  29386. }
  29387. else if (sourceNodes.size() == 1)
  29388. {
  29389. // channel with a straightforward single input..
  29390. const int srcNode = sourceNodes.getUnchecked(0);
  29391. const int srcChan = sourceOutputChans.getUnchecked(0);
  29392. bufIndex = getBufferContaining (srcNode, srcChan);
  29393. if (bufIndex < 0)
  29394. {
  29395. // if not found, this is probably a feedback loop
  29396. bufIndex = getReadOnlyEmptyBuffer();
  29397. jassert (bufIndex >= 0);
  29398. }
  29399. if (inputChan < numOuts
  29400. && isBufferNeededLater (ourRenderingIndex,
  29401. inputChan,
  29402. srcNode, srcChan))
  29403. {
  29404. // can't mess up this channel because it's needed later by another node, so we
  29405. // need to use a copy of it..
  29406. const int newFreeBuffer = getFreeBuffer (false);
  29407. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29408. bufIndex = newFreeBuffer;
  29409. }
  29410. }
  29411. else
  29412. {
  29413. // channel with a mix of several inputs..
  29414. // try to find a re-usable channel from our inputs..
  29415. int reusableInputIndex = -1;
  29416. for (int i = 0; i < sourceNodes.size(); ++i)
  29417. {
  29418. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29419. sourceOutputChans.getUnchecked(i));
  29420. if (sourceBufIndex >= 0
  29421. && ! isBufferNeededLater (ourRenderingIndex,
  29422. inputChan,
  29423. sourceNodes.getUnchecked(i),
  29424. sourceOutputChans.getUnchecked(i)))
  29425. {
  29426. // we've found one of our input chans that can be re-used..
  29427. reusableInputIndex = i;
  29428. bufIndex = sourceBufIndex;
  29429. break;
  29430. }
  29431. }
  29432. if (reusableInputIndex < 0)
  29433. {
  29434. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29435. bufIndex = getFreeBuffer (false);
  29436. jassert (bufIndex != 0);
  29437. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29438. sourceOutputChans.getUnchecked (0));
  29439. if (srcIndex < 0)
  29440. {
  29441. // if not found, this is probably a feedback loop
  29442. renderingOps.add (new ClearChannelOp (bufIndex));
  29443. }
  29444. else
  29445. {
  29446. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29447. }
  29448. reusableInputIndex = 0;
  29449. }
  29450. for (int j = 0; j < sourceNodes.size(); ++j)
  29451. {
  29452. if (j != reusableInputIndex)
  29453. {
  29454. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29455. sourceOutputChans.getUnchecked(j));
  29456. if (srcIndex >= 0)
  29457. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29458. }
  29459. }
  29460. }
  29461. jassert (bufIndex >= 0);
  29462. audioChannelsToUse.add (bufIndex);
  29463. if (inputChan < numOuts)
  29464. markBufferAsContaining (bufIndex, node->id, inputChan);
  29465. }
  29466. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29467. {
  29468. const int bufIndex = getFreeBuffer (false);
  29469. jassert (bufIndex != 0);
  29470. audioChannelsToUse.add (bufIndex);
  29471. markBufferAsContaining (bufIndex, node->id, outputChan);
  29472. }
  29473. // Now the same thing for midi..
  29474. Array <int> midiSourceNodes;
  29475. for (int i = graph.getNumConnections(); --i >= 0;)
  29476. {
  29477. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29478. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29479. midiSourceNodes.add (c->sourceNodeId);
  29480. }
  29481. if (midiSourceNodes.size() == 0)
  29482. {
  29483. // No midi inputs..
  29484. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29485. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29486. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29487. }
  29488. else if (midiSourceNodes.size() == 1)
  29489. {
  29490. // One midi input..
  29491. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29492. AudioProcessorGraph::midiChannelIndex);
  29493. if (midiBufferToUse >= 0)
  29494. {
  29495. if (isBufferNeededLater (ourRenderingIndex,
  29496. AudioProcessorGraph::midiChannelIndex,
  29497. midiSourceNodes.getUnchecked(0),
  29498. AudioProcessorGraph::midiChannelIndex))
  29499. {
  29500. // can't mess up this channel because it's needed later by another node, so we
  29501. // need to use a copy of it..
  29502. const int newFreeBuffer = getFreeBuffer (true);
  29503. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29504. midiBufferToUse = newFreeBuffer;
  29505. }
  29506. }
  29507. else
  29508. {
  29509. // probably a feedback loop, so just use an empty one..
  29510. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29511. }
  29512. }
  29513. else
  29514. {
  29515. // More than one midi input being mixed..
  29516. int reusableInputIndex = -1;
  29517. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29518. {
  29519. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29520. AudioProcessorGraph::midiChannelIndex);
  29521. if (sourceBufIndex >= 0
  29522. && ! isBufferNeededLater (ourRenderingIndex,
  29523. AudioProcessorGraph::midiChannelIndex,
  29524. midiSourceNodes.getUnchecked(i),
  29525. AudioProcessorGraph::midiChannelIndex))
  29526. {
  29527. // we've found one of our input buffers that can be re-used..
  29528. reusableInputIndex = i;
  29529. midiBufferToUse = sourceBufIndex;
  29530. break;
  29531. }
  29532. }
  29533. if (reusableInputIndex < 0)
  29534. {
  29535. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29536. midiBufferToUse = getFreeBuffer (true);
  29537. jassert (midiBufferToUse >= 0);
  29538. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29539. AudioProcessorGraph::midiChannelIndex);
  29540. if (srcIndex >= 0)
  29541. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29542. else
  29543. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29544. reusableInputIndex = 0;
  29545. }
  29546. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29547. {
  29548. if (j != reusableInputIndex)
  29549. {
  29550. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29551. AudioProcessorGraph::midiChannelIndex);
  29552. if (srcIndex >= 0)
  29553. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29554. }
  29555. }
  29556. }
  29557. if (node->getProcessor()->producesMidi())
  29558. markBufferAsContaining (midiBufferToUse, node->id,
  29559. AudioProcessorGraph::midiChannelIndex);
  29560. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29561. totalChans, midiBufferToUse));
  29562. }
  29563. int getFreeBuffer (const bool forMidi)
  29564. {
  29565. if (forMidi)
  29566. {
  29567. for (int i = 1; i < midiNodeIds.size(); ++i)
  29568. if (midiNodeIds.getUnchecked(i) < 0)
  29569. return i;
  29570. midiNodeIds.add (-1);
  29571. return midiNodeIds.size() - 1;
  29572. }
  29573. else
  29574. {
  29575. for (int i = 1; i < nodeIds.size(); ++i)
  29576. if (nodeIds.getUnchecked(i) < 0)
  29577. return i;
  29578. nodeIds.add (-1);
  29579. channels.add (0);
  29580. return nodeIds.size() - 1;
  29581. }
  29582. }
  29583. int getReadOnlyEmptyBuffer() const
  29584. {
  29585. return 0;
  29586. }
  29587. int getBufferContaining (const int nodeId, const int outputChannel) const
  29588. {
  29589. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29590. {
  29591. for (int i = midiNodeIds.size(); --i >= 0;)
  29592. if (midiNodeIds.getUnchecked(i) == nodeId)
  29593. return i;
  29594. }
  29595. else
  29596. {
  29597. for (int i = nodeIds.size(); --i >= 0;)
  29598. if (nodeIds.getUnchecked(i) == nodeId
  29599. && channels.getUnchecked(i) == outputChannel)
  29600. return i;
  29601. }
  29602. return -1;
  29603. }
  29604. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29605. {
  29606. int i;
  29607. for (i = 0; i < nodeIds.size(); ++i)
  29608. {
  29609. if (nodeIds.getUnchecked(i) >= 0
  29610. && ! isBufferNeededLater (stepIndex, -1,
  29611. nodeIds.getUnchecked(i),
  29612. channels.getUnchecked(i)))
  29613. {
  29614. nodeIds.set (i, -1);
  29615. }
  29616. }
  29617. for (i = 0; i < midiNodeIds.size(); ++i)
  29618. {
  29619. if (midiNodeIds.getUnchecked(i) >= 0
  29620. && ! isBufferNeededLater (stepIndex, -1,
  29621. midiNodeIds.getUnchecked(i),
  29622. AudioProcessorGraph::midiChannelIndex))
  29623. {
  29624. midiNodeIds.set (i, -1);
  29625. }
  29626. }
  29627. }
  29628. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29629. int inputChannelOfIndexToIgnore,
  29630. const int nodeId,
  29631. const int outputChanIndex) const
  29632. {
  29633. while (stepIndexToSearchFrom < orderedNodes.size())
  29634. {
  29635. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29636. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29637. {
  29638. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29639. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29640. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29641. return true;
  29642. }
  29643. else
  29644. {
  29645. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29646. if (i != inputChannelOfIndexToIgnore
  29647. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29648. node->id, i) != 0)
  29649. return true;
  29650. }
  29651. inputChannelOfIndexToIgnore = -1;
  29652. ++stepIndexToSearchFrom;
  29653. }
  29654. return false;
  29655. }
  29656. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  29657. {
  29658. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29659. {
  29660. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29661. midiNodeIds.set (bufferNum, nodeId);
  29662. }
  29663. else
  29664. {
  29665. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29666. nodeIds.set (bufferNum, nodeId);
  29667. channels.set (bufferNum, outputIndex);
  29668. }
  29669. }
  29670. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  29671. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  29672. };
  29673. }
  29674. void AudioProcessorGraph::clearRenderingSequence()
  29675. {
  29676. const ScopedLock sl (renderLock);
  29677. for (int i = renderingOps.size(); --i >= 0;)
  29678. {
  29679. GraphRenderingOps::AudioGraphRenderingOp* const r
  29680. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29681. renderingOps.remove (i);
  29682. delete r;
  29683. }
  29684. }
  29685. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29686. const uint32 possibleDestinationId,
  29687. const int recursionCheck) const
  29688. {
  29689. if (recursionCheck > 0)
  29690. {
  29691. for (int i = connections.size(); --i >= 0;)
  29692. {
  29693. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29694. if (c->destNodeId == possibleDestinationId
  29695. && (c->sourceNodeId == possibleInputId
  29696. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29697. return true;
  29698. }
  29699. }
  29700. return false;
  29701. }
  29702. void AudioProcessorGraph::buildRenderingSequence()
  29703. {
  29704. Array<void*> newRenderingOps;
  29705. int numRenderingBuffersNeeded = 2;
  29706. int numMidiBuffersNeeded = 1;
  29707. {
  29708. MessageManagerLock mml;
  29709. Array<void*> orderedNodes;
  29710. int i;
  29711. for (i = 0; i < nodes.size(); ++i)
  29712. {
  29713. Node* const node = nodes.getUnchecked(i);
  29714. node->prepare (getSampleRate(), getBlockSize(), this);
  29715. int j = 0;
  29716. for (; j < orderedNodes.size(); ++j)
  29717. if (isAnInputTo (node->id,
  29718. ((Node*) orderedNodes.getUnchecked (j))->id,
  29719. nodes.size() + 1))
  29720. break;
  29721. orderedNodes.insert (j, node);
  29722. }
  29723. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29724. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29725. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29726. }
  29727. Array<void*> oldRenderingOps (renderingOps);
  29728. {
  29729. // swap over to the new rendering sequence..
  29730. const ScopedLock sl (renderLock);
  29731. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29732. renderingBuffers.clear();
  29733. for (int i = midiBuffers.size(); --i >= 0;)
  29734. midiBuffers.getUnchecked(i)->clear();
  29735. while (midiBuffers.size() < numMidiBuffersNeeded)
  29736. midiBuffers.add (new MidiBuffer());
  29737. renderingOps = newRenderingOps;
  29738. }
  29739. for (int i = oldRenderingOps.size(); --i >= 0;)
  29740. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29741. }
  29742. void AudioProcessorGraph::handleAsyncUpdate()
  29743. {
  29744. buildRenderingSequence();
  29745. }
  29746. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29747. {
  29748. currentAudioInputBuffer = 0;
  29749. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29750. currentMidiInputBuffer = 0;
  29751. currentMidiOutputBuffer.clear();
  29752. clearRenderingSequence();
  29753. buildRenderingSequence();
  29754. }
  29755. void AudioProcessorGraph::releaseResources()
  29756. {
  29757. for (int i = 0; i < nodes.size(); ++i)
  29758. nodes.getUnchecked(i)->unprepare();
  29759. renderingBuffers.setSize (1, 1);
  29760. midiBuffers.clear();
  29761. currentAudioInputBuffer = 0;
  29762. currentAudioOutputBuffer.setSize (1, 1);
  29763. currentMidiInputBuffer = 0;
  29764. currentMidiOutputBuffer.clear();
  29765. }
  29766. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29767. {
  29768. const int numSamples = buffer.getNumSamples();
  29769. const ScopedLock sl (renderLock);
  29770. currentAudioInputBuffer = &buffer;
  29771. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29772. currentAudioOutputBuffer.clear();
  29773. currentMidiInputBuffer = &midiMessages;
  29774. currentMidiOutputBuffer.clear();
  29775. int i;
  29776. for (i = 0; i < renderingOps.size(); ++i)
  29777. {
  29778. GraphRenderingOps::AudioGraphRenderingOp* const op
  29779. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29780. op->perform (renderingBuffers, midiBuffers, numSamples);
  29781. }
  29782. for (i = 0; i < buffer.getNumChannels(); ++i)
  29783. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29784. midiMessages.clear();
  29785. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29786. }
  29787. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29788. {
  29789. return "Input " + String (channelIndex + 1);
  29790. }
  29791. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29792. {
  29793. return "Output " + String (channelIndex + 1);
  29794. }
  29795. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29796. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29797. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29798. bool AudioProcessorGraph::producesMidi() const { return true; }
  29799. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29800. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29801. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29802. : type (type_),
  29803. graph (0)
  29804. {
  29805. }
  29806. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29807. {
  29808. }
  29809. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29810. {
  29811. switch (type)
  29812. {
  29813. case audioOutputNode: return "Audio Output";
  29814. case audioInputNode: return "Audio Input";
  29815. case midiOutputNode: return "Midi Output";
  29816. case midiInputNode: return "Midi Input";
  29817. default: break;
  29818. }
  29819. return String::empty;
  29820. }
  29821. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29822. {
  29823. d.name = getName();
  29824. d.uid = d.name.hashCode();
  29825. d.category = "I/O devices";
  29826. d.pluginFormatName = "Internal";
  29827. d.manufacturerName = "Raw Material Software";
  29828. d.version = "1.0";
  29829. d.isInstrument = false;
  29830. d.numInputChannels = getNumInputChannels();
  29831. if (type == audioOutputNode && graph != 0)
  29832. d.numInputChannels = graph->getNumInputChannels();
  29833. d.numOutputChannels = getNumOutputChannels();
  29834. if (type == audioInputNode && graph != 0)
  29835. d.numOutputChannels = graph->getNumOutputChannels();
  29836. }
  29837. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29838. {
  29839. jassert (graph != 0);
  29840. }
  29841. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29842. {
  29843. }
  29844. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29845. MidiBuffer& midiMessages)
  29846. {
  29847. jassert (graph != 0);
  29848. switch (type)
  29849. {
  29850. case audioOutputNode:
  29851. {
  29852. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29853. buffer.getNumChannels()); --i >= 0;)
  29854. {
  29855. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29856. }
  29857. break;
  29858. }
  29859. case audioInputNode:
  29860. {
  29861. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29862. buffer.getNumChannels()); --i >= 0;)
  29863. {
  29864. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29865. }
  29866. break;
  29867. }
  29868. case midiOutputNode:
  29869. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29870. break;
  29871. case midiInputNode:
  29872. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29873. break;
  29874. default:
  29875. break;
  29876. }
  29877. }
  29878. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29879. {
  29880. return type == midiOutputNode;
  29881. }
  29882. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29883. {
  29884. return type == midiInputNode;
  29885. }
  29886. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29887. {
  29888. switch (type)
  29889. {
  29890. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29891. case midiOutputNode: return "Midi Output";
  29892. default: break;
  29893. }
  29894. return String::empty;
  29895. }
  29896. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29897. {
  29898. switch (type)
  29899. {
  29900. case audioInputNode: return "Input " + String (channelIndex + 1);
  29901. case midiInputNode: return "Midi Input";
  29902. default: break;
  29903. }
  29904. return String::empty;
  29905. }
  29906. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29907. {
  29908. return type == audioInputNode || type == audioOutputNode;
  29909. }
  29910. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29911. {
  29912. return isInputChannelStereoPair (index);
  29913. }
  29914. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29915. {
  29916. return type == audioInputNode || type == midiInputNode;
  29917. }
  29918. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29919. {
  29920. return type == audioOutputNode || type == midiOutputNode;
  29921. }
  29922. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  29923. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  29924. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29925. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29926. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29927. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29928. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29929. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29930. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29931. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29932. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29933. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29934. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29935. {
  29936. }
  29937. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29938. {
  29939. }
  29940. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29941. {
  29942. graph = newGraph;
  29943. if (graph != 0)
  29944. {
  29945. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29946. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29947. getSampleRate(),
  29948. getBlockSize());
  29949. updateHostDisplay();
  29950. }
  29951. }
  29952. END_JUCE_NAMESPACE
  29953. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29954. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29955. BEGIN_JUCE_NAMESPACE
  29956. AudioProcessorPlayer::AudioProcessorPlayer()
  29957. : processor (0),
  29958. sampleRate (0),
  29959. blockSize (0),
  29960. isPrepared (false),
  29961. numInputChans (0),
  29962. numOutputChans (0),
  29963. tempBuffer (1, 1)
  29964. {
  29965. }
  29966. AudioProcessorPlayer::~AudioProcessorPlayer()
  29967. {
  29968. setProcessor (0);
  29969. }
  29970. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29971. {
  29972. if (processor != processorToPlay)
  29973. {
  29974. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29975. {
  29976. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29977. sampleRate, blockSize);
  29978. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29979. }
  29980. AudioProcessor* oldOne;
  29981. {
  29982. const ScopedLock sl (lock);
  29983. oldOne = isPrepared ? processor : 0;
  29984. processor = processorToPlay;
  29985. isPrepared = true;
  29986. }
  29987. if (oldOne != 0)
  29988. oldOne->releaseResources();
  29989. }
  29990. }
  29991. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29992. const int numInputChannels,
  29993. float** const outputChannelData,
  29994. const int numOutputChannels,
  29995. const int numSamples)
  29996. {
  29997. // these should have been prepared by audioDeviceAboutToStart()...
  29998. jassert (sampleRate > 0 && blockSize > 0);
  29999. incomingMidi.clear();
  30000. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  30001. int i, totalNumChans = 0;
  30002. if (numInputChannels > numOutputChannels)
  30003. {
  30004. // if there aren't enough output channels for the number of
  30005. // inputs, we need to create some temporary extra ones (can't
  30006. // use the input data in case it gets written to)
  30007. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  30008. false, false, true);
  30009. for (i = 0; i < numOutputChannels; ++i)
  30010. {
  30011. channels[totalNumChans] = outputChannelData[i];
  30012. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30013. ++totalNumChans;
  30014. }
  30015. for (i = numOutputChannels; i < numInputChannels; ++i)
  30016. {
  30017. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  30018. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30019. ++totalNumChans;
  30020. }
  30021. }
  30022. else
  30023. {
  30024. for (i = 0; i < numInputChannels; ++i)
  30025. {
  30026. channels[totalNumChans] = outputChannelData[i];
  30027. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30028. ++totalNumChans;
  30029. }
  30030. for (i = numInputChannels; i < numOutputChannels; ++i)
  30031. {
  30032. channels[totalNumChans] = outputChannelData[i];
  30033. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30034. ++totalNumChans;
  30035. }
  30036. }
  30037. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30038. const ScopedLock sl (lock);
  30039. if (processor != 0)
  30040. {
  30041. const ScopedLock sl (processor->getCallbackLock());
  30042. if (processor->isSuspended())
  30043. {
  30044. for (i = 0; i < numOutputChannels; ++i)
  30045. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30046. }
  30047. else
  30048. {
  30049. processor->processBlock (buffer, incomingMidi);
  30050. }
  30051. }
  30052. }
  30053. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30054. {
  30055. const ScopedLock sl (lock);
  30056. sampleRate = device->getCurrentSampleRate();
  30057. blockSize = device->getCurrentBufferSizeSamples();
  30058. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30059. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30060. messageCollector.reset (sampleRate);
  30061. zeromem (channels, sizeof (channels));
  30062. if (processor != 0)
  30063. {
  30064. if (isPrepared)
  30065. processor->releaseResources();
  30066. AudioProcessor* const oldProcessor = processor;
  30067. setProcessor (0);
  30068. setProcessor (oldProcessor);
  30069. }
  30070. }
  30071. void AudioProcessorPlayer::audioDeviceStopped()
  30072. {
  30073. const ScopedLock sl (lock);
  30074. if (processor != 0 && isPrepared)
  30075. processor->releaseResources();
  30076. sampleRate = 0.0;
  30077. blockSize = 0;
  30078. isPrepared = false;
  30079. tempBuffer.setSize (1, 1);
  30080. }
  30081. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30082. {
  30083. messageCollector.addMessageToQueue (message);
  30084. }
  30085. END_JUCE_NAMESPACE
  30086. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30087. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30088. BEGIN_JUCE_NAMESPACE
  30089. class ProcessorParameterPropertyComp : public PropertyComponent,
  30090. public AudioProcessorListener,
  30091. public AsyncUpdater
  30092. {
  30093. public:
  30094. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, int index_)
  30095. : PropertyComponent (name),
  30096. owner (owner_),
  30097. index (index_),
  30098. slider (owner_, index_)
  30099. {
  30100. addAndMakeVisible (&slider);
  30101. owner_.addListener (this);
  30102. }
  30103. ~ProcessorParameterPropertyComp()
  30104. {
  30105. owner.removeListener (this);
  30106. }
  30107. void refresh()
  30108. {
  30109. slider.setValue (owner.getParameter (index), false);
  30110. }
  30111. void audioProcessorChanged (AudioProcessor*) {}
  30112. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30113. {
  30114. if (parameterIndex == index)
  30115. triggerAsyncUpdate();
  30116. }
  30117. void handleAsyncUpdate()
  30118. {
  30119. refresh();
  30120. }
  30121. juce_UseDebuggingNewOperator
  30122. private:
  30123. class ParamSlider : public Slider
  30124. {
  30125. public:
  30126. ParamSlider (AudioProcessor& owner_, const int index_)
  30127. : Slider (String::empty),
  30128. owner (owner_),
  30129. index (index_)
  30130. {
  30131. setRange (0.0, 1.0, 0.0);
  30132. setSliderStyle (Slider::LinearBar);
  30133. setTextBoxIsEditable (false);
  30134. setScrollWheelEnabled (false);
  30135. }
  30136. ~ParamSlider()
  30137. {
  30138. }
  30139. void valueChanged()
  30140. {
  30141. const float newVal = (float) getValue();
  30142. if (owner.getParameter (index) != newVal)
  30143. owner.setParameter (index, newVal);
  30144. }
  30145. const String getTextFromValue (double /*value*/)
  30146. {
  30147. return owner.getParameterText (index);
  30148. }
  30149. juce_UseDebuggingNewOperator
  30150. private:
  30151. AudioProcessor& owner;
  30152. const int index;
  30153. ParamSlider (const ParamSlider&);
  30154. ParamSlider& operator= (const ParamSlider&);
  30155. };
  30156. AudioProcessor& owner;
  30157. const int index;
  30158. ParamSlider slider;
  30159. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  30160. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  30161. };
  30162. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30163. : AudioProcessorEditor (owner_)
  30164. {
  30165. jassert (owner_ != 0);
  30166. setOpaque (true);
  30167. addAndMakeVisible (panel = new PropertyPanel());
  30168. Array <PropertyComponent*> params;
  30169. const int numParams = owner_->getNumParameters();
  30170. int totalHeight = 0;
  30171. for (int i = 0; i < numParams; ++i)
  30172. {
  30173. String name (owner_->getParameterName (i));
  30174. if (name.trim().isEmpty())
  30175. name = "Unnamed";
  30176. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30177. params.add (pc);
  30178. totalHeight += pc->getPreferredHeight();
  30179. }
  30180. panel->addProperties (params);
  30181. setSize (400, jlimit (25, 400, totalHeight));
  30182. }
  30183. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30184. {
  30185. deleteAllChildren();
  30186. }
  30187. void GenericAudioProcessorEditor::paint (Graphics& g)
  30188. {
  30189. g.fillAll (Colours::white);
  30190. }
  30191. void GenericAudioProcessorEditor::resized()
  30192. {
  30193. panel->setSize (getWidth(), getHeight());
  30194. }
  30195. END_JUCE_NAMESPACE
  30196. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30197. /*** Start of inlined file: juce_Sampler.cpp ***/
  30198. BEGIN_JUCE_NAMESPACE
  30199. SamplerSound::SamplerSound (const String& name_,
  30200. AudioFormatReader& source,
  30201. const BigInteger& midiNotes_,
  30202. const int midiNoteForNormalPitch,
  30203. const double attackTimeSecs,
  30204. const double releaseTimeSecs,
  30205. const double maxSampleLengthSeconds)
  30206. : name (name_),
  30207. midiNotes (midiNotes_),
  30208. midiRootNote (midiNoteForNormalPitch)
  30209. {
  30210. sourceSampleRate = source.sampleRate;
  30211. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30212. {
  30213. length = 0;
  30214. attackSamples = 0;
  30215. releaseSamples = 0;
  30216. }
  30217. else
  30218. {
  30219. length = jmin ((int) source.lengthInSamples,
  30220. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30221. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30222. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30223. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30224. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30225. }
  30226. }
  30227. SamplerSound::~SamplerSound()
  30228. {
  30229. }
  30230. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30231. {
  30232. return midiNotes [midiNoteNumber];
  30233. }
  30234. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30235. {
  30236. return true;
  30237. }
  30238. SamplerVoice::SamplerVoice()
  30239. : pitchRatio (0.0),
  30240. sourceSamplePosition (0.0),
  30241. lgain (0.0f),
  30242. rgain (0.0f),
  30243. isInAttack (false),
  30244. isInRelease (false)
  30245. {
  30246. }
  30247. SamplerVoice::~SamplerVoice()
  30248. {
  30249. }
  30250. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30251. {
  30252. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30253. }
  30254. void SamplerVoice::startNote (const int midiNoteNumber,
  30255. const float velocity,
  30256. SynthesiserSound* s,
  30257. const int /*currentPitchWheelPosition*/)
  30258. {
  30259. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30260. jassert (sound != 0); // this object can only play SamplerSounds!
  30261. if (sound != 0)
  30262. {
  30263. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30264. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30265. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30266. sourceSamplePosition = 0.0;
  30267. lgain = velocity;
  30268. rgain = velocity;
  30269. isInAttack = (sound->attackSamples > 0);
  30270. isInRelease = false;
  30271. if (isInAttack)
  30272. {
  30273. attackReleaseLevel = 0.0f;
  30274. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30275. }
  30276. else
  30277. {
  30278. attackReleaseLevel = 1.0f;
  30279. attackDelta = 0.0f;
  30280. }
  30281. if (sound->releaseSamples > 0)
  30282. {
  30283. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30284. }
  30285. else
  30286. {
  30287. releaseDelta = 0.0f;
  30288. }
  30289. }
  30290. }
  30291. void SamplerVoice::stopNote (const bool allowTailOff)
  30292. {
  30293. if (allowTailOff)
  30294. {
  30295. isInAttack = false;
  30296. isInRelease = true;
  30297. }
  30298. else
  30299. {
  30300. clearCurrentNote();
  30301. }
  30302. }
  30303. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30304. {
  30305. }
  30306. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30307. const int /*newValue*/)
  30308. {
  30309. }
  30310. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30311. {
  30312. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30313. if (playingSound != 0)
  30314. {
  30315. const float* const inL = playingSound->data->getSampleData (0, 0);
  30316. const float* const inR = playingSound->data->getNumChannels() > 1
  30317. ? playingSound->data->getSampleData (1, 0) : 0;
  30318. float* outL = outputBuffer.getSampleData (0, startSample);
  30319. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30320. while (--numSamples >= 0)
  30321. {
  30322. const int pos = (int) sourceSamplePosition;
  30323. const float alpha = (float) (sourceSamplePosition - pos);
  30324. const float invAlpha = 1.0f - alpha;
  30325. // just using a very simple linear interpolation here..
  30326. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30327. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30328. : l;
  30329. l *= lgain;
  30330. r *= rgain;
  30331. if (isInAttack)
  30332. {
  30333. l *= attackReleaseLevel;
  30334. r *= attackReleaseLevel;
  30335. attackReleaseLevel += attackDelta;
  30336. if (attackReleaseLevel >= 1.0f)
  30337. {
  30338. attackReleaseLevel = 1.0f;
  30339. isInAttack = false;
  30340. }
  30341. }
  30342. else if (isInRelease)
  30343. {
  30344. l *= attackReleaseLevel;
  30345. r *= attackReleaseLevel;
  30346. attackReleaseLevel += releaseDelta;
  30347. if (attackReleaseLevel <= 0.0f)
  30348. {
  30349. stopNote (false);
  30350. break;
  30351. }
  30352. }
  30353. if (outR != 0)
  30354. {
  30355. *outL++ += l;
  30356. *outR++ += r;
  30357. }
  30358. else
  30359. {
  30360. *outL++ += (l + r) * 0.5f;
  30361. }
  30362. sourceSamplePosition += pitchRatio;
  30363. if (sourceSamplePosition > playingSound->length)
  30364. {
  30365. stopNote (false);
  30366. break;
  30367. }
  30368. }
  30369. }
  30370. }
  30371. END_JUCE_NAMESPACE
  30372. /*** End of inlined file: juce_Sampler.cpp ***/
  30373. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30374. BEGIN_JUCE_NAMESPACE
  30375. SynthesiserSound::SynthesiserSound()
  30376. {
  30377. }
  30378. SynthesiserSound::~SynthesiserSound()
  30379. {
  30380. }
  30381. SynthesiserVoice::SynthesiserVoice()
  30382. : currentSampleRate (44100.0),
  30383. currentlyPlayingNote (-1),
  30384. noteOnTime (0),
  30385. currentlyPlayingSound (0)
  30386. {
  30387. }
  30388. SynthesiserVoice::~SynthesiserVoice()
  30389. {
  30390. }
  30391. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30392. {
  30393. return currentlyPlayingSound != 0
  30394. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30395. }
  30396. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30397. {
  30398. currentSampleRate = newRate;
  30399. }
  30400. void SynthesiserVoice::clearCurrentNote()
  30401. {
  30402. currentlyPlayingNote = -1;
  30403. currentlyPlayingSound = 0;
  30404. }
  30405. Synthesiser::Synthesiser()
  30406. : sampleRate (0),
  30407. lastNoteOnCounter (0),
  30408. shouldStealNotes (true)
  30409. {
  30410. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30411. lastPitchWheelValues[i] = 0x2000;
  30412. }
  30413. Synthesiser::~Synthesiser()
  30414. {
  30415. }
  30416. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30417. {
  30418. const ScopedLock sl (lock);
  30419. return voices [index];
  30420. }
  30421. void Synthesiser::clearVoices()
  30422. {
  30423. const ScopedLock sl (lock);
  30424. voices.clear();
  30425. }
  30426. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30427. {
  30428. const ScopedLock sl (lock);
  30429. voices.add (newVoice);
  30430. }
  30431. void Synthesiser::removeVoice (const int index)
  30432. {
  30433. const ScopedLock sl (lock);
  30434. voices.remove (index);
  30435. }
  30436. void Synthesiser::clearSounds()
  30437. {
  30438. const ScopedLock sl (lock);
  30439. sounds.clear();
  30440. }
  30441. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30442. {
  30443. const ScopedLock sl (lock);
  30444. sounds.add (newSound);
  30445. }
  30446. void Synthesiser::removeSound (const int index)
  30447. {
  30448. const ScopedLock sl (lock);
  30449. sounds.remove (index);
  30450. }
  30451. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30452. {
  30453. shouldStealNotes = shouldStealNotes_;
  30454. }
  30455. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30456. {
  30457. if (sampleRate != newRate)
  30458. {
  30459. const ScopedLock sl (lock);
  30460. allNotesOff (0, false);
  30461. sampleRate = newRate;
  30462. for (int i = voices.size(); --i >= 0;)
  30463. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30464. }
  30465. }
  30466. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30467. const MidiBuffer& midiData,
  30468. int startSample,
  30469. int numSamples)
  30470. {
  30471. // must set the sample rate before using this!
  30472. jassert (sampleRate != 0);
  30473. const ScopedLock sl (lock);
  30474. MidiBuffer::Iterator midiIterator (midiData);
  30475. midiIterator.setNextSamplePosition (startSample);
  30476. MidiMessage m (0xf4, 0.0);
  30477. while (numSamples > 0)
  30478. {
  30479. int midiEventPos;
  30480. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30481. && midiEventPos < startSample + numSamples;
  30482. const int numThisTime = useEvent ? midiEventPos - startSample
  30483. : numSamples;
  30484. if (numThisTime > 0)
  30485. {
  30486. for (int i = voices.size(); --i >= 0;)
  30487. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30488. }
  30489. if (useEvent)
  30490. {
  30491. if (m.isNoteOn())
  30492. {
  30493. const int channel = m.getChannel();
  30494. noteOn (channel,
  30495. m.getNoteNumber(),
  30496. m.getFloatVelocity());
  30497. }
  30498. else if (m.isNoteOff())
  30499. {
  30500. noteOff (m.getChannel(),
  30501. m.getNoteNumber(),
  30502. true);
  30503. }
  30504. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30505. {
  30506. allNotesOff (m.getChannel(), true);
  30507. }
  30508. else if (m.isPitchWheel())
  30509. {
  30510. const int channel = m.getChannel();
  30511. const int wheelPos = m.getPitchWheelValue();
  30512. lastPitchWheelValues [channel - 1] = wheelPos;
  30513. handlePitchWheel (channel, wheelPos);
  30514. }
  30515. else if (m.isController())
  30516. {
  30517. handleController (m.getChannel(),
  30518. m.getControllerNumber(),
  30519. m.getControllerValue());
  30520. }
  30521. }
  30522. startSample += numThisTime;
  30523. numSamples -= numThisTime;
  30524. }
  30525. }
  30526. void Synthesiser::noteOn (const int midiChannel,
  30527. const int midiNoteNumber,
  30528. const float velocity)
  30529. {
  30530. const ScopedLock sl (lock);
  30531. for (int i = sounds.size(); --i >= 0;)
  30532. {
  30533. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30534. if (sound->appliesToNote (midiNoteNumber)
  30535. && sound->appliesToChannel (midiChannel))
  30536. {
  30537. startVoice (findFreeVoice (sound, shouldStealNotes),
  30538. sound, midiChannel, midiNoteNumber, velocity);
  30539. }
  30540. }
  30541. }
  30542. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30543. SynthesiserSound* const sound,
  30544. const int midiChannel,
  30545. const int midiNoteNumber,
  30546. const float velocity)
  30547. {
  30548. if (voice != 0 && sound != 0)
  30549. {
  30550. if (voice->currentlyPlayingSound != 0)
  30551. voice->stopNote (false);
  30552. voice->startNote (midiNoteNumber,
  30553. velocity,
  30554. sound,
  30555. lastPitchWheelValues [midiChannel - 1]);
  30556. voice->currentlyPlayingNote = midiNoteNumber;
  30557. voice->noteOnTime = ++lastNoteOnCounter;
  30558. voice->currentlyPlayingSound = sound;
  30559. }
  30560. }
  30561. void Synthesiser::noteOff (const int midiChannel,
  30562. const int midiNoteNumber,
  30563. const bool allowTailOff)
  30564. {
  30565. const ScopedLock sl (lock);
  30566. for (int i = voices.size(); --i >= 0;)
  30567. {
  30568. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30569. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30570. {
  30571. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30572. if (sound != 0
  30573. && sound->appliesToNote (midiNoteNumber)
  30574. && sound->appliesToChannel (midiChannel))
  30575. {
  30576. voice->stopNote (allowTailOff);
  30577. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30578. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30579. }
  30580. }
  30581. }
  30582. }
  30583. void Synthesiser::allNotesOff (const int midiChannel,
  30584. const bool allowTailOff)
  30585. {
  30586. const ScopedLock sl (lock);
  30587. for (int i = voices.size(); --i >= 0;)
  30588. {
  30589. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30590. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30591. voice->stopNote (allowTailOff);
  30592. }
  30593. }
  30594. void Synthesiser::handlePitchWheel (const int midiChannel,
  30595. const int wheelValue)
  30596. {
  30597. const ScopedLock sl (lock);
  30598. for (int i = voices.size(); --i >= 0;)
  30599. {
  30600. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30601. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30602. {
  30603. voice->pitchWheelMoved (wheelValue);
  30604. }
  30605. }
  30606. }
  30607. void Synthesiser::handleController (const int midiChannel,
  30608. const int controllerNumber,
  30609. const int controllerValue)
  30610. {
  30611. const ScopedLock sl (lock);
  30612. for (int i = voices.size(); --i >= 0;)
  30613. {
  30614. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30615. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30616. voice->controllerMoved (controllerNumber, controllerValue);
  30617. }
  30618. }
  30619. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30620. const bool stealIfNoneAvailable) const
  30621. {
  30622. const ScopedLock sl (lock);
  30623. for (int i = voices.size(); --i >= 0;)
  30624. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30625. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30626. return voices.getUnchecked (i);
  30627. if (stealIfNoneAvailable)
  30628. {
  30629. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30630. SynthesiserVoice* oldest = 0;
  30631. for (int i = voices.size(); --i >= 0;)
  30632. {
  30633. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30634. if (voice->canPlaySound (soundToPlay)
  30635. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30636. oldest = voice;
  30637. }
  30638. jassert (oldest != 0);
  30639. return oldest;
  30640. }
  30641. return 0;
  30642. }
  30643. END_JUCE_NAMESPACE
  30644. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30645. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30646. BEGIN_JUCE_NAMESPACE
  30647. ActionBroadcaster::ActionBroadcaster() throw()
  30648. {
  30649. // are you trying to create this object before or after juce has been intialised??
  30650. jassert (MessageManager::instance != 0);
  30651. }
  30652. ActionBroadcaster::~ActionBroadcaster()
  30653. {
  30654. // all event-based objects must be deleted BEFORE juce is shut down!
  30655. jassert (MessageManager::instance != 0);
  30656. }
  30657. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30658. {
  30659. actionListenerList.addActionListener (listener);
  30660. }
  30661. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30662. {
  30663. jassert (actionListenerList.isValidMessageListener());
  30664. if (actionListenerList.isValidMessageListener())
  30665. actionListenerList.removeActionListener (listener);
  30666. }
  30667. void ActionBroadcaster::removeAllActionListeners()
  30668. {
  30669. actionListenerList.removeAllActionListeners();
  30670. }
  30671. void ActionBroadcaster::sendActionMessage (const String& message) const
  30672. {
  30673. actionListenerList.sendActionMessage (message);
  30674. }
  30675. END_JUCE_NAMESPACE
  30676. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30677. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  30678. BEGIN_JUCE_NAMESPACE
  30679. // special message of our own with a string in it
  30680. class ActionMessage : public Message
  30681. {
  30682. public:
  30683. const String message;
  30684. ActionMessage (const String& messageText, void* const listener_) throw()
  30685. : message (messageText)
  30686. {
  30687. pointerParameter = listener_;
  30688. }
  30689. ~ActionMessage() throw()
  30690. {
  30691. }
  30692. private:
  30693. ActionMessage (const ActionMessage&);
  30694. ActionMessage& operator= (const ActionMessage&);
  30695. };
  30696. ActionListenerList::ActionListenerList()
  30697. {
  30698. }
  30699. ActionListenerList::~ActionListenerList()
  30700. {
  30701. }
  30702. void ActionListenerList::addActionListener (ActionListener* const listener)
  30703. {
  30704. const ScopedLock sl (actionListenerLock_);
  30705. jassert (listener != 0);
  30706. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  30707. if (listener != 0)
  30708. actionListeners_.add (listener);
  30709. }
  30710. void ActionListenerList::removeActionListener (ActionListener* const listener)
  30711. {
  30712. const ScopedLock sl (actionListenerLock_);
  30713. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  30714. actionListeners_.removeValue (listener);
  30715. }
  30716. void ActionListenerList::removeAllActionListeners()
  30717. {
  30718. const ScopedLock sl (actionListenerLock_);
  30719. actionListeners_.clear();
  30720. }
  30721. void ActionListenerList::sendActionMessage (const String& message) const
  30722. {
  30723. const ScopedLock sl (actionListenerLock_);
  30724. for (int i = actionListeners_.size(); --i >= 0;)
  30725. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  30726. }
  30727. void ActionListenerList::handleMessage (const Message& message)
  30728. {
  30729. const ActionMessage& am = (const ActionMessage&) message;
  30730. if (actionListeners_.contains (am.pointerParameter))
  30731. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  30732. }
  30733. END_JUCE_NAMESPACE
  30734. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  30735. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30736. BEGIN_JUCE_NAMESPACE
  30737. AsyncUpdater::AsyncUpdater() throw()
  30738. : asyncMessagePending (false)
  30739. {
  30740. internalAsyncHandler.owner = this;
  30741. }
  30742. AsyncUpdater::~AsyncUpdater()
  30743. {
  30744. }
  30745. void AsyncUpdater::triggerAsyncUpdate()
  30746. {
  30747. if (! asyncMessagePending)
  30748. {
  30749. asyncMessagePending = true;
  30750. internalAsyncHandler.postMessage (new Message());
  30751. }
  30752. }
  30753. void AsyncUpdater::cancelPendingUpdate() throw()
  30754. {
  30755. asyncMessagePending = false;
  30756. }
  30757. void AsyncUpdater::handleUpdateNowIfNeeded()
  30758. {
  30759. if (asyncMessagePending)
  30760. {
  30761. asyncMessagePending = false;
  30762. handleAsyncUpdate();
  30763. }
  30764. }
  30765. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  30766. {
  30767. owner->handleUpdateNowIfNeeded();
  30768. }
  30769. END_JUCE_NAMESPACE
  30770. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30771. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30772. BEGIN_JUCE_NAMESPACE
  30773. ChangeBroadcaster::ChangeBroadcaster() throw()
  30774. {
  30775. // are you trying to create this object before or after juce has been intialised??
  30776. jassert (MessageManager::instance != 0);
  30777. }
  30778. ChangeBroadcaster::~ChangeBroadcaster()
  30779. {
  30780. // all event-based objects must be deleted BEFORE juce is shut down!
  30781. jassert (MessageManager::instance != 0);
  30782. }
  30783. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30784. {
  30785. changeListenerList.addChangeListener (listener);
  30786. }
  30787. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30788. {
  30789. jassert (changeListenerList.isValidMessageListener());
  30790. if (changeListenerList.isValidMessageListener())
  30791. changeListenerList.removeChangeListener (listener);
  30792. }
  30793. void ChangeBroadcaster::removeAllChangeListeners()
  30794. {
  30795. changeListenerList.removeAllChangeListeners();
  30796. }
  30797. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged)
  30798. {
  30799. changeListenerList.sendChangeMessage (objectThatHasChanged);
  30800. }
  30801. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  30802. {
  30803. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  30804. }
  30805. void ChangeBroadcaster::dispatchPendingMessages()
  30806. {
  30807. changeListenerList.dispatchPendingMessages();
  30808. }
  30809. END_JUCE_NAMESPACE
  30810. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30811. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  30812. BEGIN_JUCE_NAMESPACE
  30813. ChangeListenerList::ChangeListenerList()
  30814. : lastChangedObject (0),
  30815. messagePending (false)
  30816. {
  30817. }
  30818. ChangeListenerList::~ChangeListenerList()
  30819. {
  30820. }
  30821. void ChangeListenerList::addChangeListener (ChangeListener* const listener)
  30822. {
  30823. const ScopedLock sl (lock);
  30824. jassert (listener != 0);
  30825. if (listener != 0)
  30826. listeners.add (listener);
  30827. }
  30828. void ChangeListenerList::removeChangeListener (ChangeListener* const listener)
  30829. {
  30830. const ScopedLock sl (lock);
  30831. listeners.removeValue (listener);
  30832. }
  30833. void ChangeListenerList::removeAllChangeListeners()
  30834. {
  30835. const ScopedLock sl (lock);
  30836. listeners.clear();
  30837. }
  30838. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged)
  30839. {
  30840. const ScopedLock sl (lock);
  30841. if ((! messagePending) && (listeners.size() > 0))
  30842. {
  30843. lastChangedObject = objectThatHasChanged;
  30844. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30845. messagePending = true;
  30846. }
  30847. }
  30848. void ChangeListenerList::handleMessage (const Message& message)
  30849. {
  30850. sendSynchronousChangeMessage (message.pointerParameter);
  30851. }
  30852. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30853. {
  30854. const ScopedLock sl (lock);
  30855. messagePending = false;
  30856. for (int i = listeners.size(); --i >= 0;)
  30857. {
  30858. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30859. {
  30860. const ScopedUnlock tempUnlocker (lock);
  30861. l->changeListenerCallback (objectThatHasChanged);
  30862. }
  30863. i = jmin (i, listeners.size());
  30864. }
  30865. }
  30866. void ChangeListenerList::dispatchPendingMessages()
  30867. {
  30868. if (messagePending)
  30869. sendSynchronousChangeMessage (lastChangedObject);
  30870. }
  30871. END_JUCE_NAMESPACE
  30872. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30873. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30874. BEGIN_JUCE_NAMESPACE
  30875. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30876. const uint32 magicMessageHeaderNumber)
  30877. : Thread ("Juce IPC connection"),
  30878. callbackConnectionState (false),
  30879. useMessageThread (callbacksOnMessageThread),
  30880. magicMessageHeader (magicMessageHeaderNumber),
  30881. pipeReceiveMessageTimeout (-1)
  30882. {
  30883. }
  30884. InterprocessConnection::~InterprocessConnection()
  30885. {
  30886. callbackConnectionState = false;
  30887. disconnect();
  30888. }
  30889. bool InterprocessConnection::connectToSocket (const String& hostName,
  30890. const int portNumber,
  30891. const int timeOutMillisecs)
  30892. {
  30893. disconnect();
  30894. const ScopedLock sl (pipeAndSocketLock);
  30895. socket = new StreamingSocket();
  30896. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30897. {
  30898. connectionMadeInt();
  30899. startThread();
  30900. return true;
  30901. }
  30902. else
  30903. {
  30904. socket = 0;
  30905. return false;
  30906. }
  30907. }
  30908. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30909. const int pipeReceiveMessageTimeoutMs)
  30910. {
  30911. disconnect();
  30912. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30913. if (newPipe->openExisting (pipeName))
  30914. {
  30915. const ScopedLock sl (pipeAndSocketLock);
  30916. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30917. initialiseWithPipe (newPipe.release());
  30918. return true;
  30919. }
  30920. return false;
  30921. }
  30922. bool InterprocessConnection::createPipe (const String& pipeName,
  30923. const int pipeReceiveMessageTimeoutMs)
  30924. {
  30925. disconnect();
  30926. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30927. if (newPipe->createNewPipe (pipeName))
  30928. {
  30929. const ScopedLock sl (pipeAndSocketLock);
  30930. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30931. initialiseWithPipe (newPipe.release());
  30932. return true;
  30933. }
  30934. return false;
  30935. }
  30936. void InterprocessConnection::disconnect()
  30937. {
  30938. if (socket != 0)
  30939. socket->close();
  30940. if (pipe != 0)
  30941. {
  30942. pipe->cancelPendingReads();
  30943. pipe->close();
  30944. }
  30945. stopThread (4000);
  30946. {
  30947. const ScopedLock sl (pipeAndSocketLock);
  30948. socket = 0;
  30949. pipe = 0;
  30950. }
  30951. connectionLostInt();
  30952. }
  30953. bool InterprocessConnection::isConnected() const
  30954. {
  30955. const ScopedLock sl (pipeAndSocketLock);
  30956. return ((socket != 0 && socket->isConnected())
  30957. || (pipe != 0 && pipe->isOpen()))
  30958. && isThreadRunning();
  30959. }
  30960. const String InterprocessConnection::getConnectedHostName() const
  30961. {
  30962. if (pipe != 0)
  30963. {
  30964. return "localhost";
  30965. }
  30966. else if (socket != 0)
  30967. {
  30968. if (! socket->isLocal())
  30969. return socket->getHostName();
  30970. return "localhost";
  30971. }
  30972. return String::empty;
  30973. }
  30974. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30975. {
  30976. uint32 messageHeader[2];
  30977. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30978. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30979. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30980. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30981. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30982. size_t bytesWritten = 0;
  30983. const ScopedLock sl (pipeAndSocketLock);
  30984. if (socket != 0)
  30985. {
  30986. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30987. }
  30988. else if (pipe != 0)
  30989. {
  30990. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30991. }
  30992. if (bytesWritten < 0)
  30993. {
  30994. // error..
  30995. return false;
  30996. }
  30997. return (bytesWritten == messageData.getSize());
  30998. }
  30999. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  31000. {
  31001. jassert (socket == 0);
  31002. socket = socket_;
  31003. connectionMadeInt();
  31004. startThread();
  31005. }
  31006. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  31007. {
  31008. jassert (pipe == 0);
  31009. pipe = pipe_;
  31010. connectionMadeInt();
  31011. startThread();
  31012. }
  31013. const int messageMagicNumber = 0xb734128b;
  31014. void InterprocessConnection::handleMessage (const Message& message)
  31015. {
  31016. if (message.intParameter1 == messageMagicNumber)
  31017. {
  31018. switch (message.intParameter2)
  31019. {
  31020. case 0:
  31021. {
  31022. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  31023. messageReceived (*data);
  31024. break;
  31025. }
  31026. case 1:
  31027. connectionMade();
  31028. break;
  31029. case 2:
  31030. connectionLost();
  31031. break;
  31032. }
  31033. }
  31034. }
  31035. void InterprocessConnection::connectionMadeInt()
  31036. {
  31037. if (! callbackConnectionState)
  31038. {
  31039. callbackConnectionState = true;
  31040. if (useMessageThread)
  31041. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  31042. else
  31043. connectionMade();
  31044. }
  31045. }
  31046. void InterprocessConnection::connectionLostInt()
  31047. {
  31048. if (callbackConnectionState)
  31049. {
  31050. callbackConnectionState = false;
  31051. if (useMessageThread)
  31052. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  31053. else
  31054. connectionLost();
  31055. }
  31056. }
  31057. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  31058. {
  31059. jassert (callbackConnectionState);
  31060. if (useMessageThread)
  31061. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  31062. else
  31063. messageReceived (data);
  31064. }
  31065. bool InterprocessConnection::readNextMessageInt()
  31066. {
  31067. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  31068. uint32 messageHeader[2];
  31069. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31070. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31071. if (bytes == sizeof (messageHeader)
  31072. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31073. {
  31074. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31075. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31076. {
  31077. MemoryBlock messageData (bytesInMessage, true);
  31078. int bytesRead = 0;
  31079. while (bytesInMessage > 0)
  31080. {
  31081. if (threadShouldExit())
  31082. return false;
  31083. const int numThisTime = jmin (bytesInMessage, 65536);
  31084. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31085. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31086. if (bytesIn <= 0)
  31087. break;
  31088. bytesRead += bytesIn;
  31089. bytesInMessage -= bytesIn;
  31090. }
  31091. if (bytesRead >= 0)
  31092. deliverDataInt (messageData);
  31093. }
  31094. }
  31095. else if (bytes < 0)
  31096. {
  31097. {
  31098. const ScopedLock sl (pipeAndSocketLock);
  31099. socket = 0;
  31100. }
  31101. connectionLostInt();
  31102. return false;
  31103. }
  31104. return true;
  31105. }
  31106. void InterprocessConnection::run()
  31107. {
  31108. while (! threadShouldExit())
  31109. {
  31110. if (socket != 0)
  31111. {
  31112. const int ready = socket->waitUntilReady (true, 0);
  31113. if (ready < 0)
  31114. {
  31115. {
  31116. const ScopedLock sl (pipeAndSocketLock);
  31117. socket = 0;
  31118. }
  31119. connectionLostInt();
  31120. break;
  31121. }
  31122. else if (ready > 0)
  31123. {
  31124. if (! readNextMessageInt())
  31125. break;
  31126. }
  31127. else
  31128. {
  31129. Thread::sleep (2);
  31130. }
  31131. }
  31132. else if (pipe != 0)
  31133. {
  31134. if (! pipe->isOpen())
  31135. {
  31136. {
  31137. const ScopedLock sl (pipeAndSocketLock);
  31138. pipe = 0;
  31139. }
  31140. connectionLostInt();
  31141. break;
  31142. }
  31143. else
  31144. {
  31145. if (! readNextMessageInt())
  31146. break;
  31147. }
  31148. }
  31149. else
  31150. {
  31151. break;
  31152. }
  31153. }
  31154. }
  31155. END_JUCE_NAMESPACE
  31156. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31157. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31158. BEGIN_JUCE_NAMESPACE
  31159. InterprocessConnectionServer::InterprocessConnectionServer()
  31160. : Thread ("Juce IPC server")
  31161. {
  31162. }
  31163. InterprocessConnectionServer::~InterprocessConnectionServer()
  31164. {
  31165. stop();
  31166. }
  31167. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31168. {
  31169. stop();
  31170. socket = new StreamingSocket();
  31171. if (socket->createListener (portNumber))
  31172. {
  31173. startThread();
  31174. return true;
  31175. }
  31176. socket = 0;
  31177. return false;
  31178. }
  31179. void InterprocessConnectionServer::stop()
  31180. {
  31181. signalThreadShouldExit();
  31182. if (socket != 0)
  31183. socket->close();
  31184. stopThread (4000);
  31185. socket = 0;
  31186. }
  31187. void InterprocessConnectionServer::run()
  31188. {
  31189. while ((! threadShouldExit()) && socket != 0)
  31190. {
  31191. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31192. if (clientSocket != 0)
  31193. {
  31194. InterprocessConnection* newConnection = createConnectionObject();
  31195. if (newConnection != 0)
  31196. newConnection->initialiseWithSocket (clientSocket.release());
  31197. }
  31198. }
  31199. }
  31200. END_JUCE_NAMESPACE
  31201. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31202. /*** Start of inlined file: juce_Message.cpp ***/
  31203. BEGIN_JUCE_NAMESPACE
  31204. Message::Message() throw()
  31205. : intParameter1 (0),
  31206. intParameter2 (0),
  31207. intParameter3 (0),
  31208. pointerParameter (0)
  31209. {
  31210. }
  31211. Message::Message (const int intParameter1_,
  31212. const int intParameter2_,
  31213. const int intParameter3_,
  31214. void* const pointerParameter_) throw()
  31215. : intParameter1 (intParameter1_),
  31216. intParameter2 (intParameter2_),
  31217. intParameter3 (intParameter3_),
  31218. pointerParameter (pointerParameter_)
  31219. {
  31220. }
  31221. Message::~Message() throw()
  31222. {
  31223. }
  31224. END_JUCE_NAMESPACE
  31225. /*** End of inlined file: juce_Message.cpp ***/
  31226. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31227. BEGIN_JUCE_NAMESPACE
  31228. MessageListener::MessageListener() throw()
  31229. {
  31230. // are you trying to create a messagelistener before or after juce has been intialised??
  31231. jassert (MessageManager::instance != 0);
  31232. if (MessageManager::instance != 0)
  31233. MessageManager::instance->messageListeners.add (this);
  31234. }
  31235. MessageListener::~MessageListener()
  31236. {
  31237. if (MessageManager::instance != 0)
  31238. MessageManager::instance->messageListeners.removeValue (this);
  31239. }
  31240. void MessageListener::postMessage (Message* const message) const throw()
  31241. {
  31242. message->messageRecipient = const_cast <MessageListener*> (this);
  31243. if (MessageManager::instance == 0)
  31244. MessageManager::getInstance();
  31245. MessageManager::instance->postMessageToQueue (message);
  31246. }
  31247. bool MessageListener::isValidMessageListener() const throw()
  31248. {
  31249. return (MessageManager::instance != 0)
  31250. && MessageManager::instance->messageListeners.contains (this);
  31251. }
  31252. END_JUCE_NAMESPACE
  31253. /*** End of inlined file: juce_MessageListener.cpp ***/
  31254. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31255. BEGIN_JUCE_NAMESPACE
  31256. // platform-specific functions..
  31257. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31258. bool juce_postMessageToSystemQueue (Message* message);
  31259. MessageManager* MessageManager::instance = 0;
  31260. static const int quitMessageId = 0xfffff321;
  31261. MessageManager::MessageManager() throw()
  31262. : quitMessagePosted (false),
  31263. quitMessageReceived (false),
  31264. threadWithLock (0)
  31265. {
  31266. messageThreadId = Thread::getCurrentThreadId();
  31267. }
  31268. MessageManager::~MessageManager() throw()
  31269. {
  31270. broadcastListeners = 0;
  31271. doPlatformSpecificShutdown();
  31272. // If you hit this assertion, then you've probably leaked a Component or some other
  31273. // kind of MessageListener object...
  31274. jassert (messageListeners.size() == 0);
  31275. jassert (instance == this);
  31276. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31277. }
  31278. MessageManager* MessageManager::getInstance() throw()
  31279. {
  31280. if (instance == 0)
  31281. {
  31282. instance = new MessageManager();
  31283. doPlatformSpecificInitialisation();
  31284. }
  31285. return instance;
  31286. }
  31287. void MessageManager::postMessageToQueue (Message* const message)
  31288. {
  31289. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31290. delete message;
  31291. }
  31292. CallbackMessage::CallbackMessage() throw() {}
  31293. CallbackMessage::~CallbackMessage() throw() {}
  31294. void CallbackMessage::post()
  31295. {
  31296. if (MessageManager::instance != 0)
  31297. MessageManager::instance->postCallbackMessage (this);
  31298. }
  31299. void MessageManager::postCallbackMessage (Message* const message)
  31300. {
  31301. message->messageRecipient = 0;
  31302. postMessageToQueue (message);
  31303. }
  31304. // not for public use..
  31305. void MessageManager::deliverMessage (Message* const message)
  31306. {
  31307. const ScopedPointer <Message> messageDeleter (message);
  31308. MessageListener* const recipient = message->messageRecipient;
  31309. JUCE_TRY
  31310. {
  31311. if (messageListeners.contains (recipient))
  31312. {
  31313. recipient->handleMessage (*message);
  31314. }
  31315. else if (recipient == 0)
  31316. {
  31317. if (message->intParameter1 == quitMessageId)
  31318. {
  31319. quitMessageReceived = true;
  31320. }
  31321. else
  31322. {
  31323. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  31324. if (cm != 0)
  31325. cm->messageCallback();
  31326. }
  31327. }
  31328. }
  31329. JUCE_CATCH_EXCEPTION
  31330. }
  31331. #if ! (JUCE_MAC || JUCE_IOS)
  31332. void MessageManager::runDispatchLoop()
  31333. {
  31334. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31335. runDispatchLoopUntil (-1);
  31336. }
  31337. void MessageManager::stopDispatchLoop()
  31338. {
  31339. Message* const m = new Message (quitMessageId, 0, 0, 0);
  31340. m->messageRecipient = 0;
  31341. postMessageToQueue (m);
  31342. quitMessagePosted = true;
  31343. }
  31344. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31345. {
  31346. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31347. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31348. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31349. && ! quitMessageReceived)
  31350. {
  31351. JUCE_TRY
  31352. {
  31353. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31354. {
  31355. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31356. if (msToWait > 0)
  31357. Thread::sleep (jmin (5, msToWait));
  31358. }
  31359. }
  31360. JUCE_CATCH_EXCEPTION
  31361. }
  31362. return ! quitMessageReceived;
  31363. }
  31364. #endif
  31365. void MessageManager::deliverBroadcastMessage (const String& value)
  31366. {
  31367. if (broadcastListeners != 0)
  31368. broadcastListeners->sendActionMessage (value);
  31369. }
  31370. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31371. {
  31372. if (broadcastListeners == 0)
  31373. broadcastListeners = new ActionListenerList();
  31374. broadcastListeners->addActionListener (listener);
  31375. }
  31376. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31377. {
  31378. if (broadcastListeners != 0)
  31379. broadcastListeners->removeActionListener (listener);
  31380. }
  31381. bool MessageManager::isThisTheMessageThread() const throw()
  31382. {
  31383. return Thread::getCurrentThreadId() == messageThreadId;
  31384. }
  31385. void MessageManager::setCurrentThreadAsMessageThread()
  31386. {
  31387. if (messageThreadId != Thread::getCurrentThreadId())
  31388. {
  31389. messageThreadId = Thread::getCurrentThreadId();
  31390. // This is needed on windows to make sure the message window is created by this thread
  31391. doPlatformSpecificShutdown();
  31392. doPlatformSpecificInitialisation();
  31393. }
  31394. }
  31395. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31396. {
  31397. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31398. return thisThread == messageThreadId || thisThread == threadWithLock;
  31399. }
  31400. /* The only safe way to lock the message thread while another thread does
  31401. some work is by posting a special message, whose purpose is to tie up the event
  31402. loop until the other thread has finished its business.
  31403. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31404. get locked before making an event callback, because if the same OS lock gets indirectly
  31405. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31406. in Cocoa).
  31407. */
  31408. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  31409. {
  31410. public:
  31411. SharedEvents() {}
  31412. ~SharedEvents() {}
  31413. /* This class just holds a couple of events to communicate between the BlockingMessage
  31414. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  31415. this shared data must be kept in a separate, ref-counted container. */
  31416. WaitableEvent lockedEvent, releaseEvent;
  31417. private:
  31418. SharedEvents (const SharedEvents&);
  31419. SharedEvents& operator= (const SharedEvents&);
  31420. };
  31421. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31422. {
  31423. public:
  31424. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  31425. ~BlockingMessage() throw() {}
  31426. void messageCallback()
  31427. {
  31428. events->lockedEvent.signal();
  31429. events->releaseEvent.wait();
  31430. }
  31431. juce_UseDebuggingNewOperator
  31432. private:
  31433. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  31434. BlockingMessage (const BlockingMessage&);
  31435. BlockingMessage& operator= (const BlockingMessage&);
  31436. };
  31437. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31438. : sharedEvents (0),
  31439. locked (false)
  31440. {
  31441. init (threadToCheck, 0);
  31442. }
  31443. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31444. : sharedEvents (0),
  31445. locked (false)
  31446. {
  31447. init (0, jobToCheckForExitSignal);
  31448. }
  31449. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31450. {
  31451. if (MessageManager::instance != 0)
  31452. {
  31453. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31454. {
  31455. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31456. }
  31457. else
  31458. {
  31459. if (threadToCheck == 0 && job == 0)
  31460. {
  31461. MessageManager::instance->lockingLock.enter();
  31462. }
  31463. else
  31464. {
  31465. while (! MessageManager::instance->lockingLock.tryEnter())
  31466. {
  31467. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31468. || (job != 0 && job->shouldExit()))
  31469. return;
  31470. Thread::sleep (1);
  31471. }
  31472. }
  31473. sharedEvents = new SharedEvents();
  31474. sharedEvents->incReferenceCount();
  31475. (new BlockingMessage (sharedEvents))->post();
  31476. while (! sharedEvents->lockedEvent.wait (50))
  31477. {
  31478. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31479. || (job != 0 && job->shouldExit()))
  31480. {
  31481. sharedEvents->releaseEvent.signal();
  31482. sharedEvents->decReferenceCount();
  31483. sharedEvents = 0;
  31484. MessageManager::instance->lockingLock.exit();
  31485. return;
  31486. }
  31487. }
  31488. jassert (MessageManager::instance->threadWithLock == 0);
  31489. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31490. locked = true;
  31491. }
  31492. }
  31493. }
  31494. MessageManagerLock::~MessageManagerLock() throw()
  31495. {
  31496. if (sharedEvents != 0)
  31497. {
  31498. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31499. sharedEvents->releaseEvent.signal();
  31500. sharedEvents->decReferenceCount();
  31501. if (MessageManager::instance != 0)
  31502. {
  31503. MessageManager::instance->threadWithLock = 0;
  31504. MessageManager::instance->lockingLock.exit();
  31505. }
  31506. }
  31507. }
  31508. END_JUCE_NAMESPACE
  31509. /*** End of inlined file: juce_MessageManager.cpp ***/
  31510. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31511. BEGIN_JUCE_NAMESPACE
  31512. class MultiTimer::MultiTimerCallback : public Timer
  31513. {
  31514. public:
  31515. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31516. : timerId (timerId_),
  31517. owner (owner_)
  31518. {
  31519. }
  31520. ~MultiTimerCallback()
  31521. {
  31522. }
  31523. void timerCallback()
  31524. {
  31525. owner.timerCallback (timerId);
  31526. }
  31527. const int timerId;
  31528. private:
  31529. MultiTimer& owner;
  31530. };
  31531. MultiTimer::MultiTimer() throw()
  31532. {
  31533. }
  31534. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31535. {
  31536. }
  31537. MultiTimer::~MultiTimer()
  31538. {
  31539. const ScopedLock sl (timerListLock);
  31540. timers.clear();
  31541. }
  31542. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31543. {
  31544. const ScopedLock sl (timerListLock);
  31545. for (int i = timers.size(); --i >= 0;)
  31546. {
  31547. MultiTimerCallback* const t = timers.getUnchecked(i);
  31548. if (t->timerId == timerId)
  31549. {
  31550. t->startTimer (intervalInMilliseconds);
  31551. return;
  31552. }
  31553. }
  31554. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31555. timers.add (newTimer);
  31556. newTimer->startTimer (intervalInMilliseconds);
  31557. }
  31558. void MultiTimer::stopTimer (const int timerId) throw()
  31559. {
  31560. const ScopedLock sl (timerListLock);
  31561. for (int i = timers.size(); --i >= 0;)
  31562. {
  31563. MultiTimerCallback* const t = timers.getUnchecked(i);
  31564. if (t->timerId == timerId)
  31565. t->stopTimer();
  31566. }
  31567. }
  31568. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31569. {
  31570. const ScopedLock sl (timerListLock);
  31571. for (int i = timers.size(); --i >= 0;)
  31572. {
  31573. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31574. if (t->timerId == timerId)
  31575. return t->isTimerRunning();
  31576. }
  31577. return false;
  31578. }
  31579. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31580. {
  31581. const ScopedLock sl (timerListLock);
  31582. for (int i = timers.size(); --i >= 0;)
  31583. {
  31584. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31585. if (t->timerId == timerId)
  31586. return t->getTimerInterval();
  31587. }
  31588. return 0;
  31589. }
  31590. END_JUCE_NAMESPACE
  31591. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31592. /*** Start of inlined file: juce_Timer.cpp ***/
  31593. BEGIN_JUCE_NAMESPACE
  31594. class InternalTimerThread : private Thread,
  31595. private MessageListener,
  31596. private DeletedAtShutdown,
  31597. private AsyncUpdater
  31598. {
  31599. public:
  31600. InternalTimerThread()
  31601. : Thread ("Juce Timer"),
  31602. firstTimer (0),
  31603. callbackNeeded (0)
  31604. {
  31605. triggerAsyncUpdate();
  31606. }
  31607. ~InternalTimerThread() throw()
  31608. {
  31609. stopThread (4000);
  31610. jassert (instance == this || instance == 0);
  31611. if (instance == this)
  31612. instance = 0;
  31613. }
  31614. void run()
  31615. {
  31616. uint32 lastTime = Time::getMillisecondCounter();
  31617. while (! threadShouldExit())
  31618. {
  31619. const uint32 now = Time::getMillisecondCounter();
  31620. if (now <= lastTime)
  31621. {
  31622. wait (2);
  31623. continue;
  31624. }
  31625. const int elapsed = now - lastTime;
  31626. lastTime = now;
  31627. int timeUntilFirstTimer = 1000;
  31628. {
  31629. const ScopedLock sl (lock);
  31630. decrementAllCounters (elapsed);
  31631. if (firstTimer != 0)
  31632. timeUntilFirstTimer = firstTimer->countdownMs;
  31633. }
  31634. if (timeUntilFirstTimer <= 0)
  31635. {
  31636. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31637. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31638. but if it fails it means the message-thread changed the value from under us so at least
  31639. some processing is happenening and we can just loop around and try again
  31640. */
  31641. if (callbackNeeded.compareAndSetBool (1, 0))
  31642. {
  31643. postMessage (new Message());
  31644. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31645. when the app has a modal loop), so this is how long to wait before assuming the
  31646. message has been lost and trying again.
  31647. */
  31648. const uint32 messageDeliveryTimeout = now + 2000;
  31649. while (callbackNeeded.get() != 0)
  31650. {
  31651. wait (4);
  31652. if (threadShouldExit())
  31653. return;
  31654. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31655. break;
  31656. }
  31657. }
  31658. }
  31659. else
  31660. {
  31661. // don't wait for too long because running this loop also helps keep the
  31662. // Time::getApproximateMillisecondTimer value stay up-to-date
  31663. wait (jlimit (1, 50, timeUntilFirstTimer));
  31664. }
  31665. }
  31666. }
  31667. void callTimers()
  31668. {
  31669. const ScopedLock sl (lock);
  31670. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31671. {
  31672. Timer* const t = firstTimer;
  31673. t->countdownMs = t->periodMs;
  31674. removeTimer (t);
  31675. addTimer (t);
  31676. const ScopedUnlock ul (lock);
  31677. JUCE_TRY
  31678. {
  31679. t->timerCallback();
  31680. }
  31681. JUCE_CATCH_EXCEPTION
  31682. }
  31683. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31684. before the boolean is set. This set should never fail since if it was false in the first place,
  31685. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31686. get a message then the value is true and the other thread can only set it to true again and
  31687. we will get another callback to set it to false.
  31688. */
  31689. callbackNeeded.set (0);
  31690. }
  31691. void handleMessage (const Message&)
  31692. {
  31693. callTimers();
  31694. }
  31695. void callTimersSynchronously()
  31696. {
  31697. if (! isThreadRunning())
  31698. {
  31699. // (This is relied on by some plugins in cases where the MM has
  31700. // had to restart and the async callback never started)
  31701. cancelPendingUpdate();
  31702. triggerAsyncUpdate();
  31703. }
  31704. callTimers();
  31705. }
  31706. static void callAnyTimersSynchronously()
  31707. {
  31708. if (InternalTimerThread::instance != 0)
  31709. InternalTimerThread::instance->callTimersSynchronously();
  31710. }
  31711. static inline void add (Timer* const tim) throw()
  31712. {
  31713. if (instance == 0)
  31714. instance = new InternalTimerThread();
  31715. const ScopedLock sl (instance->lock);
  31716. instance->addTimer (tim);
  31717. }
  31718. static inline void remove (Timer* const tim) throw()
  31719. {
  31720. if (instance != 0)
  31721. {
  31722. const ScopedLock sl (instance->lock);
  31723. instance->removeTimer (tim);
  31724. }
  31725. }
  31726. static inline void resetCounter (Timer* const tim,
  31727. const int newCounter) throw()
  31728. {
  31729. if (instance != 0)
  31730. {
  31731. tim->countdownMs = newCounter;
  31732. tim->periodMs = newCounter;
  31733. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31734. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31735. {
  31736. const ScopedLock sl (instance->lock);
  31737. instance->removeTimer (tim);
  31738. instance->addTimer (tim);
  31739. }
  31740. }
  31741. }
  31742. private:
  31743. friend class Timer;
  31744. static InternalTimerThread* instance;
  31745. static CriticalSection lock;
  31746. Timer* volatile firstTimer;
  31747. Atomic <int> callbackNeeded;
  31748. void addTimer (Timer* const t) throw()
  31749. {
  31750. #if JUCE_DEBUG
  31751. Timer* tt = firstTimer;
  31752. while (tt != 0)
  31753. {
  31754. // trying to add a timer that's already here - shouldn't get to this point,
  31755. // so if you get this assertion, let me know!
  31756. jassert (tt != t);
  31757. tt = tt->next;
  31758. }
  31759. jassert (t->previous == 0 && t->next == 0);
  31760. #endif
  31761. Timer* i = firstTimer;
  31762. if (i == 0 || i->countdownMs > t->countdownMs)
  31763. {
  31764. t->next = firstTimer;
  31765. firstTimer = t;
  31766. }
  31767. else
  31768. {
  31769. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31770. i = i->next;
  31771. jassert (i != 0);
  31772. t->next = i->next;
  31773. t->previous = i;
  31774. i->next = t;
  31775. }
  31776. if (t->next != 0)
  31777. t->next->previous = t;
  31778. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31779. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31780. notify();
  31781. }
  31782. void removeTimer (Timer* const t) throw()
  31783. {
  31784. #if JUCE_DEBUG
  31785. Timer* tt = firstTimer;
  31786. bool found = false;
  31787. while (tt != 0)
  31788. {
  31789. if (tt == t)
  31790. {
  31791. found = true;
  31792. break;
  31793. }
  31794. tt = tt->next;
  31795. }
  31796. // trying to remove a timer that's not here - shouldn't get to this point,
  31797. // so if you get this assertion, let me know!
  31798. jassert (found);
  31799. #endif
  31800. if (t->previous != 0)
  31801. {
  31802. jassert (firstTimer != t);
  31803. t->previous->next = t->next;
  31804. }
  31805. else
  31806. {
  31807. jassert (firstTimer == t);
  31808. firstTimer = t->next;
  31809. }
  31810. if (t->next != 0)
  31811. t->next->previous = t->previous;
  31812. t->next = 0;
  31813. t->previous = 0;
  31814. }
  31815. void decrementAllCounters (const int numMillisecs) const
  31816. {
  31817. Timer* t = firstTimer;
  31818. while (t != 0)
  31819. {
  31820. t->countdownMs -= numMillisecs;
  31821. t = t->next;
  31822. }
  31823. }
  31824. void handleAsyncUpdate()
  31825. {
  31826. startThread (7);
  31827. }
  31828. InternalTimerThread (const InternalTimerThread&);
  31829. InternalTimerThread& operator= (const InternalTimerThread&);
  31830. };
  31831. InternalTimerThread* InternalTimerThread::instance = 0;
  31832. CriticalSection InternalTimerThread::lock;
  31833. void juce_callAnyTimersSynchronously()
  31834. {
  31835. InternalTimerThread::callAnyTimersSynchronously();
  31836. }
  31837. #if JUCE_DEBUG
  31838. static SortedSet <Timer*> activeTimers;
  31839. #endif
  31840. Timer::Timer() throw()
  31841. : countdownMs (0),
  31842. periodMs (0),
  31843. previous (0),
  31844. next (0)
  31845. {
  31846. #if JUCE_DEBUG
  31847. activeTimers.add (this);
  31848. #endif
  31849. }
  31850. Timer::Timer (const Timer&) throw()
  31851. : countdownMs (0),
  31852. periodMs (0),
  31853. previous (0),
  31854. next (0)
  31855. {
  31856. #if JUCE_DEBUG
  31857. activeTimers.add (this);
  31858. #endif
  31859. }
  31860. Timer::~Timer()
  31861. {
  31862. stopTimer();
  31863. #if JUCE_DEBUG
  31864. activeTimers.removeValue (this);
  31865. #endif
  31866. }
  31867. void Timer::startTimer (const int interval) throw()
  31868. {
  31869. const ScopedLock sl (InternalTimerThread::lock);
  31870. #if JUCE_DEBUG
  31871. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31872. jassert (activeTimers.contains (this));
  31873. #endif
  31874. if (periodMs == 0)
  31875. {
  31876. countdownMs = interval;
  31877. periodMs = jmax (1, interval);
  31878. InternalTimerThread::add (this);
  31879. }
  31880. else
  31881. {
  31882. InternalTimerThread::resetCounter (this, interval);
  31883. }
  31884. }
  31885. void Timer::stopTimer() throw()
  31886. {
  31887. const ScopedLock sl (InternalTimerThread::lock);
  31888. #if JUCE_DEBUG
  31889. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31890. jassert (activeTimers.contains (this));
  31891. #endif
  31892. if (periodMs > 0)
  31893. {
  31894. InternalTimerThread::remove (this);
  31895. periodMs = 0;
  31896. }
  31897. }
  31898. END_JUCE_NAMESPACE
  31899. /*** End of inlined file: juce_Timer.cpp ***/
  31900. #endif
  31901. #if JUCE_BUILD_GUI
  31902. /*** Start of inlined file: juce_Component.cpp ***/
  31903. BEGIN_JUCE_NAMESPACE
  31904. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31905. enum ComponentMessageNumbers
  31906. {
  31907. customCommandMessage = 0x7fff0001,
  31908. exitModalStateMessage = 0x7fff0002
  31909. };
  31910. static uint32 nextComponentUID = 0;
  31911. Component* Component::currentlyFocusedComponent = 0;
  31912. Component::Component()
  31913. : parentComponent_ (0),
  31914. componentUID (++nextComponentUID),
  31915. numDeepMouseListeners (0),
  31916. lookAndFeel_ (0),
  31917. effect_ (0),
  31918. bufferedImage_ (0),
  31919. mouseListeners_ (0),
  31920. keyListeners_ (0),
  31921. componentFlags_ (0)
  31922. {
  31923. }
  31924. Component::Component (const String& name)
  31925. : componentName_ (name),
  31926. parentComponent_ (0),
  31927. componentUID (++nextComponentUID),
  31928. numDeepMouseListeners (0),
  31929. lookAndFeel_ (0),
  31930. effect_ (0),
  31931. bufferedImage_ (0),
  31932. mouseListeners_ (0),
  31933. keyListeners_ (0),
  31934. componentFlags_ (0)
  31935. {
  31936. }
  31937. Component::~Component()
  31938. {
  31939. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31940. if (parentComponent_ != 0)
  31941. {
  31942. parentComponent_->removeChildComponent (this);
  31943. }
  31944. else if ((currentlyFocusedComponent == this)
  31945. || isParentOf (currentlyFocusedComponent))
  31946. {
  31947. giveAwayFocus();
  31948. }
  31949. if (flags.hasHeavyweightPeerFlag)
  31950. removeFromDesktop();
  31951. for (int i = childComponentList_.size(); --i >= 0;)
  31952. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31953. delete mouseListeners_;
  31954. delete keyListeners_;
  31955. }
  31956. void Component::setName (const String& name)
  31957. {
  31958. // if component methods are being called from threads other than the message
  31959. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31960. checkMessageManagerIsLocked
  31961. if (componentName_ != name)
  31962. {
  31963. componentName_ = name;
  31964. if (flags.hasHeavyweightPeerFlag)
  31965. {
  31966. ComponentPeer* const peer = getPeer();
  31967. jassert (peer != 0);
  31968. if (peer != 0)
  31969. peer->setTitle (name);
  31970. }
  31971. BailOutChecker checker (this);
  31972. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31973. }
  31974. }
  31975. void Component::setVisible (bool shouldBeVisible)
  31976. {
  31977. if (flags.visibleFlag != shouldBeVisible)
  31978. {
  31979. // if component methods are being called from threads other than the message
  31980. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31981. checkMessageManagerIsLocked
  31982. SafePointer<Component> safePointer (this);
  31983. flags.visibleFlag = shouldBeVisible;
  31984. internalRepaint (0, 0, getWidth(), getHeight());
  31985. sendFakeMouseMove();
  31986. if (! shouldBeVisible)
  31987. {
  31988. if (currentlyFocusedComponent == this
  31989. || isParentOf (currentlyFocusedComponent))
  31990. {
  31991. if (parentComponent_ != 0)
  31992. parentComponent_->grabKeyboardFocus();
  31993. else
  31994. giveAwayFocus();
  31995. }
  31996. }
  31997. if (safePointer != 0)
  31998. {
  31999. sendVisibilityChangeMessage();
  32000. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32001. {
  32002. ComponentPeer* const peer = getPeer();
  32003. jassert (peer != 0);
  32004. if (peer != 0)
  32005. {
  32006. peer->setVisible (shouldBeVisible);
  32007. internalHierarchyChanged();
  32008. }
  32009. }
  32010. }
  32011. }
  32012. }
  32013. void Component::visibilityChanged()
  32014. {
  32015. }
  32016. void Component::sendVisibilityChangeMessage()
  32017. {
  32018. BailOutChecker checker (this);
  32019. visibilityChanged();
  32020. if (! checker.shouldBailOut())
  32021. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32022. }
  32023. bool Component::isShowing() const
  32024. {
  32025. if (flags.visibleFlag)
  32026. {
  32027. if (parentComponent_ != 0)
  32028. {
  32029. return parentComponent_->isShowing();
  32030. }
  32031. else
  32032. {
  32033. const ComponentPeer* const peer = getPeer();
  32034. return peer != 0 && ! peer->isMinimised();
  32035. }
  32036. }
  32037. return false;
  32038. }
  32039. class FadeOutProxyComponent : public Component,
  32040. public Timer
  32041. {
  32042. public:
  32043. FadeOutProxyComponent (Component* comp,
  32044. const int fadeLengthMs,
  32045. const int deltaXToMove,
  32046. const int deltaYToMove,
  32047. const float scaleFactorAtEnd)
  32048. : lastTime (0),
  32049. alpha (1.0f),
  32050. scale (1.0f)
  32051. {
  32052. image = comp->createComponentSnapshot (comp->getLocalBounds());
  32053. setBounds (comp->getBounds());
  32054. comp->getParentComponent()->addAndMakeVisible (this);
  32055. toBehind (comp);
  32056. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  32057. centreX = comp->getX() + comp->getWidth() * 0.5f;
  32058. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  32059. centreY = comp->getY() + comp->getHeight() * 0.5f;
  32060. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  32061. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  32062. setInterceptsMouseClicks (false, false);
  32063. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  32064. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  32065. }
  32066. ~FadeOutProxyComponent()
  32067. {
  32068. }
  32069. void paint (Graphics& g)
  32070. {
  32071. g.setOpacity (alpha);
  32072. g.drawImage (image,
  32073. 0, 0, getWidth(), getHeight(),
  32074. 0, 0, image.getWidth(), image.getHeight());
  32075. }
  32076. void timerCallback()
  32077. {
  32078. const uint32 now = Time::getMillisecondCounter();
  32079. if (lastTime == 0)
  32080. lastTime = now;
  32081. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  32082. lastTime = now;
  32083. alpha += alphaChangePerMs * msPassed;
  32084. if (alpha > 0)
  32085. {
  32086. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  32087. {
  32088. centreX += xChangePerMs * msPassed;
  32089. centreY += yChangePerMs * msPassed;
  32090. scale += scaleChangePerMs * msPassed;
  32091. const int w = roundToInt (image.getWidth() * scale);
  32092. const int h = roundToInt (image.getHeight() * scale);
  32093. setBounds (roundToInt (centreX) - w / 2,
  32094. roundToInt (centreY) - h / 2,
  32095. w, h);
  32096. }
  32097. repaint();
  32098. }
  32099. else
  32100. {
  32101. delete this;
  32102. }
  32103. }
  32104. juce_UseDebuggingNewOperator
  32105. private:
  32106. Image image;
  32107. uint32 lastTime;
  32108. float alpha, alphaChangePerMs;
  32109. float centreX, xChangePerMs;
  32110. float centreY, yChangePerMs;
  32111. float scale, scaleChangePerMs;
  32112. FadeOutProxyComponent (const FadeOutProxyComponent&);
  32113. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  32114. };
  32115. void Component::fadeOutComponent (const int millisecondsToFade,
  32116. const int deltaXToMove,
  32117. const int deltaYToMove,
  32118. const float scaleFactorAtEnd)
  32119. {
  32120. //xxx won't work for comps without parents
  32121. if (isShowing() && millisecondsToFade > 0)
  32122. new FadeOutProxyComponent (this, millisecondsToFade,
  32123. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  32124. setVisible (false);
  32125. }
  32126. bool Component::isValidComponent() const
  32127. {
  32128. return (this != 0) && isValidMessageListener();
  32129. }
  32130. void* Component::getWindowHandle() const
  32131. {
  32132. const ComponentPeer* const peer = getPeer();
  32133. if (peer != 0)
  32134. return peer->getNativeHandle();
  32135. return 0;
  32136. }
  32137. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32138. {
  32139. // if component methods are being called from threads other than the message
  32140. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32141. checkMessageManagerIsLocked
  32142. if (isOpaque())
  32143. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32144. else
  32145. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32146. int currentStyleFlags = 0;
  32147. // don't use getPeer(), so that we only get the peer that's specifically
  32148. // for this comp, and not for one of its parents.
  32149. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32150. if (peer != 0)
  32151. currentStyleFlags = peer->getStyleFlags();
  32152. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32153. {
  32154. SafePointer<Component> safePointer (this);
  32155. #if JUCE_LINUX
  32156. // it's wise to give the component a non-zero size before
  32157. // putting it on the desktop, as X windows get confused by this, and
  32158. // a (1, 1) minimum size is enforced here.
  32159. setSize (jmax (1, getWidth()),
  32160. jmax (1, getHeight()));
  32161. #endif
  32162. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  32163. bool wasFullscreen = false;
  32164. bool wasMinimised = false;
  32165. ComponentBoundsConstrainer* currentConstainer = 0;
  32166. Rectangle<int> oldNonFullScreenBounds;
  32167. if (peer != 0)
  32168. {
  32169. wasFullscreen = peer->isFullScreen();
  32170. wasMinimised = peer->isMinimised();
  32171. currentConstainer = peer->getConstrainer();
  32172. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32173. removeFromDesktop();
  32174. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32175. }
  32176. if (parentComponent_ != 0)
  32177. parentComponent_->removeChildComponent (this);
  32178. if (safePointer != 0)
  32179. {
  32180. flags.hasHeavyweightPeerFlag = true;
  32181. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32182. Desktop::getInstance().addDesktopComponent (this);
  32183. bounds_.setPosition (topLeft);
  32184. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32185. peer->setVisible (isVisible());
  32186. if (wasFullscreen)
  32187. {
  32188. peer->setFullScreen (true);
  32189. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32190. }
  32191. if (wasMinimised)
  32192. peer->setMinimised (true);
  32193. if (isAlwaysOnTop())
  32194. peer->setAlwaysOnTop (true);
  32195. peer->setConstrainer (currentConstainer);
  32196. repaint();
  32197. }
  32198. internalHierarchyChanged();
  32199. }
  32200. }
  32201. void Component::removeFromDesktop()
  32202. {
  32203. // if component methods are being called from threads other than the message
  32204. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32205. checkMessageManagerIsLocked
  32206. if (flags.hasHeavyweightPeerFlag)
  32207. {
  32208. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32209. flags.hasHeavyweightPeerFlag = false;
  32210. jassert (peer != 0);
  32211. delete peer;
  32212. Desktop::getInstance().removeDesktopComponent (this);
  32213. }
  32214. }
  32215. bool Component::isOnDesktop() const throw()
  32216. {
  32217. return flags.hasHeavyweightPeerFlag;
  32218. }
  32219. void Component::userTriedToCloseWindow()
  32220. {
  32221. /* This means that the user's trying to get rid of your window with the 'close window' system
  32222. menu option (on windows) or possibly the task manager - you should really handle this
  32223. and delete or hide your component in an appropriate way.
  32224. If you want to ignore the event and don't want to trigger this assertion, just override
  32225. this method and do nothing.
  32226. */
  32227. jassertfalse;
  32228. }
  32229. void Component::minimisationStateChanged (bool)
  32230. {
  32231. }
  32232. void Component::setOpaque (const bool shouldBeOpaque)
  32233. {
  32234. if (shouldBeOpaque != flags.opaqueFlag)
  32235. {
  32236. flags.opaqueFlag = shouldBeOpaque;
  32237. if (flags.hasHeavyweightPeerFlag)
  32238. {
  32239. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32240. if (peer != 0)
  32241. {
  32242. // to make it recreate the heavyweight window
  32243. addToDesktop (peer->getStyleFlags());
  32244. }
  32245. }
  32246. repaint();
  32247. }
  32248. }
  32249. bool Component::isOpaque() const throw()
  32250. {
  32251. return flags.opaqueFlag;
  32252. }
  32253. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32254. {
  32255. if (shouldBeBuffered != flags.bufferToImageFlag)
  32256. {
  32257. bufferedImage_ = Image::null;
  32258. flags.bufferToImageFlag = shouldBeBuffered;
  32259. }
  32260. }
  32261. void Component::toFront (const bool setAsForeground)
  32262. {
  32263. // if component methods are being called from threads other than the message
  32264. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32265. checkMessageManagerIsLocked
  32266. if (flags.hasHeavyweightPeerFlag)
  32267. {
  32268. ComponentPeer* const peer = getPeer();
  32269. if (peer != 0)
  32270. {
  32271. peer->toFront (setAsForeground);
  32272. if (setAsForeground && ! hasKeyboardFocus (true))
  32273. grabKeyboardFocus();
  32274. }
  32275. }
  32276. else if (parentComponent_ != 0)
  32277. {
  32278. Array<Component*>& childList = parentComponent_->childComponentList_;
  32279. if (childList.getLast() != this)
  32280. {
  32281. const int index = childList.indexOf (this);
  32282. if (index >= 0)
  32283. {
  32284. int insertIndex = -1;
  32285. if (! flags.alwaysOnTopFlag)
  32286. {
  32287. insertIndex = childList.size() - 1;
  32288. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32289. --insertIndex;
  32290. }
  32291. if (index != insertIndex)
  32292. {
  32293. childList.move (index, insertIndex);
  32294. sendFakeMouseMove();
  32295. repaintParent();
  32296. }
  32297. }
  32298. }
  32299. if (setAsForeground)
  32300. {
  32301. internalBroughtToFront();
  32302. grabKeyboardFocus();
  32303. }
  32304. }
  32305. }
  32306. void Component::toBehind (Component* const other)
  32307. {
  32308. if (other != 0 && other != this)
  32309. {
  32310. // the two components must belong to the same parent..
  32311. jassert (parentComponent_ == other->parentComponent_);
  32312. if (parentComponent_ != 0)
  32313. {
  32314. Array<Component*>& childList = parentComponent_->childComponentList_;
  32315. const int index = childList.indexOf (this);
  32316. if (index >= 0 && childList [index + 1] != other)
  32317. {
  32318. int otherIndex = childList.indexOf (other);
  32319. if (otherIndex >= 0)
  32320. {
  32321. if (index < otherIndex)
  32322. --otherIndex;
  32323. childList.move (index, otherIndex);
  32324. sendFakeMouseMove();
  32325. repaintParent();
  32326. }
  32327. }
  32328. }
  32329. else if (isOnDesktop())
  32330. {
  32331. jassert (other->isOnDesktop());
  32332. if (other->isOnDesktop())
  32333. {
  32334. ComponentPeer* const us = getPeer();
  32335. ComponentPeer* const them = other->getPeer();
  32336. jassert (us != 0 && them != 0);
  32337. if (us != 0 && them != 0)
  32338. us->toBehind (them);
  32339. }
  32340. }
  32341. }
  32342. }
  32343. void Component::toBack()
  32344. {
  32345. Array<Component*>& childList = parentComponent_->childComponentList_;
  32346. if (isOnDesktop())
  32347. {
  32348. jassertfalse; //xxx need to add this to native window
  32349. }
  32350. else if (parentComponent_ != 0 && childList.getFirst() != this)
  32351. {
  32352. const int index = childList.indexOf (this);
  32353. if (index > 0)
  32354. {
  32355. int insertIndex = 0;
  32356. if (flags.alwaysOnTopFlag)
  32357. {
  32358. while (insertIndex < childList.size()
  32359. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32360. {
  32361. ++insertIndex;
  32362. }
  32363. }
  32364. if (index != insertIndex)
  32365. {
  32366. childList.move (index, insertIndex);
  32367. sendFakeMouseMove();
  32368. repaintParent();
  32369. }
  32370. }
  32371. }
  32372. }
  32373. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32374. {
  32375. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32376. {
  32377. flags.alwaysOnTopFlag = shouldStayOnTop;
  32378. if (isOnDesktop())
  32379. {
  32380. ComponentPeer* const peer = getPeer();
  32381. jassert (peer != 0);
  32382. if (peer != 0)
  32383. {
  32384. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32385. {
  32386. // some kinds of peer can't change their always-on-top status, so
  32387. // for these, we'll need to create a new window
  32388. const int oldFlags = peer->getStyleFlags();
  32389. removeFromDesktop();
  32390. addToDesktop (oldFlags);
  32391. }
  32392. }
  32393. }
  32394. if (shouldStayOnTop)
  32395. toFront (false);
  32396. internalHierarchyChanged();
  32397. }
  32398. }
  32399. bool Component::isAlwaysOnTop() const throw()
  32400. {
  32401. return flags.alwaysOnTopFlag;
  32402. }
  32403. int Component::proportionOfWidth (const float proportion) const throw()
  32404. {
  32405. return roundToInt (proportion * bounds_.getWidth());
  32406. }
  32407. int Component::proportionOfHeight (const float proportion) const throw()
  32408. {
  32409. return roundToInt (proportion * bounds_.getHeight());
  32410. }
  32411. int Component::getParentWidth() const throw()
  32412. {
  32413. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  32414. : getParentMonitorArea().getWidth();
  32415. }
  32416. int Component::getParentHeight() const throw()
  32417. {
  32418. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  32419. : getParentMonitorArea().getHeight();
  32420. }
  32421. int Component::getScreenX() const
  32422. {
  32423. return getScreenPosition().getX();
  32424. }
  32425. int Component::getScreenY() const
  32426. {
  32427. return getScreenPosition().getY();
  32428. }
  32429. const Point<int> Component::getScreenPosition() const
  32430. {
  32431. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  32432. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  32433. : getPosition());
  32434. }
  32435. const Rectangle<int> Component::getScreenBounds() const
  32436. {
  32437. return bounds_.withPosition (getScreenPosition());
  32438. }
  32439. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32440. {
  32441. const Component* c = this;
  32442. Point<int> p (relativePosition);
  32443. do
  32444. {
  32445. if (c->flags.hasHeavyweightPeerFlag)
  32446. return c->getPeer()->relativePositionToGlobal (p);
  32447. p += c->getPosition();
  32448. c = c->parentComponent_;
  32449. }
  32450. while (c != 0);
  32451. return p;
  32452. }
  32453. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32454. {
  32455. if (flags.hasHeavyweightPeerFlag)
  32456. {
  32457. return getPeer()->globalPositionToRelative (screenPosition);
  32458. }
  32459. else
  32460. {
  32461. if (parentComponent_ != 0)
  32462. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  32463. return screenPosition - getPosition();
  32464. }
  32465. }
  32466. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32467. {
  32468. Point<int> p (positionRelativeToThis);
  32469. if (targetComponent != 0)
  32470. {
  32471. const Component* c = this;
  32472. do
  32473. {
  32474. if (c == targetComponent)
  32475. return p;
  32476. if (c->flags.hasHeavyweightPeerFlag)
  32477. {
  32478. p = c->getPeer()->relativePositionToGlobal (p);
  32479. break;
  32480. }
  32481. p += c->getPosition();
  32482. c = c->parentComponent_;
  32483. }
  32484. while (c != 0);
  32485. p = targetComponent->globalPositionToRelative (p);
  32486. }
  32487. return p;
  32488. }
  32489. void Component::setBounds (const int x, const int y, int w, int h)
  32490. {
  32491. // if component methods are being called from threads other than the message
  32492. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32493. checkMessageManagerIsLocked
  32494. if (w < 0) w = 0;
  32495. if (h < 0) h = 0;
  32496. const bool wasResized = (getWidth() != w || getHeight() != h);
  32497. const bool wasMoved = (getX() != x || getY() != y);
  32498. #if JUCE_DEBUG
  32499. // It's a very bad idea to try to resize a window during its paint() method!
  32500. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32501. #endif
  32502. if (wasMoved || wasResized)
  32503. {
  32504. if (flags.visibleFlag)
  32505. {
  32506. // send a fake mouse move to trigger enter/exit messages if needed..
  32507. sendFakeMouseMove();
  32508. if (! flags.hasHeavyweightPeerFlag)
  32509. repaintParent();
  32510. }
  32511. bounds_.setBounds (x, y, w, h);
  32512. if (wasResized)
  32513. repaint();
  32514. else if (! flags.hasHeavyweightPeerFlag)
  32515. repaintParent();
  32516. if (flags.hasHeavyweightPeerFlag)
  32517. {
  32518. ComponentPeer* const peer = getPeer();
  32519. if (peer != 0)
  32520. {
  32521. if (wasMoved && wasResized)
  32522. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32523. else if (wasMoved)
  32524. peer->setPosition (getX(), getY());
  32525. else if (wasResized)
  32526. peer->setSize (getWidth(), getHeight());
  32527. }
  32528. }
  32529. sendMovedResizedMessages (wasMoved, wasResized);
  32530. }
  32531. }
  32532. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32533. {
  32534. JUCE_TRY
  32535. {
  32536. if (wasMoved)
  32537. moved();
  32538. if (wasResized)
  32539. {
  32540. resized();
  32541. for (int i = childComponentList_.size(); --i >= 0;)
  32542. {
  32543. childComponentList_.getUnchecked(i)->parentSizeChanged();
  32544. i = jmin (i, childComponentList_.size());
  32545. }
  32546. }
  32547. BailOutChecker checker (this);
  32548. if (parentComponent_ != 0)
  32549. parentComponent_->childBoundsChanged (this);
  32550. if (! checker.shouldBailOut())
  32551. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32552. *this, wasMoved, wasResized);
  32553. }
  32554. JUCE_CATCH_EXCEPTION
  32555. }
  32556. void Component::setSize (const int w, const int h)
  32557. {
  32558. setBounds (getX(), getY(), w, h);
  32559. }
  32560. void Component::setTopLeftPosition (const int x, const int y)
  32561. {
  32562. setBounds (x, y, getWidth(), getHeight());
  32563. }
  32564. void Component::setTopRightPosition (const int x, const int y)
  32565. {
  32566. setTopLeftPosition (x - getWidth(), y);
  32567. }
  32568. void Component::setBounds (const Rectangle<int>& r)
  32569. {
  32570. setBounds (r.getX(),
  32571. r.getY(),
  32572. r.getWidth(),
  32573. r.getHeight());
  32574. }
  32575. void Component::setBoundsRelative (const float x, const float y,
  32576. const float w, const float h)
  32577. {
  32578. const int pw = getParentWidth();
  32579. const int ph = getParentHeight();
  32580. setBounds (roundToInt (x * pw),
  32581. roundToInt (y * ph),
  32582. roundToInt (w * pw),
  32583. roundToInt (h * ph));
  32584. }
  32585. void Component::setCentrePosition (const int x, const int y)
  32586. {
  32587. setTopLeftPosition (x - getWidth() / 2,
  32588. y - getHeight() / 2);
  32589. }
  32590. void Component::setCentreRelative (const float x, const float y)
  32591. {
  32592. setCentrePosition (roundToInt (getParentWidth() * x),
  32593. roundToInt (getParentHeight() * y));
  32594. }
  32595. void Component::centreWithSize (const int width, const int height)
  32596. {
  32597. const Rectangle<int> parentArea (getParentOrMainMonitorBounds());
  32598. setBounds (parentArea.getCentreX() - width / 2,
  32599. parentArea.getCentreY() - height / 2,
  32600. width, height);
  32601. }
  32602. void Component::setBoundsInset (const BorderSize& borders)
  32603. {
  32604. setBounds (borders.subtractedFrom (getParentOrMainMonitorBounds()));
  32605. }
  32606. void Component::setBoundsToFit (int x, int y, int width, int height,
  32607. const Justification& justification,
  32608. const bool onlyReduceInSize)
  32609. {
  32610. // it's no good calling this method unless both the component and
  32611. // target rectangle have a finite size.
  32612. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32613. if (getWidth() > 0 && getHeight() > 0
  32614. && width > 0 && height > 0)
  32615. {
  32616. int newW, newH;
  32617. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32618. {
  32619. newW = getWidth();
  32620. newH = getHeight();
  32621. }
  32622. else
  32623. {
  32624. const double imageRatio = getHeight() / (double) getWidth();
  32625. const double targetRatio = height / (double) width;
  32626. if (imageRatio <= targetRatio)
  32627. {
  32628. newW = width;
  32629. newH = jmin (height, roundToInt (newW * imageRatio));
  32630. }
  32631. else
  32632. {
  32633. newH = height;
  32634. newW = jmin (width, roundToInt (newH / imageRatio));
  32635. }
  32636. }
  32637. if (newW > 0 && newH > 0)
  32638. {
  32639. int newX, newY;
  32640. justification.applyToRectangle (newX, newY, newW, newH,
  32641. x, y, width, height);
  32642. setBounds (newX, newY, newW, newH);
  32643. }
  32644. }
  32645. }
  32646. bool Component::hitTest (int x, int y)
  32647. {
  32648. if (! flags.ignoresMouseClicksFlag)
  32649. return true;
  32650. if (flags.allowChildMouseClicksFlag)
  32651. {
  32652. for (int i = getNumChildComponents(); --i >= 0;)
  32653. {
  32654. Component* const c = getChildComponent (i);
  32655. if (c->isVisible()
  32656. && c->bounds_.contains (x, y)
  32657. && c->hitTest (x - c->getX(),
  32658. y - c->getY()))
  32659. {
  32660. return true;
  32661. }
  32662. }
  32663. }
  32664. return false;
  32665. }
  32666. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32667. const bool allowClicksOnChildComponents) throw()
  32668. {
  32669. flags.ignoresMouseClicksFlag = ! allowClicks;
  32670. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32671. }
  32672. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32673. bool& allowsClicksOnChildComponents) const throw()
  32674. {
  32675. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32676. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32677. }
  32678. bool Component::contains (const int x, const int y)
  32679. {
  32680. if (((unsigned int) x) < (unsigned int) getWidth()
  32681. && ((unsigned int) y) < (unsigned int) getHeight()
  32682. && hitTest (x, y))
  32683. {
  32684. if (parentComponent_ != 0)
  32685. {
  32686. return parentComponent_->contains (x + getX(),
  32687. y + getY());
  32688. }
  32689. else if (flags.hasHeavyweightPeerFlag)
  32690. {
  32691. const ComponentPeer* const peer = getPeer();
  32692. if (peer != 0)
  32693. return peer->contains (Point<int> (x, y), true);
  32694. }
  32695. }
  32696. return false;
  32697. }
  32698. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  32699. {
  32700. if (! contains (x, y))
  32701. return false;
  32702. Component* p = this;
  32703. while (p->parentComponent_ != 0)
  32704. {
  32705. x += p->getX();
  32706. y += p->getY();
  32707. p = p->parentComponent_;
  32708. }
  32709. const Component* const c = p->getComponentAt (x, y);
  32710. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  32711. }
  32712. Component* Component::getComponentAt (const Point<int>& position)
  32713. {
  32714. return getComponentAt (position.getX(), position.getY());
  32715. }
  32716. Component* Component::getComponentAt (const int x, const int y)
  32717. {
  32718. if (flags.visibleFlag
  32719. && ((unsigned int) x) < (unsigned int) getWidth()
  32720. && ((unsigned int) y) < (unsigned int) getHeight()
  32721. && hitTest (x, y))
  32722. {
  32723. for (int i = childComponentList_.size(); --i >= 0;)
  32724. {
  32725. Component* const child = childComponentList_.getUnchecked(i);
  32726. Component* const c = child->getComponentAt (x - child->getX(),
  32727. y - child->getY());
  32728. if (c != 0)
  32729. return c;
  32730. }
  32731. return this;
  32732. }
  32733. return 0;
  32734. }
  32735. void Component::addChildComponent (Component* const child, int zOrder)
  32736. {
  32737. // if component methods are being called from threads other than the message
  32738. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32739. checkMessageManagerIsLocked
  32740. if (child != 0 && child->parentComponent_ != this)
  32741. {
  32742. if (child->parentComponent_ != 0)
  32743. child->parentComponent_->removeChildComponent (child);
  32744. else
  32745. child->removeFromDesktop();
  32746. child->parentComponent_ = this;
  32747. if (child->isVisible())
  32748. child->repaintParent();
  32749. if (! child->isAlwaysOnTop())
  32750. {
  32751. if (zOrder < 0 || zOrder > childComponentList_.size())
  32752. zOrder = childComponentList_.size();
  32753. while (zOrder > 0)
  32754. {
  32755. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32756. break;
  32757. --zOrder;
  32758. }
  32759. }
  32760. childComponentList_.insert (zOrder, child);
  32761. child->internalHierarchyChanged();
  32762. internalChildrenChanged();
  32763. }
  32764. }
  32765. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32766. {
  32767. if (child != 0)
  32768. {
  32769. child->setVisible (true);
  32770. addChildComponent (child, zOrder);
  32771. }
  32772. }
  32773. void Component::removeChildComponent (Component* const child)
  32774. {
  32775. removeChildComponent (childComponentList_.indexOf (child));
  32776. }
  32777. Component* Component::removeChildComponent (const int index)
  32778. {
  32779. // if component methods are being called from threads other than the message
  32780. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32781. checkMessageManagerIsLocked
  32782. Component* const child = childComponentList_ [index];
  32783. if (child != 0)
  32784. {
  32785. sendFakeMouseMove();
  32786. child->repaintParent();
  32787. childComponentList_.remove (index);
  32788. child->parentComponent_ = 0;
  32789. JUCE_TRY
  32790. {
  32791. if ((currentlyFocusedComponent == child)
  32792. || child->isParentOf (currentlyFocusedComponent))
  32793. {
  32794. // get rid first to force the grabKeyboardFocus to change to us.
  32795. giveAwayFocus();
  32796. grabKeyboardFocus();
  32797. }
  32798. }
  32799. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32800. catch (const std::exception& e)
  32801. {
  32802. currentlyFocusedComponent = 0;
  32803. Desktop::getInstance().triggerFocusCallback();
  32804. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32805. }
  32806. catch (...)
  32807. {
  32808. currentlyFocusedComponent = 0;
  32809. Desktop::getInstance().triggerFocusCallback();
  32810. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32811. }
  32812. #endif
  32813. child->internalHierarchyChanged();
  32814. internalChildrenChanged();
  32815. }
  32816. return child;
  32817. }
  32818. void Component::removeAllChildren()
  32819. {
  32820. while (childComponentList_.size() > 0)
  32821. removeChildComponent (childComponentList_.size() - 1);
  32822. }
  32823. void Component::deleteAllChildren()
  32824. {
  32825. while (childComponentList_.size() > 0)
  32826. delete (removeChildComponent (childComponentList_.size() - 1));
  32827. }
  32828. int Component::getNumChildComponents() const throw()
  32829. {
  32830. return childComponentList_.size();
  32831. }
  32832. Component* Component::getChildComponent (const int index) const throw()
  32833. {
  32834. return childComponentList_ [index];
  32835. }
  32836. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32837. {
  32838. return childComponentList_.indexOf (const_cast <Component*> (child));
  32839. }
  32840. Component* Component::getTopLevelComponent() const throw()
  32841. {
  32842. const Component* comp = this;
  32843. while (comp->parentComponent_ != 0)
  32844. comp = comp->parentComponent_;
  32845. return const_cast <Component*> (comp);
  32846. }
  32847. bool Component::isParentOf (const Component* possibleChild) const throw()
  32848. {
  32849. if (! possibleChild->isValidComponent())
  32850. {
  32851. jassert (possibleChild == 0);
  32852. return false;
  32853. }
  32854. while (possibleChild != 0)
  32855. {
  32856. possibleChild = possibleChild->parentComponent_;
  32857. if (possibleChild == this)
  32858. return true;
  32859. }
  32860. return false;
  32861. }
  32862. void Component::parentHierarchyChanged()
  32863. {
  32864. }
  32865. void Component::childrenChanged()
  32866. {
  32867. }
  32868. void Component::internalChildrenChanged()
  32869. {
  32870. if (componentListeners.isEmpty())
  32871. {
  32872. childrenChanged();
  32873. }
  32874. else
  32875. {
  32876. BailOutChecker checker (this);
  32877. childrenChanged();
  32878. if (! checker.shouldBailOut())
  32879. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32880. }
  32881. }
  32882. void Component::internalHierarchyChanged()
  32883. {
  32884. BailOutChecker checker (this);
  32885. parentHierarchyChanged();
  32886. if (checker.shouldBailOut())
  32887. return;
  32888. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32889. if (checker.shouldBailOut())
  32890. return;
  32891. for (int i = childComponentList_.size(); --i >= 0;)
  32892. {
  32893. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32894. if (checker.shouldBailOut())
  32895. {
  32896. // you really shouldn't delete the parent component during a callback telling you
  32897. // that it's changed..
  32898. jassertfalse;
  32899. return;
  32900. }
  32901. i = jmin (i, childComponentList_.size());
  32902. }
  32903. }
  32904. void* Component::runModalLoopCallback (void* userData)
  32905. {
  32906. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32907. }
  32908. int Component::runModalLoop()
  32909. {
  32910. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32911. {
  32912. // use a callback so this can be called from non-gui threads
  32913. return (int) (pointer_sized_int) MessageManager::getInstance()
  32914. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32915. }
  32916. if (! isCurrentlyModal())
  32917. enterModalState (true);
  32918. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32919. }
  32920. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  32921. {
  32922. // if component methods are being called from threads other than the message
  32923. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32924. checkMessageManagerIsLocked
  32925. // Check for an attempt to make a component modal when it already is!
  32926. // This can cause nasty problems..
  32927. jassert (! flags.currentlyModalFlag);
  32928. if (! isCurrentlyModal())
  32929. {
  32930. ModalComponentManager::getInstance()->startModal (this, callback);
  32931. flags.currentlyModalFlag = true;
  32932. setVisible (true);
  32933. if (takeKeyboardFocus_)
  32934. grabKeyboardFocus();
  32935. }
  32936. }
  32937. void Component::exitModalState (const int returnValue)
  32938. {
  32939. if (isCurrentlyModal())
  32940. {
  32941. if (MessageManager::getInstance()->isThisTheMessageThread())
  32942. {
  32943. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32944. flags.currentlyModalFlag = false;
  32945. bringModalComponentToFront();
  32946. }
  32947. else
  32948. {
  32949. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32950. }
  32951. }
  32952. }
  32953. bool Component::isCurrentlyModal() const throw()
  32954. {
  32955. return flags.currentlyModalFlag
  32956. && getCurrentlyModalComponent() == this;
  32957. }
  32958. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32959. {
  32960. Component* const mc = getCurrentlyModalComponent();
  32961. return mc != 0
  32962. && mc != this
  32963. && (! mc->isParentOf (this))
  32964. && ! mc->canModalEventBeSentToComponent (this);
  32965. }
  32966. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32967. {
  32968. return ModalComponentManager::getInstance()->getNumModalComponents();
  32969. }
  32970. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32971. {
  32972. return ModalComponentManager::getInstance()->getModalComponent (index);
  32973. }
  32974. void Component::bringModalComponentToFront()
  32975. {
  32976. ComponentPeer* lastOne = 0;
  32977. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32978. {
  32979. Component* const c = getCurrentlyModalComponent (i);
  32980. if (c == 0)
  32981. break;
  32982. ComponentPeer* peer = c->getPeer();
  32983. if (peer != 0 && peer != lastOne)
  32984. {
  32985. if (lastOne == 0)
  32986. {
  32987. peer->toFront (true);
  32988. peer->grabFocus();
  32989. }
  32990. else
  32991. peer->toBehind (lastOne);
  32992. lastOne = peer;
  32993. }
  32994. }
  32995. }
  32996. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32997. {
  32998. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32999. }
  33000. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33001. {
  33002. return flags.bringToFrontOnClickFlag;
  33003. }
  33004. void Component::setMouseCursor (const MouseCursor& cursor)
  33005. {
  33006. if (cursor_ != cursor)
  33007. {
  33008. cursor_ = cursor;
  33009. if (flags.visibleFlag)
  33010. updateMouseCursor();
  33011. }
  33012. }
  33013. const MouseCursor Component::getMouseCursor()
  33014. {
  33015. return cursor_;
  33016. }
  33017. void Component::updateMouseCursor() const
  33018. {
  33019. sendFakeMouseMove();
  33020. }
  33021. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33022. {
  33023. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33024. }
  33025. void Component::repaintParent()
  33026. {
  33027. if (flags.visibleFlag)
  33028. internalRepaint (0, 0, getWidth(), getHeight());
  33029. }
  33030. void Component::repaint()
  33031. {
  33032. repaint (0, 0, getWidth(), getHeight());
  33033. }
  33034. void Component::repaint (const int x, const int y,
  33035. const int w, const int h)
  33036. {
  33037. bufferedImage_ = Image::null;
  33038. if (flags.visibleFlag)
  33039. internalRepaint (x, y, w, h);
  33040. }
  33041. void Component::repaint (const Rectangle<int>& area)
  33042. {
  33043. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33044. }
  33045. void Component::internalRepaint (int x, int y, int w, int h)
  33046. {
  33047. // if component methods are being called from threads other than the message
  33048. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33049. checkMessageManagerIsLocked
  33050. if (x < 0)
  33051. {
  33052. w += x;
  33053. x = 0;
  33054. }
  33055. if (x + w > getWidth())
  33056. w = getWidth() - x;
  33057. if (w > 0)
  33058. {
  33059. if (y < 0)
  33060. {
  33061. h += y;
  33062. y = 0;
  33063. }
  33064. if (y + h > getHeight())
  33065. h = getHeight() - y;
  33066. if (h > 0)
  33067. {
  33068. if (parentComponent_ != 0)
  33069. {
  33070. x += getX();
  33071. y += getY();
  33072. if (parentComponent_->flags.visibleFlag)
  33073. parentComponent_->internalRepaint (x, y, w, h);
  33074. }
  33075. else if (flags.hasHeavyweightPeerFlag)
  33076. {
  33077. ComponentPeer* const peer = getPeer();
  33078. if (peer != 0)
  33079. peer->repaint (Rectangle<int> (x, y, w, h));
  33080. }
  33081. }
  33082. }
  33083. }
  33084. void Component::renderComponent (Graphics& g)
  33085. {
  33086. const Rectangle<int> clipBounds (g.getClipBounds());
  33087. g.saveState();
  33088. clipObscuredRegions (g, clipBounds, 0, 0);
  33089. if (! g.isClipEmpty())
  33090. {
  33091. if (flags.bufferToImageFlag)
  33092. {
  33093. if (bufferedImage_.isNull())
  33094. {
  33095. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33096. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33097. Graphics imG (bufferedImage_);
  33098. paint (imG);
  33099. }
  33100. g.setColour (Colours::black);
  33101. g.drawImageAt (bufferedImage_, 0, 0);
  33102. }
  33103. else
  33104. {
  33105. paint (g);
  33106. }
  33107. }
  33108. g.restoreState();
  33109. for (int i = 0; i < childComponentList_.size(); ++i)
  33110. {
  33111. Component* const child = childComponentList_.getUnchecked (i);
  33112. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  33113. {
  33114. g.saveState();
  33115. if (g.reduceClipRegion (child->getX(), child->getY(),
  33116. child->getWidth(), child->getHeight()))
  33117. {
  33118. for (int j = i + 1; j < childComponentList_.size(); ++j)
  33119. {
  33120. const Component* const sibling = childComponentList_.getUnchecked (j);
  33121. if (sibling->flags.opaqueFlag && sibling->isVisible())
  33122. g.excludeClipRegion (sibling->getBounds());
  33123. }
  33124. if (! g.isClipEmpty())
  33125. {
  33126. g.setOrigin (child->getX(), child->getY());
  33127. child->paintEntireComponent (g);
  33128. }
  33129. }
  33130. g.restoreState();
  33131. }
  33132. }
  33133. g.saveState();
  33134. paintOverChildren (g);
  33135. g.restoreState();
  33136. }
  33137. void Component::paintEntireComponent (Graphics& g)
  33138. {
  33139. jassert (! g.isClipEmpty());
  33140. #if JUCE_DEBUG
  33141. flags.isInsidePaintCall = true;
  33142. #endif
  33143. if (effect_ != 0)
  33144. {
  33145. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33146. getWidth(), getHeight(),
  33147. ! flags.opaqueFlag, Image::NativeImage);
  33148. {
  33149. Graphics g2 (effectImage);
  33150. renderComponent (g2);
  33151. }
  33152. effect_->applyEffect (effectImage, g);
  33153. }
  33154. else
  33155. {
  33156. renderComponent (g);
  33157. }
  33158. #if JUCE_DEBUG
  33159. flags.isInsidePaintCall = false;
  33160. #endif
  33161. }
  33162. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33163. const bool clipImageToComponentBounds)
  33164. {
  33165. Rectangle<int> r (areaToGrab);
  33166. if (clipImageToComponentBounds)
  33167. r = r.getIntersection (getLocalBounds());
  33168. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33169. jmax (1, r.getWidth()),
  33170. jmax (1, r.getHeight()),
  33171. true);
  33172. Graphics imageContext (componentImage);
  33173. imageContext.setOrigin (-r.getX(), -r.getY());
  33174. paintEntireComponent (imageContext);
  33175. return componentImage;
  33176. }
  33177. void Component::setComponentEffect (ImageEffectFilter* const effect)
  33178. {
  33179. if (effect_ != effect)
  33180. {
  33181. effect_ = effect;
  33182. repaint();
  33183. }
  33184. }
  33185. LookAndFeel& Component::getLookAndFeel() const throw()
  33186. {
  33187. const Component* c = this;
  33188. do
  33189. {
  33190. if (c->lookAndFeel_ != 0)
  33191. return *(c->lookAndFeel_);
  33192. c = c->parentComponent_;
  33193. }
  33194. while (c != 0);
  33195. return LookAndFeel::getDefaultLookAndFeel();
  33196. }
  33197. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33198. {
  33199. if (lookAndFeel_ != newLookAndFeel)
  33200. {
  33201. lookAndFeel_ = newLookAndFeel;
  33202. sendLookAndFeelChange();
  33203. }
  33204. }
  33205. void Component::lookAndFeelChanged()
  33206. {
  33207. }
  33208. void Component::sendLookAndFeelChange()
  33209. {
  33210. repaint();
  33211. lookAndFeelChanged();
  33212. // (it's not a great idea to do anything that would delete this component
  33213. // during the lookAndFeelChanged() callback)
  33214. jassert (isValidComponent());
  33215. SafePointer<Component> safePointer (this);
  33216. for (int i = childComponentList_.size(); --i >= 0;)
  33217. {
  33218. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  33219. if (safePointer == 0)
  33220. return;
  33221. i = jmin (i, childComponentList_.size());
  33222. }
  33223. }
  33224. static const Identifier getColourPropertyId (const int colourId)
  33225. {
  33226. String s;
  33227. s.preallocateStorage (18);
  33228. s << "jcclr_" << String::toHexString (colourId);
  33229. return s;
  33230. }
  33231. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33232. {
  33233. var* v = properties.getItem (getColourPropertyId (colourId));
  33234. if (v != 0)
  33235. return Colour ((int) *v);
  33236. if (inheritFromParent && parentComponent_ != 0)
  33237. return parentComponent_->findColour (colourId, true);
  33238. return getLookAndFeel().findColour (colourId);
  33239. }
  33240. bool Component::isColourSpecified (const int colourId) const
  33241. {
  33242. return properties.contains (getColourPropertyId (colourId));
  33243. }
  33244. void Component::removeColour (const int colourId)
  33245. {
  33246. if (properties.remove (getColourPropertyId (colourId)))
  33247. colourChanged();
  33248. }
  33249. void Component::setColour (const int colourId, const Colour& colour)
  33250. {
  33251. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  33252. colourChanged();
  33253. }
  33254. void Component::copyAllExplicitColoursTo (Component& target) const
  33255. {
  33256. bool changed = false;
  33257. for (int i = properties.size(); --i >= 0;)
  33258. {
  33259. const Identifier name (properties.getName(i));
  33260. if (name.toString().startsWith ("jcclr_"))
  33261. if (target.properties.set (name, properties [name]))
  33262. changed = true;
  33263. }
  33264. if (changed)
  33265. target.colourChanged();
  33266. }
  33267. void Component::colourChanged()
  33268. {
  33269. }
  33270. const Rectangle<int> Component::getLocalBounds() const throw()
  33271. {
  33272. return Rectangle<int> (getWidth(), getHeight());
  33273. }
  33274. const Rectangle<int> Component::getParentOrMainMonitorBounds() const
  33275. {
  33276. return parentComponent_ != 0 ? parentComponent_->getLocalBounds()
  33277. : Desktop::getInstance().getMainMonitorArea();
  33278. }
  33279. const Rectangle<int> Component::getUnclippedArea() const
  33280. {
  33281. int x = 0, y = 0, w = getWidth(), h = getHeight();
  33282. Component* p = parentComponent_;
  33283. int px = getX();
  33284. int py = getY();
  33285. while (p != 0)
  33286. {
  33287. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  33288. return Rectangle<int>();
  33289. px += p->getX();
  33290. py += p->getY();
  33291. p = p->parentComponent_;
  33292. }
  33293. return Rectangle<int> (x, y, w, h);
  33294. }
  33295. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  33296. const int deltaX, const int deltaY) const
  33297. {
  33298. for (int i = childComponentList_.size(); --i >= 0;)
  33299. {
  33300. const Component* const c = childComponentList_.getUnchecked(i);
  33301. if (c->isVisible())
  33302. {
  33303. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33304. if (! newClip.isEmpty())
  33305. {
  33306. if (c->isOpaque())
  33307. {
  33308. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  33309. }
  33310. else
  33311. {
  33312. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  33313. c->getX() + deltaX,
  33314. c->getY() + deltaY);
  33315. }
  33316. }
  33317. }
  33318. }
  33319. }
  33320. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33321. {
  33322. result.clear();
  33323. const Rectangle<int> unclipped (getUnclippedArea());
  33324. if (! unclipped.isEmpty())
  33325. {
  33326. result.add (unclipped);
  33327. if (includeSiblings)
  33328. {
  33329. const Component* const c = getTopLevelComponent();
  33330. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  33331. c->getLocalBounds(), this);
  33332. }
  33333. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  33334. result.consolidate();
  33335. }
  33336. }
  33337. void Component::subtractObscuredRegions (RectangleList& result,
  33338. const Point<int>& delta,
  33339. const Rectangle<int>& clipRect,
  33340. const Component* const compToAvoid) const
  33341. {
  33342. for (int i = childComponentList_.size(); --i >= 0;)
  33343. {
  33344. const Component* const c = childComponentList_.getUnchecked(i);
  33345. if (c != compToAvoid && c->isVisible())
  33346. {
  33347. if (c->isOpaque())
  33348. {
  33349. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  33350. childBounds.translate (delta.getX(), delta.getY());
  33351. result.subtract (childBounds);
  33352. }
  33353. else
  33354. {
  33355. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33356. newClip.translate (-c->getX(), -c->getY());
  33357. c->subtractObscuredRegions (result, c->getPosition() + delta,
  33358. newClip, compToAvoid);
  33359. }
  33360. }
  33361. }
  33362. }
  33363. void Component::mouseEnter (const MouseEvent&)
  33364. {
  33365. // base class does nothing
  33366. }
  33367. void Component::mouseExit (const MouseEvent&)
  33368. {
  33369. // base class does nothing
  33370. }
  33371. void Component::mouseDown (const MouseEvent&)
  33372. {
  33373. // base class does nothing
  33374. }
  33375. void Component::mouseUp (const MouseEvent&)
  33376. {
  33377. // base class does nothing
  33378. }
  33379. void Component::mouseDrag (const MouseEvent&)
  33380. {
  33381. // base class does nothing
  33382. }
  33383. void Component::mouseMove (const MouseEvent&)
  33384. {
  33385. // base class does nothing
  33386. }
  33387. void Component::mouseDoubleClick (const MouseEvent&)
  33388. {
  33389. // base class does nothing
  33390. }
  33391. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33392. {
  33393. // the base class just passes this event up to its parent..
  33394. if (parentComponent_ != 0)
  33395. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  33396. wheelIncrementX, wheelIncrementY);
  33397. }
  33398. void Component::resized()
  33399. {
  33400. // base class does nothing
  33401. }
  33402. void Component::moved()
  33403. {
  33404. // base class does nothing
  33405. }
  33406. void Component::childBoundsChanged (Component*)
  33407. {
  33408. // base class does nothing
  33409. }
  33410. void Component::parentSizeChanged()
  33411. {
  33412. // base class does nothing
  33413. }
  33414. void Component::addComponentListener (ComponentListener* const newListener)
  33415. {
  33416. jassert (isValidComponent());
  33417. componentListeners.add (newListener);
  33418. }
  33419. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33420. {
  33421. jassert (isValidComponent());
  33422. componentListeners.remove (listenerToRemove);
  33423. }
  33424. void Component::inputAttemptWhenModal()
  33425. {
  33426. bringModalComponentToFront();
  33427. getLookAndFeel().playAlertSound();
  33428. }
  33429. bool Component::canModalEventBeSentToComponent (const Component*)
  33430. {
  33431. return false;
  33432. }
  33433. void Component::internalModalInputAttempt()
  33434. {
  33435. Component* const current = getCurrentlyModalComponent();
  33436. if (current != 0)
  33437. current->inputAttemptWhenModal();
  33438. }
  33439. void Component::paint (Graphics&)
  33440. {
  33441. // all painting is done in the subclasses
  33442. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33443. }
  33444. void Component::paintOverChildren (Graphics&)
  33445. {
  33446. // all painting is done in the subclasses
  33447. }
  33448. void Component::handleMessage (const Message& message)
  33449. {
  33450. if (message.intParameter1 == exitModalStateMessage)
  33451. {
  33452. exitModalState (message.intParameter2);
  33453. }
  33454. else if (message.intParameter1 == customCommandMessage)
  33455. {
  33456. handleCommandMessage (message.intParameter2);
  33457. }
  33458. }
  33459. void Component::postCommandMessage (const int commandId)
  33460. {
  33461. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  33462. }
  33463. void Component::handleCommandMessage (int)
  33464. {
  33465. // used by subclasses
  33466. }
  33467. void Component::addMouseListener (MouseListener* const newListener,
  33468. const bool wantsEventsForAllNestedChildComponents)
  33469. {
  33470. // if component methods are being called from threads other than the message
  33471. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33472. checkMessageManagerIsLocked
  33473. // If you register a component as a mouselistener for itself, it'll receive all the events
  33474. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33475. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33476. if (mouseListeners_ == 0)
  33477. mouseListeners_ = new Array<MouseListener*>();
  33478. if (! mouseListeners_->contains (newListener))
  33479. {
  33480. if (wantsEventsForAllNestedChildComponents)
  33481. {
  33482. mouseListeners_->insert (0, newListener);
  33483. ++numDeepMouseListeners;
  33484. }
  33485. else
  33486. {
  33487. mouseListeners_->add (newListener);
  33488. }
  33489. }
  33490. }
  33491. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33492. {
  33493. // if component methods are being called from threads other than the message
  33494. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33495. checkMessageManagerIsLocked
  33496. if (mouseListeners_ != 0)
  33497. {
  33498. const int index = mouseListeners_->indexOf (listenerToRemove);
  33499. if (index >= 0)
  33500. {
  33501. if (index < numDeepMouseListeners)
  33502. --numDeepMouseListeners;
  33503. mouseListeners_->remove (index);
  33504. }
  33505. }
  33506. }
  33507. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33508. {
  33509. if (isCurrentlyBlockedByAnotherModalComponent())
  33510. {
  33511. // if something else is modal, always just show a normal mouse cursor
  33512. source.showMouseCursor (MouseCursor::NormalCursor);
  33513. return;
  33514. }
  33515. if (! flags.mouseInsideFlag)
  33516. {
  33517. flags.mouseInsideFlag = true;
  33518. flags.mouseOverFlag = true;
  33519. flags.draggingFlag = false;
  33520. BailOutChecker checker (this);
  33521. if (flags.repaintOnMouseActivityFlag)
  33522. repaint();
  33523. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33524. this, this, time, relativePos,
  33525. time, 0, false);
  33526. mouseEnter (me);
  33527. if (checker.shouldBailOut())
  33528. return;
  33529. Desktop::getInstance().resetTimer();
  33530. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33531. if (checker.shouldBailOut())
  33532. return;
  33533. if (mouseListeners_ != 0)
  33534. {
  33535. for (int i = mouseListeners_->size(); --i >= 0;)
  33536. {
  33537. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33538. if (checker.shouldBailOut())
  33539. return;
  33540. i = jmin (i, mouseListeners_->size());
  33541. }
  33542. }
  33543. Component* p = parentComponent_;
  33544. while (p != 0)
  33545. {
  33546. if (p->numDeepMouseListeners > 0)
  33547. {
  33548. BailOutChecker checker2 (this, p);
  33549. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33550. {
  33551. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33552. if (checker2.shouldBailOut())
  33553. return;
  33554. i = jmin (i, p->numDeepMouseListeners);
  33555. }
  33556. }
  33557. p = p->parentComponent_;
  33558. }
  33559. }
  33560. }
  33561. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33562. {
  33563. BailOutChecker checker (this);
  33564. if (flags.draggingFlag)
  33565. {
  33566. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33567. if (checker.shouldBailOut())
  33568. return;
  33569. }
  33570. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33571. {
  33572. flags.mouseInsideFlag = false;
  33573. flags.mouseOverFlag = false;
  33574. flags.draggingFlag = false;
  33575. if (flags.repaintOnMouseActivityFlag)
  33576. repaint();
  33577. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33578. this, this, time, relativePos,
  33579. time, 0, false);
  33580. mouseExit (me);
  33581. if (checker.shouldBailOut())
  33582. return;
  33583. Desktop::getInstance().resetTimer();
  33584. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33585. if (checker.shouldBailOut())
  33586. return;
  33587. if (mouseListeners_ != 0)
  33588. {
  33589. for (int i = mouseListeners_->size(); --i >= 0;)
  33590. {
  33591. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  33592. if (checker.shouldBailOut())
  33593. return;
  33594. i = jmin (i, mouseListeners_->size());
  33595. }
  33596. }
  33597. Component* p = parentComponent_;
  33598. while (p != 0)
  33599. {
  33600. if (p->numDeepMouseListeners > 0)
  33601. {
  33602. BailOutChecker checker2 (this, p);
  33603. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33604. {
  33605. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  33606. if (checker2.shouldBailOut())
  33607. return;
  33608. i = jmin (i, p->numDeepMouseListeners);
  33609. }
  33610. }
  33611. p = p->parentComponent_;
  33612. }
  33613. }
  33614. }
  33615. class InternalDragRepeater : public Timer
  33616. {
  33617. public:
  33618. InternalDragRepeater()
  33619. {}
  33620. ~InternalDragRepeater()
  33621. {
  33622. clearSingletonInstance();
  33623. }
  33624. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  33625. void timerCallback()
  33626. {
  33627. Desktop& desktop = Desktop::getInstance();
  33628. int numMiceDown = 0;
  33629. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33630. {
  33631. MouseInputSource* const source = desktop.getMouseSource(i);
  33632. if (source->isDragging())
  33633. {
  33634. source->triggerFakeMove();
  33635. ++numMiceDown;
  33636. }
  33637. }
  33638. if (numMiceDown == 0)
  33639. deleteInstance();
  33640. }
  33641. juce_UseDebuggingNewOperator
  33642. private:
  33643. InternalDragRepeater (const InternalDragRepeater&);
  33644. InternalDragRepeater& operator= (const InternalDragRepeater&);
  33645. };
  33646. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  33647. void Component::beginDragAutoRepeat (const int interval)
  33648. {
  33649. if (interval > 0)
  33650. {
  33651. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  33652. InternalDragRepeater::getInstance()->startTimer (interval);
  33653. }
  33654. else
  33655. {
  33656. InternalDragRepeater::deleteInstance();
  33657. }
  33658. }
  33659. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33660. {
  33661. Desktop& desktop = Desktop::getInstance();
  33662. BailOutChecker checker (this);
  33663. if (isCurrentlyBlockedByAnotherModalComponent())
  33664. {
  33665. internalModalInputAttempt();
  33666. if (checker.shouldBailOut())
  33667. return;
  33668. // If processing the input attempt has exited the modal loop, we'll allow the event
  33669. // to be delivered..
  33670. if (isCurrentlyBlockedByAnotherModalComponent())
  33671. {
  33672. // allow blocked mouse-events to go to global listeners..
  33673. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33674. this, this, time, relativePos, time,
  33675. source.getNumberOfMultipleClicks(), false);
  33676. desktop.resetTimer();
  33677. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33678. return;
  33679. }
  33680. }
  33681. {
  33682. Component* c = this;
  33683. while (c != 0)
  33684. {
  33685. if (c->isBroughtToFrontOnMouseClick())
  33686. {
  33687. c->toFront (true);
  33688. if (checker.shouldBailOut())
  33689. return;
  33690. }
  33691. c = c->parentComponent_;
  33692. }
  33693. }
  33694. if (! flags.dontFocusOnMouseClickFlag)
  33695. {
  33696. grabFocusInternal (focusChangedByMouseClick);
  33697. if (checker.shouldBailOut())
  33698. return;
  33699. }
  33700. flags.draggingFlag = true;
  33701. flags.mouseOverFlag = true;
  33702. if (flags.repaintOnMouseActivityFlag)
  33703. repaint();
  33704. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33705. this, this, time, relativePos, time,
  33706. source.getNumberOfMultipleClicks(), false);
  33707. mouseDown (me);
  33708. if (checker.shouldBailOut())
  33709. return;
  33710. desktop.resetTimer();
  33711. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33712. if (checker.shouldBailOut())
  33713. return;
  33714. if (mouseListeners_ != 0)
  33715. {
  33716. for (int i = mouseListeners_->size(); --i >= 0;)
  33717. {
  33718. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  33719. if (checker.shouldBailOut())
  33720. return;
  33721. i = jmin (i, mouseListeners_->size());
  33722. }
  33723. }
  33724. Component* p = parentComponent_;
  33725. while (p != 0)
  33726. {
  33727. if (p->numDeepMouseListeners > 0)
  33728. {
  33729. BailOutChecker checker2 (this, p);
  33730. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33731. {
  33732. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  33733. if (checker2.shouldBailOut())
  33734. return;
  33735. i = jmin (i, p->numDeepMouseListeners);
  33736. }
  33737. }
  33738. p = p->parentComponent_;
  33739. }
  33740. }
  33741. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33742. {
  33743. if (flags.draggingFlag)
  33744. {
  33745. Desktop& desktop = Desktop::getInstance();
  33746. flags.draggingFlag = false;
  33747. BailOutChecker checker (this);
  33748. if (flags.repaintOnMouseActivityFlag)
  33749. repaint();
  33750. const MouseEvent me (source, relativePos,
  33751. oldModifiers, this, this, time,
  33752. globalPositionToRelative (source.getLastMouseDownPosition()),
  33753. source.getLastMouseDownTime(),
  33754. source.getNumberOfMultipleClicks(),
  33755. source.hasMouseMovedSignificantlySincePressed());
  33756. mouseUp (me);
  33757. if (checker.shouldBailOut())
  33758. return;
  33759. desktop.resetTimer();
  33760. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33761. if (checker.shouldBailOut())
  33762. return;
  33763. if (mouseListeners_ != 0)
  33764. {
  33765. for (int i = mouseListeners_->size(); --i >= 0;)
  33766. {
  33767. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  33768. if (checker.shouldBailOut())
  33769. return;
  33770. i = jmin (i, mouseListeners_->size());
  33771. }
  33772. }
  33773. {
  33774. Component* p = parentComponent_;
  33775. while (p != 0)
  33776. {
  33777. if (p->numDeepMouseListeners > 0)
  33778. {
  33779. BailOutChecker checker2 (this, p);
  33780. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33781. {
  33782. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  33783. if (checker2.shouldBailOut())
  33784. return;
  33785. i = jmin (i, p->numDeepMouseListeners);
  33786. }
  33787. }
  33788. p = p->parentComponent_;
  33789. }
  33790. }
  33791. // check for double-click
  33792. if (me.getNumberOfClicks() >= 2)
  33793. {
  33794. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  33795. mouseDoubleClick (me);
  33796. if (checker.shouldBailOut())
  33797. return;
  33798. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33799. if (checker.shouldBailOut())
  33800. return;
  33801. for (int i = numListeners; --i >= 0;)
  33802. {
  33803. if (checker.shouldBailOut())
  33804. return;
  33805. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  33806. if (ml != 0)
  33807. ml->mouseDoubleClick (me);
  33808. }
  33809. if (checker.shouldBailOut())
  33810. return;
  33811. Component* p = parentComponent_;
  33812. while (p != 0)
  33813. {
  33814. if (p->numDeepMouseListeners > 0)
  33815. {
  33816. BailOutChecker checker2 (this, p);
  33817. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33818. {
  33819. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  33820. if (checker2.shouldBailOut())
  33821. return;
  33822. i = jmin (i, p->numDeepMouseListeners);
  33823. }
  33824. }
  33825. p = p->parentComponent_;
  33826. }
  33827. }
  33828. }
  33829. }
  33830. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33831. {
  33832. if (flags.draggingFlag)
  33833. {
  33834. Desktop& desktop = Desktop::getInstance();
  33835. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33836. BailOutChecker checker (this);
  33837. const MouseEvent me (source, relativePos,
  33838. source.getCurrentModifiers(), this, this, time,
  33839. globalPositionToRelative (source.getLastMouseDownPosition()),
  33840. source.getLastMouseDownTime(),
  33841. source.getNumberOfMultipleClicks(),
  33842. source.hasMouseMovedSignificantlySincePressed());
  33843. mouseDrag (me);
  33844. if (checker.shouldBailOut())
  33845. return;
  33846. desktop.resetTimer();
  33847. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33848. if (checker.shouldBailOut())
  33849. return;
  33850. if (mouseListeners_ != 0)
  33851. {
  33852. for (int i = mouseListeners_->size(); --i >= 0;)
  33853. {
  33854. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33855. if (checker.shouldBailOut())
  33856. return;
  33857. i = jmin (i, mouseListeners_->size());
  33858. }
  33859. }
  33860. Component* p = parentComponent_;
  33861. while (p != 0)
  33862. {
  33863. if (p->numDeepMouseListeners > 0)
  33864. {
  33865. BailOutChecker checker2 (this, p);
  33866. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33867. {
  33868. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33869. if (checker2.shouldBailOut())
  33870. return;
  33871. i = jmin (i, p->numDeepMouseListeners);
  33872. }
  33873. }
  33874. p = p->parentComponent_;
  33875. }
  33876. }
  33877. }
  33878. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33879. {
  33880. Desktop& desktop = Desktop::getInstance();
  33881. BailOutChecker checker (this);
  33882. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33883. this, this, time, relativePos,
  33884. time, 0, false);
  33885. if (isCurrentlyBlockedByAnotherModalComponent())
  33886. {
  33887. // allow blocked mouse-events to go to global listeners..
  33888. desktop.sendMouseMove();
  33889. }
  33890. else
  33891. {
  33892. flags.mouseOverFlag = true;
  33893. mouseMove (me);
  33894. if (checker.shouldBailOut())
  33895. return;
  33896. desktop.resetTimer();
  33897. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33898. if (checker.shouldBailOut())
  33899. return;
  33900. if (mouseListeners_ != 0)
  33901. {
  33902. for (int i = mouseListeners_->size(); --i >= 0;)
  33903. {
  33904. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33905. if (checker.shouldBailOut())
  33906. return;
  33907. i = jmin (i, mouseListeners_->size());
  33908. }
  33909. }
  33910. Component* p = parentComponent_;
  33911. while (p != 0)
  33912. {
  33913. if (p->numDeepMouseListeners > 0)
  33914. {
  33915. BailOutChecker checker2 (this, p);
  33916. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33917. {
  33918. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33919. if (checker2.shouldBailOut())
  33920. return;
  33921. i = jmin (i, p->numDeepMouseListeners);
  33922. }
  33923. }
  33924. p = p->parentComponent_;
  33925. }
  33926. }
  33927. }
  33928. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33929. const Time& time, const float amountX, const float amountY)
  33930. {
  33931. Desktop& desktop = Desktop::getInstance();
  33932. BailOutChecker checker (this);
  33933. const float wheelIncrementX = amountX / 256.0f;
  33934. const float wheelIncrementY = amountY / 256.0f;
  33935. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33936. this, this, time, relativePos, time, 0, false);
  33937. if (isCurrentlyBlockedByAnotherModalComponent())
  33938. {
  33939. // allow blocked mouse-events to go to global listeners..
  33940. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33941. }
  33942. else
  33943. {
  33944. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33945. if (checker.shouldBailOut())
  33946. return;
  33947. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33948. if (checker.shouldBailOut())
  33949. return;
  33950. if (mouseListeners_ != 0)
  33951. {
  33952. for (int i = mouseListeners_->size(); --i >= 0;)
  33953. {
  33954. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33955. if (checker.shouldBailOut())
  33956. return;
  33957. i = jmin (i, mouseListeners_->size());
  33958. }
  33959. }
  33960. Component* p = parentComponent_;
  33961. while (p != 0)
  33962. {
  33963. if (p->numDeepMouseListeners > 0)
  33964. {
  33965. BailOutChecker checker2 (this, p);
  33966. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33967. {
  33968. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33969. if (checker2.shouldBailOut())
  33970. return;
  33971. i = jmin (i, p->numDeepMouseListeners);
  33972. }
  33973. }
  33974. p = p->parentComponent_;
  33975. }
  33976. }
  33977. }
  33978. void Component::sendFakeMouseMove() const
  33979. {
  33980. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33981. }
  33982. void Component::broughtToFront()
  33983. {
  33984. }
  33985. void Component::internalBroughtToFront()
  33986. {
  33987. if (! isValidComponent())
  33988. return;
  33989. if (flags.hasHeavyweightPeerFlag)
  33990. Desktop::getInstance().componentBroughtToFront (this);
  33991. BailOutChecker checker (this);
  33992. broughtToFront();
  33993. if (checker.shouldBailOut())
  33994. return;
  33995. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33996. if (checker.shouldBailOut())
  33997. return;
  33998. // When brought to the front and there's a modal component blocking this one,
  33999. // we need to bring the modal one to the front instead..
  34000. Component* const cm = getCurrentlyModalComponent();
  34001. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  34002. bringModalComponentToFront();
  34003. }
  34004. void Component::focusGained (FocusChangeType)
  34005. {
  34006. // base class does nothing
  34007. }
  34008. void Component::internalFocusGain (const FocusChangeType cause)
  34009. {
  34010. SafePointer<Component> safePointer (this);
  34011. focusGained (cause);
  34012. if (safePointer != 0)
  34013. internalChildFocusChange (cause);
  34014. }
  34015. void Component::focusLost (FocusChangeType)
  34016. {
  34017. // base class does nothing
  34018. }
  34019. void Component::internalFocusLoss (const FocusChangeType cause)
  34020. {
  34021. SafePointer<Component> safePointer (this);
  34022. focusLost (focusChangedDirectly);
  34023. if (safePointer != 0)
  34024. internalChildFocusChange (cause);
  34025. }
  34026. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  34027. {
  34028. // base class does nothing
  34029. }
  34030. void Component::internalChildFocusChange (FocusChangeType cause)
  34031. {
  34032. const bool childIsNowFocused = hasKeyboardFocus (true);
  34033. if (flags.childCompFocusedFlag != childIsNowFocused)
  34034. {
  34035. flags.childCompFocusedFlag = childIsNowFocused;
  34036. SafePointer<Component> safePointer (this);
  34037. focusOfChildComponentChanged (cause);
  34038. if (safePointer == 0)
  34039. return;
  34040. }
  34041. if (parentComponent_ != 0)
  34042. parentComponent_->internalChildFocusChange (cause);
  34043. }
  34044. bool Component::isEnabled() const throw()
  34045. {
  34046. return (! flags.isDisabledFlag)
  34047. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  34048. }
  34049. void Component::setEnabled (const bool shouldBeEnabled)
  34050. {
  34051. if (flags.isDisabledFlag == shouldBeEnabled)
  34052. {
  34053. flags.isDisabledFlag = ! shouldBeEnabled;
  34054. // if any parent components are disabled, setting our flag won't make a difference,
  34055. // so no need to send a change message
  34056. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  34057. sendEnablementChangeMessage();
  34058. }
  34059. }
  34060. void Component::sendEnablementChangeMessage()
  34061. {
  34062. SafePointer<Component> safePointer (this);
  34063. enablementChanged();
  34064. if (safePointer == 0)
  34065. return;
  34066. for (int i = getNumChildComponents(); --i >= 0;)
  34067. {
  34068. Component* const c = getChildComponent (i);
  34069. if (c != 0)
  34070. {
  34071. c->sendEnablementChangeMessage();
  34072. if (safePointer == 0)
  34073. return;
  34074. }
  34075. }
  34076. }
  34077. void Component::enablementChanged()
  34078. {
  34079. }
  34080. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  34081. {
  34082. flags.wantsFocusFlag = wantsFocus;
  34083. }
  34084. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  34085. {
  34086. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  34087. }
  34088. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  34089. {
  34090. return ! flags.dontFocusOnMouseClickFlag;
  34091. }
  34092. bool Component::getWantsKeyboardFocus() const throw()
  34093. {
  34094. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  34095. }
  34096. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  34097. {
  34098. flags.isFocusContainerFlag = shouldBeFocusContainer;
  34099. }
  34100. bool Component::isFocusContainer() const throw()
  34101. {
  34102. return flags.isFocusContainerFlag;
  34103. }
  34104. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  34105. int Component::getExplicitFocusOrder() const
  34106. {
  34107. return properties [juce_explicitFocusOrderId];
  34108. }
  34109. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  34110. {
  34111. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  34112. }
  34113. KeyboardFocusTraverser* Component::createFocusTraverser()
  34114. {
  34115. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  34116. return new KeyboardFocusTraverser();
  34117. return parentComponent_->createFocusTraverser();
  34118. }
  34119. void Component::takeKeyboardFocus (const FocusChangeType cause)
  34120. {
  34121. // give the focus to this component
  34122. if (currentlyFocusedComponent != this)
  34123. {
  34124. JUCE_TRY
  34125. {
  34126. // get the focus onto our desktop window
  34127. ComponentPeer* const peer = getPeer();
  34128. if (peer != 0)
  34129. {
  34130. SafePointer<Component> safePointer (this);
  34131. peer->grabFocus();
  34132. if (peer->isFocused() && currentlyFocusedComponent != this)
  34133. {
  34134. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34135. currentlyFocusedComponent = this;
  34136. Desktop::getInstance().triggerFocusCallback();
  34137. // call this after setting currentlyFocusedComponent so that the one that's
  34138. // losing it has a chance to see where focus is going
  34139. if (componentLosingFocus != 0)
  34140. componentLosingFocus->internalFocusLoss (cause);
  34141. if (currentlyFocusedComponent == this)
  34142. {
  34143. focusGained (cause);
  34144. if (safePointer != 0)
  34145. internalChildFocusChange (cause);
  34146. }
  34147. }
  34148. }
  34149. }
  34150. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  34151. catch (const std::exception& e)
  34152. {
  34153. currentlyFocusedComponent = 0;
  34154. Desktop::getInstance().triggerFocusCallback();
  34155. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  34156. }
  34157. catch (...)
  34158. {
  34159. currentlyFocusedComponent = 0;
  34160. Desktop::getInstance().triggerFocusCallback();
  34161. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  34162. }
  34163. #endif
  34164. }
  34165. }
  34166. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  34167. {
  34168. if (isShowing())
  34169. {
  34170. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  34171. {
  34172. takeKeyboardFocus (cause);
  34173. }
  34174. else
  34175. {
  34176. if (isParentOf (currentlyFocusedComponent)
  34177. && currentlyFocusedComponent->isShowing())
  34178. {
  34179. // do nothing if the focused component is actually a child of ours..
  34180. }
  34181. else
  34182. {
  34183. // find the default child component..
  34184. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34185. if (traverser != 0)
  34186. {
  34187. Component* const defaultComp = traverser->getDefaultComponent (this);
  34188. traverser = 0;
  34189. if (defaultComp != 0)
  34190. {
  34191. defaultComp->grabFocusInternal (cause, false);
  34192. return;
  34193. }
  34194. }
  34195. if (canTryParent && parentComponent_ != 0)
  34196. {
  34197. // if no children want it and we're allowed to try our parent comp,
  34198. // then pass up to parent, which will try our siblings.
  34199. parentComponent_->grabFocusInternal (cause, true);
  34200. }
  34201. }
  34202. }
  34203. }
  34204. }
  34205. void Component::grabKeyboardFocus()
  34206. {
  34207. // if component methods are being called from threads other than the message
  34208. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34209. checkMessageManagerIsLocked
  34210. grabFocusInternal (focusChangedDirectly);
  34211. }
  34212. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  34213. {
  34214. // if component methods are being called from threads other than the message
  34215. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34216. checkMessageManagerIsLocked
  34217. if (parentComponent_ != 0)
  34218. {
  34219. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34220. if (traverser != 0)
  34221. {
  34222. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34223. : traverser->getPreviousComponent (this);
  34224. traverser = 0;
  34225. if (nextComp != 0)
  34226. {
  34227. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34228. {
  34229. SafePointer<Component> nextCompPointer (nextComp);
  34230. internalModalInputAttempt();
  34231. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34232. return;
  34233. }
  34234. nextComp->grabFocusInternal (focusChangedByTabKey);
  34235. return;
  34236. }
  34237. }
  34238. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  34239. }
  34240. }
  34241. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34242. {
  34243. return (currentlyFocusedComponent == this)
  34244. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34245. }
  34246. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34247. {
  34248. return currentlyFocusedComponent;
  34249. }
  34250. void Component::giveAwayFocus()
  34251. {
  34252. // use a copy so we can clear the value before the call
  34253. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34254. currentlyFocusedComponent = 0;
  34255. Desktop::getInstance().triggerFocusCallback();
  34256. if (componentLosingFocus != 0)
  34257. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34258. }
  34259. bool Component::isMouseOver() const throw()
  34260. {
  34261. return flags.mouseOverFlag;
  34262. }
  34263. bool Component::isMouseButtonDown() const throw()
  34264. {
  34265. return flags.draggingFlag;
  34266. }
  34267. bool Component::isMouseOverOrDragging() const throw()
  34268. {
  34269. return flags.mouseOverFlag || flags.draggingFlag;
  34270. }
  34271. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34272. {
  34273. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34274. }
  34275. const Point<int> Component::getMouseXYRelative() const
  34276. {
  34277. return globalPositionToRelative (Desktop::getMousePosition());
  34278. }
  34279. const Rectangle<int> Component::getParentMonitorArea() const
  34280. {
  34281. return Desktop::getInstance()
  34282. .getMonitorAreaContaining (relativePositionToGlobal (getLocalBounds().getCentre()));
  34283. }
  34284. void Component::addKeyListener (KeyListener* const newListener)
  34285. {
  34286. if (keyListeners_ == 0)
  34287. keyListeners_ = new Array <KeyListener*>();
  34288. keyListeners_->addIfNotAlreadyThere (newListener);
  34289. }
  34290. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34291. {
  34292. if (keyListeners_ != 0)
  34293. keyListeners_->removeValue (listenerToRemove);
  34294. }
  34295. bool Component::keyPressed (const KeyPress&)
  34296. {
  34297. return false;
  34298. }
  34299. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34300. {
  34301. return false;
  34302. }
  34303. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34304. {
  34305. if (parentComponent_ != 0)
  34306. parentComponent_->modifierKeysChanged (modifiers);
  34307. }
  34308. void Component::internalModifierKeysChanged()
  34309. {
  34310. sendFakeMouseMove();
  34311. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34312. }
  34313. ComponentPeer* Component::getPeer() const
  34314. {
  34315. if (flags.hasHeavyweightPeerFlag)
  34316. return ComponentPeer::getPeerFor (this);
  34317. else if (parentComponent_ != 0)
  34318. return parentComponent_->getPeer();
  34319. else
  34320. return 0;
  34321. }
  34322. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  34323. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  34324. {
  34325. jassert (component1 != 0);
  34326. }
  34327. bool Component::BailOutChecker::shouldBailOut() const throw()
  34328. {
  34329. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  34330. }
  34331. END_JUCE_NAMESPACE
  34332. /*** End of inlined file: juce_Component.cpp ***/
  34333. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34334. BEGIN_JUCE_NAMESPACE
  34335. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34336. void ComponentListener::componentBroughtToFront (Component&) {}
  34337. void ComponentListener::componentVisibilityChanged (Component&) {}
  34338. void ComponentListener::componentChildrenChanged (Component&) {}
  34339. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34340. void ComponentListener::componentNameChanged (Component&) {}
  34341. void ComponentListener::componentBeingDeleted (Component&) {}
  34342. END_JUCE_NAMESPACE
  34343. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34344. /*** Start of inlined file: juce_Desktop.cpp ***/
  34345. BEGIN_JUCE_NAMESPACE
  34346. Desktop::Desktop()
  34347. : mouseClickCounter (0),
  34348. kioskModeComponent (0)
  34349. {
  34350. createMouseInputSources();
  34351. refreshMonitorSizes();
  34352. }
  34353. Desktop::~Desktop()
  34354. {
  34355. jassert (instance == this);
  34356. instance = 0;
  34357. // doh! If you don't delete all your windows before exiting, you're going to
  34358. // be leaking memory!
  34359. jassert (desktopComponents.size() == 0);
  34360. }
  34361. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34362. {
  34363. if (instance == 0)
  34364. instance = new Desktop();
  34365. return *instance;
  34366. }
  34367. Desktop* Desktop::instance = 0;
  34368. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34369. const bool clipToWorkArea);
  34370. void Desktop::refreshMonitorSizes()
  34371. {
  34372. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  34373. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  34374. monitorCoordsClipped.clear();
  34375. monitorCoordsUnclipped.clear();
  34376. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34377. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34378. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34379. if (oldClipped != monitorCoordsClipped
  34380. || oldUnclipped != monitorCoordsUnclipped)
  34381. {
  34382. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34383. {
  34384. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34385. if (p != 0)
  34386. p->handleScreenSizeChange();
  34387. }
  34388. }
  34389. }
  34390. int Desktop::getNumDisplayMonitors() const throw()
  34391. {
  34392. return monitorCoordsClipped.size();
  34393. }
  34394. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34395. {
  34396. return clippedToWorkArea ? monitorCoordsClipped [index]
  34397. : monitorCoordsUnclipped [index];
  34398. }
  34399. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34400. {
  34401. RectangleList rl;
  34402. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34403. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34404. return rl;
  34405. }
  34406. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34407. {
  34408. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34409. }
  34410. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34411. {
  34412. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34413. double bestDistance = 1.0e10;
  34414. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34415. {
  34416. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34417. if (rect.contains (position))
  34418. return rect;
  34419. const double distance = rect.getCentre().getDistanceFrom (position);
  34420. if (distance < bestDistance)
  34421. {
  34422. bestDistance = distance;
  34423. best = rect;
  34424. }
  34425. }
  34426. return best;
  34427. }
  34428. int Desktop::getNumComponents() const throw()
  34429. {
  34430. return desktopComponents.size();
  34431. }
  34432. Component* Desktop::getComponent (const int index) const throw()
  34433. {
  34434. return desktopComponents [index];
  34435. }
  34436. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34437. {
  34438. for (int i = desktopComponents.size(); --i >= 0;)
  34439. {
  34440. Component* const c = desktopComponents.getUnchecked(i);
  34441. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  34442. if (c->contains (relative.getX(), relative.getY()))
  34443. return c->getComponentAt (relative.getX(), relative.getY());
  34444. }
  34445. return 0;
  34446. }
  34447. void Desktop::addDesktopComponent (Component* const c)
  34448. {
  34449. jassert (c != 0);
  34450. jassert (! desktopComponents.contains (c));
  34451. desktopComponents.addIfNotAlreadyThere (c);
  34452. }
  34453. void Desktop::removeDesktopComponent (Component* const c)
  34454. {
  34455. desktopComponents.removeValue (c);
  34456. }
  34457. void Desktop::componentBroughtToFront (Component* const c)
  34458. {
  34459. const int index = desktopComponents.indexOf (c);
  34460. jassert (index >= 0);
  34461. if (index >= 0)
  34462. {
  34463. int newIndex = -1;
  34464. if (! c->isAlwaysOnTop())
  34465. {
  34466. newIndex = desktopComponents.size();
  34467. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34468. --newIndex;
  34469. --newIndex;
  34470. }
  34471. desktopComponents.move (index, newIndex);
  34472. }
  34473. }
  34474. const Point<int> Desktop::getLastMouseDownPosition() throw()
  34475. {
  34476. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34477. }
  34478. int Desktop::getMouseButtonClickCounter() throw()
  34479. {
  34480. return getInstance().mouseClickCounter;
  34481. }
  34482. void Desktop::incrementMouseClickCounter() throw()
  34483. {
  34484. ++mouseClickCounter;
  34485. }
  34486. int Desktop::getNumDraggingMouseSources() const throw()
  34487. {
  34488. int num = 0;
  34489. for (int i = mouseSources.size(); --i >= 0;)
  34490. if (mouseSources.getUnchecked(i)->isDragging())
  34491. ++num;
  34492. return num;
  34493. }
  34494. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34495. {
  34496. int num = 0;
  34497. for (int i = mouseSources.size(); --i >= 0;)
  34498. {
  34499. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34500. if (mi->isDragging())
  34501. {
  34502. if (index == num)
  34503. return mi;
  34504. ++num;
  34505. }
  34506. }
  34507. return 0;
  34508. }
  34509. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34510. {
  34511. focusListeners.add (listener);
  34512. }
  34513. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34514. {
  34515. focusListeners.remove (listener);
  34516. }
  34517. void Desktop::triggerFocusCallback()
  34518. {
  34519. triggerAsyncUpdate();
  34520. }
  34521. void Desktop::handleAsyncUpdate()
  34522. {
  34523. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  34524. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34525. }
  34526. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34527. {
  34528. mouseListeners.add (listener);
  34529. resetTimer();
  34530. }
  34531. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34532. {
  34533. mouseListeners.remove (listener);
  34534. resetTimer();
  34535. }
  34536. void Desktop::timerCallback()
  34537. {
  34538. if (lastFakeMouseMove != getMousePosition())
  34539. sendMouseMove();
  34540. }
  34541. void Desktop::sendMouseMove()
  34542. {
  34543. if (! mouseListeners.isEmpty())
  34544. {
  34545. startTimer (20);
  34546. lastFakeMouseMove = getMousePosition();
  34547. Component* const target = findComponentAt (lastFakeMouseMove);
  34548. if (target != 0)
  34549. {
  34550. Component::BailOutChecker checker (target);
  34551. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  34552. const Time now (Time::getCurrentTime());
  34553. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34554. target, target, now, pos, now, 0, false);
  34555. if (me.mods.isAnyMouseButtonDown())
  34556. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34557. else
  34558. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34559. }
  34560. }
  34561. }
  34562. void Desktop::resetTimer()
  34563. {
  34564. if (mouseListeners.size() == 0)
  34565. stopTimer();
  34566. else
  34567. startTimer (100);
  34568. lastFakeMouseMove = getMousePosition();
  34569. }
  34570. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34571. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34572. {
  34573. if (kioskModeComponent != componentToUse)
  34574. {
  34575. // agh! Don't delete a component without first stopping it being the kiosk comp
  34576. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  34577. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  34578. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  34579. if (kioskModeComponent->isValidComponent())
  34580. {
  34581. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34582. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34583. }
  34584. kioskModeComponent = componentToUse;
  34585. if (kioskModeComponent != 0)
  34586. {
  34587. jassert (kioskModeComponent->isValidComponent());
  34588. // Only components that are already on the desktop can be put into kiosk mode!
  34589. jassert (kioskModeComponent->isOnDesktop());
  34590. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34591. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34592. }
  34593. }
  34594. }
  34595. END_JUCE_NAMESPACE
  34596. /*** End of inlined file: juce_Desktop.cpp ***/
  34597. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34598. BEGIN_JUCE_NAMESPACE
  34599. class ModalComponentManager::ModalItem : public ComponentListener
  34600. {
  34601. public:
  34602. ModalItem (Component* const comp, Callback* const callback)
  34603. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34604. {
  34605. if (callback != 0)
  34606. callbacks.add (callback);
  34607. jassert (comp != 0);
  34608. component->addComponentListener (this);
  34609. }
  34610. ~ModalItem()
  34611. {
  34612. if (! isDeleted)
  34613. component->removeComponentListener (this);
  34614. }
  34615. void componentBeingDeleted (Component&)
  34616. {
  34617. isDeleted = true;
  34618. cancel();
  34619. }
  34620. void componentVisibilityChanged (Component&)
  34621. {
  34622. if (! component->isShowing())
  34623. cancel();
  34624. }
  34625. void componentParentHierarchyChanged (Component&)
  34626. {
  34627. if (! component->isShowing())
  34628. cancel();
  34629. }
  34630. void cancel()
  34631. {
  34632. if (isActive)
  34633. {
  34634. isActive = false;
  34635. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34636. }
  34637. }
  34638. Component* component;
  34639. OwnedArray<Callback> callbacks;
  34640. int returnValue;
  34641. bool isActive, isDeleted;
  34642. private:
  34643. ModalItem (const ModalItem&);
  34644. ModalItem& operator= (const ModalItem&);
  34645. };
  34646. ModalComponentManager::ModalComponentManager()
  34647. {
  34648. }
  34649. ModalComponentManager::~ModalComponentManager()
  34650. {
  34651. clearSingletonInstance();
  34652. }
  34653. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34654. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34655. {
  34656. if (component != 0)
  34657. stack.add (new ModalItem (component, callback));
  34658. }
  34659. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34660. {
  34661. if (callback != 0)
  34662. {
  34663. ScopedPointer<Callback> callbackDeleter (callback);
  34664. for (int i = stack.size(); --i >= 0;)
  34665. {
  34666. ModalItem* const item = stack.getUnchecked(i);
  34667. if (item->component == component)
  34668. {
  34669. item->callbacks.add (callback);
  34670. callbackDeleter.release();
  34671. break;
  34672. }
  34673. }
  34674. }
  34675. }
  34676. void ModalComponentManager::endModal (Component* component)
  34677. {
  34678. for (int i = stack.size(); --i >= 0;)
  34679. {
  34680. ModalItem* const item = stack.getUnchecked(i);
  34681. if (item->component == component)
  34682. item->cancel();
  34683. }
  34684. }
  34685. void ModalComponentManager::endModal (Component* component, int returnValue)
  34686. {
  34687. for (int i = stack.size(); --i >= 0;)
  34688. {
  34689. ModalItem* const item = stack.getUnchecked(i);
  34690. if (item->component == component)
  34691. {
  34692. item->returnValue = returnValue;
  34693. item->cancel();
  34694. }
  34695. }
  34696. }
  34697. int ModalComponentManager::getNumModalComponents() const
  34698. {
  34699. int n = 0;
  34700. for (int i = 0; i < stack.size(); ++i)
  34701. if (stack.getUnchecked(i)->isActive)
  34702. ++n;
  34703. return n;
  34704. }
  34705. Component* ModalComponentManager::getModalComponent (const int index) const
  34706. {
  34707. int n = 0;
  34708. for (int i = stack.size(); --i >= 0;)
  34709. {
  34710. const ModalItem* const item = stack.getUnchecked(i);
  34711. if (item->isActive)
  34712. if (n++ == index)
  34713. return item->component;
  34714. }
  34715. return 0;
  34716. }
  34717. bool ModalComponentManager::isModal (Component* const comp) const
  34718. {
  34719. for (int i = stack.size(); --i >= 0;)
  34720. {
  34721. const ModalItem* const item = stack.getUnchecked(i);
  34722. if (item->isActive && item->component == comp)
  34723. return true;
  34724. }
  34725. return false;
  34726. }
  34727. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34728. {
  34729. return comp == getModalComponent (0);
  34730. }
  34731. void ModalComponentManager::handleAsyncUpdate()
  34732. {
  34733. for (int i = stack.size(); --i >= 0;)
  34734. {
  34735. const ModalItem* const item = stack.getUnchecked(i);
  34736. if (! item->isActive)
  34737. {
  34738. for (int j = item->callbacks.size(); --j >= 0;)
  34739. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34740. stack.remove (i);
  34741. }
  34742. }
  34743. }
  34744. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34745. {
  34746. public:
  34747. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34748. ~ReturnValueRetriever() {}
  34749. void modalStateFinished (int returnValue)
  34750. {
  34751. finished = true;
  34752. value = returnValue;
  34753. }
  34754. private:
  34755. int& value;
  34756. bool& finished;
  34757. ReturnValueRetriever (const ReturnValueRetriever&);
  34758. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  34759. };
  34760. int ModalComponentManager::runEventLoopForCurrentComponent()
  34761. {
  34762. // This can only be run from the message thread!
  34763. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34764. Component* currentlyModal = getModalComponent (0);
  34765. if (currentlyModal == 0)
  34766. return 0;
  34767. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34768. int returnValue = 0;
  34769. bool finished = false;
  34770. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34771. JUCE_TRY
  34772. {
  34773. while (! finished)
  34774. {
  34775. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34776. break;
  34777. }
  34778. }
  34779. JUCE_CATCH_EXCEPTION
  34780. if (prevFocused != 0)
  34781. prevFocused->grabKeyboardFocus();
  34782. return returnValue;
  34783. }
  34784. END_JUCE_NAMESPACE
  34785. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34786. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34787. BEGIN_JUCE_NAMESPACE
  34788. ArrowButton::ArrowButton (const String& name,
  34789. float arrowDirectionInRadians,
  34790. const Colour& arrowColour)
  34791. : Button (name),
  34792. colour (arrowColour)
  34793. {
  34794. path.lineTo (0.0f, 1.0f);
  34795. path.lineTo (1.0f, 0.5f);
  34796. path.closeSubPath();
  34797. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34798. 0.5f, 0.5f));
  34799. setComponentEffect (&shadow);
  34800. buttonStateChanged();
  34801. }
  34802. ArrowButton::~ArrowButton()
  34803. {
  34804. }
  34805. void ArrowButton::paintButton (Graphics& g,
  34806. bool /*isMouseOverButton*/,
  34807. bool /*isButtonDown*/)
  34808. {
  34809. g.setColour (colour);
  34810. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34811. (float) offset,
  34812. (float) (getWidth() - 3),
  34813. (float) (getHeight() - 3),
  34814. false));
  34815. }
  34816. void ArrowButton::buttonStateChanged()
  34817. {
  34818. offset = (isDown()) ? 1 : 0;
  34819. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34820. 0.3f, -1, 0);
  34821. }
  34822. END_JUCE_NAMESPACE
  34823. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34824. /*** Start of inlined file: juce_Button.cpp ***/
  34825. BEGIN_JUCE_NAMESPACE
  34826. class Button::RepeatTimer : public Timer
  34827. {
  34828. public:
  34829. RepeatTimer (Button& owner_) : owner (owner_) {}
  34830. void timerCallback() { owner.repeatTimerCallback(); }
  34831. juce_UseDebuggingNewOperator
  34832. private:
  34833. Button& owner;
  34834. RepeatTimer (const RepeatTimer&);
  34835. RepeatTimer& operator= (const RepeatTimer&);
  34836. };
  34837. Button::Button (const String& name)
  34838. : Component (name),
  34839. text (name),
  34840. buttonPressTime (0),
  34841. lastTimeCallbackTime (0),
  34842. commandManagerToUse (0),
  34843. autoRepeatDelay (-1),
  34844. autoRepeatSpeed (0),
  34845. autoRepeatMinimumDelay (-1),
  34846. radioGroupId (0),
  34847. commandID (0),
  34848. connectedEdgeFlags (0),
  34849. buttonState (buttonNormal),
  34850. lastToggleState (false),
  34851. clickTogglesState (false),
  34852. needsToRelease (false),
  34853. needsRepainting (false),
  34854. isKeyDown (false),
  34855. triggerOnMouseDown (false),
  34856. generateTooltip (false)
  34857. {
  34858. setWantsKeyboardFocus (true);
  34859. isOn.addListener (this);
  34860. }
  34861. Button::~Button()
  34862. {
  34863. isOn.removeListener (this);
  34864. if (commandManagerToUse != 0)
  34865. commandManagerToUse->removeListener (this);
  34866. repeatTimer = 0;
  34867. clearShortcuts();
  34868. }
  34869. void Button::setButtonText (const String& newText)
  34870. {
  34871. if (text != newText)
  34872. {
  34873. text = newText;
  34874. repaint();
  34875. }
  34876. }
  34877. void Button::setTooltip (const String& newTooltip)
  34878. {
  34879. SettableTooltipClient::setTooltip (newTooltip);
  34880. generateTooltip = false;
  34881. }
  34882. const String Button::getTooltip()
  34883. {
  34884. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34885. {
  34886. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34887. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34888. for (int i = 0; i < keyPresses.size(); ++i)
  34889. {
  34890. const String key (keyPresses.getReference(i).getTextDescription());
  34891. tt << " [";
  34892. if (key.length() == 1)
  34893. tt << TRANS("shortcut") << ": '" << key << "']";
  34894. else
  34895. tt << key << ']';
  34896. }
  34897. return tt;
  34898. }
  34899. return SettableTooltipClient::getTooltip();
  34900. }
  34901. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34902. {
  34903. if (connectedEdgeFlags != connectedEdgeFlags_)
  34904. {
  34905. connectedEdgeFlags = connectedEdgeFlags_;
  34906. repaint();
  34907. }
  34908. }
  34909. void Button::setToggleState (const bool shouldBeOn,
  34910. const bool sendChangeNotification)
  34911. {
  34912. if (shouldBeOn != lastToggleState)
  34913. {
  34914. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34915. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34916. lastToggleState = shouldBeOn;
  34917. repaint();
  34918. if (sendChangeNotification)
  34919. {
  34920. Component::SafePointer<Component> deletionWatcher (this);
  34921. sendClickMessage (ModifierKeys());
  34922. if (deletionWatcher == 0)
  34923. return;
  34924. }
  34925. if (lastToggleState)
  34926. turnOffOtherButtonsInGroup (sendChangeNotification);
  34927. }
  34928. }
  34929. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34930. {
  34931. clickTogglesState = shouldToggle;
  34932. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34933. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34934. // it is that this button represents, and the button will update its state to reflect this
  34935. // in the applicationCommandListChanged() method.
  34936. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34937. }
  34938. bool Button::getClickingTogglesState() const throw()
  34939. {
  34940. return clickTogglesState;
  34941. }
  34942. void Button::valueChanged (Value& value)
  34943. {
  34944. if (value.refersToSameSourceAs (isOn))
  34945. setToggleState (isOn.getValue(), true);
  34946. }
  34947. void Button::setRadioGroupId (const int newGroupId)
  34948. {
  34949. if (radioGroupId != newGroupId)
  34950. {
  34951. radioGroupId = newGroupId;
  34952. if (lastToggleState)
  34953. turnOffOtherButtonsInGroup (true);
  34954. }
  34955. }
  34956. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34957. {
  34958. Component* const p = getParentComponent();
  34959. if (p != 0 && radioGroupId != 0)
  34960. {
  34961. Component::SafePointer<Component> deletionWatcher (this);
  34962. for (int i = p->getNumChildComponents(); --i >= 0;)
  34963. {
  34964. Component* const c = p->getChildComponent (i);
  34965. if (c != this)
  34966. {
  34967. Button* const b = dynamic_cast <Button*> (c);
  34968. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34969. {
  34970. b->setToggleState (false, sendChangeNotification);
  34971. if (deletionWatcher == 0)
  34972. return;
  34973. }
  34974. }
  34975. }
  34976. }
  34977. }
  34978. void Button::enablementChanged()
  34979. {
  34980. updateState (0);
  34981. repaint();
  34982. }
  34983. Button::ButtonState Button::updateState (const MouseEvent* const e)
  34984. {
  34985. ButtonState state = buttonNormal;
  34986. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34987. {
  34988. Point<int> mousePos;
  34989. if (e == 0)
  34990. mousePos = getMouseXYRelative();
  34991. else
  34992. mousePos = e->getEventRelativeTo (this).getPosition();
  34993. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  34994. const bool down = isMouseButtonDown();
  34995. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34996. state = buttonDown;
  34997. else if (over)
  34998. state = buttonOver;
  34999. }
  35000. setState (state);
  35001. return state;
  35002. }
  35003. void Button::setState (const ButtonState newState)
  35004. {
  35005. if (buttonState != newState)
  35006. {
  35007. buttonState = newState;
  35008. repaint();
  35009. if (buttonState == buttonDown)
  35010. {
  35011. buttonPressTime = Time::getApproximateMillisecondCounter();
  35012. lastTimeCallbackTime = buttonPressTime;
  35013. }
  35014. sendStateMessage();
  35015. }
  35016. }
  35017. bool Button::isDown() const throw()
  35018. {
  35019. return buttonState == buttonDown;
  35020. }
  35021. bool Button::isOver() const throw()
  35022. {
  35023. return buttonState != buttonNormal;
  35024. }
  35025. void Button::buttonStateChanged()
  35026. {
  35027. }
  35028. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  35029. {
  35030. const uint32 now = Time::getApproximateMillisecondCounter();
  35031. return now > buttonPressTime ? now - buttonPressTime : 0;
  35032. }
  35033. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  35034. {
  35035. triggerOnMouseDown = isTriggeredOnMouseDown;
  35036. }
  35037. void Button::clicked()
  35038. {
  35039. }
  35040. void Button::clicked (const ModifierKeys& /*modifiers*/)
  35041. {
  35042. clicked();
  35043. }
  35044. static const int clickMessageId = 0x2f3f4f99;
  35045. void Button::triggerClick()
  35046. {
  35047. postCommandMessage (clickMessageId);
  35048. }
  35049. void Button::internalClickCallback (const ModifierKeys& modifiers)
  35050. {
  35051. if (clickTogglesState)
  35052. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  35053. sendClickMessage (modifiers);
  35054. }
  35055. void Button::flashButtonState()
  35056. {
  35057. if (isEnabled())
  35058. {
  35059. needsToRelease = true;
  35060. setState (buttonDown);
  35061. getRepeatTimer().startTimer (100);
  35062. }
  35063. }
  35064. void Button::handleCommandMessage (int commandId)
  35065. {
  35066. if (commandId == clickMessageId)
  35067. {
  35068. if (isEnabled())
  35069. {
  35070. flashButtonState();
  35071. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35072. }
  35073. }
  35074. else
  35075. {
  35076. Component::handleCommandMessage (commandId);
  35077. }
  35078. }
  35079. void Button::addButtonListener (Listener* const newListener)
  35080. {
  35081. buttonListeners.add (newListener);
  35082. }
  35083. void Button::removeButtonListener (Listener* const listener)
  35084. {
  35085. buttonListeners.remove (listener);
  35086. }
  35087. void Button::sendClickMessage (const ModifierKeys& modifiers)
  35088. {
  35089. Component::BailOutChecker checker (this);
  35090. if (commandManagerToUse != 0 && commandID != 0)
  35091. {
  35092. ApplicationCommandTarget::InvocationInfo info (commandID);
  35093. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  35094. info.originatingComponent = this;
  35095. commandManagerToUse->invoke (info, true);
  35096. }
  35097. clicked (modifiers);
  35098. if (! checker.shouldBailOut())
  35099. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  35100. }
  35101. void Button::sendStateMessage()
  35102. {
  35103. Component::BailOutChecker checker (this);
  35104. buttonStateChanged();
  35105. if (! checker.shouldBailOut())
  35106. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  35107. }
  35108. void Button::paint (Graphics& g)
  35109. {
  35110. if (needsToRelease && isEnabled())
  35111. {
  35112. needsToRelease = false;
  35113. needsRepainting = true;
  35114. }
  35115. paintButton (g, isOver(), isDown());
  35116. }
  35117. void Button::mouseEnter (const MouseEvent& e)
  35118. {
  35119. updateState (&e);
  35120. }
  35121. void Button::mouseExit (const MouseEvent& e)
  35122. {
  35123. updateState (&e);
  35124. }
  35125. void Button::mouseDown (const MouseEvent& e)
  35126. {
  35127. updateState (&e);
  35128. if (isDown())
  35129. {
  35130. if (autoRepeatDelay >= 0)
  35131. getRepeatTimer().startTimer (autoRepeatDelay);
  35132. if (triggerOnMouseDown)
  35133. internalClickCallback (e.mods);
  35134. }
  35135. }
  35136. void Button::mouseUp (const MouseEvent& e)
  35137. {
  35138. const bool wasDown = isDown();
  35139. updateState (&e);
  35140. if (wasDown && isOver() && ! triggerOnMouseDown)
  35141. internalClickCallback (e.mods);
  35142. }
  35143. void Button::mouseDrag (const MouseEvent& e)
  35144. {
  35145. const ButtonState oldState = buttonState;
  35146. updateState (&e);
  35147. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35148. getRepeatTimer().startTimer (autoRepeatSpeed);
  35149. }
  35150. void Button::focusGained (FocusChangeType)
  35151. {
  35152. updateState (0);
  35153. repaint();
  35154. }
  35155. void Button::focusLost (FocusChangeType)
  35156. {
  35157. updateState (0);
  35158. repaint();
  35159. }
  35160. void Button::setVisible (bool shouldBeVisible)
  35161. {
  35162. if (shouldBeVisible != isVisible())
  35163. {
  35164. Component::setVisible (shouldBeVisible);
  35165. if (! shouldBeVisible)
  35166. needsToRelease = false;
  35167. updateState (0);
  35168. }
  35169. else
  35170. {
  35171. Component::setVisible (shouldBeVisible);
  35172. }
  35173. }
  35174. void Button::parentHierarchyChanged()
  35175. {
  35176. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35177. if (newKeySource != keySource.getComponent())
  35178. {
  35179. if (keySource != 0)
  35180. keySource->removeKeyListener (this);
  35181. keySource = newKeySource;
  35182. if (keySource != 0)
  35183. keySource->addKeyListener (this);
  35184. }
  35185. }
  35186. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35187. const int commandID_,
  35188. const bool generateTooltip_)
  35189. {
  35190. commandID = commandID_;
  35191. generateTooltip = generateTooltip_;
  35192. if (commandManagerToUse != commandManagerToUse_)
  35193. {
  35194. if (commandManagerToUse != 0)
  35195. commandManagerToUse->removeListener (this);
  35196. commandManagerToUse = commandManagerToUse_;
  35197. if (commandManagerToUse != 0)
  35198. commandManagerToUse->addListener (this);
  35199. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35200. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35201. // it is that this button represents, and the button will update its state to reflect this
  35202. // in the applicationCommandListChanged() method.
  35203. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35204. }
  35205. if (commandManagerToUse != 0)
  35206. applicationCommandListChanged();
  35207. else
  35208. setEnabled (true);
  35209. }
  35210. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35211. {
  35212. if (info.commandID == commandID
  35213. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35214. {
  35215. flashButtonState();
  35216. }
  35217. }
  35218. void Button::applicationCommandListChanged()
  35219. {
  35220. if (commandManagerToUse != 0)
  35221. {
  35222. ApplicationCommandInfo info (0);
  35223. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35224. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35225. if (target != 0)
  35226. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35227. }
  35228. }
  35229. void Button::addShortcut (const KeyPress& key)
  35230. {
  35231. if (key.isValid())
  35232. {
  35233. jassert (! isRegisteredForShortcut (key)); // already registered!
  35234. shortcuts.add (key);
  35235. parentHierarchyChanged();
  35236. }
  35237. }
  35238. void Button::clearShortcuts()
  35239. {
  35240. shortcuts.clear();
  35241. parentHierarchyChanged();
  35242. }
  35243. bool Button::isShortcutPressed() const
  35244. {
  35245. if (! isCurrentlyBlockedByAnotherModalComponent())
  35246. {
  35247. for (int i = shortcuts.size(); --i >= 0;)
  35248. if (shortcuts.getReference(i).isCurrentlyDown())
  35249. return true;
  35250. }
  35251. return false;
  35252. }
  35253. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35254. {
  35255. for (int i = shortcuts.size(); --i >= 0;)
  35256. if (key == shortcuts.getReference(i))
  35257. return true;
  35258. return false;
  35259. }
  35260. bool Button::keyStateChanged (const bool, Component*)
  35261. {
  35262. if (! isEnabled())
  35263. return false;
  35264. const bool wasDown = isKeyDown;
  35265. isKeyDown = isShortcutPressed();
  35266. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35267. getRepeatTimer().startTimer (autoRepeatDelay);
  35268. updateState (0);
  35269. if (isEnabled() && wasDown && ! isKeyDown)
  35270. {
  35271. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35272. // (return immediately - this button may now have been deleted)
  35273. return true;
  35274. }
  35275. return wasDown || isKeyDown;
  35276. }
  35277. bool Button::keyPressed (const KeyPress&, Component*)
  35278. {
  35279. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35280. return isShortcutPressed();
  35281. }
  35282. bool Button::keyPressed (const KeyPress& key)
  35283. {
  35284. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35285. {
  35286. triggerClick();
  35287. return true;
  35288. }
  35289. return false;
  35290. }
  35291. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35292. const int repeatMillisecs,
  35293. const int minimumDelayInMillisecs) throw()
  35294. {
  35295. autoRepeatDelay = initialDelayMillisecs;
  35296. autoRepeatSpeed = repeatMillisecs;
  35297. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35298. }
  35299. void Button::repeatTimerCallback()
  35300. {
  35301. if (needsRepainting)
  35302. {
  35303. getRepeatTimer().stopTimer();
  35304. updateState (0);
  35305. needsRepainting = false;
  35306. }
  35307. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  35308. {
  35309. int repeatSpeed = autoRepeatSpeed;
  35310. if (autoRepeatMinimumDelay >= 0)
  35311. {
  35312. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35313. timeHeldDown *= timeHeldDown;
  35314. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35315. }
  35316. repeatSpeed = jmax (1, repeatSpeed);
  35317. getRepeatTimer().startTimer (repeatSpeed);
  35318. const uint32 now = Time::getApproximateMillisecondCounter();
  35319. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  35320. lastTimeCallbackTime = now;
  35321. Component::SafePointer<Component> deletionWatcher (this);
  35322. for (int i = numTimesToCallback; --i >= 0;)
  35323. {
  35324. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35325. if (deletionWatcher == 0 || ! isDown())
  35326. return;
  35327. }
  35328. }
  35329. else if (! needsToRelease)
  35330. {
  35331. getRepeatTimer().stopTimer();
  35332. }
  35333. }
  35334. Button::RepeatTimer& Button::getRepeatTimer()
  35335. {
  35336. if (repeatTimer == 0)
  35337. repeatTimer = new RepeatTimer (*this);
  35338. return *repeatTimer;
  35339. }
  35340. END_JUCE_NAMESPACE
  35341. /*** End of inlined file: juce_Button.cpp ***/
  35342. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35343. BEGIN_JUCE_NAMESPACE
  35344. DrawableButton::DrawableButton (const String& name,
  35345. const DrawableButton::ButtonStyle buttonStyle)
  35346. : Button (name),
  35347. style (buttonStyle),
  35348. edgeIndent (3)
  35349. {
  35350. if (buttonStyle == ImageOnButtonBackground)
  35351. {
  35352. backgroundOff = Colour (0xffbbbbff);
  35353. backgroundOn = Colour (0xff3333ff);
  35354. }
  35355. else
  35356. {
  35357. backgroundOff = Colours::transparentBlack;
  35358. backgroundOn = Colour (0xaabbbbff);
  35359. }
  35360. }
  35361. DrawableButton::~DrawableButton()
  35362. {
  35363. deleteImages();
  35364. }
  35365. void DrawableButton::deleteImages()
  35366. {
  35367. }
  35368. void DrawableButton::setImages (const Drawable* normal,
  35369. const Drawable* over,
  35370. const Drawable* down,
  35371. const Drawable* disabled,
  35372. const Drawable* normalOn,
  35373. const Drawable* overOn,
  35374. const Drawable* downOn,
  35375. const Drawable* disabledOn)
  35376. {
  35377. deleteImages();
  35378. jassert (normal != 0); // you really need to give it at least a normal image..
  35379. if (normal != 0)
  35380. normalImage = normal->createCopy();
  35381. if (over != 0)
  35382. overImage = over->createCopy();
  35383. if (down != 0)
  35384. downImage = down->createCopy();
  35385. if (disabled != 0)
  35386. disabledImage = disabled->createCopy();
  35387. if (normalOn != 0)
  35388. normalImageOn = normalOn->createCopy();
  35389. if (overOn != 0)
  35390. overImageOn = overOn->createCopy();
  35391. if (downOn != 0)
  35392. downImageOn = downOn->createCopy();
  35393. if (disabledOn != 0)
  35394. disabledImageOn = disabledOn->createCopy();
  35395. repaint();
  35396. }
  35397. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35398. {
  35399. if (style != newStyle)
  35400. {
  35401. style = newStyle;
  35402. repaint();
  35403. }
  35404. }
  35405. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35406. const Colour& toggledOnColour)
  35407. {
  35408. if (backgroundOff != toggledOffColour
  35409. || backgroundOn != toggledOnColour)
  35410. {
  35411. backgroundOff = toggledOffColour;
  35412. backgroundOn = toggledOnColour;
  35413. repaint();
  35414. }
  35415. }
  35416. const Colour& DrawableButton::getBackgroundColour() const throw()
  35417. {
  35418. return getToggleState() ? backgroundOn
  35419. : backgroundOff;
  35420. }
  35421. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35422. {
  35423. edgeIndent = numPixelsIndent;
  35424. repaint();
  35425. }
  35426. void DrawableButton::paintButton (Graphics& g,
  35427. bool isMouseOverButton,
  35428. bool isButtonDown)
  35429. {
  35430. Rectangle<int> imageSpace;
  35431. if (style == ImageOnButtonBackground)
  35432. {
  35433. const int insetX = getWidth() / 4;
  35434. const int insetY = getHeight() / 4;
  35435. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  35436. getLookAndFeel().drawButtonBackground (g, *this,
  35437. getBackgroundColour(),
  35438. isMouseOverButton,
  35439. isButtonDown);
  35440. }
  35441. else
  35442. {
  35443. g.fillAll (getBackgroundColour());
  35444. const int textH = (style == ImageAboveTextLabel)
  35445. ? jmin (16, proportionOfHeight (0.25f))
  35446. : 0;
  35447. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35448. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35449. imageSpace.setBounds (indentX, indentY,
  35450. getWidth() - indentX * 2,
  35451. getHeight() - indentY * 2 - textH);
  35452. if (textH > 0)
  35453. {
  35454. g.setFont ((float) textH);
  35455. g.setColour (findColour (DrawableButton::textColourId)
  35456. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35457. g.drawFittedText (getButtonText(),
  35458. 2, getHeight() - textH - 1,
  35459. getWidth() - 4, textH,
  35460. Justification::centred, 1);
  35461. }
  35462. }
  35463. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  35464. g.setOpacity (1.0f);
  35465. const Drawable* imageToDraw = 0;
  35466. if (isEnabled())
  35467. {
  35468. imageToDraw = getCurrentImage();
  35469. }
  35470. else
  35471. {
  35472. imageToDraw = getToggleState() ? disabledImageOn
  35473. : disabledImage;
  35474. if (imageToDraw == 0)
  35475. {
  35476. g.setOpacity (0.4f);
  35477. imageToDraw = getNormalImage();
  35478. }
  35479. }
  35480. if (imageToDraw != 0)
  35481. {
  35482. if (style == ImageRaw)
  35483. {
  35484. imageToDraw->draw (g, 1.0f);
  35485. }
  35486. else
  35487. {
  35488. imageToDraw->drawWithin (g,
  35489. imageSpace.getX(),
  35490. imageSpace.getY(),
  35491. imageSpace.getWidth(),
  35492. imageSpace.getHeight(),
  35493. RectanglePlacement::centred,
  35494. 1.0f);
  35495. }
  35496. }
  35497. }
  35498. const Drawable* DrawableButton::getCurrentImage() const throw()
  35499. {
  35500. if (isDown())
  35501. return getDownImage();
  35502. if (isOver())
  35503. return getOverImage();
  35504. return getNormalImage();
  35505. }
  35506. const Drawable* DrawableButton::getNormalImage() const throw()
  35507. {
  35508. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35509. : normalImage;
  35510. }
  35511. const Drawable* DrawableButton::getOverImage() const throw()
  35512. {
  35513. const Drawable* d = normalImage;
  35514. if (getToggleState())
  35515. {
  35516. if (overImageOn != 0)
  35517. d = overImageOn;
  35518. else if (normalImageOn != 0)
  35519. d = normalImageOn;
  35520. else if (overImage != 0)
  35521. d = overImage;
  35522. }
  35523. else
  35524. {
  35525. if (overImage != 0)
  35526. d = overImage;
  35527. }
  35528. return d;
  35529. }
  35530. const Drawable* DrawableButton::getDownImage() const throw()
  35531. {
  35532. const Drawable* d = normalImage;
  35533. if (getToggleState())
  35534. {
  35535. if (downImageOn != 0)
  35536. d = downImageOn;
  35537. else if (overImageOn != 0)
  35538. d = overImageOn;
  35539. else if (normalImageOn != 0)
  35540. d = normalImageOn;
  35541. else if (downImage != 0)
  35542. d = downImage;
  35543. else
  35544. d = getOverImage();
  35545. }
  35546. else
  35547. {
  35548. if (downImage != 0)
  35549. d = downImage;
  35550. else
  35551. d = getOverImage();
  35552. }
  35553. return d;
  35554. }
  35555. END_JUCE_NAMESPACE
  35556. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35557. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35558. BEGIN_JUCE_NAMESPACE
  35559. HyperlinkButton::HyperlinkButton (const String& linkText,
  35560. const URL& linkURL)
  35561. : Button (linkText),
  35562. url (linkURL),
  35563. font (14.0f, Font::underlined),
  35564. resizeFont (true),
  35565. justification (Justification::centred)
  35566. {
  35567. setMouseCursor (MouseCursor::PointingHandCursor);
  35568. setTooltip (linkURL.toString (false));
  35569. }
  35570. HyperlinkButton::~HyperlinkButton()
  35571. {
  35572. }
  35573. void HyperlinkButton::setFont (const Font& newFont,
  35574. const bool resizeToMatchComponentHeight,
  35575. const Justification& justificationType)
  35576. {
  35577. font = newFont;
  35578. resizeFont = resizeToMatchComponentHeight;
  35579. justification = justificationType;
  35580. repaint();
  35581. }
  35582. void HyperlinkButton::setURL (const URL& newURL) throw()
  35583. {
  35584. url = newURL;
  35585. setTooltip (newURL.toString (false));
  35586. }
  35587. const Font HyperlinkButton::getFontToUse() const
  35588. {
  35589. Font f (font);
  35590. if (resizeFont)
  35591. f.setHeight (getHeight() * 0.7f);
  35592. return f;
  35593. }
  35594. void HyperlinkButton::changeWidthToFitText()
  35595. {
  35596. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35597. }
  35598. void HyperlinkButton::colourChanged()
  35599. {
  35600. repaint();
  35601. }
  35602. void HyperlinkButton::clicked()
  35603. {
  35604. if (url.isWellFormed())
  35605. url.launchInDefaultBrowser();
  35606. }
  35607. void HyperlinkButton::paintButton (Graphics& g,
  35608. bool isMouseOverButton,
  35609. bool isButtonDown)
  35610. {
  35611. const Colour textColour (findColour (textColourId));
  35612. if (isEnabled())
  35613. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35614. : textColour);
  35615. else
  35616. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35617. g.setFont (getFontToUse());
  35618. g.drawText (getButtonText(),
  35619. 2, 0, getWidth() - 2, getHeight(),
  35620. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35621. true);
  35622. }
  35623. END_JUCE_NAMESPACE
  35624. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35625. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35626. BEGIN_JUCE_NAMESPACE
  35627. ImageButton::ImageButton (const String& text_)
  35628. : Button (text_),
  35629. scaleImageToFit (true),
  35630. preserveProportions (true),
  35631. alphaThreshold (0),
  35632. imageX (0),
  35633. imageY (0),
  35634. imageW (0),
  35635. imageH (0),
  35636. normalImage (0),
  35637. overImage (0),
  35638. downImage (0)
  35639. {
  35640. }
  35641. ImageButton::~ImageButton()
  35642. {
  35643. }
  35644. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35645. const bool rescaleImagesWhenButtonSizeChanges,
  35646. const bool preserveImageProportions,
  35647. const Image& normalImage_,
  35648. const float imageOpacityWhenNormal,
  35649. const Colour& overlayColourWhenNormal,
  35650. const Image& overImage_,
  35651. const float imageOpacityWhenOver,
  35652. const Colour& overlayColourWhenOver,
  35653. const Image& downImage_,
  35654. const float imageOpacityWhenDown,
  35655. const Colour& overlayColourWhenDown,
  35656. const float hitTestAlphaThreshold)
  35657. {
  35658. normalImage = normalImage_;
  35659. overImage = overImage_;
  35660. downImage = downImage_;
  35661. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35662. {
  35663. imageW = normalImage.getWidth();
  35664. imageH = normalImage.getHeight();
  35665. setSize (imageW, imageH);
  35666. }
  35667. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35668. preserveProportions = preserveImageProportions;
  35669. normalOpacity = imageOpacityWhenNormal;
  35670. normalOverlay = overlayColourWhenNormal;
  35671. overOpacity = imageOpacityWhenOver;
  35672. overOverlay = overlayColourWhenOver;
  35673. downOpacity = imageOpacityWhenDown;
  35674. downOverlay = overlayColourWhenDown;
  35675. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35676. repaint();
  35677. }
  35678. const Image ImageButton::getCurrentImage() const
  35679. {
  35680. if (isDown() || getToggleState())
  35681. return getDownImage();
  35682. if (isOver())
  35683. return getOverImage();
  35684. return getNormalImage();
  35685. }
  35686. const Image ImageButton::getNormalImage() const
  35687. {
  35688. return normalImage;
  35689. }
  35690. const Image ImageButton::getOverImage() const
  35691. {
  35692. return overImage.isValid() ? overImage
  35693. : normalImage;
  35694. }
  35695. const Image ImageButton::getDownImage() const
  35696. {
  35697. return downImage.isValid() ? downImage
  35698. : getOverImage();
  35699. }
  35700. void ImageButton::paintButton (Graphics& g,
  35701. bool isMouseOverButton,
  35702. bool isButtonDown)
  35703. {
  35704. if (! isEnabled())
  35705. {
  35706. isMouseOverButton = false;
  35707. isButtonDown = false;
  35708. }
  35709. Image im (getCurrentImage());
  35710. if (im.isValid())
  35711. {
  35712. const int iw = im.getWidth();
  35713. const int ih = im.getHeight();
  35714. imageW = getWidth();
  35715. imageH = getHeight();
  35716. imageX = (imageW - iw) >> 1;
  35717. imageY = (imageH - ih) >> 1;
  35718. if (scaleImageToFit)
  35719. {
  35720. if (preserveProportions)
  35721. {
  35722. int newW, newH;
  35723. const float imRatio = ih / (float)iw;
  35724. const float destRatio = imageH / (float)imageW;
  35725. if (imRatio > destRatio)
  35726. {
  35727. newW = roundToInt (imageH / imRatio);
  35728. newH = imageH;
  35729. }
  35730. else
  35731. {
  35732. newW = imageW;
  35733. newH = roundToInt (imageW * imRatio);
  35734. }
  35735. imageX = (imageW - newW) / 2;
  35736. imageY = (imageH - newH) / 2;
  35737. imageW = newW;
  35738. imageH = newH;
  35739. }
  35740. else
  35741. {
  35742. imageX = 0;
  35743. imageY = 0;
  35744. }
  35745. }
  35746. if (! scaleImageToFit)
  35747. {
  35748. imageW = iw;
  35749. imageH = ih;
  35750. }
  35751. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35752. isButtonDown ? downOverlay
  35753. : (isMouseOverButton ? overOverlay
  35754. : normalOverlay),
  35755. isButtonDown ? downOpacity
  35756. : (isMouseOverButton ? overOpacity
  35757. : normalOpacity),
  35758. *this);
  35759. }
  35760. }
  35761. bool ImageButton::hitTest (int x, int y)
  35762. {
  35763. if (alphaThreshold == 0)
  35764. return true;
  35765. Image im (getCurrentImage());
  35766. return im.isNull() || (imageW > 0 && imageH > 0
  35767. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35768. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35769. }
  35770. END_JUCE_NAMESPACE
  35771. /*** End of inlined file: juce_ImageButton.cpp ***/
  35772. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35773. BEGIN_JUCE_NAMESPACE
  35774. ShapeButton::ShapeButton (const String& text_,
  35775. const Colour& normalColour_,
  35776. const Colour& overColour_,
  35777. const Colour& downColour_)
  35778. : Button (text_),
  35779. normalColour (normalColour_),
  35780. overColour (overColour_),
  35781. downColour (downColour_),
  35782. maintainShapeProportions (false),
  35783. outlineWidth (0.0f)
  35784. {
  35785. }
  35786. ShapeButton::~ShapeButton()
  35787. {
  35788. }
  35789. void ShapeButton::setColours (const Colour& newNormalColour,
  35790. const Colour& newOverColour,
  35791. const Colour& newDownColour)
  35792. {
  35793. normalColour = newNormalColour;
  35794. overColour = newOverColour;
  35795. downColour = newDownColour;
  35796. }
  35797. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35798. const float newOutlineWidth)
  35799. {
  35800. outlineColour = newOutlineColour;
  35801. outlineWidth = newOutlineWidth;
  35802. }
  35803. void ShapeButton::setShape (const Path& newShape,
  35804. const bool resizeNowToFitThisShape,
  35805. const bool maintainShapeProportions_,
  35806. const bool hasShadow)
  35807. {
  35808. shape = newShape;
  35809. maintainShapeProportions = maintainShapeProportions_;
  35810. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35811. setComponentEffect ((hasShadow) ? &shadow : 0);
  35812. if (resizeNowToFitThisShape)
  35813. {
  35814. Rectangle<float> bounds (shape.getBounds());
  35815. if (hasShadow)
  35816. bounds.expand (4.0f, 4.0f);
  35817. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35818. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35819. 1 + (int) (bounds.getHeight() + outlineWidth));
  35820. }
  35821. }
  35822. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35823. {
  35824. if (! isEnabled())
  35825. {
  35826. isMouseOverButton = false;
  35827. isButtonDown = false;
  35828. }
  35829. g.setColour ((isButtonDown) ? downColour
  35830. : (isMouseOverButton) ? overColour
  35831. : normalColour);
  35832. int w = getWidth();
  35833. int h = getHeight();
  35834. if (getComponentEffect() != 0)
  35835. {
  35836. w -= 4;
  35837. h -= 4;
  35838. }
  35839. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35840. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35841. w - offset - outlineWidth,
  35842. h - offset - outlineWidth,
  35843. maintainShapeProportions));
  35844. g.fillPath (shape, trans);
  35845. if (outlineWidth > 0.0f)
  35846. {
  35847. g.setColour (outlineColour);
  35848. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35849. }
  35850. }
  35851. END_JUCE_NAMESPACE
  35852. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35853. /*** Start of inlined file: juce_TextButton.cpp ***/
  35854. BEGIN_JUCE_NAMESPACE
  35855. TextButton::TextButton (const String& name,
  35856. const String& toolTip)
  35857. : Button (name)
  35858. {
  35859. setTooltip (toolTip);
  35860. }
  35861. TextButton::~TextButton()
  35862. {
  35863. }
  35864. void TextButton::paintButton (Graphics& g,
  35865. bool isMouseOverButton,
  35866. bool isButtonDown)
  35867. {
  35868. getLookAndFeel().drawButtonBackground (g, *this,
  35869. findColour (getToggleState() ? buttonOnColourId
  35870. : buttonColourId),
  35871. isMouseOverButton,
  35872. isButtonDown);
  35873. getLookAndFeel().drawButtonText (g, *this,
  35874. isMouseOverButton,
  35875. isButtonDown);
  35876. }
  35877. void TextButton::colourChanged()
  35878. {
  35879. repaint();
  35880. }
  35881. const Font TextButton::getFont()
  35882. {
  35883. return Font (jmin (15.0f, getHeight() * 0.6f));
  35884. }
  35885. void TextButton::changeWidthToFitText (const int newHeight)
  35886. {
  35887. if (newHeight >= 0)
  35888. setSize (jmax (1, getWidth()), newHeight);
  35889. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35890. getHeight());
  35891. }
  35892. END_JUCE_NAMESPACE
  35893. /*** End of inlined file: juce_TextButton.cpp ***/
  35894. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35895. BEGIN_JUCE_NAMESPACE
  35896. ToggleButton::ToggleButton (const String& buttonText)
  35897. : Button (buttonText)
  35898. {
  35899. setClickingTogglesState (true);
  35900. }
  35901. ToggleButton::~ToggleButton()
  35902. {
  35903. }
  35904. void ToggleButton::paintButton (Graphics& g,
  35905. bool isMouseOverButton,
  35906. bool isButtonDown)
  35907. {
  35908. getLookAndFeel().drawToggleButton (g, *this,
  35909. isMouseOverButton,
  35910. isButtonDown);
  35911. }
  35912. void ToggleButton::changeWidthToFitText()
  35913. {
  35914. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35915. }
  35916. void ToggleButton::colourChanged()
  35917. {
  35918. repaint();
  35919. }
  35920. END_JUCE_NAMESPACE
  35921. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35922. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35923. BEGIN_JUCE_NAMESPACE
  35924. ToolbarButton::ToolbarButton (const int itemId_,
  35925. const String& buttonText,
  35926. Drawable* const normalImage_,
  35927. Drawable* const toggledOnImage_)
  35928. : ToolbarItemComponent (itemId_, buttonText, true),
  35929. normalImage (normalImage_),
  35930. toggledOnImage (toggledOnImage_)
  35931. {
  35932. jassert (normalImage_ != 0);
  35933. }
  35934. ToolbarButton::~ToolbarButton()
  35935. {
  35936. }
  35937. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  35938. bool /*isToolbarVertical*/,
  35939. int& preferredSize,
  35940. int& minSize, int& maxSize)
  35941. {
  35942. preferredSize = minSize = maxSize = toolbarDepth;
  35943. return true;
  35944. }
  35945. void ToolbarButton::paintButtonArea (Graphics& g,
  35946. int width, int height,
  35947. bool /*isMouseOver*/,
  35948. bool /*isMouseDown*/)
  35949. {
  35950. Drawable* d = normalImage;
  35951. if (getToggleState() && toggledOnImage != 0)
  35952. d = toggledOnImage;
  35953. if (! isEnabled())
  35954. {
  35955. Image im (Image::ARGB, width, height, true);
  35956. {
  35957. Graphics g2 (im);
  35958. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35959. }
  35960. im.desaturate();
  35961. g.drawImageAt (im, 0, 0);
  35962. }
  35963. else
  35964. {
  35965. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35966. }
  35967. }
  35968. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35969. {
  35970. }
  35971. END_JUCE_NAMESPACE
  35972. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35973. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35974. BEGIN_JUCE_NAMESPACE
  35975. class CodeDocumentLine
  35976. {
  35977. public:
  35978. CodeDocumentLine (const juce_wchar* const line_,
  35979. const int lineLength_,
  35980. const int numNewLineChars,
  35981. const int lineStartInFile_)
  35982. : line (line_, lineLength_),
  35983. lineStartInFile (lineStartInFile_),
  35984. lineLength (lineLength_),
  35985. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35986. {
  35987. }
  35988. ~CodeDocumentLine()
  35989. {
  35990. }
  35991. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35992. {
  35993. const juce_wchar* const t = text;
  35994. int pos = 0;
  35995. while (t [pos] != 0)
  35996. {
  35997. const int startOfLine = pos;
  35998. int numNewLineChars = 0;
  35999. while (t[pos] != 0)
  36000. {
  36001. if (t[pos] == '\r')
  36002. {
  36003. ++numNewLineChars;
  36004. ++pos;
  36005. if (t[pos] == '\n')
  36006. {
  36007. ++numNewLineChars;
  36008. ++pos;
  36009. }
  36010. break;
  36011. }
  36012. if (t[pos] == '\n')
  36013. {
  36014. ++numNewLineChars;
  36015. ++pos;
  36016. break;
  36017. }
  36018. ++pos;
  36019. }
  36020. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  36021. numNewLineChars, startOfLine));
  36022. }
  36023. jassert (pos == text.length());
  36024. }
  36025. bool endsWithLineBreak() const throw()
  36026. {
  36027. return lineLengthWithoutNewLines != lineLength;
  36028. }
  36029. void updateLength() throw()
  36030. {
  36031. lineLengthWithoutNewLines = lineLength = line.length();
  36032. while (lineLengthWithoutNewLines > 0
  36033. && (line [lineLengthWithoutNewLines - 1] == '\n'
  36034. || line [lineLengthWithoutNewLines - 1] == '\r'))
  36035. {
  36036. --lineLengthWithoutNewLines;
  36037. }
  36038. }
  36039. String line;
  36040. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  36041. };
  36042. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  36043. : document (document_),
  36044. currentLine (document_->lines[0]),
  36045. line (0),
  36046. position (0)
  36047. {
  36048. }
  36049. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  36050. : document (other.document),
  36051. currentLine (other.currentLine),
  36052. line (other.line),
  36053. position (other.position)
  36054. {
  36055. }
  36056. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  36057. {
  36058. document = other.document;
  36059. currentLine = other.currentLine;
  36060. line = other.line;
  36061. position = other.position;
  36062. return *this;
  36063. }
  36064. CodeDocument::Iterator::~Iterator() throw()
  36065. {
  36066. }
  36067. juce_wchar CodeDocument::Iterator::nextChar()
  36068. {
  36069. if (currentLine == 0)
  36070. return 0;
  36071. jassert (currentLine == document->lines.getUnchecked (line));
  36072. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  36073. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36074. {
  36075. ++line;
  36076. currentLine = document->lines [line];
  36077. }
  36078. return result;
  36079. }
  36080. void CodeDocument::Iterator::skip()
  36081. {
  36082. if (currentLine != 0)
  36083. {
  36084. jassert (currentLine == document->lines.getUnchecked (line));
  36085. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36086. {
  36087. ++line;
  36088. currentLine = document->lines [line];
  36089. }
  36090. }
  36091. }
  36092. void CodeDocument::Iterator::skipToEndOfLine()
  36093. {
  36094. if (currentLine != 0)
  36095. {
  36096. jassert (currentLine == document->lines.getUnchecked (line));
  36097. ++line;
  36098. currentLine = document->lines [line];
  36099. if (currentLine != 0)
  36100. position = currentLine->lineStartInFile;
  36101. else
  36102. position = document->getNumCharacters();
  36103. }
  36104. }
  36105. juce_wchar CodeDocument::Iterator::peekNextChar() const
  36106. {
  36107. if (currentLine == 0)
  36108. return 0;
  36109. jassert (currentLine == document->lines.getUnchecked (line));
  36110. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  36111. }
  36112. void CodeDocument::Iterator::skipWhitespace()
  36113. {
  36114. while (CharacterFunctions::isWhitespace (peekNextChar()))
  36115. skip();
  36116. }
  36117. bool CodeDocument::Iterator::isEOF() const throw()
  36118. {
  36119. return currentLine == 0;
  36120. }
  36121. CodeDocument::Position::Position() throw()
  36122. : owner (0), characterPos (0), line (0),
  36123. indexInLine (0), positionMaintained (false)
  36124. {
  36125. }
  36126. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36127. const int line_, const int indexInLine_) throw()
  36128. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36129. characterPos (0), line (line_),
  36130. indexInLine (indexInLine_), positionMaintained (false)
  36131. {
  36132. setLineAndIndex (line_, indexInLine_);
  36133. }
  36134. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36135. const int characterPos_) throw()
  36136. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36137. positionMaintained (false)
  36138. {
  36139. setPosition (characterPos_);
  36140. }
  36141. CodeDocument::Position::Position (const Position& other) throw()
  36142. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36143. indexInLine (other.indexInLine), positionMaintained (false)
  36144. {
  36145. jassert (*this == other);
  36146. }
  36147. CodeDocument::Position::~Position()
  36148. {
  36149. setPositionMaintained (false);
  36150. }
  36151. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36152. {
  36153. if (this != &other)
  36154. {
  36155. const bool wasPositionMaintained = positionMaintained;
  36156. if (owner != other.owner)
  36157. setPositionMaintained (false);
  36158. owner = other.owner;
  36159. line = other.line;
  36160. indexInLine = other.indexInLine;
  36161. characterPos = other.characterPos;
  36162. setPositionMaintained (wasPositionMaintained);
  36163. jassert (*this == other);
  36164. }
  36165. return *this;
  36166. }
  36167. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36168. {
  36169. jassert ((characterPos == other.characterPos)
  36170. == (line == other.line && indexInLine == other.indexInLine));
  36171. return characterPos == other.characterPos
  36172. && line == other.line
  36173. && indexInLine == other.indexInLine
  36174. && owner == other.owner;
  36175. }
  36176. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36177. {
  36178. return ! operator== (other);
  36179. }
  36180. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine)
  36181. {
  36182. jassert (owner != 0);
  36183. if (owner->lines.size() == 0)
  36184. {
  36185. line = 0;
  36186. indexInLine = 0;
  36187. characterPos = 0;
  36188. }
  36189. else
  36190. {
  36191. if (newLine >= owner->lines.size())
  36192. {
  36193. line = owner->lines.size() - 1;
  36194. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36195. jassert (l != 0);
  36196. indexInLine = l->lineLengthWithoutNewLines;
  36197. characterPos = l->lineStartInFile + indexInLine;
  36198. }
  36199. else
  36200. {
  36201. line = jmax (0, newLine);
  36202. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36203. jassert (l != 0);
  36204. if (l->lineLengthWithoutNewLines > 0)
  36205. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36206. else
  36207. indexInLine = 0;
  36208. characterPos = l->lineStartInFile + indexInLine;
  36209. }
  36210. }
  36211. }
  36212. void CodeDocument::Position::setPosition (const int newPosition)
  36213. {
  36214. jassert (owner != 0);
  36215. line = 0;
  36216. indexInLine = 0;
  36217. characterPos = 0;
  36218. if (newPosition > 0)
  36219. {
  36220. int lineStart = 0;
  36221. int lineEnd = owner->lines.size();
  36222. for (;;)
  36223. {
  36224. if (lineEnd - lineStart < 4)
  36225. {
  36226. for (int i = lineStart; i < lineEnd; ++i)
  36227. {
  36228. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36229. int index = newPosition - l->lineStartInFile;
  36230. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36231. {
  36232. line = i;
  36233. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36234. characterPos = l->lineStartInFile + indexInLine;
  36235. }
  36236. }
  36237. break;
  36238. }
  36239. else
  36240. {
  36241. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36242. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36243. if (newPosition >= mid->lineStartInFile)
  36244. lineStart = midIndex;
  36245. else
  36246. lineEnd = midIndex;
  36247. }
  36248. }
  36249. }
  36250. }
  36251. void CodeDocument::Position::moveBy (int characterDelta)
  36252. {
  36253. jassert (owner != 0);
  36254. if (characterDelta == 1)
  36255. {
  36256. setPosition (getPosition());
  36257. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36258. if (line < owner->lines.size())
  36259. {
  36260. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36261. if (indexInLine + characterDelta < l->lineLength
  36262. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36263. ++characterDelta;
  36264. }
  36265. }
  36266. setPosition (characterPos + characterDelta);
  36267. }
  36268. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36269. {
  36270. CodeDocument::Position p (*this);
  36271. p.moveBy (characterDelta);
  36272. return p;
  36273. }
  36274. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36275. {
  36276. CodeDocument::Position p (*this);
  36277. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36278. return p;
  36279. }
  36280. const juce_wchar CodeDocument::Position::getCharacter() const
  36281. {
  36282. const CodeDocumentLine* const l = owner->lines [line];
  36283. return l == 0 ? 0 : l->line [getIndexInLine()];
  36284. }
  36285. const String CodeDocument::Position::getLineText() const
  36286. {
  36287. const CodeDocumentLine* const l = owner->lines [line];
  36288. return l == 0 ? String::empty : l->line;
  36289. }
  36290. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36291. {
  36292. if (isMaintained != positionMaintained)
  36293. {
  36294. positionMaintained = isMaintained;
  36295. if (owner != 0)
  36296. {
  36297. if (isMaintained)
  36298. {
  36299. jassert (! owner->positionsToMaintain.contains (this));
  36300. owner->positionsToMaintain.add (this);
  36301. }
  36302. else
  36303. {
  36304. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36305. jassert (owner->positionsToMaintain.contains (this));
  36306. owner->positionsToMaintain.removeValue (this);
  36307. }
  36308. }
  36309. }
  36310. }
  36311. CodeDocument::CodeDocument()
  36312. : undoManager (std::numeric_limits<int>::max(), 10000),
  36313. currentActionIndex (0),
  36314. indexOfSavedState (-1),
  36315. maximumLineLength (-1),
  36316. newLineChars ("\r\n")
  36317. {
  36318. }
  36319. CodeDocument::~CodeDocument()
  36320. {
  36321. }
  36322. const String CodeDocument::getAllContent() const
  36323. {
  36324. return getTextBetween (Position (this, 0),
  36325. Position (this, lines.size(), 0));
  36326. }
  36327. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36328. {
  36329. if (end.getPosition() <= start.getPosition())
  36330. return String::empty;
  36331. const int startLine = start.getLineNumber();
  36332. const int endLine = end.getLineNumber();
  36333. if (startLine == endLine)
  36334. {
  36335. CodeDocumentLine* const line = lines [startLine];
  36336. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36337. }
  36338. String result;
  36339. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36340. String::Concatenator concatenator (result);
  36341. const int maxLine = jmin (lines.size() - 1, endLine);
  36342. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36343. {
  36344. const CodeDocumentLine* line = lines.getUnchecked(i);
  36345. int len = line->lineLength;
  36346. if (i == startLine)
  36347. {
  36348. const int index = start.getIndexInLine();
  36349. concatenator.append (line->line.substring (index, len));
  36350. }
  36351. else if (i == endLine)
  36352. {
  36353. len = end.getIndexInLine();
  36354. concatenator.append (line->line.substring (0, len));
  36355. }
  36356. else
  36357. {
  36358. concatenator.append (line->line);
  36359. }
  36360. }
  36361. return result;
  36362. }
  36363. int CodeDocument::getNumCharacters() const throw()
  36364. {
  36365. const CodeDocumentLine* const lastLine = lines.getLast();
  36366. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36367. }
  36368. const String CodeDocument::getLine (const int lineIndex) const throw()
  36369. {
  36370. const CodeDocumentLine* const line = lines [lineIndex];
  36371. return (line == 0) ? String::empty : line->line;
  36372. }
  36373. int CodeDocument::getMaximumLineLength() throw()
  36374. {
  36375. if (maximumLineLength < 0)
  36376. {
  36377. maximumLineLength = 0;
  36378. for (int i = lines.size(); --i >= 0;)
  36379. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36380. }
  36381. return maximumLineLength;
  36382. }
  36383. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36384. {
  36385. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36386. }
  36387. void CodeDocument::insertText (const Position& position, const String& text)
  36388. {
  36389. insert (text, position.getPosition(), true);
  36390. }
  36391. void CodeDocument::replaceAllContent (const String& newContent)
  36392. {
  36393. remove (0, getNumCharacters(), true);
  36394. insert (newContent, 0, true);
  36395. }
  36396. bool CodeDocument::loadFromStream (InputStream& stream)
  36397. {
  36398. replaceAllContent (stream.readEntireStreamAsString());
  36399. setSavePoint();
  36400. clearUndoHistory();
  36401. return true;
  36402. }
  36403. bool CodeDocument::writeToStream (OutputStream& stream)
  36404. {
  36405. for (int i = 0; i < lines.size(); ++i)
  36406. {
  36407. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36408. const char* utf8 = temp.toUTF8();
  36409. if (! stream.write (utf8, (int) strlen (utf8)))
  36410. return false;
  36411. }
  36412. return true;
  36413. }
  36414. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  36415. {
  36416. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  36417. newLineChars = newLine;
  36418. }
  36419. void CodeDocument::newTransaction()
  36420. {
  36421. undoManager.beginNewTransaction (String::empty);
  36422. }
  36423. void CodeDocument::undo()
  36424. {
  36425. newTransaction();
  36426. undoManager.undo();
  36427. }
  36428. void CodeDocument::redo()
  36429. {
  36430. undoManager.redo();
  36431. }
  36432. void CodeDocument::clearUndoHistory()
  36433. {
  36434. undoManager.clearUndoHistory();
  36435. }
  36436. void CodeDocument::setSavePoint() throw()
  36437. {
  36438. indexOfSavedState = currentActionIndex;
  36439. }
  36440. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36441. {
  36442. return currentActionIndex != indexOfSavedState;
  36443. }
  36444. static int getCodeCharacterCategory (const juce_wchar character) throw()
  36445. {
  36446. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36447. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36448. }
  36449. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36450. {
  36451. Position p (position);
  36452. const int maxDistance = 256;
  36453. int i = 0;
  36454. while (i < maxDistance
  36455. && CharacterFunctions::isWhitespace (p.getCharacter())
  36456. && (i == 0 || (p.getCharacter() != '\n'
  36457. && p.getCharacter() != '\r')))
  36458. {
  36459. ++i;
  36460. p.moveBy (1);
  36461. }
  36462. if (i == 0)
  36463. {
  36464. const int type = getCodeCharacterCategory (p.getCharacter());
  36465. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  36466. {
  36467. ++i;
  36468. p.moveBy (1);
  36469. }
  36470. while (i < maxDistance
  36471. && CharacterFunctions::isWhitespace (p.getCharacter())
  36472. && (i == 0 || (p.getCharacter() != '\n'
  36473. && p.getCharacter() != '\r')))
  36474. {
  36475. ++i;
  36476. p.moveBy (1);
  36477. }
  36478. }
  36479. return p;
  36480. }
  36481. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36482. {
  36483. Position p (position);
  36484. const int maxDistance = 256;
  36485. int i = 0;
  36486. bool stoppedAtLineStart = false;
  36487. while (i < maxDistance)
  36488. {
  36489. const juce_wchar c = p.movedBy (-1).getCharacter();
  36490. if (c == '\r' || c == '\n')
  36491. {
  36492. stoppedAtLineStart = true;
  36493. if (i > 0)
  36494. break;
  36495. }
  36496. if (! CharacterFunctions::isWhitespace (c))
  36497. break;
  36498. p.moveBy (-1);
  36499. ++i;
  36500. }
  36501. if (i < maxDistance && ! stoppedAtLineStart)
  36502. {
  36503. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  36504. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  36505. {
  36506. p.moveBy (-1);
  36507. ++i;
  36508. }
  36509. }
  36510. return p;
  36511. }
  36512. void CodeDocument::checkLastLineStatus()
  36513. {
  36514. while (lines.size() > 0
  36515. && lines.getLast()->lineLength == 0
  36516. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36517. {
  36518. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36519. lines.removeLast();
  36520. }
  36521. const CodeDocumentLine* const lastLine = lines.getLast();
  36522. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36523. {
  36524. // check that there's an empty line at the end if the preceding one ends in a newline..
  36525. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36526. }
  36527. }
  36528. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36529. {
  36530. listeners.add (listener);
  36531. }
  36532. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36533. {
  36534. listeners.remove (listener);
  36535. }
  36536. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36537. {
  36538. Position startPos (this, startLine, 0);
  36539. Position endPos (this, endLine, 0);
  36540. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36541. }
  36542. class CodeDocumentInsertAction : public UndoableAction
  36543. {
  36544. CodeDocument& owner;
  36545. const String text;
  36546. int insertPos;
  36547. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  36548. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  36549. public:
  36550. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36551. : owner (owner_),
  36552. text (text_),
  36553. insertPos (insertPos_)
  36554. {
  36555. }
  36556. ~CodeDocumentInsertAction() {}
  36557. bool perform()
  36558. {
  36559. owner.currentActionIndex++;
  36560. owner.insert (text, insertPos, false);
  36561. return true;
  36562. }
  36563. bool undo()
  36564. {
  36565. owner.currentActionIndex--;
  36566. owner.remove (insertPos, insertPos + text.length(), false);
  36567. return true;
  36568. }
  36569. int getSizeInUnits() { return text.length() + 32; }
  36570. };
  36571. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36572. {
  36573. if (text.isEmpty())
  36574. return;
  36575. if (undoable)
  36576. {
  36577. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36578. }
  36579. else
  36580. {
  36581. Position pos (this, insertPos);
  36582. const int firstAffectedLine = pos.getLineNumber();
  36583. int lastAffectedLine = firstAffectedLine + 1;
  36584. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36585. String textInsideOriginalLine (text);
  36586. if (firstLine != 0)
  36587. {
  36588. const int index = pos.getIndexInLine();
  36589. textInsideOriginalLine = firstLine->line.substring (0, index)
  36590. + textInsideOriginalLine
  36591. + firstLine->line.substring (index);
  36592. }
  36593. maximumLineLength = -1;
  36594. Array <CodeDocumentLine*> newLines;
  36595. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36596. jassert (newLines.size() > 0);
  36597. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36598. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36599. lines.set (firstAffectedLine, newFirstLine);
  36600. if (newLines.size() > 1)
  36601. {
  36602. for (int i = 1; i < newLines.size(); ++i)
  36603. {
  36604. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36605. lines.insert (firstAffectedLine + i, l);
  36606. }
  36607. lastAffectedLine = lines.size();
  36608. }
  36609. int i, lineStart = newFirstLine->lineStartInFile;
  36610. for (i = firstAffectedLine; i < lines.size(); ++i)
  36611. {
  36612. CodeDocumentLine* const l = lines.getUnchecked (i);
  36613. l->lineStartInFile = lineStart;
  36614. lineStart += l->lineLength;
  36615. }
  36616. checkLastLineStatus();
  36617. const int newTextLength = text.length();
  36618. for (i = 0; i < positionsToMaintain.size(); ++i)
  36619. {
  36620. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36621. if (p->getPosition() >= insertPos)
  36622. p->setPosition (p->getPosition() + newTextLength);
  36623. }
  36624. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36625. }
  36626. }
  36627. class CodeDocumentDeleteAction : public UndoableAction
  36628. {
  36629. CodeDocument& owner;
  36630. int startPos, endPos;
  36631. String removedText;
  36632. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  36633. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  36634. public:
  36635. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36636. : owner (owner_),
  36637. startPos (startPos_),
  36638. endPos (endPos_)
  36639. {
  36640. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36641. CodeDocument::Position (&owner, endPos));
  36642. }
  36643. ~CodeDocumentDeleteAction() {}
  36644. bool perform()
  36645. {
  36646. owner.currentActionIndex++;
  36647. owner.remove (startPos, endPos, false);
  36648. return true;
  36649. }
  36650. bool undo()
  36651. {
  36652. owner.currentActionIndex--;
  36653. owner.insert (removedText, startPos, false);
  36654. return true;
  36655. }
  36656. int getSizeInUnits() { return removedText.length() + 32; }
  36657. };
  36658. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36659. {
  36660. if (endPos <= startPos)
  36661. return;
  36662. if (undoable)
  36663. {
  36664. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36665. }
  36666. else
  36667. {
  36668. Position startPosition (this, startPos);
  36669. Position endPosition (this, endPos);
  36670. maximumLineLength = -1;
  36671. const int firstAffectedLine = startPosition.getLineNumber();
  36672. const int endLine = endPosition.getLineNumber();
  36673. int lastAffectedLine = firstAffectedLine + 1;
  36674. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36675. if (firstAffectedLine == endLine)
  36676. {
  36677. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36678. + firstLine->line.substring (endPosition.getIndexInLine());
  36679. firstLine->updateLength();
  36680. }
  36681. else
  36682. {
  36683. lastAffectedLine = lines.size();
  36684. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36685. jassert (lastLine != 0);
  36686. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36687. + lastLine->line.substring (endPosition.getIndexInLine());
  36688. firstLine->updateLength();
  36689. int numLinesToRemove = endLine - firstAffectedLine;
  36690. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36691. }
  36692. int i;
  36693. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36694. {
  36695. CodeDocumentLine* const l = lines.getUnchecked (i);
  36696. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36697. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36698. }
  36699. checkLastLineStatus();
  36700. const int totalChars = getNumCharacters();
  36701. for (i = 0; i < positionsToMaintain.size(); ++i)
  36702. {
  36703. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36704. if (p->getPosition() > startPosition.getPosition())
  36705. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36706. if (p->getPosition() > totalChars)
  36707. p->setPosition (totalChars);
  36708. }
  36709. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36710. }
  36711. }
  36712. END_JUCE_NAMESPACE
  36713. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36714. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36715. BEGIN_JUCE_NAMESPACE
  36716. class CodeEditorComponent::CaretComponent : public Component,
  36717. public Timer
  36718. {
  36719. public:
  36720. CaretComponent (CodeEditorComponent& owner_)
  36721. : owner (owner_)
  36722. {
  36723. setAlwaysOnTop (true);
  36724. setInterceptsMouseClicks (false, false);
  36725. }
  36726. ~CaretComponent()
  36727. {
  36728. }
  36729. void paint (Graphics& g)
  36730. {
  36731. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36732. }
  36733. void timerCallback()
  36734. {
  36735. setVisible (shouldBeShown() && ! isVisible());
  36736. }
  36737. void updatePosition()
  36738. {
  36739. startTimer (400);
  36740. setVisible (shouldBeShown());
  36741. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36742. }
  36743. private:
  36744. CodeEditorComponent& owner;
  36745. CaretComponent (const CaretComponent&);
  36746. CaretComponent& operator= (const CaretComponent&);
  36747. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36748. };
  36749. class CodeEditorComponent::CodeEditorLine
  36750. {
  36751. public:
  36752. CodeEditorLine() throw()
  36753. : highlightColumnStart (0), highlightColumnEnd (0)
  36754. {
  36755. }
  36756. ~CodeEditorLine() throw()
  36757. {
  36758. }
  36759. bool update (CodeDocument& document, int lineNum,
  36760. CodeDocument::Iterator& source,
  36761. CodeTokeniser* analyser, const int spacesPerTab,
  36762. const CodeDocument::Position& selectionStart,
  36763. const CodeDocument::Position& selectionEnd)
  36764. {
  36765. Array <SyntaxToken> newTokens;
  36766. newTokens.ensureStorageAllocated (8);
  36767. if (analyser == 0)
  36768. {
  36769. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36770. }
  36771. else if (lineNum < document.getNumLines())
  36772. {
  36773. const CodeDocument::Position pos (&document, lineNum, 0);
  36774. createTokens (pos.getPosition(), pos.getLineText(),
  36775. source, analyser, newTokens);
  36776. }
  36777. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36778. int newHighlightStart = 0;
  36779. int newHighlightEnd = 0;
  36780. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36781. {
  36782. const String line (document.getLine (lineNum));
  36783. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36784. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36785. line, spacesPerTab);
  36786. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36787. line, spacesPerTab);
  36788. }
  36789. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36790. {
  36791. highlightColumnStart = newHighlightStart;
  36792. highlightColumnEnd = newHighlightEnd;
  36793. }
  36794. else
  36795. {
  36796. if (tokens.size() == newTokens.size())
  36797. {
  36798. bool allTheSame = true;
  36799. for (int i = newTokens.size(); --i >= 0;)
  36800. {
  36801. if (tokens.getReference(i) != newTokens.getReference(i))
  36802. {
  36803. allTheSame = false;
  36804. break;
  36805. }
  36806. }
  36807. if (allTheSame)
  36808. return false;
  36809. }
  36810. }
  36811. tokens.swapWithArray (newTokens);
  36812. return true;
  36813. }
  36814. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36815. float x, const int y, const int baselineOffset, const int lineHeight,
  36816. const Colour& highlightColour) const
  36817. {
  36818. if (highlightColumnStart < highlightColumnEnd)
  36819. {
  36820. g.setColour (highlightColour);
  36821. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36822. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36823. }
  36824. int lastType = std::numeric_limits<int>::min();
  36825. for (int i = 0; i < tokens.size(); ++i)
  36826. {
  36827. SyntaxToken& token = tokens.getReference(i);
  36828. if (lastType != token.tokenType)
  36829. {
  36830. lastType = token.tokenType;
  36831. g.setColour (owner.getColourForTokenType (lastType));
  36832. }
  36833. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36834. if (i < tokens.size() - 1)
  36835. {
  36836. if (token.width < 0)
  36837. token.width = font.getStringWidthFloat (token.text);
  36838. x += token.width;
  36839. }
  36840. }
  36841. }
  36842. private:
  36843. struct SyntaxToken
  36844. {
  36845. String text;
  36846. int tokenType;
  36847. float width;
  36848. SyntaxToken (const String& text_, const int type) throw()
  36849. : text (text_), tokenType (type), width (-1.0f)
  36850. {
  36851. }
  36852. bool operator!= (const SyntaxToken& other) const throw()
  36853. {
  36854. return text != other.text || tokenType != other.tokenType;
  36855. }
  36856. };
  36857. Array <SyntaxToken> tokens;
  36858. int highlightColumnStart, highlightColumnEnd;
  36859. static void createTokens (int startPosition, const String& lineText,
  36860. CodeDocument::Iterator& source,
  36861. CodeTokeniser* analyser,
  36862. Array <SyntaxToken>& newTokens)
  36863. {
  36864. CodeDocument::Iterator lastIterator (source);
  36865. const int lineLength = lineText.length();
  36866. for (;;)
  36867. {
  36868. int tokenType = analyser->readNextToken (source);
  36869. int tokenStart = lastIterator.getPosition();
  36870. int tokenEnd = source.getPosition();
  36871. if (tokenEnd <= tokenStart)
  36872. break;
  36873. tokenEnd -= startPosition;
  36874. if (tokenEnd > 0)
  36875. {
  36876. tokenStart -= startPosition;
  36877. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36878. tokenType));
  36879. if (tokenEnd >= lineLength)
  36880. break;
  36881. }
  36882. lastIterator = source;
  36883. }
  36884. source = lastIterator;
  36885. }
  36886. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36887. {
  36888. int x = 0;
  36889. for (int i = 0; i < tokens.size(); ++i)
  36890. {
  36891. SyntaxToken& t = tokens.getReference(i);
  36892. for (;;)
  36893. {
  36894. int tabPos = t.text.indexOfChar ('\t');
  36895. if (tabPos < 0)
  36896. break;
  36897. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36898. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36899. }
  36900. x += t.text.length();
  36901. }
  36902. }
  36903. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36904. {
  36905. jassert (index <= line.length());
  36906. int col = 0;
  36907. for (int i = 0; i < index; ++i)
  36908. {
  36909. if (line[i] != '\t')
  36910. ++col;
  36911. else
  36912. col += spacesPerTab - (col % spacesPerTab);
  36913. }
  36914. return col;
  36915. }
  36916. };
  36917. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36918. CodeTokeniser* const codeTokeniser_)
  36919. : document (document_),
  36920. firstLineOnScreen (0),
  36921. gutter (5),
  36922. spacesPerTab (4),
  36923. lineHeight (0),
  36924. linesOnScreen (0),
  36925. columnsOnScreen (0),
  36926. scrollbarThickness (16),
  36927. columnToTryToMaintain (-1),
  36928. useSpacesForTabs (false),
  36929. xOffset (0),
  36930. codeTokeniser (codeTokeniser_)
  36931. {
  36932. caretPos = CodeDocument::Position (&document_, 0, 0);
  36933. caretPos.setPositionMaintained (true);
  36934. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36935. selectionStart.setPositionMaintained (true);
  36936. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36937. selectionEnd.setPositionMaintained (true);
  36938. setOpaque (true);
  36939. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36940. setWantsKeyboardFocus (true);
  36941. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  36942. verticalScrollBar->setSingleStepSize (1.0);
  36943. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  36944. horizontalScrollBar->setSingleStepSize (1.0);
  36945. addAndMakeVisible (caret = new CaretComponent (*this));
  36946. Font f (12.0f);
  36947. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36948. setFont (f);
  36949. resetToDefaultColours();
  36950. verticalScrollBar->addListener (this);
  36951. horizontalScrollBar->addListener (this);
  36952. document.addListener (this);
  36953. }
  36954. CodeEditorComponent::~CodeEditorComponent()
  36955. {
  36956. document.removeListener (this);
  36957. deleteAllChildren();
  36958. }
  36959. void CodeEditorComponent::loadContent (const String& newContent)
  36960. {
  36961. clearCachedIterators (0);
  36962. document.replaceAllContent (newContent);
  36963. document.clearUndoHistory();
  36964. document.setSavePoint();
  36965. caretPos.setPosition (0);
  36966. selectionStart.setPosition (0);
  36967. selectionEnd.setPosition (0);
  36968. scrollToLine (0);
  36969. }
  36970. bool CodeEditorComponent::isTextInputActive() const
  36971. {
  36972. return true;
  36973. }
  36974. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36975. const CodeDocument::Position& affectedTextEnd)
  36976. {
  36977. clearCachedIterators (affectedTextStart.getLineNumber());
  36978. triggerAsyncUpdate();
  36979. caret->updatePosition();
  36980. columnToTryToMaintain = -1;
  36981. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36982. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36983. deselectAll();
  36984. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36985. || caretPos.getPosition() < affectedTextStart.getPosition())
  36986. moveCaretTo (affectedTextStart, false);
  36987. updateScrollBars();
  36988. }
  36989. void CodeEditorComponent::resized()
  36990. {
  36991. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36992. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36993. lines.clear();
  36994. rebuildLineTokens();
  36995. caret->updatePosition();
  36996. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36997. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36998. updateScrollBars();
  36999. }
  37000. void CodeEditorComponent::paint (Graphics& g)
  37001. {
  37002. handleUpdateNowIfNeeded();
  37003. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  37004. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  37005. g.setFont (font);
  37006. const int baselineOffset = (int) font.getAscent();
  37007. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  37008. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  37009. const Rectangle<int> clip (g.getClipBounds());
  37010. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  37011. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  37012. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  37013. {
  37014. lines.getUnchecked(j)->draw (*this, g, font,
  37015. (float) (gutter - xOffset * charWidth),
  37016. lineHeight * j, baselineOffset, lineHeight,
  37017. highlightColour);
  37018. }
  37019. }
  37020. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  37021. {
  37022. if (scrollbarThickness != thickness)
  37023. {
  37024. scrollbarThickness = thickness;
  37025. resized();
  37026. }
  37027. }
  37028. void CodeEditorComponent::handleAsyncUpdate()
  37029. {
  37030. rebuildLineTokens();
  37031. }
  37032. void CodeEditorComponent::rebuildLineTokens()
  37033. {
  37034. cancelPendingUpdate();
  37035. const int numNeeded = linesOnScreen + 1;
  37036. int minLineToRepaint = numNeeded;
  37037. int maxLineToRepaint = 0;
  37038. if (numNeeded != lines.size())
  37039. {
  37040. lines.clear();
  37041. for (int i = numNeeded; --i >= 0;)
  37042. lines.add (new CodeEditorLine());
  37043. minLineToRepaint = 0;
  37044. maxLineToRepaint = numNeeded;
  37045. }
  37046. jassert (numNeeded == lines.size());
  37047. CodeDocument::Iterator source (&document);
  37048. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  37049. for (int i = 0; i < numNeeded; ++i)
  37050. {
  37051. CodeEditorLine* const line = lines.getUnchecked(i);
  37052. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  37053. selectionStart, selectionEnd))
  37054. {
  37055. minLineToRepaint = jmin (minLineToRepaint, i);
  37056. maxLineToRepaint = jmax (maxLineToRepaint, i);
  37057. }
  37058. }
  37059. if (minLineToRepaint <= maxLineToRepaint)
  37060. {
  37061. repaint (gutter, lineHeight * minLineToRepaint - 1,
  37062. verticalScrollBar->getX() - gutter,
  37063. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  37064. }
  37065. }
  37066. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  37067. {
  37068. caretPos = newPos;
  37069. columnToTryToMaintain = -1;
  37070. if (highlighting)
  37071. {
  37072. if (dragType == notDragging)
  37073. {
  37074. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  37075. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  37076. dragType = draggingSelectionStart;
  37077. else
  37078. dragType = draggingSelectionEnd;
  37079. }
  37080. if (dragType == draggingSelectionStart)
  37081. {
  37082. selectionStart = caretPos;
  37083. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37084. {
  37085. const CodeDocument::Position temp (selectionStart);
  37086. selectionStart = selectionEnd;
  37087. selectionEnd = temp;
  37088. dragType = draggingSelectionEnd;
  37089. }
  37090. }
  37091. else
  37092. {
  37093. selectionEnd = caretPos;
  37094. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37095. {
  37096. const CodeDocument::Position temp (selectionStart);
  37097. selectionStart = selectionEnd;
  37098. selectionEnd = temp;
  37099. dragType = draggingSelectionStart;
  37100. }
  37101. }
  37102. triggerAsyncUpdate();
  37103. }
  37104. else
  37105. {
  37106. deselectAll();
  37107. }
  37108. caret->updatePosition();
  37109. scrollToKeepCaretOnScreen();
  37110. updateScrollBars();
  37111. }
  37112. void CodeEditorComponent::deselectAll()
  37113. {
  37114. if (selectionStart != selectionEnd)
  37115. triggerAsyncUpdate();
  37116. selectionStart = caretPos;
  37117. selectionEnd = caretPos;
  37118. }
  37119. void CodeEditorComponent::updateScrollBars()
  37120. {
  37121. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  37122. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  37123. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  37124. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  37125. }
  37126. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  37127. {
  37128. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  37129. newFirstLineOnScreen);
  37130. if (newFirstLineOnScreen != firstLineOnScreen)
  37131. {
  37132. firstLineOnScreen = newFirstLineOnScreen;
  37133. caret->updatePosition();
  37134. updateCachedIterators (firstLineOnScreen);
  37135. triggerAsyncUpdate();
  37136. }
  37137. }
  37138. void CodeEditorComponent::scrollToColumnInternal (double column)
  37139. {
  37140. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37141. if (xOffset != newOffset)
  37142. {
  37143. xOffset = newOffset;
  37144. caret->updatePosition();
  37145. repaint();
  37146. }
  37147. }
  37148. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37149. {
  37150. scrollToLineInternal (newFirstLineOnScreen);
  37151. updateScrollBars();
  37152. }
  37153. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37154. {
  37155. scrollToColumnInternal (newFirstColumnOnScreen);
  37156. updateScrollBars();
  37157. }
  37158. void CodeEditorComponent::scrollBy (int deltaLines)
  37159. {
  37160. scrollToLine (firstLineOnScreen + deltaLines);
  37161. }
  37162. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37163. {
  37164. if (caretPos.getLineNumber() < firstLineOnScreen)
  37165. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37166. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37167. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37168. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37169. if (column >= xOffset + columnsOnScreen - 1)
  37170. scrollToColumn (column + 1 - columnsOnScreen);
  37171. else if (column < xOffset)
  37172. scrollToColumn (column);
  37173. }
  37174. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37175. {
  37176. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37177. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37178. roundToInt (charWidth),
  37179. lineHeight);
  37180. }
  37181. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37182. {
  37183. const int line = y / lineHeight + firstLineOnScreen;
  37184. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37185. const int index = columnToIndex (line, column);
  37186. return CodeDocument::Position (&document, line, index);
  37187. }
  37188. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37189. {
  37190. document.deleteSection (selectionStart, selectionEnd);
  37191. if (newText.isNotEmpty())
  37192. document.insertText (caretPos, newText);
  37193. scrollToKeepCaretOnScreen();
  37194. }
  37195. void CodeEditorComponent::insertTabAtCaret()
  37196. {
  37197. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37198. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37199. {
  37200. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37201. }
  37202. if (useSpacesForTabs)
  37203. {
  37204. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37205. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37206. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37207. }
  37208. else
  37209. {
  37210. insertTextAtCaret ("\t");
  37211. }
  37212. }
  37213. void CodeEditorComponent::cut()
  37214. {
  37215. insertTextAtCaret (String::empty);
  37216. }
  37217. void CodeEditorComponent::copy()
  37218. {
  37219. newTransaction();
  37220. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37221. if (selection.isNotEmpty())
  37222. SystemClipboard::copyTextToClipboard (selection);
  37223. }
  37224. void CodeEditorComponent::copyThenCut()
  37225. {
  37226. copy();
  37227. cut();
  37228. newTransaction();
  37229. }
  37230. void CodeEditorComponent::paste()
  37231. {
  37232. newTransaction();
  37233. const String clip (SystemClipboard::getTextFromClipboard());
  37234. if (clip.isNotEmpty())
  37235. insertTextAtCaret (clip);
  37236. newTransaction();
  37237. }
  37238. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37239. {
  37240. newTransaction();
  37241. if (moveInWholeWordSteps)
  37242. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37243. else
  37244. moveCaretTo (caretPos.movedBy (-1), selecting);
  37245. }
  37246. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37247. {
  37248. newTransaction();
  37249. if (moveInWholeWordSteps)
  37250. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37251. else
  37252. moveCaretTo (caretPos.movedBy (1), selecting);
  37253. }
  37254. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37255. {
  37256. CodeDocument::Position pos (caretPos);
  37257. const int newLineNum = pos.getLineNumber() + delta;
  37258. if (columnToTryToMaintain < 0)
  37259. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37260. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37261. const int colToMaintain = columnToTryToMaintain;
  37262. moveCaretTo (pos, selecting);
  37263. columnToTryToMaintain = colToMaintain;
  37264. }
  37265. void CodeEditorComponent::cursorDown (const bool selecting)
  37266. {
  37267. newTransaction();
  37268. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37269. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37270. else
  37271. moveLineDelta (1, selecting);
  37272. }
  37273. void CodeEditorComponent::cursorUp (const bool selecting)
  37274. {
  37275. newTransaction();
  37276. if (caretPos.getLineNumber() == 0)
  37277. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37278. else
  37279. moveLineDelta (-1, selecting);
  37280. }
  37281. void CodeEditorComponent::pageDown (const bool selecting)
  37282. {
  37283. newTransaction();
  37284. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37285. moveLineDelta (linesOnScreen, selecting);
  37286. }
  37287. void CodeEditorComponent::pageUp (const bool selecting)
  37288. {
  37289. newTransaction();
  37290. scrollBy (-linesOnScreen);
  37291. moveLineDelta (-linesOnScreen, selecting);
  37292. }
  37293. void CodeEditorComponent::scrollUp()
  37294. {
  37295. newTransaction();
  37296. scrollBy (1);
  37297. if (caretPos.getLineNumber() < firstLineOnScreen)
  37298. moveLineDelta (1, false);
  37299. }
  37300. void CodeEditorComponent::scrollDown()
  37301. {
  37302. newTransaction();
  37303. scrollBy (-1);
  37304. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37305. moveLineDelta (-1, false);
  37306. }
  37307. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37308. {
  37309. newTransaction();
  37310. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37311. }
  37312. static int findFirstNonWhitespaceChar (const String& line) throw()
  37313. {
  37314. const int len = line.length();
  37315. for (int i = 0; i < len; ++i)
  37316. if (! CharacterFunctions::isWhitespace (line [i]))
  37317. return i;
  37318. return 0;
  37319. }
  37320. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37321. {
  37322. newTransaction();
  37323. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  37324. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37325. index = 0;
  37326. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37327. }
  37328. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37329. {
  37330. newTransaction();
  37331. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37332. }
  37333. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37334. {
  37335. newTransaction();
  37336. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37337. }
  37338. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37339. {
  37340. if (moveInWholeWordSteps)
  37341. {
  37342. cut(); // in case something is already highlighted
  37343. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37344. }
  37345. else
  37346. {
  37347. if (selectionStart == selectionEnd)
  37348. selectionStart.moveBy (-1);
  37349. }
  37350. cut();
  37351. }
  37352. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37353. {
  37354. if (moveInWholeWordSteps)
  37355. {
  37356. cut(); // in case something is already highlighted
  37357. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37358. }
  37359. else
  37360. {
  37361. if (selectionStart == selectionEnd)
  37362. selectionEnd.moveBy (1);
  37363. else
  37364. newTransaction();
  37365. }
  37366. cut();
  37367. }
  37368. void CodeEditorComponent::selectAll()
  37369. {
  37370. newTransaction();
  37371. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37372. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37373. }
  37374. void CodeEditorComponent::undo()
  37375. {
  37376. document.undo();
  37377. scrollToKeepCaretOnScreen();
  37378. }
  37379. void CodeEditorComponent::redo()
  37380. {
  37381. document.redo();
  37382. scrollToKeepCaretOnScreen();
  37383. }
  37384. void CodeEditorComponent::newTransaction()
  37385. {
  37386. document.newTransaction();
  37387. startTimer (600);
  37388. }
  37389. void CodeEditorComponent::timerCallback()
  37390. {
  37391. newTransaction();
  37392. }
  37393. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37394. {
  37395. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37396. }
  37397. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37398. {
  37399. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37400. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37401. }
  37402. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37403. {
  37404. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37405. CodeDocument::Position (&document, range.getEnd()));
  37406. }
  37407. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37408. {
  37409. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37410. const bool shiftDown = key.getModifiers().isShiftDown();
  37411. if (key.isKeyCode (KeyPress::leftKey))
  37412. {
  37413. cursorLeft (moveInWholeWordSteps, shiftDown);
  37414. }
  37415. else if (key.isKeyCode (KeyPress::rightKey))
  37416. {
  37417. cursorRight (moveInWholeWordSteps, shiftDown);
  37418. }
  37419. else if (key.isKeyCode (KeyPress::upKey))
  37420. {
  37421. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37422. scrollDown();
  37423. #if JUCE_MAC
  37424. else if (key.getModifiers().isCommandDown())
  37425. goToStartOfDocument (shiftDown);
  37426. #endif
  37427. else
  37428. cursorUp (shiftDown);
  37429. }
  37430. else if (key.isKeyCode (KeyPress::downKey))
  37431. {
  37432. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37433. scrollUp();
  37434. #if JUCE_MAC
  37435. else if (key.getModifiers().isCommandDown())
  37436. goToEndOfDocument (shiftDown);
  37437. #endif
  37438. else
  37439. cursorDown (shiftDown);
  37440. }
  37441. else if (key.isKeyCode (KeyPress::pageDownKey))
  37442. {
  37443. pageDown (shiftDown);
  37444. }
  37445. else if (key.isKeyCode (KeyPress::pageUpKey))
  37446. {
  37447. pageUp (shiftDown);
  37448. }
  37449. else if (key.isKeyCode (KeyPress::homeKey))
  37450. {
  37451. if (moveInWholeWordSteps)
  37452. goToStartOfDocument (shiftDown);
  37453. else
  37454. goToStartOfLine (shiftDown);
  37455. }
  37456. else if (key.isKeyCode (KeyPress::endKey))
  37457. {
  37458. if (moveInWholeWordSteps)
  37459. goToEndOfDocument (shiftDown);
  37460. else
  37461. goToEndOfLine (shiftDown);
  37462. }
  37463. else if (key.isKeyCode (KeyPress::backspaceKey))
  37464. {
  37465. backspace (moveInWholeWordSteps);
  37466. }
  37467. else if (key.isKeyCode (KeyPress::deleteKey))
  37468. {
  37469. deleteForward (moveInWholeWordSteps);
  37470. }
  37471. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37472. {
  37473. copy();
  37474. }
  37475. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37476. {
  37477. copyThenCut();
  37478. }
  37479. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37480. {
  37481. paste();
  37482. }
  37483. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37484. {
  37485. undo();
  37486. }
  37487. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37488. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37489. {
  37490. redo();
  37491. }
  37492. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37493. {
  37494. selectAll();
  37495. }
  37496. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37497. {
  37498. insertTabAtCaret();
  37499. }
  37500. else if (key == KeyPress::returnKey)
  37501. {
  37502. newTransaction();
  37503. insertTextAtCaret (document.getNewLineCharacters());
  37504. }
  37505. else if (key.isKeyCode (KeyPress::escapeKey))
  37506. {
  37507. newTransaction();
  37508. }
  37509. else if (key.getTextCharacter() >= ' ')
  37510. {
  37511. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37512. }
  37513. else
  37514. {
  37515. return false;
  37516. }
  37517. return true;
  37518. }
  37519. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37520. {
  37521. newTransaction();
  37522. dragType = notDragging;
  37523. if (! e.mods.isPopupMenu())
  37524. {
  37525. beginDragAutoRepeat (100);
  37526. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37527. }
  37528. else
  37529. {
  37530. /*PopupMenu m;
  37531. addPopupMenuItems (m, &e);
  37532. const int result = m.show();
  37533. if (result != 0)
  37534. performPopupMenuAction (result);
  37535. */
  37536. }
  37537. }
  37538. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37539. {
  37540. if (! e.mods.isPopupMenu())
  37541. moveCaretTo (getPositionAt (e.x, e.y), true);
  37542. }
  37543. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37544. {
  37545. newTransaction();
  37546. beginDragAutoRepeat (0);
  37547. dragType = notDragging;
  37548. }
  37549. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37550. {
  37551. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37552. CodeDocument::Position tokenEnd (tokenStart);
  37553. if (e.getNumberOfClicks() > 2)
  37554. {
  37555. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37556. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37557. }
  37558. else
  37559. {
  37560. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37561. tokenEnd.moveBy (1);
  37562. tokenStart = tokenEnd;
  37563. while (tokenStart.getIndexInLine() > 0
  37564. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37565. tokenStart.moveBy (-1);
  37566. }
  37567. moveCaretTo (tokenEnd, false);
  37568. moveCaretTo (tokenStart, true);
  37569. }
  37570. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37571. {
  37572. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  37573. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  37574. {
  37575. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  37576. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  37577. }
  37578. else
  37579. {
  37580. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37581. }
  37582. }
  37583. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37584. {
  37585. if (scrollBarThatHasMoved == verticalScrollBar)
  37586. scrollToLineInternal ((int) newRangeStart);
  37587. else
  37588. scrollToColumnInternal (newRangeStart);
  37589. }
  37590. void CodeEditorComponent::focusGained (FocusChangeType)
  37591. {
  37592. caret->updatePosition();
  37593. }
  37594. void CodeEditorComponent::focusLost (FocusChangeType)
  37595. {
  37596. caret->updatePosition();
  37597. }
  37598. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37599. {
  37600. useSpacesForTabs = insertSpaces;
  37601. if (spacesPerTab != numSpaces)
  37602. {
  37603. spacesPerTab = numSpaces;
  37604. triggerAsyncUpdate();
  37605. }
  37606. }
  37607. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37608. {
  37609. const String line (document.getLine (lineNum));
  37610. jassert (index <= line.length());
  37611. int col = 0;
  37612. for (int i = 0; i < index; ++i)
  37613. {
  37614. if (line[i] != '\t')
  37615. ++col;
  37616. else
  37617. col += getTabSize() - (col % getTabSize());
  37618. }
  37619. return col;
  37620. }
  37621. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37622. {
  37623. const String line (document.getLine (lineNum));
  37624. const int lineLength = line.length();
  37625. int i, col = 0;
  37626. for (i = 0; i < lineLength; ++i)
  37627. {
  37628. if (line[i] != '\t')
  37629. ++col;
  37630. else
  37631. col += getTabSize() - (col % getTabSize());
  37632. if (col > column)
  37633. break;
  37634. }
  37635. return i;
  37636. }
  37637. void CodeEditorComponent::setFont (const Font& newFont)
  37638. {
  37639. font = newFont;
  37640. charWidth = font.getStringWidthFloat ("0");
  37641. lineHeight = roundToInt (font.getHeight());
  37642. resized();
  37643. }
  37644. void CodeEditorComponent::resetToDefaultColours()
  37645. {
  37646. coloursForTokenCategories.clear();
  37647. if (codeTokeniser != 0)
  37648. {
  37649. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37650. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37651. }
  37652. }
  37653. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37654. {
  37655. jassert (tokenType < 256);
  37656. while (coloursForTokenCategories.size() < tokenType)
  37657. coloursForTokenCategories.add (Colours::black);
  37658. coloursForTokenCategories.set (tokenType, colour);
  37659. repaint();
  37660. }
  37661. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37662. {
  37663. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  37664. return findColour (CodeEditorComponent::defaultTextColourId);
  37665. return coloursForTokenCategories.getReference (tokenType);
  37666. }
  37667. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37668. {
  37669. int i;
  37670. for (i = cachedIterators.size(); --i >= 0;)
  37671. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37672. break;
  37673. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37674. }
  37675. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37676. {
  37677. const int maxNumCachedPositions = 5000;
  37678. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37679. if (cachedIterators.size() == 0)
  37680. cachedIterators.add (new CodeDocument::Iterator (&document));
  37681. if (codeTokeniser == 0)
  37682. return;
  37683. for (;;)
  37684. {
  37685. CodeDocument::Iterator* last = cachedIterators.getLast();
  37686. if (last->getLine() >= maxLineNum)
  37687. break;
  37688. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37689. cachedIterators.add (t);
  37690. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37691. for (;;)
  37692. {
  37693. codeTokeniser->readNextToken (*t);
  37694. if (t->getLine() >= targetLine)
  37695. break;
  37696. if (t->isEOF())
  37697. return;
  37698. }
  37699. }
  37700. }
  37701. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37702. {
  37703. if (codeTokeniser == 0)
  37704. return;
  37705. for (int i = cachedIterators.size(); --i >= 0;)
  37706. {
  37707. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37708. if (t->getPosition() <= position)
  37709. {
  37710. source = *t;
  37711. break;
  37712. }
  37713. }
  37714. while (source.getPosition() < position)
  37715. {
  37716. const CodeDocument::Iterator original (source);
  37717. codeTokeniser->readNextToken (source);
  37718. if (source.getPosition() > position || source.isEOF())
  37719. {
  37720. source = original;
  37721. break;
  37722. }
  37723. }
  37724. }
  37725. END_JUCE_NAMESPACE
  37726. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37727. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37728. BEGIN_JUCE_NAMESPACE
  37729. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37730. {
  37731. }
  37732. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37733. {
  37734. }
  37735. namespace CppTokeniser
  37736. {
  37737. static bool isIdentifierStart (const juce_wchar c) throw()
  37738. {
  37739. return CharacterFunctions::isLetter (c)
  37740. || c == '_' || c == '@';
  37741. }
  37742. static bool isIdentifierBody (const juce_wchar c) throw()
  37743. {
  37744. return CharacterFunctions::isLetterOrDigit (c)
  37745. || c == '_' || c == '@';
  37746. }
  37747. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37748. {
  37749. static const juce_wchar* const keywords2Char[] =
  37750. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37751. static const juce_wchar* const keywords3Char[] =
  37752. { 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 };
  37753. static const juce_wchar* const keywords4Char[] =
  37754. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37755. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37756. static const juce_wchar* const keywords5Char[] =
  37757. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37758. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37759. static const juce_wchar* const keywords6Char[] =
  37760. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37761. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37762. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37763. static const juce_wchar* const keywordsOther[] =
  37764. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37765. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37766. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37767. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37768. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37769. const juce_wchar* const* k;
  37770. switch (tokenLength)
  37771. {
  37772. case 2: k = keywords2Char; break;
  37773. case 3: k = keywords3Char; break;
  37774. case 4: k = keywords4Char; break;
  37775. case 5: k = keywords5Char; break;
  37776. case 6: k = keywords6Char; break;
  37777. default:
  37778. if (tokenLength < 2 || tokenLength > 16)
  37779. return false;
  37780. k = keywordsOther;
  37781. break;
  37782. }
  37783. int i = 0;
  37784. while (k[i] != 0)
  37785. {
  37786. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37787. return true;
  37788. ++i;
  37789. }
  37790. return false;
  37791. }
  37792. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  37793. {
  37794. int tokenLength = 0;
  37795. juce_wchar possibleIdentifier [19];
  37796. while (isIdentifierBody (source.peekNextChar()))
  37797. {
  37798. const juce_wchar c = source.nextChar();
  37799. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37800. possibleIdentifier [tokenLength] = c;
  37801. ++tokenLength;
  37802. }
  37803. if (tokenLength > 1 && tokenLength <= 16)
  37804. {
  37805. possibleIdentifier [tokenLength] = 0;
  37806. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37807. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37808. }
  37809. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37810. }
  37811. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  37812. {
  37813. const juce_wchar c = source.peekNextChar();
  37814. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37815. source.skip();
  37816. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37817. return false;
  37818. return true;
  37819. }
  37820. static bool isHexDigit (const juce_wchar c) throw()
  37821. {
  37822. return (c >= '0' && c <= '9')
  37823. || (c >= 'a' && c <= 'f')
  37824. || (c >= 'A' && c <= 'F');
  37825. }
  37826. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37827. {
  37828. if (source.nextChar() != '0')
  37829. return false;
  37830. juce_wchar c = source.nextChar();
  37831. if (c != 'x' && c != 'X')
  37832. return false;
  37833. int numDigits = 0;
  37834. while (isHexDigit (source.peekNextChar()))
  37835. {
  37836. ++numDigits;
  37837. source.skip();
  37838. }
  37839. if (numDigits == 0)
  37840. return false;
  37841. return skipNumberSuffix (source);
  37842. }
  37843. static bool isOctalDigit (const juce_wchar c) throw()
  37844. {
  37845. return c >= '0' && c <= '7';
  37846. }
  37847. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37848. {
  37849. if (source.nextChar() != '0')
  37850. return false;
  37851. if (! isOctalDigit (source.nextChar()))
  37852. return false;
  37853. while (isOctalDigit (source.peekNextChar()))
  37854. source.skip();
  37855. return skipNumberSuffix (source);
  37856. }
  37857. static bool isDecimalDigit (const juce_wchar c) throw()
  37858. {
  37859. return c >= '0' && c <= '9';
  37860. }
  37861. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37862. {
  37863. int numChars = 0;
  37864. while (isDecimalDigit (source.peekNextChar()))
  37865. {
  37866. ++numChars;
  37867. source.skip();
  37868. }
  37869. if (numChars == 0)
  37870. return false;
  37871. return skipNumberSuffix (source);
  37872. }
  37873. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37874. {
  37875. int numDigits = 0;
  37876. while (isDecimalDigit (source.peekNextChar()))
  37877. {
  37878. source.skip();
  37879. ++numDigits;
  37880. }
  37881. const bool hasPoint = (source.peekNextChar() == '.');
  37882. if (hasPoint)
  37883. {
  37884. source.skip();
  37885. while (isDecimalDigit (source.peekNextChar()))
  37886. {
  37887. source.skip();
  37888. ++numDigits;
  37889. }
  37890. }
  37891. if (numDigits == 0)
  37892. return false;
  37893. juce_wchar c = source.peekNextChar();
  37894. const bool hasExponent = (c == 'e' || c == 'E');
  37895. if (hasExponent)
  37896. {
  37897. source.skip();
  37898. c = source.peekNextChar();
  37899. if (c == '+' || c == '-')
  37900. source.skip();
  37901. int numExpDigits = 0;
  37902. while (isDecimalDigit (source.peekNextChar()))
  37903. {
  37904. source.skip();
  37905. ++numExpDigits;
  37906. }
  37907. if (numExpDigits == 0)
  37908. return false;
  37909. }
  37910. c = source.peekNextChar();
  37911. if (c == 'f' || c == 'F')
  37912. source.skip();
  37913. else if (! (hasExponent || hasPoint))
  37914. return false;
  37915. return true;
  37916. }
  37917. static int parseNumber (CodeDocument::Iterator& source)
  37918. {
  37919. const CodeDocument::Iterator original (source);
  37920. if (parseFloatLiteral (source))
  37921. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37922. source = original;
  37923. if (parseHexLiteral (source))
  37924. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37925. source = original;
  37926. if (parseOctalLiteral (source))
  37927. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37928. source = original;
  37929. if (parseDecimalLiteral (source))
  37930. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37931. source = original;
  37932. source.skip();
  37933. return CPlusPlusCodeTokeniser::tokenType_error;
  37934. }
  37935. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  37936. {
  37937. const juce_wchar quote = source.nextChar();
  37938. for (;;)
  37939. {
  37940. const juce_wchar c = source.nextChar();
  37941. if (c == quote || c == 0)
  37942. break;
  37943. if (c == '\\')
  37944. source.skip();
  37945. }
  37946. }
  37947. static void skipComment (CodeDocument::Iterator& source) throw()
  37948. {
  37949. bool lastWasStar = false;
  37950. for (;;)
  37951. {
  37952. const juce_wchar c = source.nextChar();
  37953. if (c == 0 || (c == '/' && lastWasStar))
  37954. break;
  37955. lastWasStar = (c == '*');
  37956. }
  37957. }
  37958. }
  37959. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37960. {
  37961. int result = tokenType_error;
  37962. source.skipWhitespace();
  37963. juce_wchar firstChar = source.peekNextChar();
  37964. switch (firstChar)
  37965. {
  37966. case 0:
  37967. source.skip();
  37968. break;
  37969. case '0':
  37970. case '1':
  37971. case '2':
  37972. case '3':
  37973. case '4':
  37974. case '5':
  37975. case '6':
  37976. case '7':
  37977. case '8':
  37978. case '9':
  37979. result = CppTokeniser::parseNumber (source);
  37980. break;
  37981. case '.':
  37982. result = CppTokeniser::parseNumber (source);
  37983. if (result == tokenType_error)
  37984. result = tokenType_punctuation;
  37985. break;
  37986. case ',':
  37987. case ';':
  37988. case ':':
  37989. source.skip();
  37990. result = tokenType_punctuation;
  37991. break;
  37992. case '(':
  37993. case ')':
  37994. case '{':
  37995. case '}':
  37996. case '[':
  37997. case ']':
  37998. source.skip();
  37999. result = tokenType_bracket;
  38000. break;
  38001. case '"':
  38002. case '\'':
  38003. CppTokeniser::skipQuotedString (source);
  38004. result = tokenType_stringLiteral;
  38005. break;
  38006. case '+':
  38007. result = tokenType_operator;
  38008. source.skip();
  38009. if (source.peekNextChar() == '+')
  38010. source.skip();
  38011. else if (source.peekNextChar() == '=')
  38012. source.skip();
  38013. break;
  38014. case '-':
  38015. source.skip();
  38016. result = CppTokeniser::parseNumber (source);
  38017. if (result == tokenType_error)
  38018. {
  38019. result = tokenType_operator;
  38020. if (source.peekNextChar() == '-')
  38021. source.skip();
  38022. else if (source.peekNextChar() == '=')
  38023. source.skip();
  38024. }
  38025. break;
  38026. case '*':
  38027. case '%':
  38028. case '=':
  38029. case '!':
  38030. result = tokenType_operator;
  38031. source.skip();
  38032. if (source.peekNextChar() == '=')
  38033. source.skip();
  38034. break;
  38035. case '/':
  38036. result = tokenType_operator;
  38037. source.skip();
  38038. if (source.peekNextChar() == '=')
  38039. {
  38040. source.skip();
  38041. }
  38042. else if (source.peekNextChar() == '/')
  38043. {
  38044. result = tokenType_comment;
  38045. source.skipToEndOfLine();
  38046. }
  38047. else if (source.peekNextChar() == '*')
  38048. {
  38049. source.skip();
  38050. result = tokenType_comment;
  38051. CppTokeniser::skipComment (source);
  38052. }
  38053. break;
  38054. case '?':
  38055. case '~':
  38056. source.skip();
  38057. result = tokenType_operator;
  38058. break;
  38059. case '<':
  38060. source.skip();
  38061. result = tokenType_operator;
  38062. if (source.peekNextChar() == '=')
  38063. {
  38064. source.skip();
  38065. }
  38066. else if (source.peekNextChar() == '<')
  38067. {
  38068. source.skip();
  38069. if (source.peekNextChar() == '=')
  38070. source.skip();
  38071. }
  38072. break;
  38073. case '>':
  38074. source.skip();
  38075. result = tokenType_operator;
  38076. if (source.peekNextChar() == '=')
  38077. {
  38078. source.skip();
  38079. }
  38080. else if (source.peekNextChar() == '<')
  38081. {
  38082. source.skip();
  38083. if (source.peekNextChar() == '=')
  38084. source.skip();
  38085. }
  38086. break;
  38087. case '|':
  38088. source.skip();
  38089. result = tokenType_operator;
  38090. if (source.peekNextChar() == '=')
  38091. {
  38092. source.skip();
  38093. }
  38094. else if (source.peekNextChar() == '|')
  38095. {
  38096. source.skip();
  38097. if (source.peekNextChar() == '=')
  38098. source.skip();
  38099. }
  38100. break;
  38101. case '&':
  38102. source.skip();
  38103. result = tokenType_operator;
  38104. if (source.peekNextChar() == '=')
  38105. {
  38106. source.skip();
  38107. }
  38108. else if (source.peekNextChar() == '&')
  38109. {
  38110. source.skip();
  38111. if (source.peekNextChar() == '=')
  38112. source.skip();
  38113. }
  38114. break;
  38115. case '^':
  38116. source.skip();
  38117. result = tokenType_operator;
  38118. if (source.peekNextChar() == '=')
  38119. {
  38120. source.skip();
  38121. }
  38122. else if (source.peekNextChar() == '^')
  38123. {
  38124. source.skip();
  38125. if (source.peekNextChar() == '=')
  38126. source.skip();
  38127. }
  38128. break;
  38129. case '#':
  38130. result = tokenType_preprocessor;
  38131. source.skipToEndOfLine();
  38132. break;
  38133. default:
  38134. if (CppTokeniser::isIdentifierStart (firstChar))
  38135. result = CppTokeniser::parseIdentifier (source);
  38136. else
  38137. source.skip();
  38138. break;
  38139. }
  38140. return result;
  38141. }
  38142. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38143. {
  38144. const char* const types[] =
  38145. {
  38146. "Error",
  38147. "Comment",
  38148. "C++ keyword",
  38149. "Identifier",
  38150. "Integer literal",
  38151. "Float literal",
  38152. "String literal",
  38153. "Operator",
  38154. "Bracket",
  38155. "Punctuation",
  38156. "Preprocessor line",
  38157. 0
  38158. };
  38159. return StringArray (types);
  38160. }
  38161. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38162. {
  38163. const uint32 colours[] =
  38164. {
  38165. 0xffcc0000, // error
  38166. 0xff00aa00, // comment
  38167. 0xff0000cc, // keyword
  38168. 0xff000000, // identifier
  38169. 0xff880000, // int literal
  38170. 0xff885500, // float literal
  38171. 0xff990099, // string literal
  38172. 0xff225500, // operator
  38173. 0xff000055, // bracket
  38174. 0xff004400, // punctuation
  38175. 0xff660000 // preprocessor
  38176. };
  38177. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38178. return Colour (colours [tokenType]);
  38179. return Colours::black;
  38180. }
  38181. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38182. {
  38183. return CppTokeniser::isReservedKeyword (token, token.length());
  38184. }
  38185. END_JUCE_NAMESPACE
  38186. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38187. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38188. BEGIN_JUCE_NAMESPACE
  38189. ComboBox::ComboBox (const String& name)
  38190. : Component (name),
  38191. lastCurrentId (0),
  38192. isButtonDown (false),
  38193. separatorPending (false),
  38194. menuActive (false),
  38195. label (0)
  38196. {
  38197. noChoicesMessage = TRANS("(no choices)");
  38198. setRepaintsOnMouseActivity (true);
  38199. lookAndFeelChanged();
  38200. currentId.addListener (this);
  38201. }
  38202. ComboBox::~ComboBox()
  38203. {
  38204. currentId.removeListener (this);
  38205. if (menuActive)
  38206. PopupMenu::dismissAllActiveMenus();
  38207. label = 0;
  38208. deleteAllChildren();
  38209. }
  38210. void ComboBox::setEditableText (const bool isEditable)
  38211. {
  38212. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38213. {
  38214. label->setEditable (isEditable, isEditable, false);
  38215. setWantsKeyboardFocus (! isEditable);
  38216. resized();
  38217. }
  38218. }
  38219. bool ComboBox::isTextEditable() const throw()
  38220. {
  38221. return label->isEditable();
  38222. }
  38223. void ComboBox::setJustificationType (const Justification& justification)
  38224. {
  38225. label->setJustificationType (justification);
  38226. }
  38227. const Justification ComboBox::getJustificationType() const throw()
  38228. {
  38229. return label->getJustificationType();
  38230. }
  38231. void ComboBox::setTooltip (const String& newTooltip)
  38232. {
  38233. SettableTooltipClient::setTooltip (newTooltip);
  38234. label->setTooltip (newTooltip);
  38235. }
  38236. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38237. {
  38238. // you can't add empty strings to the list..
  38239. jassert (newItemText.isNotEmpty());
  38240. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38241. jassert (newItemId != 0);
  38242. // you shouldn't use duplicate item IDs!
  38243. jassert (getItemForId (newItemId) == 0);
  38244. if (newItemText.isNotEmpty() && newItemId != 0)
  38245. {
  38246. if (separatorPending)
  38247. {
  38248. separatorPending = false;
  38249. ItemInfo* const item = new ItemInfo();
  38250. item->itemId = 0;
  38251. item->isEnabled = false;
  38252. item->isHeading = false;
  38253. items.add (item);
  38254. }
  38255. ItemInfo* const item = new ItemInfo();
  38256. item->name = newItemText;
  38257. item->itemId = newItemId;
  38258. item->isEnabled = true;
  38259. item->isHeading = false;
  38260. items.add (item);
  38261. }
  38262. }
  38263. void ComboBox::addSeparator()
  38264. {
  38265. separatorPending = (items.size() > 0);
  38266. }
  38267. void ComboBox::addSectionHeading (const String& headingName)
  38268. {
  38269. // you can't add empty strings to the list..
  38270. jassert (headingName.isNotEmpty());
  38271. if (headingName.isNotEmpty())
  38272. {
  38273. if (separatorPending)
  38274. {
  38275. separatorPending = false;
  38276. ItemInfo* const item = new ItemInfo();
  38277. item->itemId = 0;
  38278. item->isEnabled = false;
  38279. item->isHeading = false;
  38280. items.add (item);
  38281. }
  38282. ItemInfo* const item = new ItemInfo();
  38283. item->name = headingName;
  38284. item->itemId = 0;
  38285. item->isEnabled = true;
  38286. item->isHeading = true;
  38287. items.add (item);
  38288. }
  38289. }
  38290. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38291. {
  38292. ItemInfo* const item = getItemForId (itemId);
  38293. if (item != 0)
  38294. item->isEnabled = shouldBeEnabled;
  38295. }
  38296. void ComboBox::changeItemText (const int itemId, const String& newText)
  38297. {
  38298. ItemInfo* const item = getItemForId (itemId);
  38299. jassert (item != 0);
  38300. if (item != 0)
  38301. item->name = newText;
  38302. }
  38303. void ComboBox::clear (const bool dontSendChangeMessage)
  38304. {
  38305. items.clear();
  38306. separatorPending = false;
  38307. if (! label->isEditable())
  38308. setSelectedItemIndex (-1, dontSendChangeMessage);
  38309. }
  38310. bool ComboBox::ItemInfo::isSeparator() const throw()
  38311. {
  38312. return name.isEmpty();
  38313. }
  38314. bool ComboBox::ItemInfo::isRealItem() const throw()
  38315. {
  38316. return ! (isHeading || name.isEmpty());
  38317. }
  38318. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38319. {
  38320. if (itemId != 0)
  38321. {
  38322. for (int i = items.size(); --i >= 0;)
  38323. if (items.getUnchecked(i)->itemId == itemId)
  38324. return items.getUnchecked(i);
  38325. }
  38326. return 0;
  38327. }
  38328. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38329. {
  38330. int n = 0;
  38331. for (int i = 0; i < items.size(); ++i)
  38332. {
  38333. ItemInfo* const item = items.getUnchecked(i);
  38334. if (item->isRealItem())
  38335. if (n++ == index)
  38336. return item;
  38337. }
  38338. return 0;
  38339. }
  38340. int ComboBox::getNumItems() const throw()
  38341. {
  38342. int n = 0;
  38343. for (int i = items.size(); --i >= 0;)
  38344. if (items.getUnchecked(i)->isRealItem())
  38345. ++n;
  38346. return n;
  38347. }
  38348. const String ComboBox::getItemText (const int index) const
  38349. {
  38350. const ItemInfo* const item = getItemForIndex (index);
  38351. if (item != 0)
  38352. return item->name;
  38353. return String::empty;
  38354. }
  38355. int ComboBox::getItemId (const int index) const throw()
  38356. {
  38357. const ItemInfo* const item = getItemForIndex (index);
  38358. return (item != 0) ? item->itemId : 0;
  38359. }
  38360. int ComboBox::indexOfItemId (const int itemId) const throw()
  38361. {
  38362. int n = 0;
  38363. for (int i = 0; i < items.size(); ++i)
  38364. {
  38365. const ItemInfo* const item = items.getUnchecked(i);
  38366. if (item->isRealItem())
  38367. {
  38368. if (item->itemId == itemId)
  38369. return n;
  38370. ++n;
  38371. }
  38372. }
  38373. return -1;
  38374. }
  38375. int ComboBox::getSelectedItemIndex() const
  38376. {
  38377. int index = indexOfItemId (currentId.getValue());
  38378. if (getText() != getItemText (index))
  38379. index = -1;
  38380. return index;
  38381. }
  38382. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38383. {
  38384. setSelectedId (getItemId (index), dontSendChangeMessage);
  38385. }
  38386. int ComboBox::getSelectedId() const throw()
  38387. {
  38388. const ItemInfo* const item = getItemForId (currentId.getValue());
  38389. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38390. }
  38391. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38392. {
  38393. const ItemInfo* const item = getItemForId (newItemId);
  38394. const String newItemText (item != 0 ? item->name : String::empty);
  38395. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38396. {
  38397. if (! dontSendChangeMessage)
  38398. triggerAsyncUpdate();
  38399. label->setText (newItemText, false);
  38400. lastCurrentId = newItemId;
  38401. currentId = newItemId;
  38402. repaint(); // for the benefit of the 'none selected' text
  38403. }
  38404. }
  38405. void ComboBox::valueChanged (Value&)
  38406. {
  38407. if (lastCurrentId != (int) currentId.getValue())
  38408. setSelectedId (currentId.getValue(), false);
  38409. }
  38410. const String ComboBox::getText() const
  38411. {
  38412. return label->getText();
  38413. }
  38414. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38415. {
  38416. for (int i = items.size(); --i >= 0;)
  38417. {
  38418. const ItemInfo* const item = items.getUnchecked(i);
  38419. if (item->isRealItem()
  38420. && item->name == newText)
  38421. {
  38422. setSelectedId (item->itemId, dontSendChangeMessage);
  38423. return;
  38424. }
  38425. }
  38426. lastCurrentId = 0;
  38427. currentId = 0;
  38428. if (label->getText() != newText)
  38429. {
  38430. label->setText (newText, false);
  38431. if (! dontSendChangeMessage)
  38432. triggerAsyncUpdate();
  38433. }
  38434. repaint();
  38435. }
  38436. void ComboBox::showEditor()
  38437. {
  38438. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38439. label->showEditor();
  38440. }
  38441. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38442. {
  38443. if (textWhenNothingSelected != newMessage)
  38444. {
  38445. textWhenNothingSelected = newMessage;
  38446. repaint();
  38447. }
  38448. }
  38449. const String ComboBox::getTextWhenNothingSelected() const
  38450. {
  38451. return textWhenNothingSelected;
  38452. }
  38453. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38454. {
  38455. noChoicesMessage = newMessage;
  38456. }
  38457. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38458. {
  38459. return noChoicesMessage;
  38460. }
  38461. void ComboBox::paint (Graphics& g)
  38462. {
  38463. getLookAndFeel().drawComboBox (g,
  38464. getWidth(),
  38465. getHeight(),
  38466. isButtonDown,
  38467. label->getRight(),
  38468. 0,
  38469. getWidth() - label->getRight(),
  38470. getHeight(),
  38471. *this);
  38472. if (textWhenNothingSelected.isNotEmpty()
  38473. && label->getText().isEmpty()
  38474. && ! label->isBeingEdited())
  38475. {
  38476. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38477. g.setFont (label->getFont());
  38478. g.drawFittedText (textWhenNothingSelected,
  38479. label->getX() + 2, label->getY() + 1,
  38480. label->getWidth() - 4, label->getHeight() - 2,
  38481. label->getJustificationType(),
  38482. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38483. }
  38484. }
  38485. void ComboBox::resized()
  38486. {
  38487. if (getHeight() > 0 && getWidth() > 0)
  38488. getLookAndFeel().positionComboBoxText (*this, *label);
  38489. }
  38490. void ComboBox::enablementChanged()
  38491. {
  38492. repaint();
  38493. }
  38494. void ComboBox::lookAndFeelChanged()
  38495. {
  38496. repaint();
  38497. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  38498. if (label != 0)
  38499. {
  38500. newLabel->setEditable (label->isEditable());
  38501. newLabel->setJustificationType (label->getJustificationType());
  38502. newLabel->setTooltip (label->getTooltip());
  38503. newLabel->setText (label->getText(), false);
  38504. }
  38505. label = newLabel;
  38506. addAndMakeVisible (newLabel);
  38507. newLabel->addListener (this);
  38508. newLabel->addMouseListener (this, false);
  38509. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38510. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38511. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38512. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38513. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38514. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38515. resized();
  38516. }
  38517. void ComboBox::colourChanged()
  38518. {
  38519. lookAndFeelChanged();
  38520. }
  38521. bool ComboBox::keyPressed (const KeyPress& key)
  38522. {
  38523. bool used = false;
  38524. if (key.isKeyCode (KeyPress::upKey)
  38525. || key.isKeyCode (KeyPress::leftKey))
  38526. {
  38527. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  38528. used = true;
  38529. }
  38530. else if (key.isKeyCode (KeyPress::downKey)
  38531. || key.isKeyCode (KeyPress::rightKey))
  38532. {
  38533. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  38534. used = true;
  38535. }
  38536. else if (key.isKeyCode (KeyPress::returnKey))
  38537. {
  38538. showPopup();
  38539. used = true;
  38540. }
  38541. return used;
  38542. }
  38543. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38544. {
  38545. // only forward key events that aren't used by this component
  38546. return isKeyDown
  38547. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38548. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38549. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38550. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38551. }
  38552. void ComboBox::focusGained (FocusChangeType)
  38553. {
  38554. repaint();
  38555. }
  38556. void ComboBox::focusLost (FocusChangeType)
  38557. {
  38558. repaint();
  38559. }
  38560. void ComboBox::labelTextChanged (Label*)
  38561. {
  38562. triggerAsyncUpdate();
  38563. }
  38564. class ComboBox::Callback : public ModalComponentManager::Callback
  38565. {
  38566. public:
  38567. Callback (ComboBox* const box_)
  38568. : box (box_)
  38569. {
  38570. }
  38571. void modalStateFinished (int returnValue)
  38572. {
  38573. if (box != 0)
  38574. {
  38575. box->menuActive = false;
  38576. if (returnValue != 0)
  38577. box->setSelectedId (returnValue);
  38578. }
  38579. }
  38580. private:
  38581. Component::SafePointer<ComboBox> box;
  38582. Callback (const Callback&);
  38583. Callback& operator= (const Callback&);
  38584. };
  38585. void ComboBox::showPopup()
  38586. {
  38587. if (! menuActive)
  38588. {
  38589. const int selectedId = getSelectedId();
  38590. PopupMenu menu;
  38591. menu.setLookAndFeel (&getLookAndFeel());
  38592. for (int i = 0; i < items.size(); ++i)
  38593. {
  38594. const ItemInfo* const item = items.getUnchecked(i);
  38595. if (item->isSeparator())
  38596. menu.addSeparator();
  38597. else if (item->isHeading)
  38598. menu.addSectionHeader (item->name);
  38599. else
  38600. menu.addItem (item->itemId, item->name,
  38601. item->isEnabled, item->itemId == selectedId);
  38602. }
  38603. if (items.size() == 0)
  38604. menu.addItem (1, noChoicesMessage, false);
  38605. menuActive = true;
  38606. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38607. new Callback (this));
  38608. }
  38609. }
  38610. void ComboBox::mouseDown (const MouseEvent& e)
  38611. {
  38612. beginDragAutoRepeat (300);
  38613. isButtonDown = isEnabled();
  38614. if (isButtonDown
  38615. && (e.eventComponent == this || ! label->isEditable()))
  38616. {
  38617. showPopup();
  38618. }
  38619. }
  38620. void ComboBox::mouseDrag (const MouseEvent& e)
  38621. {
  38622. beginDragAutoRepeat (50);
  38623. if (isButtonDown && ! e.mouseWasClicked())
  38624. showPopup();
  38625. }
  38626. void ComboBox::mouseUp (const MouseEvent& e2)
  38627. {
  38628. if (isButtonDown)
  38629. {
  38630. isButtonDown = false;
  38631. repaint();
  38632. const MouseEvent e (e2.getEventRelativeTo (this));
  38633. if (reallyContains (e.x, e.y, true)
  38634. && (e2.eventComponent == this || ! label->isEditable()))
  38635. {
  38636. showPopup();
  38637. }
  38638. }
  38639. }
  38640. void ComboBox::addListener (Listener* const listener)
  38641. {
  38642. listeners.add (listener);
  38643. }
  38644. void ComboBox::removeListener (Listener* const listener)
  38645. {
  38646. listeners.remove (listener);
  38647. }
  38648. void ComboBox::handleAsyncUpdate()
  38649. {
  38650. Component::BailOutChecker checker (this);
  38651. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38652. }
  38653. END_JUCE_NAMESPACE
  38654. /*** End of inlined file: juce_ComboBox.cpp ***/
  38655. /*** Start of inlined file: juce_Label.cpp ***/
  38656. BEGIN_JUCE_NAMESPACE
  38657. Label::Label (const String& componentName,
  38658. const String& labelText)
  38659. : Component (componentName),
  38660. textValue (labelText),
  38661. lastTextValue (labelText),
  38662. font (15.0f),
  38663. justification (Justification::centredLeft),
  38664. ownerComponent (0),
  38665. horizontalBorderSize (5),
  38666. verticalBorderSize (1),
  38667. minimumHorizontalScale (0.7f),
  38668. editSingleClick (false),
  38669. editDoubleClick (false),
  38670. lossOfFocusDiscardsChanges (false)
  38671. {
  38672. setColour (TextEditor::textColourId, Colours::black);
  38673. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38674. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38675. textValue.addListener (this);
  38676. }
  38677. Label::~Label()
  38678. {
  38679. textValue.removeListener (this);
  38680. if (ownerComponent != 0)
  38681. ownerComponent->removeComponentListener (this);
  38682. editor = 0;
  38683. }
  38684. void Label::setText (const String& newText,
  38685. const bool broadcastChangeMessage)
  38686. {
  38687. hideEditor (true);
  38688. if (lastTextValue != newText)
  38689. {
  38690. lastTextValue = newText;
  38691. textValue = newText;
  38692. repaint();
  38693. textWasChanged();
  38694. if (ownerComponent != 0)
  38695. componentMovedOrResized (*ownerComponent, true, true);
  38696. if (broadcastChangeMessage)
  38697. callChangeListeners();
  38698. }
  38699. }
  38700. const String Label::getText (const bool returnActiveEditorContents) const
  38701. {
  38702. return (returnActiveEditorContents && isBeingEdited())
  38703. ? editor->getText()
  38704. : textValue.toString();
  38705. }
  38706. void Label::valueChanged (Value&)
  38707. {
  38708. if (lastTextValue != textValue.toString())
  38709. setText (textValue.toString(), true);
  38710. }
  38711. void Label::setFont (const Font& newFont)
  38712. {
  38713. if (font != newFont)
  38714. {
  38715. font = newFont;
  38716. repaint();
  38717. }
  38718. }
  38719. const Font& Label::getFont() const throw()
  38720. {
  38721. return font;
  38722. }
  38723. void Label::setEditable (const bool editOnSingleClick,
  38724. const bool editOnDoubleClick,
  38725. const bool lossOfFocusDiscardsChanges_)
  38726. {
  38727. editSingleClick = editOnSingleClick;
  38728. editDoubleClick = editOnDoubleClick;
  38729. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38730. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38731. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38732. }
  38733. void Label::setJustificationType (const Justification& newJustification)
  38734. {
  38735. if (justification != newJustification)
  38736. {
  38737. justification = newJustification;
  38738. repaint();
  38739. }
  38740. }
  38741. void Label::setBorderSize (int h, int v)
  38742. {
  38743. if (horizontalBorderSize != h || verticalBorderSize != v)
  38744. {
  38745. horizontalBorderSize = h;
  38746. verticalBorderSize = v;
  38747. repaint();
  38748. }
  38749. }
  38750. Component* Label::getAttachedComponent() const
  38751. {
  38752. return static_cast<Component*> (ownerComponent);
  38753. }
  38754. void Label::attachToComponent (Component* owner,
  38755. const bool onLeft)
  38756. {
  38757. if (ownerComponent != 0)
  38758. ownerComponent->removeComponentListener (this);
  38759. ownerComponent = owner;
  38760. leftOfOwnerComp = onLeft;
  38761. if (ownerComponent != 0)
  38762. {
  38763. setVisible (owner->isVisible());
  38764. ownerComponent->addComponentListener (this);
  38765. componentParentHierarchyChanged (*ownerComponent);
  38766. componentMovedOrResized (*ownerComponent, true, true);
  38767. }
  38768. }
  38769. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38770. {
  38771. if (leftOfOwnerComp)
  38772. {
  38773. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38774. component.getHeight());
  38775. setTopRightPosition (component.getX(), component.getY());
  38776. }
  38777. else
  38778. {
  38779. setSize (component.getWidth(),
  38780. 8 + roundToInt (getFont().getHeight()));
  38781. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38782. }
  38783. }
  38784. void Label::componentParentHierarchyChanged (Component& component)
  38785. {
  38786. if (component.getParentComponent() != 0)
  38787. component.getParentComponent()->addChildComponent (this);
  38788. }
  38789. void Label::componentVisibilityChanged (Component& component)
  38790. {
  38791. setVisible (component.isVisible());
  38792. }
  38793. void Label::textWasEdited()
  38794. {
  38795. }
  38796. void Label::textWasChanged()
  38797. {
  38798. }
  38799. void Label::showEditor()
  38800. {
  38801. if (editor == 0)
  38802. {
  38803. addAndMakeVisible (editor = createEditorComponent());
  38804. editor->setText (getText(), false);
  38805. editor->addListener (this);
  38806. editor->grabKeyboardFocus();
  38807. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38808. editor->addListener (this);
  38809. resized();
  38810. repaint();
  38811. editorShown (editor);
  38812. enterModalState (false);
  38813. editor->grabKeyboardFocus();
  38814. }
  38815. }
  38816. void Label::editorShown (TextEditor* /*editorComponent*/)
  38817. {
  38818. }
  38819. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38820. {
  38821. }
  38822. bool Label::updateFromTextEditorContents()
  38823. {
  38824. jassert (editor != 0);
  38825. const String newText (editor->getText());
  38826. if (textValue.toString() != newText)
  38827. {
  38828. lastTextValue = newText;
  38829. textValue = newText;
  38830. repaint();
  38831. textWasChanged();
  38832. if (ownerComponent != 0)
  38833. componentMovedOrResized (*ownerComponent, true, true);
  38834. return true;
  38835. }
  38836. return false;
  38837. }
  38838. void Label::hideEditor (const bool discardCurrentEditorContents)
  38839. {
  38840. if (editor != 0)
  38841. {
  38842. Component::SafePointer<Component> deletionChecker (this);
  38843. editorAboutToBeHidden (editor);
  38844. const bool changed = (! discardCurrentEditorContents)
  38845. && updateFromTextEditorContents();
  38846. editor = 0;
  38847. repaint();
  38848. if (changed)
  38849. textWasEdited();
  38850. if (deletionChecker != 0)
  38851. exitModalState (0);
  38852. if (changed && deletionChecker != 0)
  38853. callChangeListeners();
  38854. }
  38855. }
  38856. void Label::inputAttemptWhenModal()
  38857. {
  38858. if (editor != 0)
  38859. {
  38860. if (lossOfFocusDiscardsChanges)
  38861. textEditorEscapeKeyPressed (*editor);
  38862. else
  38863. textEditorReturnKeyPressed (*editor);
  38864. }
  38865. }
  38866. bool Label::isBeingEdited() const throw()
  38867. {
  38868. return editor != 0;
  38869. }
  38870. TextEditor* Label::createEditorComponent()
  38871. {
  38872. TextEditor* const ed = new TextEditor (getName());
  38873. ed->setFont (font);
  38874. // copy these colours from our own settings..
  38875. const int cols[] = { TextEditor::backgroundColourId,
  38876. TextEditor::textColourId,
  38877. TextEditor::highlightColourId,
  38878. TextEditor::highlightedTextColourId,
  38879. TextEditor::caretColourId,
  38880. TextEditor::outlineColourId,
  38881. TextEditor::focusedOutlineColourId,
  38882. TextEditor::shadowColourId };
  38883. for (int i = 0; i < numElementsInArray (cols); ++i)
  38884. ed->setColour (cols[i], findColour (cols[i]));
  38885. return ed;
  38886. }
  38887. void Label::paint (Graphics& g)
  38888. {
  38889. getLookAndFeel().drawLabel (g, *this);
  38890. }
  38891. void Label::mouseUp (const MouseEvent& e)
  38892. {
  38893. if (editSingleClick
  38894. && e.mouseWasClicked()
  38895. && contains (e.x, e.y)
  38896. && ! e.mods.isPopupMenu())
  38897. {
  38898. showEditor();
  38899. }
  38900. }
  38901. void Label::mouseDoubleClick (const MouseEvent& e)
  38902. {
  38903. if (editDoubleClick && ! e.mods.isPopupMenu())
  38904. showEditor();
  38905. }
  38906. void Label::resized()
  38907. {
  38908. if (editor != 0)
  38909. editor->setBoundsInset (BorderSize (0));
  38910. }
  38911. void Label::focusGained (FocusChangeType cause)
  38912. {
  38913. if (editSingleClick && cause == focusChangedByTabKey)
  38914. showEditor();
  38915. }
  38916. void Label::enablementChanged()
  38917. {
  38918. repaint();
  38919. }
  38920. void Label::colourChanged()
  38921. {
  38922. repaint();
  38923. }
  38924. void Label::setMinimumHorizontalScale (const float newScale)
  38925. {
  38926. if (minimumHorizontalScale != newScale)
  38927. {
  38928. minimumHorizontalScale = newScale;
  38929. repaint();
  38930. }
  38931. }
  38932. // We'll use a custom focus traverser here to make sure focus goes from the
  38933. // text editor to another component rather than back to the label itself.
  38934. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38935. {
  38936. public:
  38937. LabelKeyboardFocusTraverser() {}
  38938. Component* getNextComponent (Component* current)
  38939. {
  38940. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38941. ? current->getParentComponent() : current);
  38942. }
  38943. Component* getPreviousComponent (Component* current)
  38944. {
  38945. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38946. ? current->getParentComponent() : current);
  38947. }
  38948. };
  38949. KeyboardFocusTraverser* Label::createFocusTraverser()
  38950. {
  38951. return new LabelKeyboardFocusTraverser();
  38952. }
  38953. void Label::addListener (Listener* const listener)
  38954. {
  38955. listeners.add (listener);
  38956. }
  38957. void Label::removeListener (Listener* const listener)
  38958. {
  38959. listeners.remove (listener);
  38960. }
  38961. void Label::callChangeListeners()
  38962. {
  38963. Component::BailOutChecker checker (this);
  38964. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38965. }
  38966. void Label::textEditorTextChanged (TextEditor& ed)
  38967. {
  38968. if (editor != 0)
  38969. {
  38970. jassert (&ed == editor);
  38971. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38972. {
  38973. if (lossOfFocusDiscardsChanges)
  38974. textEditorEscapeKeyPressed (ed);
  38975. else
  38976. textEditorReturnKeyPressed (ed);
  38977. }
  38978. }
  38979. }
  38980. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38981. {
  38982. if (editor != 0)
  38983. {
  38984. jassert (&ed == editor);
  38985. (void) ed;
  38986. const bool changed = updateFromTextEditorContents();
  38987. hideEditor (true);
  38988. if (changed)
  38989. {
  38990. Component::SafePointer<Component> deletionChecker (this);
  38991. textWasEdited();
  38992. if (deletionChecker != 0)
  38993. callChangeListeners();
  38994. }
  38995. }
  38996. }
  38997. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38998. {
  38999. if (editor != 0)
  39000. {
  39001. jassert (&ed == editor);
  39002. (void) ed;
  39003. editor->setText (textValue.toString(), false);
  39004. hideEditor (true);
  39005. }
  39006. }
  39007. void Label::textEditorFocusLost (TextEditor& ed)
  39008. {
  39009. textEditorTextChanged (ed);
  39010. }
  39011. END_JUCE_NAMESPACE
  39012. /*** End of inlined file: juce_Label.cpp ***/
  39013. /*** Start of inlined file: juce_ListBox.cpp ***/
  39014. BEGIN_JUCE_NAMESPACE
  39015. class ListBoxRowComponent : public Component,
  39016. public TooltipClient
  39017. {
  39018. public:
  39019. ListBoxRowComponent (ListBox& owner_)
  39020. : owner (owner_),
  39021. row (-1),
  39022. selected (false),
  39023. isDragging (false)
  39024. {
  39025. }
  39026. ~ListBoxRowComponent()
  39027. {
  39028. deleteAllChildren();
  39029. }
  39030. void paint (Graphics& g)
  39031. {
  39032. if (owner.getModel() != 0)
  39033. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  39034. }
  39035. void update (const int row_, const bool selected_)
  39036. {
  39037. if (row != row_ || selected != selected_)
  39038. {
  39039. repaint();
  39040. row = row_;
  39041. selected = selected_;
  39042. }
  39043. if (owner.getModel() != 0)
  39044. {
  39045. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  39046. if (customComp != 0)
  39047. {
  39048. addAndMakeVisible (customComp);
  39049. customComp->setBounds (getLocalBounds());
  39050. for (int i = getNumChildComponents(); --i >= 0;)
  39051. if (getChildComponent (i) != customComp)
  39052. delete getChildComponent (i);
  39053. }
  39054. else
  39055. {
  39056. deleteAllChildren();
  39057. }
  39058. }
  39059. }
  39060. void mouseDown (const MouseEvent& e)
  39061. {
  39062. isDragging = false;
  39063. selectRowOnMouseUp = false;
  39064. if (isEnabled())
  39065. {
  39066. if (! selected)
  39067. {
  39068. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39069. if (owner.getModel() != 0)
  39070. owner.getModel()->listBoxItemClicked (row, e);
  39071. }
  39072. else
  39073. {
  39074. selectRowOnMouseUp = true;
  39075. }
  39076. }
  39077. }
  39078. void mouseUp (const MouseEvent& e)
  39079. {
  39080. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  39081. {
  39082. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39083. if (owner.getModel() != 0)
  39084. owner.getModel()->listBoxItemClicked (row, e);
  39085. }
  39086. }
  39087. void mouseDoubleClick (const MouseEvent& e)
  39088. {
  39089. if (owner.getModel() != 0 && isEnabled())
  39090. owner.getModel()->listBoxItemDoubleClicked (row, e);
  39091. }
  39092. void mouseDrag (const MouseEvent& e)
  39093. {
  39094. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  39095. {
  39096. const SparseSet<int> selectedRows (owner.getSelectedRows());
  39097. if (selectedRows.size() > 0)
  39098. {
  39099. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  39100. if (dragDescription.isNotEmpty())
  39101. {
  39102. isDragging = true;
  39103. owner.startDragAndDrop (e, dragDescription);
  39104. }
  39105. }
  39106. }
  39107. }
  39108. void resized()
  39109. {
  39110. if (getNumChildComponents() > 0)
  39111. getChildComponent(0)->setBounds (getLocalBounds());
  39112. }
  39113. const String getTooltip()
  39114. {
  39115. if (owner.getModel() != 0)
  39116. return owner.getModel()->getTooltipForRow (row);
  39117. return String::empty;
  39118. }
  39119. juce_UseDebuggingNewOperator
  39120. bool neededFlag;
  39121. private:
  39122. ListBox& owner;
  39123. int row;
  39124. bool selected, isDragging, selectRowOnMouseUp;
  39125. ListBoxRowComponent (const ListBoxRowComponent&);
  39126. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  39127. };
  39128. class ListViewport : public Viewport
  39129. {
  39130. public:
  39131. int firstIndex, firstWholeIndex, lastWholeIndex;
  39132. bool hasUpdated;
  39133. ListViewport (ListBox& owner_)
  39134. : owner (owner_)
  39135. {
  39136. setWantsKeyboardFocus (false);
  39137. setViewedComponent (new Component());
  39138. getViewedComponent()->addMouseListener (this, false);
  39139. getViewedComponent()->setWantsKeyboardFocus (false);
  39140. }
  39141. ~ListViewport()
  39142. {
  39143. getViewedComponent()->removeMouseListener (this);
  39144. getViewedComponent()->deleteAllChildren();
  39145. }
  39146. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  39147. {
  39148. return static_cast <ListBoxRowComponent*>
  39149. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  39150. }
  39151. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  39152. {
  39153. const int index = getIndexOfChildComponent (rowComponent);
  39154. const int num = getViewedComponent()->getNumChildComponents();
  39155. for (int i = num; --i >= 0;)
  39156. if (((firstIndex + i) % jmax (1, num)) == index)
  39157. return firstIndex + i;
  39158. return -1;
  39159. }
  39160. Component* getComponentForRowIfOnscreen (const int row) const throw()
  39161. {
  39162. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  39163. ? getComponentForRow (row) : 0;
  39164. }
  39165. void visibleAreaChanged (int, int, int, int)
  39166. {
  39167. updateVisibleArea (true);
  39168. if (owner.getModel() != 0)
  39169. owner.getModel()->listWasScrolled();
  39170. }
  39171. void updateVisibleArea (const bool makeSureItUpdatesContent)
  39172. {
  39173. hasUpdated = false;
  39174. const int newX = getViewedComponent()->getX();
  39175. int newY = getViewedComponent()->getY();
  39176. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39177. const int newH = owner.totalItems * owner.getRowHeight();
  39178. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39179. newY = getMaximumVisibleHeight() - newH;
  39180. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39181. if (makeSureItUpdatesContent && ! hasUpdated)
  39182. updateContents();
  39183. }
  39184. void updateContents()
  39185. {
  39186. hasUpdated = true;
  39187. const int rowHeight = owner.getRowHeight();
  39188. if (rowHeight > 0)
  39189. {
  39190. const int y = getViewPositionY();
  39191. const int w = getViewedComponent()->getWidth();
  39192. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39193. while (numNeeded > getViewedComponent()->getNumChildComponents())
  39194. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  39195. jassert (numNeeded >= 0);
  39196. while (numNeeded < getViewedComponent()->getNumChildComponents())
  39197. {
  39198. Component* const rowToRemove
  39199. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  39200. delete rowToRemove;
  39201. }
  39202. firstIndex = y / rowHeight;
  39203. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39204. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39205. for (int i = 0; i < numNeeded; ++i)
  39206. {
  39207. const int row = i + firstIndex;
  39208. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39209. if (rowComp != 0)
  39210. {
  39211. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39212. rowComp->update (row, owner.isRowSelected (row));
  39213. }
  39214. }
  39215. }
  39216. if (owner.headerComponent != 0)
  39217. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39218. owner.outlineThickness,
  39219. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39220. getViewedComponent()->getWidth()),
  39221. owner.headerComponent->getHeight());
  39222. }
  39223. void paint (Graphics& g)
  39224. {
  39225. if (isOpaque())
  39226. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39227. }
  39228. bool keyPressed (const KeyPress& key)
  39229. {
  39230. if (key.isKeyCode (KeyPress::upKey)
  39231. || key.isKeyCode (KeyPress::downKey)
  39232. || key.isKeyCode (KeyPress::pageUpKey)
  39233. || key.isKeyCode (KeyPress::pageDownKey)
  39234. || key.isKeyCode (KeyPress::homeKey)
  39235. || key.isKeyCode (KeyPress::endKey))
  39236. {
  39237. // we want to avoid these keypresses going to the viewport, and instead allow
  39238. // them to pass up to our listbox..
  39239. return false;
  39240. }
  39241. return Viewport::keyPressed (key);
  39242. }
  39243. juce_UseDebuggingNewOperator
  39244. private:
  39245. ListBox& owner;
  39246. ListViewport (const ListViewport&);
  39247. ListViewport& operator= (const ListViewport&);
  39248. };
  39249. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39250. : Component (name),
  39251. model (model_),
  39252. totalItems (0),
  39253. rowHeight (22),
  39254. minimumRowWidth (0),
  39255. outlineThickness (0),
  39256. lastRowSelected (-1),
  39257. mouseMoveSelects (false),
  39258. multipleSelection (false),
  39259. hasDoneInitialUpdate (false)
  39260. {
  39261. addAndMakeVisible (viewport = new ListViewport (*this));
  39262. setWantsKeyboardFocus (true);
  39263. colourChanged();
  39264. }
  39265. ListBox::~ListBox()
  39266. {
  39267. headerComponent = 0;
  39268. viewport = 0;
  39269. }
  39270. void ListBox::setModel (ListBoxModel* const newModel)
  39271. {
  39272. if (model != newModel)
  39273. {
  39274. model = newModel;
  39275. updateContent();
  39276. }
  39277. }
  39278. void ListBox::setMultipleSelectionEnabled (bool b)
  39279. {
  39280. multipleSelection = b;
  39281. }
  39282. void ListBox::setMouseMoveSelectsRows (bool b)
  39283. {
  39284. mouseMoveSelects = b;
  39285. if (b)
  39286. addMouseListener (this, true);
  39287. }
  39288. void ListBox::paint (Graphics& g)
  39289. {
  39290. if (! hasDoneInitialUpdate)
  39291. updateContent();
  39292. g.fillAll (findColour (backgroundColourId));
  39293. }
  39294. void ListBox::paintOverChildren (Graphics& g)
  39295. {
  39296. if (outlineThickness > 0)
  39297. {
  39298. g.setColour (findColour (outlineColourId));
  39299. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39300. }
  39301. }
  39302. void ListBox::resized()
  39303. {
  39304. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39305. outlineThickness,
  39306. outlineThickness,
  39307. outlineThickness));
  39308. viewport->setSingleStepSizes (20, getRowHeight());
  39309. viewport->updateVisibleArea (false);
  39310. }
  39311. void ListBox::visibilityChanged()
  39312. {
  39313. viewport->updateVisibleArea (true);
  39314. }
  39315. Viewport* ListBox::getViewport() const throw()
  39316. {
  39317. return viewport;
  39318. }
  39319. void ListBox::updateContent()
  39320. {
  39321. hasDoneInitialUpdate = true;
  39322. totalItems = (model != 0) ? model->getNumRows() : 0;
  39323. bool selectionChanged = false;
  39324. if (selected [selected.size() - 1] >= totalItems)
  39325. {
  39326. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39327. lastRowSelected = getSelectedRow (0);
  39328. selectionChanged = true;
  39329. }
  39330. viewport->updateVisibleArea (isVisible());
  39331. viewport->resized();
  39332. if (selectionChanged && model != 0)
  39333. model->selectedRowsChanged (lastRowSelected);
  39334. }
  39335. void ListBox::selectRow (const int row,
  39336. bool dontScroll,
  39337. bool deselectOthersFirst)
  39338. {
  39339. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39340. }
  39341. void ListBox::selectRowInternal (const int row,
  39342. bool dontScroll,
  39343. bool deselectOthersFirst,
  39344. bool isMouseClick)
  39345. {
  39346. if (! multipleSelection)
  39347. deselectOthersFirst = true;
  39348. if ((! isRowSelected (row))
  39349. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39350. {
  39351. if (((unsigned int) row) < (unsigned int) totalItems)
  39352. {
  39353. if (deselectOthersFirst)
  39354. selected.clear();
  39355. selected.addRange (Range<int> (row, row + 1));
  39356. if (getHeight() == 0 || getWidth() == 0)
  39357. dontScroll = true;
  39358. viewport->hasUpdated = false;
  39359. if (row < viewport->firstWholeIndex && ! dontScroll)
  39360. {
  39361. viewport->setViewPosition (viewport->getViewPositionX(),
  39362. row * getRowHeight());
  39363. }
  39364. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  39365. {
  39366. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  39367. if (row >= lastRowSelected + rowsOnScreen
  39368. && rowsOnScreen < totalItems - 1
  39369. && ! isMouseClick)
  39370. {
  39371. viewport->setViewPosition (viewport->getViewPositionX(),
  39372. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  39373. * getRowHeight());
  39374. }
  39375. else
  39376. {
  39377. viewport->setViewPosition (viewport->getViewPositionX(),
  39378. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39379. }
  39380. }
  39381. if (! viewport->hasUpdated)
  39382. viewport->updateContents();
  39383. lastRowSelected = row;
  39384. model->selectedRowsChanged (row);
  39385. }
  39386. else
  39387. {
  39388. if (deselectOthersFirst)
  39389. deselectAllRows();
  39390. }
  39391. }
  39392. }
  39393. void ListBox::deselectRow (const int row)
  39394. {
  39395. if (selected.contains (row))
  39396. {
  39397. selected.removeRange (Range <int> (row, row + 1));
  39398. if (row == lastRowSelected)
  39399. lastRowSelected = getSelectedRow (0);
  39400. viewport->updateContents();
  39401. model->selectedRowsChanged (lastRowSelected);
  39402. }
  39403. }
  39404. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39405. const bool sendNotificationEventToModel)
  39406. {
  39407. selected = setOfRowsToBeSelected;
  39408. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39409. if (! isRowSelected (lastRowSelected))
  39410. lastRowSelected = getSelectedRow (0);
  39411. viewport->updateContents();
  39412. if ((model != 0) && sendNotificationEventToModel)
  39413. model->selectedRowsChanged (lastRowSelected);
  39414. }
  39415. const SparseSet<int> ListBox::getSelectedRows() const
  39416. {
  39417. return selected;
  39418. }
  39419. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39420. {
  39421. if (multipleSelection && (firstRow != lastRow))
  39422. {
  39423. const int numRows = totalItems - 1;
  39424. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39425. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39426. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39427. jmax (firstRow, lastRow) + 1));
  39428. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39429. }
  39430. selectRowInternal (lastRow, false, false, true);
  39431. }
  39432. void ListBox::flipRowSelection (const int row)
  39433. {
  39434. if (isRowSelected (row))
  39435. deselectRow (row);
  39436. else
  39437. selectRowInternal (row, false, false, true);
  39438. }
  39439. void ListBox::deselectAllRows()
  39440. {
  39441. if (! selected.isEmpty())
  39442. {
  39443. selected.clear();
  39444. lastRowSelected = -1;
  39445. viewport->updateContents();
  39446. if (model != 0)
  39447. model->selectedRowsChanged (lastRowSelected);
  39448. }
  39449. }
  39450. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39451. const ModifierKeys& mods)
  39452. {
  39453. if (multipleSelection && mods.isCommandDown())
  39454. {
  39455. flipRowSelection (row);
  39456. }
  39457. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39458. {
  39459. selectRangeOfRows (lastRowSelected, row);
  39460. }
  39461. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39462. {
  39463. selectRowInternal (row, false, true, true);
  39464. }
  39465. }
  39466. int ListBox::getNumSelectedRows() const
  39467. {
  39468. return selected.size();
  39469. }
  39470. int ListBox::getSelectedRow (const int index) const
  39471. {
  39472. return (((unsigned int) index) < (unsigned int) selected.size())
  39473. ? selected [index] : -1;
  39474. }
  39475. bool ListBox::isRowSelected (const int row) const
  39476. {
  39477. return selected.contains (row);
  39478. }
  39479. int ListBox::getLastRowSelected() const
  39480. {
  39481. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39482. }
  39483. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39484. {
  39485. if (((unsigned int) x) < (unsigned int) getWidth())
  39486. {
  39487. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39488. if (((unsigned int) row) < (unsigned int) totalItems)
  39489. return row;
  39490. }
  39491. return -1;
  39492. }
  39493. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39494. {
  39495. if (((unsigned int) x) < (unsigned int) getWidth())
  39496. {
  39497. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39498. return jlimit (0, totalItems, row);
  39499. }
  39500. return -1;
  39501. }
  39502. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39503. {
  39504. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39505. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  39506. }
  39507. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39508. {
  39509. return viewport->getRowNumberOfComponent (rowComponent);
  39510. }
  39511. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39512. const bool relativeToComponentTopLeft) const throw()
  39513. {
  39514. int y = viewport->getY() + rowHeight * rowNumber;
  39515. if (relativeToComponentTopLeft)
  39516. y -= viewport->getViewPositionY();
  39517. return Rectangle<int> (viewport->getX(), y,
  39518. viewport->getViewedComponent()->getWidth(), rowHeight);
  39519. }
  39520. void ListBox::setVerticalPosition (const double proportion)
  39521. {
  39522. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39523. viewport->setViewPosition (viewport->getViewPositionX(),
  39524. jmax (0, roundToInt (proportion * offscreen)));
  39525. }
  39526. double ListBox::getVerticalPosition() const
  39527. {
  39528. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39529. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39530. : 0;
  39531. }
  39532. int ListBox::getVisibleRowWidth() const throw()
  39533. {
  39534. return viewport->getViewWidth();
  39535. }
  39536. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39537. {
  39538. if (row < viewport->firstWholeIndex)
  39539. {
  39540. viewport->setViewPosition (viewport->getViewPositionX(),
  39541. row * getRowHeight());
  39542. }
  39543. else if (row >= viewport->lastWholeIndex)
  39544. {
  39545. viewport->setViewPosition (viewport->getViewPositionX(),
  39546. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39547. }
  39548. }
  39549. bool ListBox::keyPressed (const KeyPress& key)
  39550. {
  39551. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39552. const bool multiple = multipleSelection
  39553. && (lastRowSelected >= 0)
  39554. && (key.getModifiers().isShiftDown()
  39555. || key.getModifiers().isCtrlDown()
  39556. || key.getModifiers().isCommandDown());
  39557. if (key.isKeyCode (KeyPress::upKey))
  39558. {
  39559. if (multiple)
  39560. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39561. else
  39562. selectRow (jmax (0, lastRowSelected - 1));
  39563. }
  39564. else if (key.isKeyCode (KeyPress::returnKey)
  39565. && isRowSelected (lastRowSelected))
  39566. {
  39567. if (model != 0)
  39568. model->returnKeyPressed (lastRowSelected);
  39569. }
  39570. else if (key.isKeyCode (KeyPress::pageUpKey))
  39571. {
  39572. if (multiple)
  39573. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39574. else
  39575. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39576. }
  39577. else if (key.isKeyCode (KeyPress::pageDownKey))
  39578. {
  39579. if (multiple)
  39580. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39581. else
  39582. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39583. }
  39584. else if (key.isKeyCode (KeyPress::homeKey))
  39585. {
  39586. if (multiple && key.getModifiers().isShiftDown())
  39587. selectRangeOfRows (lastRowSelected, 0);
  39588. else
  39589. selectRow (0);
  39590. }
  39591. else if (key.isKeyCode (KeyPress::endKey))
  39592. {
  39593. if (multiple && key.getModifiers().isShiftDown())
  39594. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39595. else
  39596. selectRow (totalItems - 1);
  39597. }
  39598. else if (key.isKeyCode (KeyPress::downKey))
  39599. {
  39600. if (multiple)
  39601. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39602. else
  39603. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39604. }
  39605. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39606. && isRowSelected (lastRowSelected))
  39607. {
  39608. if (model != 0)
  39609. model->deleteKeyPressed (lastRowSelected);
  39610. }
  39611. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39612. {
  39613. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39614. }
  39615. else
  39616. {
  39617. return false;
  39618. }
  39619. return true;
  39620. }
  39621. bool ListBox::keyStateChanged (const bool isKeyDown)
  39622. {
  39623. return isKeyDown
  39624. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39625. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39626. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39627. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39628. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39629. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39630. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39631. }
  39632. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39633. {
  39634. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39635. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39636. }
  39637. void ListBox::mouseMove (const MouseEvent& e)
  39638. {
  39639. if (mouseMoveSelects)
  39640. {
  39641. const MouseEvent e2 (e.getEventRelativeTo (this));
  39642. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39643. }
  39644. }
  39645. void ListBox::mouseExit (const MouseEvent& e)
  39646. {
  39647. mouseMove (e);
  39648. }
  39649. void ListBox::mouseUp (const MouseEvent& e)
  39650. {
  39651. if (e.mouseWasClicked() && model != 0)
  39652. model->backgroundClicked();
  39653. }
  39654. void ListBox::setRowHeight (const int newHeight)
  39655. {
  39656. rowHeight = jmax (1, newHeight);
  39657. viewport->setSingleStepSizes (20, rowHeight);
  39658. updateContent();
  39659. }
  39660. int ListBox::getNumRowsOnScreen() const throw()
  39661. {
  39662. return viewport->getMaximumVisibleHeight() / rowHeight;
  39663. }
  39664. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39665. {
  39666. minimumRowWidth = newMinimumWidth;
  39667. updateContent();
  39668. }
  39669. int ListBox::getVisibleContentWidth() const throw()
  39670. {
  39671. return viewport->getMaximumVisibleWidth();
  39672. }
  39673. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39674. {
  39675. return viewport->getVerticalScrollBar();
  39676. }
  39677. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39678. {
  39679. return viewport->getHorizontalScrollBar();
  39680. }
  39681. void ListBox::colourChanged()
  39682. {
  39683. setOpaque (findColour (backgroundColourId).isOpaque());
  39684. viewport->setOpaque (isOpaque());
  39685. repaint();
  39686. }
  39687. void ListBox::setOutlineThickness (const int outlineThickness_)
  39688. {
  39689. outlineThickness = outlineThickness_;
  39690. resized();
  39691. }
  39692. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39693. {
  39694. if (newHeaderComponent != headerComponent)
  39695. {
  39696. headerComponent = newHeaderComponent;
  39697. addAndMakeVisible (newHeaderComponent);
  39698. ListBox::resized();
  39699. }
  39700. }
  39701. void ListBox::repaintRow (const int rowNumber) throw()
  39702. {
  39703. repaint (getRowPosition (rowNumber, true));
  39704. }
  39705. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39706. {
  39707. Rectangle<int> imageArea;
  39708. const int firstRow = getRowContainingPosition (0, 0);
  39709. int i;
  39710. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39711. {
  39712. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39713. if (rowComp != 0 && isRowSelected (firstRow + i))
  39714. {
  39715. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39716. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39717. imageArea = imageArea.getUnion (rowRect);
  39718. }
  39719. }
  39720. imageArea = imageArea.getIntersection (getLocalBounds());
  39721. imageX = imageArea.getX();
  39722. imageY = imageArea.getY();
  39723. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39724. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39725. {
  39726. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39727. if (rowComp != 0 && isRowSelected (firstRow + i))
  39728. {
  39729. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39730. Graphics g (snapshot);
  39731. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39732. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  39733. rowComp->paintEntireComponent (g);
  39734. }
  39735. }
  39736. return snapshot;
  39737. }
  39738. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39739. {
  39740. DragAndDropContainer* const dragContainer
  39741. = DragAndDropContainer::findParentDragContainerFor (this);
  39742. if (dragContainer != 0)
  39743. {
  39744. int x, y;
  39745. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39746. dragImage.multiplyAllAlphas (0.6f);
  39747. MouseEvent e2 (e.getEventRelativeTo (this));
  39748. const Point<int> p (x - e2.x, y - e2.y);
  39749. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39750. }
  39751. else
  39752. {
  39753. // to be able to do a drag-and-drop operation, the listbox needs to
  39754. // be inside a component which is also a DragAndDropContainer.
  39755. jassertfalse;
  39756. }
  39757. }
  39758. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39759. {
  39760. (void) existingComponentToUpdate;
  39761. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39762. return 0;
  39763. }
  39764. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  39765. {
  39766. }
  39767. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  39768. {
  39769. }
  39770. void ListBoxModel::backgroundClicked()
  39771. {
  39772. }
  39773. void ListBoxModel::selectedRowsChanged (int)
  39774. {
  39775. }
  39776. void ListBoxModel::deleteKeyPressed (int)
  39777. {
  39778. }
  39779. void ListBoxModel::returnKeyPressed (int)
  39780. {
  39781. }
  39782. void ListBoxModel::listWasScrolled()
  39783. {
  39784. }
  39785. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  39786. {
  39787. return String::empty;
  39788. }
  39789. const String ListBoxModel::getTooltipForRow (int)
  39790. {
  39791. return String::empty;
  39792. }
  39793. END_JUCE_NAMESPACE
  39794. /*** End of inlined file: juce_ListBox.cpp ***/
  39795. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39796. BEGIN_JUCE_NAMESPACE
  39797. ProgressBar::ProgressBar (double& progress_)
  39798. : progress (progress_),
  39799. displayPercentage (true),
  39800. lastCallbackTime (0)
  39801. {
  39802. currentValue = jlimit (0.0, 1.0, progress);
  39803. }
  39804. ProgressBar::~ProgressBar()
  39805. {
  39806. }
  39807. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39808. {
  39809. displayPercentage = shouldDisplayPercentage;
  39810. repaint();
  39811. }
  39812. void ProgressBar::setTextToDisplay (const String& text)
  39813. {
  39814. displayPercentage = false;
  39815. displayedMessage = text;
  39816. }
  39817. void ProgressBar::lookAndFeelChanged()
  39818. {
  39819. setOpaque (findColour (backgroundColourId).isOpaque());
  39820. }
  39821. void ProgressBar::colourChanged()
  39822. {
  39823. lookAndFeelChanged();
  39824. }
  39825. void ProgressBar::paint (Graphics& g)
  39826. {
  39827. String text;
  39828. if (displayPercentage)
  39829. {
  39830. if (currentValue >= 0 && currentValue <= 1.0)
  39831. text << roundToInt (currentValue * 100.0) << '%';
  39832. }
  39833. else
  39834. {
  39835. text = displayedMessage;
  39836. }
  39837. getLookAndFeel().drawProgressBar (g, *this,
  39838. getWidth(), getHeight(),
  39839. currentValue, text);
  39840. }
  39841. void ProgressBar::visibilityChanged()
  39842. {
  39843. if (isVisible())
  39844. startTimer (30);
  39845. else
  39846. stopTimer();
  39847. }
  39848. void ProgressBar::timerCallback()
  39849. {
  39850. double newProgress = progress;
  39851. const uint32 now = Time::getMillisecondCounter();
  39852. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39853. lastCallbackTime = now;
  39854. if (currentValue != newProgress
  39855. || newProgress < 0 || newProgress >= 1.0
  39856. || currentMessage != displayedMessage)
  39857. {
  39858. if (currentValue < newProgress
  39859. && newProgress >= 0 && newProgress < 1.0
  39860. && currentValue >= 0 && currentValue < 1.0)
  39861. {
  39862. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39863. newProgress);
  39864. }
  39865. currentValue = newProgress;
  39866. currentMessage = displayedMessage;
  39867. repaint();
  39868. }
  39869. }
  39870. END_JUCE_NAMESPACE
  39871. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39872. /*** Start of inlined file: juce_Slider.cpp ***/
  39873. BEGIN_JUCE_NAMESPACE
  39874. class SliderPopupDisplayComponent : public BubbleComponent
  39875. {
  39876. public:
  39877. SliderPopupDisplayComponent (Slider* const owner_)
  39878. : owner (owner_),
  39879. font (15.0f, Font::bold)
  39880. {
  39881. setAlwaysOnTop (true);
  39882. }
  39883. ~SliderPopupDisplayComponent()
  39884. {
  39885. }
  39886. void paintContent (Graphics& g, int w, int h)
  39887. {
  39888. g.setFont (font);
  39889. g.setColour (Colours::black);
  39890. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39891. }
  39892. void getContentSize (int& w, int& h)
  39893. {
  39894. w = font.getStringWidth (text) + 18;
  39895. h = (int) (font.getHeight() * 1.6f);
  39896. }
  39897. void updatePosition (const String& newText)
  39898. {
  39899. if (text != newText)
  39900. {
  39901. text = newText;
  39902. repaint();
  39903. }
  39904. BubbleComponent::setPosition (owner);
  39905. }
  39906. juce_UseDebuggingNewOperator
  39907. private:
  39908. Slider* owner;
  39909. Font font;
  39910. String text;
  39911. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39912. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39913. };
  39914. Slider::Slider (const String& name)
  39915. : Component (name),
  39916. lastCurrentValue (0),
  39917. lastValueMin (0),
  39918. lastValueMax (0),
  39919. minimum (0),
  39920. maximum (10),
  39921. interval (0),
  39922. skewFactor (1.0),
  39923. velocityModeSensitivity (1.0),
  39924. velocityModeOffset (0.0),
  39925. velocityModeThreshold (1),
  39926. rotaryStart (float_Pi * 1.2f),
  39927. rotaryEnd (float_Pi * 2.8f),
  39928. numDecimalPlaces (7),
  39929. sliderRegionStart (0),
  39930. sliderRegionSize (1),
  39931. sliderBeingDragged (-1),
  39932. pixelsForFullDragExtent (250),
  39933. style (LinearHorizontal),
  39934. textBoxPos (TextBoxLeft),
  39935. textBoxWidth (80),
  39936. textBoxHeight (20),
  39937. incDecButtonMode (incDecButtonsNotDraggable),
  39938. editableText (true),
  39939. doubleClickToValue (false),
  39940. isVelocityBased (false),
  39941. userKeyOverridesVelocity (true),
  39942. rotaryStop (true),
  39943. incDecButtonsSideBySide (false),
  39944. sendChangeOnlyOnRelease (false),
  39945. popupDisplayEnabled (false),
  39946. menuEnabled (false),
  39947. menuShown (false),
  39948. scrollWheelEnabled (true),
  39949. snapsToMousePos (true),
  39950. valueBox (0),
  39951. incButton (0),
  39952. decButton (0),
  39953. popupDisplay (0),
  39954. parentForPopupDisplay (0)
  39955. {
  39956. setWantsKeyboardFocus (false);
  39957. setRepaintsOnMouseActivity (true);
  39958. lookAndFeelChanged();
  39959. updateText();
  39960. currentValue.addListener (this);
  39961. valueMin.addListener (this);
  39962. valueMax.addListener (this);
  39963. }
  39964. Slider::~Slider()
  39965. {
  39966. currentValue.removeListener (this);
  39967. valueMin.removeListener (this);
  39968. valueMax.removeListener (this);
  39969. popupDisplay = 0;
  39970. deleteAllChildren();
  39971. }
  39972. void Slider::handleAsyncUpdate()
  39973. {
  39974. cancelPendingUpdate();
  39975. Component::BailOutChecker checker (this);
  39976. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39977. }
  39978. void Slider::sendDragStart()
  39979. {
  39980. startedDragging();
  39981. Component::BailOutChecker checker (this);
  39982. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39983. }
  39984. void Slider::sendDragEnd()
  39985. {
  39986. stoppedDragging();
  39987. sliderBeingDragged = -1;
  39988. Component::BailOutChecker checker (this);
  39989. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39990. }
  39991. void Slider::addListener (Listener* const listener)
  39992. {
  39993. listeners.add (listener);
  39994. }
  39995. void Slider::removeListener (Listener* const listener)
  39996. {
  39997. listeners.remove (listener);
  39998. }
  39999. void Slider::setSliderStyle (const SliderStyle newStyle)
  40000. {
  40001. if (style != newStyle)
  40002. {
  40003. style = newStyle;
  40004. repaint();
  40005. lookAndFeelChanged();
  40006. }
  40007. }
  40008. void Slider::setRotaryParameters (const float startAngleRadians,
  40009. const float endAngleRadians,
  40010. const bool stopAtEnd)
  40011. {
  40012. // make sure the values are sensible..
  40013. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  40014. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  40015. jassert (rotaryStart < rotaryEnd);
  40016. rotaryStart = startAngleRadians;
  40017. rotaryEnd = endAngleRadians;
  40018. rotaryStop = stopAtEnd;
  40019. }
  40020. void Slider::setVelocityBasedMode (const bool velBased)
  40021. {
  40022. isVelocityBased = velBased;
  40023. }
  40024. void Slider::setVelocityModeParameters (const double sensitivity,
  40025. const int threshold,
  40026. const double offset,
  40027. const bool userCanPressKeyToSwapMode)
  40028. {
  40029. jassert (threshold >= 0);
  40030. jassert (sensitivity > 0);
  40031. jassert (offset >= 0);
  40032. velocityModeSensitivity = sensitivity;
  40033. velocityModeOffset = offset;
  40034. velocityModeThreshold = threshold;
  40035. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  40036. }
  40037. void Slider::setSkewFactor (const double factor)
  40038. {
  40039. skewFactor = factor;
  40040. }
  40041. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  40042. {
  40043. if (maximum > minimum)
  40044. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  40045. / (maximum - minimum));
  40046. }
  40047. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  40048. {
  40049. jassert (distanceForFullScaleDrag > 0);
  40050. pixelsForFullDragExtent = distanceForFullScaleDrag;
  40051. }
  40052. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  40053. {
  40054. if (incDecButtonMode != mode)
  40055. {
  40056. incDecButtonMode = mode;
  40057. lookAndFeelChanged();
  40058. }
  40059. }
  40060. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  40061. const bool isReadOnly,
  40062. const int textEntryBoxWidth,
  40063. const int textEntryBoxHeight)
  40064. {
  40065. if (textBoxPos != newPosition
  40066. || editableText != (! isReadOnly)
  40067. || textBoxWidth != textEntryBoxWidth
  40068. || textBoxHeight != textEntryBoxHeight)
  40069. {
  40070. textBoxPos = newPosition;
  40071. editableText = ! isReadOnly;
  40072. textBoxWidth = textEntryBoxWidth;
  40073. textBoxHeight = textEntryBoxHeight;
  40074. repaint();
  40075. lookAndFeelChanged();
  40076. }
  40077. }
  40078. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  40079. {
  40080. editableText = shouldBeEditable;
  40081. if (valueBox != 0)
  40082. valueBox->setEditable (shouldBeEditable && isEnabled());
  40083. }
  40084. void Slider::showTextBox()
  40085. {
  40086. jassert (editableText); // this should probably be avoided in read-only sliders.
  40087. if (valueBox != 0)
  40088. valueBox->showEditor();
  40089. }
  40090. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  40091. {
  40092. if (valueBox != 0)
  40093. {
  40094. valueBox->hideEditor (discardCurrentEditorContents);
  40095. if (discardCurrentEditorContents)
  40096. updateText();
  40097. }
  40098. }
  40099. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  40100. {
  40101. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  40102. }
  40103. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  40104. {
  40105. snapsToMousePos = shouldSnapToMouse;
  40106. }
  40107. void Slider::setPopupDisplayEnabled (const bool enabled,
  40108. Component* const parentComponentToUse)
  40109. {
  40110. popupDisplayEnabled = enabled;
  40111. parentForPopupDisplay = parentComponentToUse;
  40112. }
  40113. void Slider::colourChanged()
  40114. {
  40115. lookAndFeelChanged();
  40116. }
  40117. void Slider::lookAndFeelChanged()
  40118. {
  40119. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  40120. : getTextFromValue (currentValue.getValue()));
  40121. deleteAllChildren();
  40122. valueBox = 0;
  40123. LookAndFeel& lf = getLookAndFeel();
  40124. if (textBoxPos != NoTextBox)
  40125. {
  40126. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  40127. valueBox->setWantsKeyboardFocus (false);
  40128. valueBox->setText (previousTextBoxContent, false);
  40129. valueBox->setEditable (editableText && isEnabled());
  40130. valueBox->addListener (this);
  40131. if (style == LinearBar)
  40132. valueBox->addMouseListener (this, false);
  40133. valueBox->setTooltip (getTooltip());
  40134. }
  40135. if (style == IncDecButtons)
  40136. {
  40137. addAndMakeVisible (incButton = lf.createSliderButton (true));
  40138. incButton->addButtonListener (this);
  40139. addAndMakeVisible (decButton = lf.createSliderButton (false));
  40140. decButton->addButtonListener (this);
  40141. if (incDecButtonMode != incDecButtonsNotDraggable)
  40142. {
  40143. incButton->addMouseListener (this, false);
  40144. decButton->addMouseListener (this, false);
  40145. }
  40146. else
  40147. {
  40148. incButton->setRepeatSpeed (300, 100, 20);
  40149. incButton->addMouseListener (decButton, false);
  40150. decButton->setRepeatSpeed (300, 100, 20);
  40151. decButton->addMouseListener (incButton, false);
  40152. }
  40153. incButton->setTooltip (getTooltip());
  40154. decButton->setTooltip (getTooltip());
  40155. }
  40156. setComponentEffect (lf.getSliderEffect());
  40157. resized();
  40158. repaint();
  40159. }
  40160. void Slider::setRange (const double newMin,
  40161. const double newMax,
  40162. const double newInt)
  40163. {
  40164. if (minimum != newMin
  40165. || maximum != newMax
  40166. || interval != newInt)
  40167. {
  40168. minimum = newMin;
  40169. maximum = newMax;
  40170. interval = newInt;
  40171. // figure out the number of DPs needed to display all values at this
  40172. // interval setting.
  40173. numDecimalPlaces = 7;
  40174. if (newInt != 0)
  40175. {
  40176. int v = abs ((int) (newInt * 10000000));
  40177. while ((v % 10) == 0)
  40178. {
  40179. --numDecimalPlaces;
  40180. v /= 10;
  40181. }
  40182. }
  40183. // keep the current values inside the new range..
  40184. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40185. {
  40186. setValue (getValue(), false, false);
  40187. }
  40188. else
  40189. {
  40190. setMinValue (getMinValue(), false, false);
  40191. setMaxValue (getMaxValue(), false, false);
  40192. }
  40193. updateText();
  40194. }
  40195. }
  40196. void Slider::triggerChangeMessage (const bool synchronous)
  40197. {
  40198. if (synchronous)
  40199. handleAsyncUpdate();
  40200. else
  40201. triggerAsyncUpdate();
  40202. valueChanged();
  40203. }
  40204. void Slider::valueChanged (Value& value)
  40205. {
  40206. if (value.refersToSameSourceAs (currentValue))
  40207. {
  40208. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40209. setValue (currentValue.getValue(), false, false);
  40210. }
  40211. else if (value.refersToSameSourceAs (valueMin))
  40212. setMinValue (valueMin.getValue(), false, false, true);
  40213. else if (value.refersToSameSourceAs (valueMax))
  40214. setMaxValue (valueMax.getValue(), false, false, true);
  40215. }
  40216. double Slider::getValue() const
  40217. {
  40218. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40219. // methods to get the two values.
  40220. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40221. return currentValue.getValue();
  40222. }
  40223. void Slider::setValue (double newValue,
  40224. const bool sendUpdateMessage,
  40225. const bool sendMessageSynchronously)
  40226. {
  40227. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40228. // methods to set the two values.
  40229. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40230. newValue = constrainedValue (newValue);
  40231. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40232. {
  40233. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40234. newValue = jlimit ((double) valueMin.getValue(),
  40235. (double) valueMax.getValue(),
  40236. newValue);
  40237. }
  40238. if (newValue != lastCurrentValue)
  40239. {
  40240. if (valueBox != 0)
  40241. valueBox->hideEditor (true);
  40242. lastCurrentValue = newValue;
  40243. currentValue = newValue;
  40244. updateText();
  40245. repaint();
  40246. if (popupDisplay != 0)
  40247. {
  40248. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40249. ->updatePosition (getTextFromValue (newValue));
  40250. popupDisplay->repaint();
  40251. }
  40252. if (sendUpdateMessage)
  40253. triggerChangeMessage (sendMessageSynchronously);
  40254. }
  40255. }
  40256. double Slider::getMinValue() const
  40257. {
  40258. // The minimum value only applies to sliders that are in two- or three-value mode.
  40259. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40260. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40261. return valueMin.getValue();
  40262. }
  40263. double Slider::getMaxValue() const
  40264. {
  40265. // The maximum value only applies to sliders that are in two- or three-value mode.
  40266. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40267. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40268. return valueMax.getValue();
  40269. }
  40270. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40271. {
  40272. // The minimum value only applies to sliders that are in two- or three-value mode.
  40273. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40274. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40275. newValue = constrainedValue (newValue);
  40276. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40277. {
  40278. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40279. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40280. newValue = jmin ((double) valueMax.getValue(), newValue);
  40281. }
  40282. else
  40283. {
  40284. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40285. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40286. newValue = jmin (lastCurrentValue, newValue);
  40287. }
  40288. if (lastValueMin != newValue)
  40289. {
  40290. lastValueMin = newValue;
  40291. valueMin = newValue;
  40292. repaint();
  40293. if (popupDisplay != 0)
  40294. {
  40295. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40296. ->updatePosition (getTextFromValue (newValue));
  40297. popupDisplay->repaint();
  40298. }
  40299. if (sendUpdateMessage)
  40300. triggerChangeMessage (sendMessageSynchronously);
  40301. }
  40302. }
  40303. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40304. {
  40305. // The maximum value only applies to sliders that are in two- or three-value mode.
  40306. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40307. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40308. newValue = constrainedValue (newValue);
  40309. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40310. {
  40311. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40312. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40313. newValue = jmax ((double) valueMin.getValue(), newValue);
  40314. }
  40315. else
  40316. {
  40317. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40318. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40319. newValue = jmax (lastCurrentValue, newValue);
  40320. }
  40321. if (lastValueMax != newValue)
  40322. {
  40323. lastValueMax = newValue;
  40324. valueMax = newValue;
  40325. repaint();
  40326. if (popupDisplay != 0)
  40327. {
  40328. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40329. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40330. popupDisplay->repaint();
  40331. }
  40332. if (sendUpdateMessage)
  40333. triggerChangeMessage (sendMessageSynchronously);
  40334. }
  40335. }
  40336. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40337. const double valueToSetOnDoubleClick)
  40338. {
  40339. doubleClickToValue = isDoubleClickEnabled;
  40340. doubleClickReturnValue = valueToSetOnDoubleClick;
  40341. }
  40342. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40343. {
  40344. isEnabled_ = doubleClickToValue;
  40345. return doubleClickReturnValue;
  40346. }
  40347. void Slider::updateText()
  40348. {
  40349. if (valueBox != 0)
  40350. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40351. }
  40352. void Slider::setTextValueSuffix (const String& suffix)
  40353. {
  40354. if (textSuffix != suffix)
  40355. {
  40356. textSuffix = suffix;
  40357. updateText();
  40358. }
  40359. }
  40360. const String Slider::getTextValueSuffix() const
  40361. {
  40362. return textSuffix;
  40363. }
  40364. const String Slider::getTextFromValue (double v)
  40365. {
  40366. if (getNumDecimalPlacesToDisplay() > 0)
  40367. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40368. else
  40369. return String (roundToInt (v)) + getTextValueSuffix();
  40370. }
  40371. double Slider::getValueFromText (const String& text)
  40372. {
  40373. String t (text.trimStart());
  40374. if (t.endsWith (textSuffix))
  40375. t = t.substring (0, t.length() - textSuffix.length());
  40376. while (t.startsWithChar ('+'))
  40377. t = t.substring (1).trimStart();
  40378. return t.initialSectionContainingOnly ("0123456789.,-")
  40379. .getDoubleValue();
  40380. }
  40381. double Slider::proportionOfLengthToValue (double proportion)
  40382. {
  40383. if (skewFactor != 1.0 && proportion > 0.0)
  40384. proportion = exp (log (proportion) / skewFactor);
  40385. return minimum + (maximum - minimum) * proportion;
  40386. }
  40387. double Slider::valueToProportionOfLength (double value)
  40388. {
  40389. const double n = (value - minimum) / (maximum - minimum);
  40390. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40391. }
  40392. double Slider::snapValue (double attemptedValue, const bool)
  40393. {
  40394. return attemptedValue;
  40395. }
  40396. void Slider::startedDragging()
  40397. {
  40398. }
  40399. void Slider::stoppedDragging()
  40400. {
  40401. }
  40402. void Slider::valueChanged()
  40403. {
  40404. }
  40405. void Slider::enablementChanged()
  40406. {
  40407. repaint();
  40408. }
  40409. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40410. {
  40411. menuEnabled = menuEnabled_;
  40412. }
  40413. void Slider::setScrollWheelEnabled (const bool enabled)
  40414. {
  40415. scrollWheelEnabled = enabled;
  40416. }
  40417. void Slider::labelTextChanged (Label* label)
  40418. {
  40419. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40420. if (newValue != (double) currentValue.getValue())
  40421. {
  40422. sendDragStart();
  40423. setValue (newValue, true, true);
  40424. sendDragEnd();
  40425. }
  40426. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40427. }
  40428. void Slider::buttonClicked (Button* button)
  40429. {
  40430. if (style == IncDecButtons)
  40431. {
  40432. sendDragStart();
  40433. if (button == incButton)
  40434. setValue (snapValue (getValue() + interval, false), true, true);
  40435. else if (button == decButton)
  40436. setValue (snapValue (getValue() - interval, false), true, true);
  40437. sendDragEnd();
  40438. }
  40439. }
  40440. double Slider::constrainedValue (double value) const
  40441. {
  40442. if (interval > 0)
  40443. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40444. if (value <= minimum || maximum <= minimum)
  40445. value = minimum;
  40446. else if (value >= maximum)
  40447. value = maximum;
  40448. return value;
  40449. }
  40450. float Slider::getLinearSliderPos (const double value)
  40451. {
  40452. double sliderPosProportional;
  40453. if (maximum > minimum)
  40454. {
  40455. if (value < minimum)
  40456. {
  40457. sliderPosProportional = 0.0;
  40458. }
  40459. else if (value > maximum)
  40460. {
  40461. sliderPosProportional = 1.0;
  40462. }
  40463. else
  40464. {
  40465. sliderPosProportional = valueToProportionOfLength (value);
  40466. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40467. }
  40468. }
  40469. else
  40470. {
  40471. sliderPosProportional = 0.5;
  40472. }
  40473. if (isVertical() || style == IncDecButtons)
  40474. sliderPosProportional = 1.0 - sliderPosProportional;
  40475. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40476. }
  40477. bool Slider::isHorizontal() const
  40478. {
  40479. return style == LinearHorizontal
  40480. || style == LinearBar
  40481. || style == TwoValueHorizontal
  40482. || style == ThreeValueHorizontal;
  40483. }
  40484. bool Slider::isVertical() const
  40485. {
  40486. return style == LinearVertical
  40487. || style == TwoValueVertical
  40488. || style == ThreeValueVertical;
  40489. }
  40490. bool Slider::incDecDragDirectionIsHorizontal() const
  40491. {
  40492. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40493. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40494. }
  40495. float Slider::getPositionOfValue (const double value)
  40496. {
  40497. if (isHorizontal() || isVertical())
  40498. {
  40499. return getLinearSliderPos (value);
  40500. }
  40501. else
  40502. {
  40503. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40504. return 0.0f;
  40505. }
  40506. }
  40507. void Slider::paint (Graphics& g)
  40508. {
  40509. if (style != IncDecButtons)
  40510. {
  40511. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40512. {
  40513. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40514. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40515. getLookAndFeel().drawRotarySlider (g,
  40516. sliderRect.getX(),
  40517. sliderRect.getY(),
  40518. sliderRect.getWidth(),
  40519. sliderRect.getHeight(),
  40520. sliderPos,
  40521. rotaryStart, rotaryEnd,
  40522. *this);
  40523. }
  40524. else
  40525. {
  40526. getLookAndFeel().drawLinearSlider (g,
  40527. sliderRect.getX(),
  40528. sliderRect.getY(),
  40529. sliderRect.getWidth(),
  40530. sliderRect.getHeight(),
  40531. getLinearSliderPos (lastCurrentValue),
  40532. getLinearSliderPos (lastValueMin),
  40533. getLinearSliderPos (lastValueMax),
  40534. style,
  40535. *this);
  40536. }
  40537. if (style == LinearBar && valueBox == 0)
  40538. {
  40539. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40540. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40541. }
  40542. }
  40543. }
  40544. void Slider::resized()
  40545. {
  40546. int minXSpace = 0;
  40547. int minYSpace = 0;
  40548. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40549. minXSpace = 30;
  40550. else
  40551. minYSpace = 15;
  40552. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40553. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40554. if (style == LinearBar)
  40555. {
  40556. if (valueBox != 0)
  40557. valueBox->setBounds (getLocalBounds());
  40558. }
  40559. else
  40560. {
  40561. if (textBoxPos == NoTextBox)
  40562. {
  40563. sliderRect = getLocalBounds();
  40564. }
  40565. else if (textBoxPos == TextBoxLeft)
  40566. {
  40567. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40568. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40569. }
  40570. else if (textBoxPos == TextBoxRight)
  40571. {
  40572. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40573. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40574. }
  40575. else if (textBoxPos == TextBoxAbove)
  40576. {
  40577. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40578. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40579. }
  40580. else if (textBoxPos == TextBoxBelow)
  40581. {
  40582. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40583. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40584. }
  40585. }
  40586. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40587. if (style == LinearBar)
  40588. {
  40589. const int barIndent = 1;
  40590. sliderRegionStart = barIndent;
  40591. sliderRegionSize = getWidth() - barIndent * 2;
  40592. sliderRect.setBounds (sliderRegionStart, barIndent,
  40593. sliderRegionSize, getHeight() - barIndent * 2);
  40594. }
  40595. else if (isHorizontal())
  40596. {
  40597. sliderRegionStart = sliderRect.getX() + indent;
  40598. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40599. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40600. sliderRegionSize, sliderRect.getHeight());
  40601. }
  40602. else if (isVertical())
  40603. {
  40604. sliderRegionStart = sliderRect.getY() + indent;
  40605. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40606. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40607. sliderRect.getWidth(), sliderRegionSize);
  40608. }
  40609. else
  40610. {
  40611. sliderRegionStart = 0;
  40612. sliderRegionSize = 100;
  40613. }
  40614. if (style == IncDecButtons)
  40615. {
  40616. Rectangle<int> buttonRect (sliderRect);
  40617. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40618. buttonRect.expand (-2, 0);
  40619. else
  40620. buttonRect.expand (0, -2);
  40621. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40622. if (incDecButtonsSideBySide)
  40623. {
  40624. decButton->setBounds (buttonRect.getX(),
  40625. buttonRect.getY(),
  40626. buttonRect.getWidth() / 2,
  40627. buttonRect.getHeight());
  40628. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40629. incButton->setBounds (buttonRect.getCentreX(),
  40630. buttonRect.getY(),
  40631. buttonRect.getWidth() / 2,
  40632. buttonRect.getHeight());
  40633. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40634. }
  40635. else
  40636. {
  40637. incButton->setBounds (buttonRect.getX(),
  40638. buttonRect.getY(),
  40639. buttonRect.getWidth(),
  40640. buttonRect.getHeight() / 2);
  40641. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40642. decButton->setBounds (buttonRect.getX(),
  40643. buttonRect.getCentreY(),
  40644. buttonRect.getWidth(),
  40645. buttonRect.getHeight() / 2);
  40646. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40647. }
  40648. }
  40649. }
  40650. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40651. {
  40652. repaint();
  40653. }
  40654. void Slider::mouseDown (const MouseEvent& e)
  40655. {
  40656. mouseWasHidden = false;
  40657. incDecDragged = false;
  40658. mouseXWhenLastDragged = e.x;
  40659. mouseYWhenLastDragged = e.y;
  40660. mouseDragStartX = e.getMouseDownX();
  40661. mouseDragStartY = e.getMouseDownY();
  40662. if (isEnabled())
  40663. {
  40664. if (e.mods.isPopupMenu() && menuEnabled)
  40665. {
  40666. menuShown = true;
  40667. PopupMenu m;
  40668. m.setLookAndFeel (&getLookAndFeel());
  40669. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40670. m.addSeparator();
  40671. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40672. {
  40673. PopupMenu rotaryMenu;
  40674. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40675. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40676. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40677. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40678. }
  40679. const int r = m.show();
  40680. if (r == 1)
  40681. {
  40682. setVelocityBasedMode (! isVelocityBased);
  40683. }
  40684. else if (r == 2)
  40685. {
  40686. setSliderStyle (Rotary);
  40687. }
  40688. else if (r == 3)
  40689. {
  40690. setSliderStyle (RotaryHorizontalDrag);
  40691. }
  40692. else if (r == 4)
  40693. {
  40694. setSliderStyle (RotaryVerticalDrag);
  40695. }
  40696. }
  40697. else if (maximum > minimum)
  40698. {
  40699. menuShown = false;
  40700. if (valueBox != 0)
  40701. valueBox->hideEditor (true);
  40702. sliderBeingDragged = 0;
  40703. if (style == TwoValueHorizontal
  40704. || style == TwoValueVertical
  40705. || style == ThreeValueHorizontal
  40706. || style == ThreeValueVertical)
  40707. {
  40708. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40709. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40710. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40711. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40712. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40713. {
  40714. if (maxPosDistance <= minPosDistance)
  40715. sliderBeingDragged = 2;
  40716. else
  40717. sliderBeingDragged = 1;
  40718. }
  40719. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40720. {
  40721. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40722. sliderBeingDragged = 1;
  40723. else if (normalPosDistance >= maxPosDistance)
  40724. sliderBeingDragged = 2;
  40725. }
  40726. }
  40727. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40728. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40729. * valueToProportionOfLength (currentValue.getValue());
  40730. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40731. : ((sliderBeingDragged == 1) ? valueMin
  40732. : currentValue)).getValue();
  40733. valueOnMouseDown = valueWhenLastDragged;
  40734. if (popupDisplayEnabled)
  40735. {
  40736. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40737. popupDisplay = popup;
  40738. if (parentForPopupDisplay != 0)
  40739. {
  40740. parentForPopupDisplay->addChildComponent (popup);
  40741. }
  40742. else
  40743. {
  40744. popup->addToDesktop (0);
  40745. }
  40746. popup->setVisible (true);
  40747. }
  40748. sendDragStart();
  40749. mouseDrag (e);
  40750. }
  40751. }
  40752. }
  40753. void Slider::mouseUp (const MouseEvent&)
  40754. {
  40755. if (isEnabled()
  40756. && (! menuShown)
  40757. && (maximum > minimum)
  40758. && (style != IncDecButtons || incDecDragged))
  40759. {
  40760. restoreMouseIfHidden();
  40761. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40762. triggerChangeMessage (false);
  40763. sendDragEnd();
  40764. popupDisplay = 0;
  40765. if (style == IncDecButtons)
  40766. {
  40767. incButton->setState (Button::buttonNormal);
  40768. decButton->setState (Button::buttonNormal);
  40769. }
  40770. }
  40771. }
  40772. void Slider::restoreMouseIfHidden()
  40773. {
  40774. if (mouseWasHidden)
  40775. {
  40776. mouseWasHidden = false;
  40777. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40778. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40779. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40780. : ((sliderBeingDragged == 1) ? getMinValue()
  40781. : (double) currentValue.getValue());
  40782. Point<int> mousePos;
  40783. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40784. {
  40785. mousePos = Desktop::getLastMouseDownPosition();
  40786. if (style == RotaryHorizontalDrag)
  40787. {
  40788. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40789. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40790. }
  40791. else
  40792. {
  40793. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40794. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40795. }
  40796. }
  40797. else
  40798. {
  40799. const int pixelPos = (int) getLinearSliderPos (pos);
  40800. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40801. isVertical() ? pixelPos : (getHeight() / 2)));
  40802. }
  40803. Desktop::setMousePosition (mousePos);
  40804. }
  40805. }
  40806. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40807. {
  40808. if (isEnabled()
  40809. && style != IncDecButtons
  40810. && style != Rotary
  40811. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40812. {
  40813. restoreMouseIfHidden();
  40814. }
  40815. }
  40816. static double smallestAngleBetween (double a1, double a2)
  40817. {
  40818. return jmin (std::abs (a1 - a2),
  40819. std::abs (a1 + double_Pi * 2.0 - a2),
  40820. std::abs (a2 + double_Pi * 2.0 - a1));
  40821. }
  40822. void Slider::mouseDrag (const MouseEvent& e)
  40823. {
  40824. if (isEnabled()
  40825. && (! menuShown)
  40826. && (maximum > minimum))
  40827. {
  40828. if (style == Rotary)
  40829. {
  40830. int dx = e.x - sliderRect.getCentreX();
  40831. int dy = e.y - sliderRect.getCentreY();
  40832. if (dx * dx + dy * dy > 25)
  40833. {
  40834. double angle = std::atan2 ((double) dx, (double) -dy);
  40835. while (angle < 0.0)
  40836. angle += double_Pi * 2.0;
  40837. if (rotaryStop && ! e.mouseWasClicked())
  40838. {
  40839. if (std::abs (angle - lastAngle) > double_Pi)
  40840. {
  40841. if (angle >= lastAngle)
  40842. angle -= double_Pi * 2.0;
  40843. else
  40844. angle += double_Pi * 2.0;
  40845. }
  40846. if (angle >= lastAngle)
  40847. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40848. else
  40849. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40850. }
  40851. else
  40852. {
  40853. while (angle < rotaryStart)
  40854. angle += double_Pi * 2.0;
  40855. if (angle > rotaryEnd)
  40856. {
  40857. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  40858. angle = rotaryStart;
  40859. else
  40860. angle = rotaryEnd;
  40861. }
  40862. }
  40863. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40864. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40865. lastAngle = angle;
  40866. }
  40867. }
  40868. else
  40869. {
  40870. if (style == LinearBar && e.mouseWasClicked()
  40871. && valueBox != 0 && valueBox->isEditable())
  40872. return;
  40873. if (style == IncDecButtons && ! incDecDragged)
  40874. {
  40875. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40876. return;
  40877. incDecDragged = true;
  40878. mouseDragStartX = e.x;
  40879. mouseDragStartY = e.y;
  40880. }
  40881. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40882. : false))
  40883. || ((maximum - minimum) / sliderRegionSize < interval))
  40884. {
  40885. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40886. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40887. if (style == RotaryHorizontalDrag
  40888. || style == RotaryVerticalDrag
  40889. || style == IncDecButtons
  40890. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40891. && ! snapsToMousePos))
  40892. {
  40893. const int mouseDiff = (style == RotaryHorizontalDrag
  40894. || style == LinearHorizontal
  40895. || style == LinearBar
  40896. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40897. ? e.x - mouseDragStartX
  40898. : mouseDragStartY - e.y;
  40899. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40900. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40901. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40902. if (style == IncDecButtons)
  40903. {
  40904. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40905. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40906. }
  40907. }
  40908. else
  40909. {
  40910. if (isVertical())
  40911. scaledMousePos = 1.0 - scaledMousePos;
  40912. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40913. }
  40914. }
  40915. else
  40916. {
  40917. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40918. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40919. ? e.x - mouseXWhenLastDragged
  40920. : e.y - mouseYWhenLastDragged;
  40921. const double maxSpeed = jmax (200, sliderRegionSize);
  40922. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40923. if (speed != 0)
  40924. {
  40925. speed = 0.2 * velocityModeSensitivity
  40926. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40927. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40928. / maxSpeed))));
  40929. if (mouseDiff < 0)
  40930. speed = -speed;
  40931. if (isVertical() || style == RotaryVerticalDrag
  40932. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40933. speed = -speed;
  40934. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40935. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40936. e.source.enableUnboundedMouseMovement (true, false);
  40937. mouseWasHidden = true;
  40938. }
  40939. }
  40940. }
  40941. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40942. if (sliderBeingDragged == 0)
  40943. {
  40944. setValue (snapValue (valueWhenLastDragged, true),
  40945. ! sendChangeOnlyOnRelease, true);
  40946. }
  40947. else if (sliderBeingDragged == 1)
  40948. {
  40949. setMinValue (snapValue (valueWhenLastDragged, true),
  40950. ! sendChangeOnlyOnRelease, false, true);
  40951. if (e.mods.isShiftDown())
  40952. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40953. else
  40954. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40955. }
  40956. else
  40957. {
  40958. jassert (sliderBeingDragged == 2);
  40959. setMaxValue (snapValue (valueWhenLastDragged, true),
  40960. ! sendChangeOnlyOnRelease, false, true);
  40961. if (e.mods.isShiftDown())
  40962. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40963. else
  40964. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40965. }
  40966. mouseXWhenLastDragged = e.x;
  40967. mouseYWhenLastDragged = e.y;
  40968. }
  40969. }
  40970. void Slider::mouseDoubleClick (const MouseEvent&)
  40971. {
  40972. if (doubleClickToValue
  40973. && isEnabled()
  40974. && style != IncDecButtons
  40975. && minimum <= doubleClickReturnValue
  40976. && maximum >= doubleClickReturnValue)
  40977. {
  40978. sendDragStart();
  40979. setValue (doubleClickReturnValue, true, true);
  40980. sendDragEnd();
  40981. }
  40982. }
  40983. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40984. {
  40985. if (scrollWheelEnabled && isEnabled()
  40986. && style != TwoValueHorizontal
  40987. && style != TwoValueVertical)
  40988. {
  40989. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40990. {
  40991. if (valueBox != 0)
  40992. valueBox->hideEditor (false);
  40993. const double value = (double) currentValue.getValue();
  40994. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40995. const double currentPos = valueToProportionOfLength (value);
  40996. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40997. double delta = (newValue != value)
  40998. ? jmax (std::abs (newValue - value), interval) : 0;
  40999. if (value > newValue)
  41000. delta = -delta;
  41001. sendDragStart();
  41002. setValue (snapValue (value + delta, false), true, true);
  41003. sendDragEnd();
  41004. }
  41005. }
  41006. else
  41007. {
  41008. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  41009. }
  41010. }
  41011. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  41012. {
  41013. }
  41014. void SliderListener::sliderDragEnded (Slider*)
  41015. {
  41016. }
  41017. END_JUCE_NAMESPACE
  41018. /*** End of inlined file: juce_Slider.cpp ***/
  41019. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  41020. BEGIN_JUCE_NAMESPACE
  41021. class DragOverlayComp : public Component
  41022. {
  41023. public:
  41024. DragOverlayComp (const Image& image_)
  41025. : image (image_)
  41026. {
  41027. image.duplicateIfShared();
  41028. image.multiplyAllAlphas (0.8f);
  41029. setAlwaysOnTop (true);
  41030. }
  41031. ~DragOverlayComp()
  41032. {
  41033. }
  41034. void paint (Graphics& g)
  41035. {
  41036. g.drawImageAt (image, 0, 0);
  41037. }
  41038. private:
  41039. Image image;
  41040. DragOverlayComp (const DragOverlayComp&);
  41041. DragOverlayComp& operator= (const DragOverlayComp&);
  41042. };
  41043. TableHeaderComponent::TableHeaderComponent()
  41044. : columnsChanged (false),
  41045. columnsResized (false),
  41046. sortChanged (false),
  41047. menuActive (true),
  41048. stretchToFit (false),
  41049. columnIdBeingResized (0),
  41050. columnIdBeingDragged (0),
  41051. columnIdUnderMouse (0),
  41052. lastDeliberateWidth (0)
  41053. {
  41054. }
  41055. TableHeaderComponent::~TableHeaderComponent()
  41056. {
  41057. dragOverlayComp = 0;
  41058. }
  41059. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  41060. {
  41061. menuActive = hasMenu;
  41062. }
  41063. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  41064. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  41065. {
  41066. if (onlyCountVisibleColumns)
  41067. {
  41068. int num = 0;
  41069. for (int i = columns.size(); --i >= 0;)
  41070. if (columns.getUnchecked(i)->isVisible())
  41071. ++num;
  41072. return num;
  41073. }
  41074. else
  41075. {
  41076. return columns.size();
  41077. }
  41078. }
  41079. const String TableHeaderComponent::getColumnName (const int columnId) const
  41080. {
  41081. const ColumnInfo* const ci = getInfoForId (columnId);
  41082. return ci != 0 ? ci->name : String::empty;
  41083. }
  41084. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  41085. {
  41086. ColumnInfo* const ci = getInfoForId (columnId);
  41087. if (ci != 0 && ci->name != newName)
  41088. {
  41089. ci->name = newName;
  41090. sendColumnsChanged();
  41091. }
  41092. }
  41093. void TableHeaderComponent::addColumn (const String& columnName,
  41094. const int columnId,
  41095. const int width,
  41096. const int minimumWidth,
  41097. const int maximumWidth,
  41098. const int propertyFlags,
  41099. const int insertIndex)
  41100. {
  41101. // can't have a duplicate or null ID!
  41102. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  41103. jassert (width > 0);
  41104. ColumnInfo* const ci = new ColumnInfo();
  41105. ci->name = columnName;
  41106. ci->id = columnId;
  41107. ci->width = width;
  41108. ci->lastDeliberateWidth = width;
  41109. ci->minimumWidth = minimumWidth;
  41110. ci->maximumWidth = maximumWidth;
  41111. if (ci->maximumWidth < 0)
  41112. ci->maximumWidth = std::numeric_limits<int>::max();
  41113. jassert (ci->maximumWidth >= ci->minimumWidth);
  41114. ci->propertyFlags = propertyFlags;
  41115. columns.insert (insertIndex, ci);
  41116. sendColumnsChanged();
  41117. }
  41118. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  41119. {
  41120. const int index = getIndexOfColumnId (columnIdToRemove, false);
  41121. if (index >= 0)
  41122. {
  41123. columns.remove (index);
  41124. sortChanged = true;
  41125. sendColumnsChanged();
  41126. }
  41127. }
  41128. void TableHeaderComponent::removeAllColumns()
  41129. {
  41130. if (columns.size() > 0)
  41131. {
  41132. columns.clear();
  41133. sendColumnsChanged();
  41134. }
  41135. }
  41136. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  41137. {
  41138. const int currentIndex = getIndexOfColumnId (columnId, false);
  41139. newIndex = visibleIndexToTotalIndex (newIndex);
  41140. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  41141. {
  41142. columns.move (currentIndex, newIndex);
  41143. sendColumnsChanged();
  41144. }
  41145. }
  41146. int TableHeaderComponent::getColumnWidth (const int columnId) const
  41147. {
  41148. const ColumnInfo* const ci = getInfoForId (columnId);
  41149. return ci != 0 ? ci->width : 0;
  41150. }
  41151. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  41152. {
  41153. ColumnInfo* const ci = getInfoForId (columnId);
  41154. if (ci != 0 && ci->width != newWidth)
  41155. {
  41156. const int numColumns = getNumColumns (true);
  41157. ci->lastDeliberateWidth = ci->width
  41158. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  41159. if (stretchToFit)
  41160. {
  41161. const int index = getIndexOfColumnId (columnId, true) + 1;
  41162. if (((unsigned int) index) < (unsigned int) numColumns)
  41163. {
  41164. const int x = getColumnPosition (index).getX();
  41165. if (lastDeliberateWidth == 0)
  41166. lastDeliberateWidth = getTotalWidth();
  41167. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  41168. }
  41169. }
  41170. repaint();
  41171. columnsResized = true;
  41172. triggerAsyncUpdate();
  41173. }
  41174. }
  41175. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41176. {
  41177. int n = 0;
  41178. for (int i = 0; i < columns.size(); ++i)
  41179. {
  41180. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41181. {
  41182. if (columns.getUnchecked(i)->id == columnId)
  41183. return n;
  41184. ++n;
  41185. }
  41186. }
  41187. return -1;
  41188. }
  41189. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41190. {
  41191. if (onlyCountVisibleColumns)
  41192. index = visibleIndexToTotalIndex (index);
  41193. const ColumnInfo* const ci = columns [index];
  41194. return (ci != 0) ? ci->id : 0;
  41195. }
  41196. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41197. {
  41198. int x = 0, width = 0, n = 0;
  41199. for (int i = 0; i < columns.size(); ++i)
  41200. {
  41201. x += width;
  41202. if (columns.getUnchecked(i)->isVisible())
  41203. {
  41204. width = columns.getUnchecked(i)->width;
  41205. if (n++ == index)
  41206. break;
  41207. }
  41208. else
  41209. {
  41210. width = 0;
  41211. }
  41212. }
  41213. return Rectangle<int> (x, 0, width, getHeight());
  41214. }
  41215. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41216. {
  41217. if (xToFind >= 0)
  41218. {
  41219. int x = 0;
  41220. for (int i = 0; i < columns.size(); ++i)
  41221. {
  41222. const ColumnInfo* const ci = columns.getUnchecked(i);
  41223. if (ci->isVisible())
  41224. {
  41225. x += ci->width;
  41226. if (xToFind < x)
  41227. return ci->id;
  41228. }
  41229. }
  41230. }
  41231. return 0;
  41232. }
  41233. int TableHeaderComponent::getTotalWidth() const
  41234. {
  41235. int w = 0;
  41236. for (int i = columns.size(); --i >= 0;)
  41237. if (columns.getUnchecked(i)->isVisible())
  41238. w += columns.getUnchecked(i)->width;
  41239. return w;
  41240. }
  41241. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41242. {
  41243. stretchToFit = shouldStretchToFit;
  41244. lastDeliberateWidth = getTotalWidth();
  41245. resized();
  41246. }
  41247. bool TableHeaderComponent::isStretchToFitActive() const
  41248. {
  41249. return stretchToFit;
  41250. }
  41251. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41252. {
  41253. if (stretchToFit && getWidth() > 0
  41254. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41255. {
  41256. lastDeliberateWidth = targetTotalWidth;
  41257. resizeColumnsToFit (0, targetTotalWidth);
  41258. }
  41259. }
  41260. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41261. {
  41262. targetTotalWidth = jmax (targetTotalWidth, 0);
  41263. StretchableObjectResizer sor;
  41264. int i;
  41265. for (i = firstColumnIndex; i < columns.size(); ++i)
  41266. {
  41267. ColumnInfo* const ci = columns.getUnchecked(i);
  41268. if (ci->isVisible())
  41269. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41270. }
  41271. sor.resizeToFit (targetTotalWidth);
  41272. int visIndex = 0;
  41273. for (i = firstColumnIndex; i < columns.size(); ++i)
  41274. {
  41275. ColumnInfo* const ci = columns.getUnchecked(i);
  41276. if (ci->isVisible())
  41277. {
  41278. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41279. (int) std::floor (sor.getItemSize (visIndex++)));
  41280. if (newWidth != ci->width)
  41281. {
  41282. ci->width = newWidth;
  41283. repaint();
  41284. columnsResized = true;
  41285. triggerAsyncUpdate();
  41286. }
  41287. }
  41288. }
  41289. }
  41290. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41291. {
  41292. ColumnInfo* const ci = getInfoForId (columnId);
  41293. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41294. {
  41295. if (shouldBeVisible)
  41296. ci->propertyFlags |= visible;
  41297. else
  41298. ci->propertyFlags &= ~visible;
  41299. sendColumnsChanged();
  41300. resized();
  41301. }
  41302. }
  41303. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41304. {
  41305. const ColumnInfo* const ci = getInfoForId (columnId);
  41306. return ci != 0 && ci->isVisible();
  41307. }
  41308. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41309. {
  41310. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41311. {
  41312. for (int i = columns.size(); --i >= 0;)
  41313. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41314. ColumnInfo* const ci = getInfoForId (columnId);
  41315. if (ci != 0)
  41316. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41317. reSortTable();
  41318. }
  41319. }
  41320. int TableHeaderComponent::getSortColumnId() const
  41321. {
  41322. for (int i = columns.size(); --i >= 0;)
  41323. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41324. return columns.getUnchecked(i)->id;
  41325. return 0;
  41326. }
  41327. bool TableHeaderComponent::isSortedForwards() const
  41328. {
  41329. for (int i = columns.size(); --i >= 0;)
  41330. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41331. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41332. return true;
  41333. }
  41334. void TableHeaderComponent::reSortTable()
  41335. {
  41336. sortChanged = true;
  41337. repaint();
  41338. triggerAsyncUpdate();
  41339. }
  41340. const String TableHeaderComponent::toString() const
  41341. {
  41342. String s;
  41343. XmlElement doc ("TABLELAYOUT");
  41344. doc.setAttribute ("sortedCol", getSortColumnId());
  41345. doc.setAttribute ("sortForwards", isSortedForwards());
  41346. for (int i = 0; i < columns.size(); ++i)
  41347. {
  41348. const ColumnInfo* const ci = columns.getUnchecked (i);
  41349. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41350. e->setAttribute ("id", ci->id);
  41351. e->setAttribute ("visible", ci->isVisible());
  41352. e->setAttribute ("width", ci->width);
  41353. }
  41354. return doc.createDocument (String::empty, true, false);
  41355. }
  41356. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41357. {
  41358. XmlDocument doc (storedVersion);
  41359. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  41360. int index = 0;
  41361. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41362. {
  41363. forEachXmlChildElement (*storedXml, col)
  41364. {
  41365. const int tabId = col->getIntAttribute ("id");
  41366. ColumnInfo* const ci = getInfoForId (tabId);
  41367. if (ci != 0)
  41368. {
  41369. columns.move (columns.indexOf (ci), index);
  41370. ci->width = col->getIntAttribute ("width");
  41371. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41372. }
  41373. ++index;
  41374. }
  41375. columnsResized = true;
  41376. sendColumnsChanged();
  41377. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41378. storedXml->getBoolAttribute ("sortForwards", true));
  41379. }
  41380. }
  41381. void TableHeaderComponent::addListener (Listener* const newListener)
  41382. {
  41383. listeners.addIfNotAlreadyThere (newListener);
  41384. }
  41385. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41386. {
  41387. listeners.removeValue (listenerToRemove);
  41388. }
  41389. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41390. {
  41391. const ColumnInfo* const ci = getInfoForId (columnId);
  41392. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41393. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41394. }
  41395. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41396. {
  41397. for (int i = 0; i < columns.size(); ++i)
  41398. {
  41399. const ColumnInfo* const ci = columns.getUnchecked(i);
  41400. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41401. menu.addItem (ci->id, ci->name,
  41402. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41403. isColumnVisible (ci->id));
  41404. }
  41405. }
  41406. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41407. {
  41408. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41409. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41410. }
  41411. void TableHeaderComponent::paint (Graphics& g)
  41412. {
  41413. LookAndFeel& lf = getLookAndFeel();
  41414. lf.drawTableHeaderBackground (g, *this);
  41415. const Rectangle<int> clip (g.getClipBounds());
  41416. int x = 0;
  41417. for (int i = 0; i < columns.size(); ++i)
  41418. {
  41419. const ColumnInfo* const ci = columns.getUnchecked(i);
  41420. if (ci->isVisible())
  41421. {
  41422. if (x + ci->width > clip.getX()
  41423. && (ci->id != columnIdBeingDragged
  41424. || dragOverlayComp == 0
  41425. || ! dragOverlayComp->isVisible()))
  41426. {
  41427. g.saveState();
  41428. g.setOrigin (x, 0);
  41429. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41430. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41431. ci->id == columnIdUnderMouse,
  41432. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41433. ci->propertyFlags);
  41434. g.restoreState();
  41435. }
  41436. x += ci->width;
  41437. if (x >= clip.getRight())
  41438. break;
  41439. }
  41440. }
  41441. }
  41442. void TableHeaderComponent::resized()
  41443. {
  41444. }
  41445. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41446. {
  41447. updateColumnUnderMouse (e.x, e.y);
  41448. }
  41449. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41450. {
  41451. updateColumnUnderMouse (e.x, e.y);
  41452. }
  41453. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41454. {
  41455. updateColumnUnderMouse (e.x, e.y);
  41456. }
  41457. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41458. {
  41459. repaint();
  41460. columnIdBeingResized = 0;
  41461. columnIdBeingDragged = 0;
  41462. if (columnIdUnderMouse != 0)
  41463. {
  41464. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41465. if (e.mods.isPopupMenu())
  41466. columnClicked (columnIdUnderMouse, e.mods);
  41467. }
  41468. if (menuActive && e.mods.isPopupMenu())
  41469. showColumnChooserMenu (columnIdUnderMouse);
  41470. }
  41471. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41472. {
  41473. if (columnIdBeingResized == 0
  41474. && columnIdBeingDragged == 0
  41475. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41476. {
  41477. dragOverlayComp = 0;
  41478. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41479. if (columnIdBeingResized != 0)
  41480. {
  41481. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41482. initialColumnWidth = ci->width;
  41483. }
  41484. else
  41485. {
  41486. beginDrag (e);
  41487. }
  41488. }
  41489. if (columnIdBeingResized != 0)
  41490. {
  41491. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41492. if (ci != 0)
  41493. {
  41494. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41495. initialColumnWidth + e.getDistanceFromDragStartX());
  41496. if (stretchToFit)
  41497. {
  41498. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41499. int minWidthOnRight = 0;
  41500. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41501. if (columns.getUnchecked (i)->isVisible())
  41502. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41503. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41504. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41505. }
  41506. setColumnWidth (columnIdBeingResized, w);
  41507. }
  41508. }
  41509. else if (columnIdBeingDragged != 0)
  41510. {
  41511. if (e.y >= -50 && e.y < getHeight() + 50)
  41512. {
  41513. if (dragOverlayComp != 0)
  41514. {
  41515. dragOverlayComp->setVisible (true);
  41516. dragOverlayComp->setBounds (jlimit (0,
  41517. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41518. e.x - draggingColumnOffset),
  41519. 0,
  41520. dragOverlayComp->getWidth(),
  41521. getHeight());
  41522. for (int i = columns.size(); --i >= 0;)
  41523. {
  41524. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41525. int newIndex = currentIndex;
  41526. if (newIndex > 0)
  41527. {
  41528. // if the previous column isn't draggable, we can't move our column
  41529. // past it, because that'd change the undraggable column's position..
  41530. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41531. if ((previous->propertyFlags & draggable) != 0)
  41532. {
  41533. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41534. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41535. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41536. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41537. {
  41538. --newIndex;
  41539. }
  41540. }
  41541. }
  41542. if (newIndex < columns.size() - 1)
  41543. {
  41544. // if the next column isn't draggable, we can't move our column
  41545. // past it, because that'd change the undraggable column's position..
  41546. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41547. if ((nextCol->propertyFlags & draggable) != 0)
  41548. {
  41549. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41550. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41551. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41552. > abs (dragOverlayComp->getRight() - rightOfNext))
  41553. {
  41554. ++newIndex;
  41555. }
  41556. }
  41557. }
  41558. if (newIndex != currentIndex)
  41559. moveColumn (columnIdBeingDragged, newIndex);
  41560. else
  41561. break;
  41562. }
  41563. }
  41564. }
  41565. else
  41566. {
  41567. endDrag (draggingColumnOriginalIndex);
  41568. }
  41569. }
  41570. }
  41571. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41572. {
  41573. if (columnIdBeingDragged == 0)
  41574. {
  41575. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41576. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41577. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41578. {
  41579. columnIdBeingDragged = 0;
  41580. }
  41581. else
  41582. {
  41583. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41584. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41585. const int temp = columnIdBeingDragged;
  41586. columnIdBeingDragged = 0;
  41587. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41588. columnIdBeingDragged = temp;
  41589. dragOverlayComp->setBounds (columnRect);
  41590. for (int i = listeners.size(); --i >= 0;)
  41591. {
  41592. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41593. i = jmin (i, listeners.size() - 1);
  41594. }
  41595. }
  41596. }
  41597. }
  41598. void TableHeaderComponent::endDrag (const int finalIndex)
  41599. {
  41600. if (columnIdBeingDragged != 0)
  41601. {
  41602. moveColumn (columnIdBeingDragged, finalIndex);
  41603. columnIdBeingDragged = 0;
  41604. repaint();
  41605. for (int i = listeners.size(); --i >= 0;)
  41606. {
  41607. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41608. i = jmin (i, listeners.size() - 1);
  41609. }
  41610. }
  41611. }
  41612. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41613. {
  41614. mouseDrag (e);
  41615. for (int i = columns.size(); --i >= 0;)
  41616. if (columns.getUnchecked (i)->isVisible())
  41617. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41618. columnIdBeingResized = 0;
  41619. repaint();
  41620. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41621. updateColumnUnderMouse (e.x, e.y);
  41622. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41623. columnClicked (columnIdUnderMouse, e.mods);
  41624. dragOverlayComp = 0;
  41625. }
  41626. const MouseCursor TableHeaderComponent::getMouseCursor()
  41627. {
  41628. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41629. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41630. return Component::getMouseCursor();
  41631. }
  41632. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41633. {
  41634. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41635. }
  41636. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41637. {
  41638. for (int i = columns.size(); --i >= 0;)
  41639. if (columns.getUnchecked(i)->id == id)
  41640. return columns.getUnchecked(i);
  41641. return 0;
  41642. }
  41643. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41644. {
  41645. int n = 0;
  41646. for (int i = 0; i < columns.size(); ++i)
  41647. {
  41648. if (columns.getUnchecked(i)->isVisible())
  41649. {
  41650. if (n == visibleIndex)
  41651. return i;
  41652. ++n;
  41653. }
  41654. }
  41655. return -1;
  41656. }
  41657. void TableHeaderComponent::sendColumnsChanged()
  41658. {
  41659. if (stretchToFit && lastDeliberateWidth > 0)
  41660. resizeAllColumnsToFit (lastDeliberateWidth);
  41661. repaint();
  41662. columnsChanged = true;
  41663. triggerAsyncUpdate();
  41664. }
  41665. void TableHeaderComponent::handleAsyncUpdate()
  41666. {
  41667. const bool changed = columnsChanged || sortChanged;
  41668. const bool sized = columnsResized || changed;
  41669. const bool sorted = sortChanged;
  41670. columnsChanged = false;
  41671. columnsResized = false;
  41672. sortChanged = false;
  41673. if (sorted)
  41674. {
  41675. for (int i = listeners.size(); --i >= 0;)
  41676. {
  41677. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41678. i = jmin (i, listeners.size() - 1);
  41679. }
  41680. }
  41681. if (changed)
  41682. {
  41683. for (int i = listeners.size(); --i >= 0;)
  41684. {
  41685. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41686. i = jmin (i, listeners.size() - 1);
  41687. }
  41688. }
  41689. if (sized)
  41690. {
  41691. for (int i = listeners.size(); --i >= 0;)
  41692. {
  41693. listeners.getUnchecked(i)->tableColumnsResized (this);
  41694. i = jmin (i, listeners.size() - 1);
  41695. }
  41696. }
  41697. }
  41698. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41699. {
  41700. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  41701. {
  41702. const int draggableDistance = 3;
  41703. int x = 0;
  41704. for (int i = 0; i < columns.size(); ++i)
  41705. {
  41706. const ColumnInfo* const ci = columns.getUnchecked(i);
  41707. if (ci->isVisible())
  41708. {
  41709. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41710. && (ci->propertyFlags & resizable) != 0)
  41711. return ci->id;
  41712. x += ci->width;
  41713. }
  41714. }
  41715. }
  41716. return 0;
  41717. }
  41718. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41719. {
  41720. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  41721. ? getColumnIdAtX (x) : 0;
  41722. if (newCol != columnIdUnderMouse)
  41723. {
  41724. columnIdUnderMouse = newCol;
  41725. repaint();
  41726. }
  41727. }
  41728. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41729. {
  41730. PopupMenu m;
  41731. addMenuItems (m, columnIdClicked);
  41732. if (m.getNumItems() > 0)
  41733. {
  41734. m.setLookAndFeel (&getLookAndFeel());
  41735. const int result = m.show();
  41736. if (result != 0)
  41737. reactToMenuItem (result, columnIdClicked);
  41738. }
  41739. }
  41740. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41741. {
  41742. }
  41743. END_JUCE_NAMESPACE
  41744. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41745. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41746. BEGIN_JUCE_NAMESPACE
  41747. static const char* const tableColumnPropertyTag = "_tableColumnID";
  41748. class TableListRowComp : public Component,
  41749. public TooltipClient
  41750. {
  41751. public:
  41752. TableListRowComp (TableListBox& owner_)
  41753. : owner (owner_),
  41754. row (-1),
  41755. isSelected (false)
  41756. {
  41757. }
  41758. ~TableListRowComp()
  41759. {
  41760. deleteAllChildren();
  41761. }
  41762. void paint (Graphics& g)
  41763. {
  41764. TableListBoxModel* const model = owner.getModel();
  41765. if (model != 0)
  41766. {
  41767. const TableHeaderComponent* const header = owner.getHeader();
  41768. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41769. const int numColumns = header->getNumColumns (true);
  41770. for (int i = 0; i < numColumns; ++i)
  41771. {
  41772. if (! columnsWithComponents [i])
  41773. {
  41774. const int columnId = header->getColumnIdOfIndex (i, true);
  41775. Rectangle<int> columnRect (header->getColumnPosition (i));
  41776. columnRect.setSize (columnRect.getWidth(), getHeight());
  41777. g.saveState();
  41778. g.reduceClipRegion (columnRect);
  41779. g.setOrigin (columnRect.getX(), 0);
  41780. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41781. g.restoreState();
  41782. }
  41783. }
  41784. }
  41785. }
  41786. void update (const int newRow, const bool isNowSelected)
  41787. {
  41788. if (newRow != row || isNowSelected != isSelected)
  41789. {
  41790. row = newRow;
  41791. isSelected = isNowSelected;
  41792. repaint();
  41793. deleteAllChildren();
  41794. }
  41795. if (row < owner.getNumRows())
  41796. {
  41797. jassert (row >= 0);
  41798. const Identifier tagPropertyName ("_tableLastUseNum");
  41799. const int newTag = Random::getSystemRandom().nextInt();
  41800. const TableHeaderComponent* const header = owner.getHeader();
  41801. const int numColumns = header->getNumColumns (true);
  41802. columnsWithComponents.clear();
  41803. if (owner.getModel() != 0)
  41804. {
  41805. for (int i = 0; i < numColumns; ++i)
  41806. {
  41807. const int columnId = header->getColumnIdOfIndex (i, true);
  41808. Component* const newComp
  41809. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  41810. findChildComponentForColumn (columnId));
  41811. if (newComp != 0)
  41812. {
  41813. addAndMakeVisible (newComp);
  41814. newComp->getProperties().set (tagPropertyName, newTag);
  41815. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  41816. const Rectangle<int> columnRect (header->getColumnPosition (i));
  41817. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41818. columnsWithComponents.setBit (i);
  41819. }
  41820. }
  41821. }
  41822. for (int i = getNumChildComponents(); --i >= 0;)
  41823. {
  41824. Component* const c = getChildComponent (i);
  41825. if ((int) c->getProperties() [tagPropertyName] != newTag)
  41826. delete c;
  41827. }
  41828. }
  41829. else
  41830. {
  41831. columnsWithComponents.clear();
  41832. deleteAllChildren();
  41833. }
  41834. }
  41835. void resized()
  41836. {
  41837. for (int i = getNumChildComponents(); --i >= 0;)
  41838. {
  41839. Component* const c = getChildComponent (i);
  41840. const int columnId = c->getProperties() [tableColumnPropertyTag];
  41841. if (columnId != 0)
  41842. {
  41843. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  41844. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41845. }
  41846. }
  41847. }
  41848. void mouseDown (const MouseEvent& e)
  41849. {
  41850. isDragging = false;
  41851. selectRowOnMouseUp = false;
  41852. if (isEnabled())
  41853. {
  41854. if (! isSelected)
  41855. {
  41856. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41857. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41858. if (columnId != 0 && owner.getModel() != 0)
  41859. owner.getModel()->cellClicked (row, columnId, e);
  41860. }
  41861. else
  41862. {
  41863. selectRowOnMouseUp = true;
  41864. }
  41865. }
  41866. }
  41867. void mouseDrag (const MouseEvent& e)
  41868. {
  41869. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41870. {
  41871. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41872. if (selectedRows.size() > 0)
  41873. {
  41874. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41875. if (dragDescription.isNotEmpty())
  41876. {
  41877. isDragging = true;
  41878. owner.startDragAndDrop (e, dragDescription);
  41879. }
  41880. }
  41881. }
  41882. }
  41883. void mouseUp (const MouseEvent& e)
  41884. {
  41885. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41886. {
  41887. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41888. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41889. if (columnId != 0 && owner.getModel() != 0)
  41890. owner.getModel()->cellClicked (row, columnId, e);
  41891. }
  41892. }
  41893. void mouseDoubleClick (const MouseEvent& e)
  41894. {
  41895. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41896. if (columnId != 0 && owner.getModel() != 0)
  41897. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41898. }
  41899. const String getTooltip()
  41900. {
  41901. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  41902. if (columnId != 0 && owner.getModel() != 0)
  41903. return owner.getModel()->getCellTooltip (row, columnId);
  41904. return String::empty;
  41905. }
  41906. Component* findChildComponentForColumn (const int columnId) const
  41907. {
  41908. for (int i = getNumChildComponents(); --i >= 0;)
  41909. {
  41910. Component* const c = getChildComponent (i);
  41911. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  41912. return c;
  41913. }
  41914. return 0;
  41915. }
  41916. juce_UseDebuggingNewOperator
  41917. private:
  41918. TableListBox& owner;
  41919. int row;
  41920. bool isSelected, isDragging, selectRowOnMouseUp;
  41921. BigInteger columnsWithComponents;
  41922. TableListRowComp (const TableListRowComp&);
  41923. TableListRowComp& operator= (const TableListRowComp&);
  41924. };
  41925. class TableListBoxHeader : public TableHeaderComponent
  41926. {
  41927. public:
  41928. TableListBoxHeader (TableListBox& owner_)
  41929. : owner (owner_)
  41930. {
  41931. }
  41932. ~TableListBoxHeader()
  41933. {
  41934. }
  41935. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41936. {
  41937. if (owner.isAutoSizeMenuOptionShown())
  41938. {
  41939. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  41940. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  41941. menu.addSeparator();
  41942. }
  41943. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41944. }
  41945. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41946. {
  41947. if (menuReturnId == 0xf836743)
  41948. {
  41949. owner.autoSizeColumn (columnIdClicked);
  41950. }
  41951. else if (menuReturnId == 0xf836744)
  41952. {
  41953. owner.autoSizeAllColumns();
  41954. }
  41955. else
  41956. {
  41957. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  41958. }
  41959. }
  41960. juce_UseDebuggingNewOperator
  41961. private:
  41962. TableListBox& owner;
  41963. TableListBoxHeader (const TableListBoxHeader&);
  41964. TableListBoxHeader& operator= (const TableListBoxHeader&);
  41965. };
  41966. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41967. : ListBox (name, 0),
  41968. model (model_),
  41969. autoSizeOptionsShown (true)
  41970. {
  41971. ListBox::model = this;
  41972. header = new TableListBoxHeader (*this);
  41973. header->setSize (100, 28);
  41974. header->addListener (this);
  41975. setHeaderComponent (header);
  41976. }
  41977. TableListBox::~TableListBox()
  41978. {
  41979. header = 0;
  41980. }
  41981. void TableListBox::setModel (TableListBoxModel* const newModel)
  41982. {
  41983. if (model != newModel)
  41984. {
  41985. model = newModel;
  41986. updateContent();
  41987. }
  41988. }
  41989. int TableListBox::getHeaderHeight() const
  41990. {
  41991. return header->getHeight();
  41992. }
  41993. void TableListBox::setHeaderHeight (const int newHeight)
  41994. {
  41995. header->setSize (header->getWidth(), newHeight);
  41996. resized();
  41997. }
  41998. void TableListBox::autoSizeColumn (const int columnId)
  41999. {
  42000. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  42001. if (width > 0)
  42002. header->setColumnWidth (columnId, width);
  42003. }
  42004. void TableListBox::autoSizeAllColumns()
  42005. {
  42006. for (int i = 0; i < header->getNumColumns (true); ++i)
  42007. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  42008. }
  42009. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  42010. {
  42011. autoSizeOptionsShown = shouldBeShown;
  42012. }
  42013. bool TableListBox::isAutoSizeMenuOptionShown() const
  42014. {
  42015. return autoSizeOptionsShown;
  42016. }
  42017. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  42018. const int rowNumber,
  42019. const bool relativeToComponentTopLeft) const
  42020. {
  42021. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42022. if (relativeToComponentTopLeft)
  42023. headerCell.translate (header->getX(), 0);
  42024. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  42025. return Rectangle<int> (headerCell.getX(), row.getY(),
  42026. headerCell.getWidth(), row.getHeight());
  42027. }
  42028. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  42029. {
  42030. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  42031. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  42032. }
  42033. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  42034. {
  42035. ScrollBar* const scrollbar = getHorizontalScrollBar();
  42036. if (scrollbar != 0)
  42037. {
  42038. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42039. double x = scrollbar->getCurrentRangeStart();
  42040. const double w = scrollbar->getCurrentRangeSize();
  42041. if (pos.getX() < x)
  42042. x = pos.getX();
  42043. else if (pos.getRight() > x + w)
  42044. x += jmax (0.0, pos.getRight() - (x + w));
  42045. scrollbar->setCurrentRangeStart (x);
  42046. }
  42047. }
  42048. int TableListBox::getNumRows()
  42049. {
  42050. return model != 0 ? model->getNumRows() : 0;
  42051. }
  42052. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  42053. {
  42054. }
  42055. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  42056. {
  42057. if (existingComponentToUpdate == 0)
  42058. existingComponentToUpdate = new TableListRowComp (*this);
  42059. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  42060. return existingComponentToUpdate;
  42061. }
  42062. void TableListBox::selectedRowsChanged (int row)
  42063. {
  42064. if (model != 0)
  42065. model->selectedRowsChanged (row);
  42066. }
  42067. void TableListBox::deleteKeyPressed (int row)
  42068. {
  42069. if (model != 0)
  42070. model->deleteKeyPressed (row);
  42071. }
  42072. void TableListBox::returnKeyPressed (int row)
  42073. {
  42074. if (model != 0)
  42075. model->returnKeyPressed (row);
  42076. }
  42077. void TableListBox::backgroundClicked()
  42078. {
  42079. if (model != 0)
  42080. model->backgroundClicked();
  42081. }
  42082. void TableListBox::listWasScrolled()
  42083. {
  42084. if (model != 0)
  42085. model->listWasScrolled();
  42086. }
  42087. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  42088. {
  42089. setMinimumContentWidth (header->getTotalWidth());
  42090. repaint();
  42091. updateColumnComponents();
  42092. }
  42093. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  42094. {
  42095. setMinimumContentWidth (header->getTotalWidth());
  42096. repaint();
  42097. updateColumnComponents();
  42098. }
  42099. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  42100. {
  42101. if (model != 0)
  42102. model->sortOrderChanged (header->getSortColumnId(),
  42103. header->isSortedForwards());
  42104. }
  42105. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  42106. {
  42107. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  42108. repaint();
  42109. }
  42110. void TableListBox::resized()
  42111. {
  42112. ListBox::resized();
  42113. header->resizeAllColumnsToFit (getVisibleContentWidth());
  42114. setMinimumContentWidth (header->getTotalWidth());
  42115. }
  42116. void TableListBox::updateColumnComponents() const
  42117. {
  42118. const int firstRow = getRowContainingPosition (0, 0);
  42119. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  42120. {
  42121. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  42122. if (rowComp != 0)
  42123. rowComp->resized();
  42124. }
  42125. }
  42126. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  42127. {
  42128. }
  42129. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  42130. {
  42131. }
  42132. void TableListBoxModel::backgroundClicked()
  42133. {
  42134. }
  42135. void TableListBoxModel::sortOrderChanged (int, const bool)
  42136. {
  42137. }
  42138. int TableListBoxModel::getColumnAutoSizeWidth (int)
  42139. {
  42140. return 0;
  42141. }
  42142. void TableListBoxModel::selectedRowsChanged (int)
  42143. {
  42144. }
  42145. void TableListBoxModel::deleteKeyPressed (int)
  42146. {
  42147. }
  42148. void TableListBoxModel::returnKeyPressed (int)
  42149. {
  42150. }
  42151. void TableListBoxModel::listWasScrolled()
  42152. {
  42153. }
  42154. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  42155. {
  42156. return String::empty;
  42157. }
  42158. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  42159. {
  42160. return String::empty;
  42161. }
  42162. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  42163. {
  42164. (void) existingComponentToUpdate;
  42165. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  42166. return 0;
  42167. }
  42168. END_JUCE_NAMESPACE
  42169. /*** End of inlined file: juce_TableListBox.cpp ***/
  42170. /*** Start of inlined file: juce_TextEditor.cpp ***/
  42171. BEGIN_JUCE_NAMESPACE
  42172. // a word or space that can't be broken down any further
  42173. struct TextAtom
  42174. {
  42175. String atomText;
  42176. float width;
  42177. int numChars;
  42178. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  42179. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  42180. const String getText (const juce_wchar passwordCharacter) const
  42181. {
  42182. if (passwordCharacter == 0)
  42183. return atomText;
  42184. else
  42185. return String::repeatedString (String::charToString (passwordCharacter),
  42186. atomText.length());
  42187. }
  42188. const String getTrimmedText (const juce_wchar passwordCharacter) const
  42189. {
  42190. if (passwordCharacter == 0)
  42191. return atomText.substring (0, numChars);
  42192. else if (isNewLine())
  42193. return String::empty;
  42194. else
  42195. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  42196. }
  42197. };
  42198. // a run of text with a single font and colour
  42199. class TextEditor::UniformTextSection
  42200. {
  42201. public:
  42202. UniformTextSection (const String& text,
  42203. const Font& font_,
  42204. const Colour& colour_,
  42205. const juce_wchar passwordCharacter)
  42206. : font (font_),
  42207. colour (colour_)
  42208. {
  42209. initialiseAtoms (text, passwordCharacter);
  42210. }
  42211. UniformTextSection (const UniformTextSection& other)
  42212. : font (other.font),
  42213. colour (other.colour)
  42214. {
  42215. atoms.ensureStorageAllocated (other.atoms.size());
  42216. for (int i = 0; i < other.atoms.size(); ++i)
  42217. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  42218. }
  42219. ~UniformTextSection()
  42220. {
  42221. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  42222. }
  42223. void clear()
  42224. {
  42225. for (int i = atoms.size(); --i >= 0;)
  42226. delete getAtom(i);
  42227. atoms.clear();
  42228. }
  42229. int getNumAtoms() const
  42230. {
  42231. return atoms.size();
  42232. }
  42233. TextAtom* getAtom (const int index) const throw()
  42234. {
  42235. return atoms.getUnchecked (index);
  42236. }
  42237. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42238. {
  42239. if (other.atoms.size() > 0)
  42240. {
  42241. TextAtom* const lastAtom = atoms.getLast();
  42242. int i = 0;
  42243. if (lastAtom != 0)
  42244. {
  42245. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42246. {
  42247. TextAtom* const first = other.getAtom(0);
  42248. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42249. {
  42250. lastAtom->atomText += first->atomText;
  42251. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42252. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42253. delete first;
  42254. ++i;
  42255. }
  42256. }
  42257. }
  42258. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42259. while (i < other.atoms.size())
  42260. {
  42261. atoms.add (other.getAtom(i));
  42262. ++i;
  42263. }
  42264. }
  42265. }
  42266. UniformTextSection* split (const int indexToBreakAt,
  42267. const juce_wchar passwordCharacter)
  42268. {
  42269. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42270. font, colour,
  42271. passwordCharacter);
  42272. int index = 0;
  42273. for (int i = 0; i < atoms.size(); ++i)
  42274. {
  42275. TextAtom* const atom = getAtom(i);
  42276. const int nextIndex = index + atom->numChars;
  42277. if (index == indexToBreakAt)
  42278. {
  42279. int j;
  42280. for (j = i; j < atoms.size(); ++j)
  42281. section2->atoms.add (getAtom (j));
  42282. for (j = atoms.size(); --j >= i;)
  42283. atoms.remove (j);
  42284. break;
  42285. }
  42286. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42287. {
  42288. TextAtom* const secondAtom = new TextAtom();
  42289. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42290. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42291. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42292. section2->atoms.add (secondAtom);
  42293. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42294. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42295. atom->numChars = (uint16) (indexToBreakAt - index);
  42296. int j;
  42297. for (j = i + 1; j < atoms.size(); ++j)
  42298. section2->atoms.add (getAtom (j));
  42299. for (j = atoms.size(); --j > i;)
  42300. atoms.remove (j);
  42301. break;
  42302. }
  42303. index = nextIndex;
  42304. }
  42305. return section2;
  42306. }
  42307. void appendAllText (String::Concatenator& concatenator) const
  42308. {
  42309. for (int i = 0; i < atoms.size(); ++i)
  42310. concatenator.append (getAtom(i)->atomText);
  42311. }
  42312. void appendSubstring (String::Concatenator& concatenator,
  42313. const Range<int>& range) const
  42314. {
  42315. int index = 0;
  42316. for (int i = 0; i < atoms.size(); ++i)
  42317. {
  42318. const TextAtom* const atom = getAtom (i);
  42319. const int nextIndex = index + atom->numChars;
  42320. if (range.getStart() < nextIndex)
  42321. {
  42322. if (range.getEnd() <= index)
  42323. break;
  42324. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42325. if (! r.isEmpty())
  42326. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42327. }
  42328. index = nextIndex;
  42329. }
  42330. }
  42331. int getTotalLength() const
  42332. {
  42333. int total = 0;
  42334. for (int i = atoms.size(); --i >= 0;)
  42335. total += getAtom(i)->numChars;
  42336. return total;
  42337. }
  42338. void setFont (const Font& newFont,
  42339. const juce_wchar passwordCharacter)
  42340. {
  42341. if (font != newFont)
  42342. {
  42343. font = newFont;
  42344. for (int i = atoms.size(); --i >= 0;)
  42345. {
  42346. TextAtom* const atom = atoms.getUnchecked(i);
  42347. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42348. }
  42349. }
  42350. }
  42351. juce_UseDebuggingNewOperator
  42352. Font font;
  42353. Colour colour;
  42354. private:
  42355. Array <TextAtom*> atoms;
  42356. void initialiseAtoms (const String& textToParse,
  42357. const juce_wchar passwordCharacter)
  42358. {
  42359. int i = 0;
  42360. const int len = textToParse.length();
  42361. const juce_wchar* const text = textToParse;
  42362. while (i < len)
  42363. {
  42364. int start = i;
  42365. // create a whitespace atom unless it starts with non-ws
  42366. if (CharacterFunctions::isWhitespace (text[i])
  42367. && text[i] != '\r'
  42368. && text[i] != '\n')
  42369. {
  42370. while (i < len
  42371. && CharacterFunctions::isWhitespace (text[i])
  42372. && text[i] != '\r'
  42373. && text[i] != '\n')
  42374. {
  42375. ++i;
  42376. }
  42377. }
  42378. else
  42379. {
  42380. if (text[i] == '\r')
  42381. {
  42382. ++i;
  42383. if ((i < len) && (text[i] == '\n'))
  42384. {
  42385. ++start;
  42386. ++i;
  42387. }
  42388. }
  42389. else if (text[i] == '\n')
  42390. {
  42391. ++i;
  42392. }
  42393. else
  42394. {
  42395. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42396. ++i;
  42397. }
  42398. }
  42399. TextAtom* const atom = new TextAtom();
  42400. atom->atomText = String (text + start, i - start);
  42401. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42402. atom->numChars = (uint16) (i - start);
  42403. atoms.add (atom);
  42404. }
  42405. }
  42406. UniformTextSection& operator= (const UniformTextSection& other);
  42407. };
  42408. class TextEditor::Iterator
  42409. {
  42410. public:
  42411. Iterator (const Array <UniformTextSection*>& sections_,
  42412. const float wordWrapWidth_,
  42413. const juce_wchar passwordCharacter_)
  42414. : indexInText (0),
  42415. lineY (0),
  42416. lineHeight (0),
  42417. maxDescent (0),
  42418. atomX (0),
  42419. atomRight (0),
  42420. atom (0),
  42421. currentSection (0),
  42422. sections (sections_),
  42423. sectionIndex (0),
  42424. atomIndex (0),
  42425. wordWrapWidth (wordWrapWidth_),
  42426. passwordCharacter (passwordCharacter_)
  42427. {
  42428. jassert (wordWrapWidth_ > 0);
  42429. if (sections.size() > 0)
  42430. {
  42431. currentSection = sections.getUnchecked (sectionIndex);
  42432. if (currentSection != 0)
  42433. beginNewLine();
  42434. }
  42435. }
  42436. Iterator (const Iterator& other)
  42437. : indexInText (other.indexInText),
  42438. lineY (other.lineY),
  42439. lineHeight (other.lineHeight),
  42440. maxDescent (other.maxDescent),
  42441. atomX (other.atomX),
  42442. atomRight (other.atomRight),
  42443. atom (other.atom),
  42444. currentSection (other.currentSection),
  42445. sections (other.sections),
  42446. sectionIndex (other.sectionIndex),
  42447. atomIndex (other.atomIndex),
  42448. wordWrapWidth (other.wordWrapWidth),
  42449. passwordCharacter (other.passwordCharacter),
  42450. tempAtom (other.tempAtom)
  42451. {
  42452. }
  42453. ~Iterator()
  42454. {
  42455. }
  42456. bool next()
  42457. {
  42458. if (atom == &tempAtom)
  42459. {
  42460. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42461. if (numRemaining > 0)
  42462. {
  42463. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42464. atomX = 0;
  42465. if (tempAtom.numChars > 0)
  42466. lineY += lineHeight;
  42467. indexInText += tempAtom.numChars;
  42468. GlyphArrangement g;
  42469. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42470. int split;
  42471. for (split = 0; split < g.getNumGlyphs(); ++split)
  42472. if (shouldWrap (g.getGlyph (split).getRight()))
  42473. break;
  42474. if (split > 0 && split <= numRemaining)
  42475. {
  42476. tempAtom.numChars = (uint16) split;
  42477. tempAtom.width = g.getGlyph (split - 1).getRight();
  42478. atomRight = atomX + tempAtom.width;
  42479. return true;
  42480. }
  42481. }
  42482. }
  42483. bool forceNewLine = false;
  42484. if (sectionIndex >= sections.size())
  42485. {
  42486. moveToEndOfLastAtom();
  42487. return false;
  42488. }
  42489. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42490. {
  42491. if (atomIndex >= currentSection->getNumAtoms())
  42492. {
  42493. if (++sectionIndex >= sections.size())
  42494. {
  42495. moveToEndOfLastAtom();
  42496. return false;
  42497. }
  42498. atomIndex = 0;
  42499. currentSection = sections.getUnchecked (sectionIndex);
  42500. }
  42501. else
  42502. {
  42503. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42504. if (! lastAtom->isWhitespace())
  42505. {
  42506. // handle the case where the last atom in a section is actually part of the same
  42507. // word as the first atom of the next section...
  42508. float right = atomRight + lastAtom->width;
  42509. float lineHeight2 = lineHeight;
  42510. float maxDescent2 = maxDescent;
  42511. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42512. {
  42513. const UniformTextSection* const s = sections.getUnchecked (section);
  42514. if (s->getNumAtoms() == 0)
  42515. break;
  42516. const TextAtom* const nextAtom = s->getAtom (0);
  42517. if (nextAtom->isWhitespace())
  42518. break;
  42519. right += nextAtom->width;
  42520. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42521. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42522. if (shouldWrap (right))
  42523. {
  42524. lineHeight = lineHeight2;
  42525. maxDescent = maxDescent2;
  42526. forceNewLine = true;
  42527. break;
  42528. }
  42529. if (s->getNumAtoms() > 1)
  42530. break;
  42531. }
  42532. }
  42533. }
  42534. }
  42535. if (atom != 0)
  42536. {
  42537. atomX = atomRight;
  42538. indexInText += atom->numChars;
  42539. if (atom->isNewLine())
  42540. beginNewLine();
  42541. }
  42542. atom = currentSection->getAtom (atomIndex);
  42543. atomRight = atomX + atom->width;
  42544. ++atomIndex;
  42545. if (shouldWrap (atomRight) || forceNewLine)
  42546. {
  42547. if (atom->isWhitespace())
  42548. {
  42549. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42550. atomRight = jmin (atomRight, wordWrapWidth);
  42551. }
  42552. else
  42553. {
  42554. atomRight = atom->width;
  42555. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42556. {
  42557. tempAtom = *atom;
  42558. tempAtom.width = 0;
  42559. tempAtom.numChars = 0;
  42560. atom = &tempAtom;
  42561. if (atomX > 0)
  42562. beginNewLine();
  42563. return next();
  42564. }
  42565. beginNewLine();
  42566. return true;
  42567. }
  42568. }
  42569. return true;
  42570. }
  42571. void beginNewLine()
  42572. {
  42573. atomX = 0;
  42574. lineY += lineHeight;
  42575. int tempSectionIndex = sectionIndex;
  42576. int tempAtomIndex = atomIndex;
  42577. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42578. lineHeight = section->font.getHeight();
  42579. maxDescent = section->font.getDescent();
  42580. float x = (atom != 0) ? atom->width : 0;
  42581. while (! shouldWrap (x))
  42582. {
  42583. if (tempSectionIndex >= sections.size())
  42584. break;
  42585. bool checkSize = false;
  42586. if (tempAtomIndex >= section->getNumAtoms())
  42587. {
  42588. if (++tempSectionIndex >= sections.size())
  42589. break;
  42590. tempAtomIndex = 0;
  42591. section = sections.getUnchecked (tempSectionIndex);
  42592. checkSize = true;
  42593. }
  42594. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42595. if (nextAtom == 0)
  42596. break;
  42597. x += nextAtom->width;
  42598. if (shouldWrap (x) || nextAtom->isNewLine())
  42599. break;
  42600. if (checkSize)
  42601. {
  42602. lineHeight = jmax (lineHeight, section->font.getHeight());
  42603. maxDescent = jmax (maxDescent, section->font.getDescent());
  42604. }
  42605. ++tempAtomIndex;
  42606. }
  42607. }
  42608. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42609. {
  42610. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42611. {
  42612. if (lastSection != currentSection)
  42613. {
  42614. lastSection = currentSection;
  42615. g.setColour (currentSection->colour);
  42616. g.setFont (currentSection->font);
  42617. }
  42618. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42619. GlyphArrangement ga;
  42620. ga.addLineOfText (currentSection->font,
  42621. atom->getTrimmedText (passwordCharacter),
  42622. atomX,
  42623. (float) roundToInt (lineY + lineHeight - maxDescent));
  42624. ga.draw (g);
  42625. }
  42626. }
  42627. void drawSelection (Graphics& g,
  42628. const Range<int>& selection) const
  42629. {
  42630. const int startX = roundToInt (indexToX (selection.getStart()));
  42631. const int endX = roundToInt (indexToX (selection.getEnd()));
  42632. const int y = roundToInt (lineY);
  42633. const int nextY = roundToInt (lineY + lineHeight);
  42634. g.fillRect (startX, y, endX - startX, nextY - y);
  42635. }
  42636. void drawSelectedText (Graphics& g,
  42637. const Range<int>& selection,
  42638. const Colour& selectedTextColour) const
  42639. {
  42640. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42641. {
  42642. GlyphArrangement ga;
  42643. ga.addLineOfText (currentSection->font,
  42644. atom->getTrimmedText (passwordCharacter),
  42645. atomX,
  42646. (float) roundToInt (lineY + lineHeight - maxDescent));
  42647. if (selection.getEnd() < indexInText + atom->numChars)
  42648. {
  42649. GlyphArrangement ga2 (ga);
  42650. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42651. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42652. g.setColour (currentSection->colour);
  42653. ga2.draw (g);
  42654. }
  42655. if (selection.getStart() > indexInText)
  42656. {
  42657. GlyphArrangement ga2 (ga);
  42658. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42659. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42660. g.setColour (currentSection->colour);
  42661. ga2.draw (g);
  42662. }
  42663. g.setColour (selectedTextColour);
  42664. ga.draw (g);
  42665. }
  42666. }
  42667. float indexToX (const int indexToFind) const
  42668. {
  42669. if (indexToFind <= indexInText)
  42670. return atomX;
  42671. if (indexToFind >= indexInText + atom->numChars)
  42672. return atomRight;
  42673. GlyphArrangement g;
  42674. g.addLineOfText (currentSection->font,
  42675. atom->getText (passwordCharacter),
  42676. atomX, 0.0f);
  42677. if (indexToFind - indexInText >= g.getNumGlyphs())
  42678. return atomRight;
  42679. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42680. }
  42681. int xToIndex (const float xToFind) const
  42682. {
  42683. if (xToFind <= atomX || atom->isNewLine())
  42684. return indexInText;
  42685. if (xToFind >= atomRight)
  42686. return indexInText + atom->numChars;
  42687. GlyphArrangement g;
  42688. g.addLineOfText (currentSection->font,
  42689. atom->getText (passwordCharacter),
  42690. atomX, 0.0f);
  42691. int j;
  42692. for (j = 0; j < g.getNumGlyphs(); ++j)
  42693. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42694. break;
  42695. return indexInText + j;
  42696. }
  42697. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42698. {
  42699. while (next())
  42700. {
  42701. if (indexInText + atom->numChars > index)
  42702. {
  42703. cx = indexToX (index);
  42704. cy = lineY;
  42705. lineHeight_ = lineHeight;
  42706. return true;
  42707. }
  42708. }
  42709. cx = atomX;
  42710. cy = lineY;
  42711. lineHeight_ = lineHeight;
  42712. return false;
  42713. }
  42714. juce_UseDebuggingNewOperator
  42715. int indexInText;
  42716. float lineY, lineHeight, maxDescent;
  42717. float atomX, atomRight;
  42718. const TextAtom* atom;
  42719. const UniformTextSection* currentSection;
  42720. private:
  42721. const Array <UniformTextSection*>& sections;
  42722. int sectionIndex, atomIndex;
  42723. const float wordWrapWidth;
  42724. const juce_wchar passwordCharacter;
  42725. TextAtom tempAtom;
  42726. Iterator& operator= (const Iterator&);
  42727. void moveToEndOfLastAtom()
  42728. {
  42729. if (atom != 0)
  42730. {
  42731. atomX = atomRight;
  42732. if (atom->isNewLine())
  42733. {
  42734. atomX = 0.0f;
  42735. lineY += lineHeight;
  42736. }
  42737. }
  42738. }
  42739. bool shouldWrap (const float x) const
  42740. {
  42741. return (x - 0.0001f) >= wordWrapWidth;
  42742. }
  42743. };
  42744. class TextEditor::InsertAction : public UndoableAction
  42745. {
  42746. TextEditor& owner;
  42747. const String text;
  42748. const int insertIndex, oldCaretPos, newCaretPos;
  42749. const Font font;
  42750. const Colour colour;
  42751. InsertAction (const InsertAction&);
  42752. InsertAction& operator= (const InsertAction&);
  42753. public:
  42754. InsertAction (TextEditor& owner_,
  42755. const String& text_,
  42756. const int insertIndex_,
  42757. const Font& font_,
  42758. const Colour& colour_,
  42759. const int oldCaretPos_,
  42760. const int newCaretPos_)
  42761. : owner (owner_),
  42762. text (text_),
  42763. insertIndex (insertIndex_),
  42764. oldCaretPos (oldCaretPos_),
  42765. newCaretPos (newCaretPos_),
  42766. font (font_),
  42767. colour (colour_)
  42768. {
  42769. }
  42770. ~InsertAction()
  42771. {
  42772. }
  42773. bool perform()
  42774. {
  42775. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42776. return true;
  42777. }
  42778. bool undo()
  42779. {
  42780. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42781. return true;
  42782. }
  42783. int getSizeInUnits()
  42784. {
  42785. return text.length() + 16;
  42786. }
  42787. };
  42788. class TextEditor::RemoveAction : public UndoableAction
  42789. {
  42790. TextEditor& owner;
  42791. const Range<int> range;
  42792. const int oldCaretPos, newCaretPos;
  42793. Array <UniformTextSection*> removedSections;
  42794. RemoveAction (const RemoveAction&);
  42795. RemoveAction& operator= (const RemoveAction&);
  42796. public:
  42797. RemoveAction (TextEditor& owner_,
  42798. const Range<int> range_,
  42799. const int oldCaretPos_,
  42800. const int newCaretPos_,
  42801. const Array <UniformTextSection*>& removedSections_)
  42802. : owner (owner_),
  42803. range (range_),
  42804. oldCaretPos (oldCaretPos_),
  42805. newCaretPos (newCaretPos_),
  42806. removedSections (removedSections_)
  42807. {
  42808. }
  42809. ~RemoveAction()
  42810. {
  42811. for (int i = removedSections.size(); --i >= 0;)
  42812. {
  42813. UniformTextSection* const section = removedSections.getUnchecked (i);
  42814. section->clear();
  42815. delete section;
  42816. }
  42817. }
  42818. bool perform()
  42819. {
  42820. owner.remove (range, 0, newCaretPos);
  42821. return true;
  42822. }
  42823. bool undo()
  42824. {
  42825. owner.reinsert (range.getStart(), removedSections);
  42826. owner.moveCursorTo (oldCaretPos, false);
  42827. return true;
  42828. }
  42829. int getSizeInUnits()
  42830. {
  42831. int n = 0;
  42832. for (int i = removedSections.size(); --i >= 0;)
  42833. n += removedSections.getUnchecked (i)->getTotalLength();
  42834. return n + 16;
  42835. }
  42836. };
  42837. class TextEditor::TextHolderComponent : public Component,
  42838. public Timer,
  42839. public Value::Listener
  42840. {
  42841. public:
  42842. TextHolderComponent (TextEditor& owner_)
  42843. : owner (owner_)
  42844. {
  42845. setWantsKeyboardFocus (false);
  42846. setInterceptsMouseClicks (false, true);
  42847. owner.getTextValue().addListener (this);
  42848. }
  42849. ~TextHolderComponent()
  42850. {
  42851. owner.getTextValue().removeListener (this);
  42852. }
  42853. void paint (Graphics& g)
  42854. {
  42855. owner.drawContent (g);
  42856. }
  42857. void timerCallback()
  42858. {
  42859. owner.timerCallbackInt();
  42860. }
  42861. const MouseCursor getMouseCursor()
  42862. {
  42863. return owner.getMouseCursor();
  42864. }
  42865. void valueChanged (Value&)
  42866. {
  42867. owner.textWasChangedByValue();
  42868. }
  42869. private:
  42870. TextEditor& owner;
  42871. TextHolderComponent (const TextHolderComponent&);
  42872. TextHolderComponent& operator= (const TextHolderComponent&);
  42873. };
  42874. class TextEditorViewport : public Viewport
  42875. {
  42876. public:
  42877. TextEditorViewport (TextEditor* const owner_)
  42878. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42879. {
  42880. }
  42881. ~TextEditorViewport()
  42882. {
  42883. }
  42884. void visibleAreaChanged (int, int, int, int)
  42885. {
  42886. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42887. // appear and disappear, causing the wrap width to change.
  42888. {
  42889. const float wordWrapWidth = owner->getWordWrapWidth();
  42890. if (wordWrapWidth != lastWordWrapWidth)
  42891. {
  42892. lastWordWrapWidth = wordWrapWidth;
  42893. rentrant = true;
  42894. owner->updateTextHolderSize();
  42895. rentrant = false;
  42896. }
  42897. }
  42898. }
  42899. private:
  42900. TextEditor* const owner;
  42901. float lastWordWrapWidth;
  42902. bool rentrant;
  42903. TextEditorViewport (const TextEditorViewport&);
  42904. TextEditorViewport& operator= (const TextEditorViewport&);
  42905. };
  42906. namespace TextEditorDefs
  42907. {
  42908. const int flashSpeedIntervalMs = 380;
  42909. const int textChangeMessageId = 0x10003001;
  42910. const int returnKeyMessageId = 0x10003002;
  42911. const int escapeKeyMessageId = 0x10003003;
  42912. const int focusLossMessageId = 0x10003004;
  42913. const int maxActionsPerTransaction = 100;
  42914. static int getCharacterCategory (const juce_wchar character)
  42915. {
  42916. return CharacterFunctions::isLetterOrDigit (character)
  42917. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42918. }
  42919. }
  42920. TextEditor::TextEditor (const String& name,
  42921. const juce_wchar passwordCharacter_)
  42922. : Component (name),
  42923. borderSize (1, 1, 1, 3),
  42924. readOnly (false),
  42925. multiline (false),
  42926. wordWrap (false),
  42927. returnKeyStartsNewLine (false),
  42928. caretVisible (true),
  42929. popupMenuEnabled (true),
  42930. selectAllTextWhenFocused (false),
  42931. scrollbarVisible (true),
  42932. wasFocused (false),
  42933. caretFlashState (true),
  42934. keepCursorOnScreen (true),
  42935. tabKeyUsed (false),
  42936. menuActive (false),
  42937. valueTextNeedsUpdating (false),
  42938. cursorX (0),
  42939. cursorY (0),
  42940. cursorHeight (0),
  42941. maxTextLength (0),
  42942. leftIndent (4),
  42943. topIndent (4),
  42944. lastTransactionTime (0),
  42945. currentFont (14.0f),
  42946. totalNumChars (0),
  42947. caretPosition (0),
  42948. passwordCharacter (passwordCharacter_),
  42949. dragType (notDragging)
  42950. {
  42951. setOpaque (true);
  42952. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42953. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42954. viewport->setWantsKeyboardFocus (false);
  42955. viewport->setScrollBarsShown (false, false);
  42956. setMouseCursor (MouseCursor::IBeamCursor);
  42957. setWantsKeyboardFocus (true);
  42958. }
  42959. TextEditor::~TextEditor()
  42960. {
  42961. textValue.referTo (Value());
  42962. clearInternal (0);
  42963. viewport = 0;
  42964. textHolder = 0;
  42965. }
  42966. void TextEditor::newTransaction()
  42967. {
  42968. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42969. undoManager.beginNewTransaction();
  42970. }
  42971. void TextEditor::doUndoRedo (const bool isRedo)
  42972. {
  42973. if (! isReadOnly())
  42974. {
  42975. if (isRedo ? undoManager.redo()
  42976. : undoManager.undo())
  42977. {
  42978. scrollToMakeSureCursorIsVisible();
  42979. repaint();
  42980. textChanged();
  42981. }
  42982. }
  42983. }
  42984. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42985. const bool shouldWordWrap)
  42986. {
  42987. if (multiline != shouldBeMultiLine
  42988. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42989. {
  42990. multiline = shouldBeMultiLine;
  42991. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42992. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42993. scrollbarVisible && multiline);
  42994. viewport->setViewPosition (0, 0);
  42995. resized();
  42996. scrollToMakeSureCursorIsVisible();
  42997. }
  42998. }
  42999. bool TextEditor::isMultiLine() const
  43000. {
  43001. return multiline;
  43002. }
  43003. void TextEditor::setScrollbarsShown (bool shown)
  43004. {
  43005. if (scrollbarVisible != shown)
  43006. {
  43007. scrollbarVisible = shown;
  43008. shown = shown && isMultiLine();
  43009. viewport->setScrollBarsShown (shown, shown);
  43010. }
  43011. }
  43012. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  43013. {
  43014. if (readOnly != shouldBeReadOnly)
  43015. {
  43016. readOnly = shouldBeReadOnly;
  43017. enablementChanged();
  43018. }
  43019. }
  43020. bool TextEditor::isReadOnly() const
  43021. {
  43022. return readOnly || ! isEnabled();
  43023. }
  43024. bool TextEditor::isTextInputActive() const
  43025. {
  43026. return ! isReadOnly();
  43027. }
  43028. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  43029. {
  43030. returnKeyStartsNewLine = shouldStartNewLine;
  43031. }
  43032. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  43033. {
  43034. tabKeyUsed = shouldTabKeyBeUsed;
  43035. }
  43036. void TextEditor::setPopupMenuEnabled (const bool b)
  43037. {
  43038. popupMenuEnabled = b;
  43039. }
  43040. void TextEditor::setSelectAllWhenFocused (const bool b)
  43041. {
  43042. selectAllTextWhenFocused = b;
  43043. }
  43044. const Font TextEditor::getFont() const
  43045. {
  43046. return currentFont;
  43047. }
  43048. void TextEditor::setFont (const Font& newFont)
  43049. {
  43050. currentFont = newFont;
  43051. scrollToMakeSureCursorIsVisible();
  43052. }
  43053. void TextEditor::applyFontToAllText (const Font& newFont)
  43054. {
  43055. currentFont = newFont;
  43056. const Colour overallColour (findColour (textColourId));
  43057. for (int i = sections.size(); --i >= 0;)
  43058. {
  43059. UniformTextSection* const uts = sections.getUnchecked (i);
  43060. uts->setFont (newFont, passwordCharacter);
  43061. uts->colour = overallColour;
  43062. }
  43063. coalesceSimilarSections();
  43064. updateTextHolderSize();
  43065. scrollToMakeSureCursorIsVisible();
  43066. repaint();
  43067. }
  43068. void TextEditor::colourChanged()
  43069. {
  43070. setOpaque (findColour (backgroundColourId).isOpaque());
  43071. repaint();
  43072. }
  43073. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  43074. {
  43075. caretVisible = shouldCaretBeVisible;
  43076. if (shouldCaretBeVisible)
  43077. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43078. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  43079. : MouseCursor::NormalCursor);
  43080. }
  43081. void TextEditor::setInputRestrictions (const int maxLen,
  43082. const String& chars)
  43083. {
  43084. maxTextLength = jmax (0, maxLen);
  43085. allowedCharacters = chars;
  43086. }
  43087. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  43088. {
  43089. textToShowWhenEmpty = text;
  43090. colourForTextWhenEmpty = colourToUse;
  43091. }
  43092. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  43093. {
  43094. if (passwordCharacter != newPasswordCharacter)
  43095. {
  43096. passwordCharacter = newPasswordCharacter;
  43097. resized();
  43098. repaint();
  43099. }
  43100. }
  43101. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  43102. {
  43103. viewport->setScrollBarThickness (newThicknessPixels);
  43104. }
  43105. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  43106. {
  43107. viewport->setScrollBarButtonVisibility (buttonsVisible);
  43108. }
  43109. void TextEditor::clear()
  43110. {
  43111. clearInternal (0);
  43112. updateTextHolderSize();
  43113. undoManager.clearUndoHistory();
  43114. }
  43115. void TextEditor::setText (const String& newText,
  43116. const bool sendTextChangeMessage)
  43117. {
  43118. const int newLength = newText.length();
  43119. if (newLength != getTotalNumChars() || getText() != newText)
  43120. {
  43121. const int oldCursorPos = caretPosition;
  43122. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  43123. clearInternal (0);
  43124. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  43125. // if you're adding text with line-feeds to a single-line text editor, it
  43126. // ain't gonna look right!
  43127. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  43128. if (cursorWasAtEnd && ! isMultiLine())
  43129. moveCursorTo (getTotalNumChars(), false);
  43130. else
  43131. moveCursorTo (oldCursorPos, false);
  43132. if (sendTextChangeMessage)
  43133. textChanged();
  43134. updateTextHolderSize();
  43135. scrollToMakeSureCursorIsVisible();
  43136. undoManager.clearUndoHistory();
  43137. repaint();
  43138. }
  43139. }
  43140. Value& TextEditor::getTextValue()
  43141. {
  43142. if (valueTextNeedsUpdating)
  43143. {
  43144. valueTextNeedsUpdating = false;
  43145. textValue = getText();
  43146. }
  43147. return textValue;
  43148. }
  43149. void TextEditor::textWasChangedByValue()
  43150. {
  43151. if (textValue.getValueSource().getReferenceCount() > 1)
  43152. setText (textValue.getValue());
  43153. }
  43154. void TextEditor::textChanged()
  43155. {
  43156. updateTextHolderSize();
  43157. postCommandMessage (TextEditorDefs::textChangeMessageId);
  43158. if (textValue.getValueSource().getReferenceCount() > 1)
  43159. {
  43160. valueTextNeedsUpdating = false;
  43161. textValue = getText();
  43162. }
  43163. }
  43164. void TextEditor::returnPressed()
  43165. {
  43166. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  43167. }
  43168. void TextEditor::escapePressed()
  43169. {
  43170. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  43171. }
  43172. void TextEditor::addListener (Listener* const newListener)
  43173. {
  43174. listeners.add (newListener);
  43175. }
  43176. void TextEditor::removeListener (Listener* const listenerToRemove)
  43177. {
  43178. listeners.remove (listenerToRemove);
  43179. }
  43180. void TextEditor::timerCallbackInt()
  43181. {
  43182. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  43183. if (caretFlashState != newState)
  43184. {
  43185. caretFlashState = newState;
  43186. if (caretFlashState)
  43187. wasFocused = true;
  43188. if (caretVisible
  43189. && hasKeyboardFocus (false)
  43190. && ! isReadOnly())
  43191. {
  43192. repaintCaret();
  43193. }
  43194. }
  43195. const unsigned int now = Time::getApproximateMillisecondCounter();
  43196. if (now > lastTransactionTime + 200)
  43197. newTransaction();
  43198. }
  43199. void TextEditor::repaintCaret()
  43200. {
  43201. if (! findColour (caretColourId).isTransparent())
  43202. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  43203. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  43204. 4,
  43205. roundToInt (cursorHeight) + 2);
  43206. }
  43207. void TextEditor::repaintText (const Range<int>& range)
  43208. {
  43209. if (! range.isEmpty())
  43210. {
  43211. float x = 0, y = 0, lh = currentFont.getHeight();
  43212. const float wordWrapWidth = getWordWrapWidth();
  43213. if (wordWrapWidth > 0)
  43214. {
  43215. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43216. i.getCharPosition (range.getStart(), x, y, lh);
  43217. const int y1 = (int) y;
  43218. int y2;
  43219. if (range.getEnd() >= getTotalNumChars())
  43220. {
  43221. y2 = textHolder->getHeight();
  43222. }
  43223. else
  43224. {
  43225. i.getCharPosition (range.getEnd(), x, y, lh);
  43226. y2 = (int) (y + lh * 2.0f);
  43227. }
  43228. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  43229. }
  43230. }
  43231. }
  43232. void TextEditor::moveCaret (int newCaretPos)
  43233. {
  43234. if (newCaretPos < 0)
  43235. newCaretPos = 0;
  43236. else if (newCaretPos > getTotalNumChars())
  43237. newCaretPos = getTotalNumChars();
  43238. if (newCaretPos != getCaretPosition())
  43239. {
  43240. repaintCaret();
  43241. caretFlashState = true;
  43242. caretPosition = newCaretPos;
  43243. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43244. scrollToMakeSureCursorIsVisible();
  43245. repaintCaret();
  43246. }
  43247. }
  43248. void TextEditor::setCaretPosition (const int newIndex)
  43249. {
  43250. moveCursorTo (newIndex, false);
  43251. }
  43252. int TextEditor::getCaretPosition() const
  43253. {
  43254. return caretPosition;
  43255. }
  43256. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43257. const int desiredCaretY)
  43258. {
  43259. updateCaretPosition();
  43260. int vx = roundToInt (cursorX) - desiredCaretX;
  43261. int vy = roundToInt (cursorY) - desiredCaretY;
  43262. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43263. {
  43264. vx += desiredCaretX - proportionOfWidth (0.2f);
  43265. }
  43266. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43267. {
  43268. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43269. }
  43270. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43271. if (! isMultiLine())
  43272. {
  43273. vy = viewport->getViewPositionY();
  43274. }
  43275. else
  43276. {
  43277. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43278. const int curH = roundToInt (cursorHeight);
  43279. if (desiredCaretY < 0)
  43280. {
  43281. vy = jmax (0, desiredCaretY + vy);
  43282. }
  43283. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43284. {
  43285. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43286. }
  43287. }
  43288. viewport->setViewPosition (vx, vy);
  43289. }
  43290. const Rectangle<int> TextEditor::getCaretRectangle()
  43291. {
  43292. updateCaretPosition();
  43293. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43294. roundToInt (cursorY) - viewport->getY(),
  43295. 1, roundToInt (cursorHeight));
  43296. }
  43297. float TextEditor::getWordWrapWidth() const
  43298. {
  43299. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43300. : 1.0e10f;
  43301. }
  43302. void TextEditor::updateTextHolderSize()
  43303. {
  43304. const float wordWrapWidth = getWordWrapWidth();
  43305. if (wordWrapWidth > 0)
  43306. {
  43307. float maxWidth = 0.0f;
  43308. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43309. while (i.next())
  43310. maxWidth = jmax (maxWidth, i.atomRight);
  43311. const int w = leftIndent + roundToInt (maxWidth);
  43312. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43313. currentFont.getHeight()));
  43314. textHolder->setSize (w + 1, h + 1);
  43315. }
  43316. }
  43317. int TextEditor::getTextWidth() const
  43318. {
  43319. return textHolder->getWidth();
  43320. }
  43321. int TextEditor::getTextHeight() const
  43322. {
  43323. return textHolder->getHeight();
  43324. }
  43325. void TextEditor::setIndents (const int newLeftIndent,
  43326. const int newTopIndent)
  43327. {
  43328. leftIndent = newLeftIndent;
  43329. topIndent = newTopIndent;
  43330. }
  43331. void TextEditor::setBorder (const BorderSize& border)
  43332. {
  43333. borderSize = border;
  43334. resized();
  43335. }
  43336. const BorderSize TextEditor::getBorder() const
  43337. {
  43338. return borderSize;
  43339. }
  43340. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43341. {
  43342. keepCursorOnScreen = shouldScrollToShowCursor;
  43343. }
  43344. void TextEditor::updateCaretPosition()
  43345. {
  43346. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43347. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43348. }
  43349. void TextEditor::scrollToMakeSureCursorIsVisible()
  43350. {
  43351. updateCaretPosition();
  43352. if (keepCursorOnScreen)
  43353. {
  43354. int x = viewport->getViewPositionX();
  43355. int y = viewport->getViewPositionY();
  43356. const int relativeCursorX = roundToInt (cursorX) - x;
  43357. const int relativeCursorY = roundToInt (cursorY) - y;
  43358. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43359. {
  43360. x += relativeCursorX - proportionOfWidth (0.2f);
  43361. }
  43362. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43363. {
  43364. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43365. }
  43366. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43367. if (! isMultiLine())
  43368. {
  43369. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43370. }
  43371. else
  43372. {
  43373. const int curH = roundToInt (cursorHeight);
  43374. if (relativeCursorY < 0)
  43375. {
  43376. y = jmax (0, relativeCursorY + y);
  43377. }
  43378. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43379. {
  43380. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43381. }
  43382. }
  43383. viewport->setViewPosition (x, y);
  43384. }
  43385. }
  43386. void TextEditor::moveCursorTo (const int newPosition,
  43387. const bool isSelecting)
  43388. {
  43389. if (isSelecting)
  43390. {
  43391. moveCaret (newPosition);
  43392. const Range<int> oldSelection (selection);
  43393. if (dragType == notDragging)
  43394. {
  43395. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43396. dragType = draggingSelectionStart;
  43397. else
  43398. dragType = draggingSelectionEnd;
  43399. }
  43400. if (dragType == draggingSelectionStart)
  43401. {
  43402. if (getCaretPosition() >= selection.getEnd())
  43403. dragType = draggingSelectionEnd;
  43404. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43405. }
  43406. else
  43407. {
  43408. if (getCaretPosition() < selection.getStart())
  43409. dragType = draggingSelectionStart;
  43410. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43411. }
  43412. repaintText (selection.getUnionWith (oldSelection));
  43413. }
  43414. else
  43415. {
  43416. dragType = notDragging;
  43417. repaintText (selection);
  43418. moveCaret (newPosition);
  43419. selection = Range<int>::emptyRange (getCaretPosition());
  43420. }
  43421. }
  43422. int TextEditor::getTextIndexAt (const int x,
  43423. const int y)
  43424. {
  43425. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43426. (float) (y + viewport->getViewPositionY() - topIndent));
  43427. }
  43428. void TextEditor::insertTextAtCaret (const String& newText_)
  43429. {
  43430. String newText (newText_);
  43431. if (allowedCharacters.isNotEmpty())
  43432. newText = newText.retainCharacters (allowedCharacters);
  43433. if ((! returnKeyStartsNewLine) && newText == "\n")
  43434. {
  43435. returnPressed();
  43436. return;
  43437. }
  43438. if (! isMultiLine())
  43439. newText = newText.replaceCharacters ("\r\n", " ");
  43440. else
  43441. newText = newText.replace ("\r\n", "\n");
  43442. const int newCaretPos = selection.getStart() + newText.length();
  43443. const int insertIndex = selection.getStart();
  43444. remove (selection, getUndoManager(),
  43445. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43446. if (maxTextLength > 0)
  43447. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43448. if (newText.isNotEmpty())
  43449. insert (newText,
  43450. insertIndex,
  43451. currentFont,
  43452. findColour (textColourId),
  43453. getUndoManager(),
  43454. newCaretPos);
  43455. textChanged();
  43456. }
  43457. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43458. {
  43459. moveCursorTo (newSelection.getStart(), false);
  43460. moveCursorTo (newSelection.getEnd(), true);
  43461. }
  43462. void TextEditor::copy()
  43463. {
  43464. if (passwordCharacter == 0)
  43465. {
  43466. const String selectedText (getHighlightedText());
  43467. if (selectedText.isNotEmpty())
  43468. SystemClipboard::copyTextToClipboard (selectedText);
  43469. }
  43470. }
  43471. void TextEditor::paste()
  43472. {
  43473. if (! isReadOnly())
  43474. {
  43475. const String clip (SystemClipboard::getTextFromClipboard());
  43476. if (clip.isNotEmpty())
  43477. insertTextAtCaret (clip);
  43478. }
  43479. }
  43480. void TextEditor::cut()
  43481. {
  43482. if (! isReadOnly())
  43483. {
  43484. moveCaret (selection.getEnd());
  43485. insertTextAtCaret (String::empty);
  43486. }
  43487. }
  43488. void TextEditor::drawContent (Graphics& g)
  43489. {
  43490. const float wordWrapWidth = getWordWrapWidth();
  43491. if (wordWrapWidth > 0)
  43492. {
  43493. g.setOrigin (leftIndent, topIndent);
  43494. const Rectangle<int> clip (g.getClipBounds());
  43495. Colour selectedTextColour;
  43496. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43497. while (i.lineY + 200.0 < clip.getY() && i.next())
  43498. {}
  43499. if (! selection.isEmpty())
  43500. {
  43501. g.setColour (findColour (highlightColourId)
  43502. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43503. selectedTextColour = findColour (highlightedTextColourId);
  43504. Iterator i2 (i);
  43505. while (i2.next() && i2.lineY < clip.getBottom())
  43506. {
  43507. if (i2.lineY + i2.lineHeight >= clip.getY()
  43508. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43509. {
  43510. i2.drawSelection (g, selection);
  43511. }
  43512. }
  43513. }
  43514. const UniformTextSection* lastSection = 0;
  43515. while (i.next() && i.lineY < clip.getBottom())
  43516. {
  43517. if (i.lineY + i.lineHeight >= clip.getY())
  43518. {
  43519. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43520. {
  43521. i.drawSelectedText (g, selection, selectedTextColour);
  43522. lastSection = 0;
  43523. }
  43524. else
  43525. {
  43526. i.draw (g, lastSection);
  43527. }
  43528. }
  43529. }
  43530. }
  43531. }
  43532. void TextEditor::paint (Graphics& g)
  43533. {
  43534. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43535. }
  43536. void TextEditor::paintOverChildren (Graphics& g)
  43537. {
  43538. if (caretFlashState
  43539. && hasKeyboardFocus (false)
  43540. && caretVisible
  43541. && ! isReadOnly())
  43542. {
  43543. g.setColour (findColour (caretColourId));
  43544. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43545. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43546. 2.0f, cursorHeight);
  43547. }
  43548. if (textToShowWhenEmpty.isNotEmpty()
  43549. && (! hasKeyboardFocus (false))
  43550. && getTotalNumChars() == 0)
  43551. {
  43552. g.setColour (colourForTextWhenEmpty);
  43553. g.setFont (getFont());
  43554. if (isMultiLine())
  43555. {
  43556. g.drawText (textToShowWhenEmpty,
  43557. 0, 0, getWidth(), getHeight(),
  43558. Justification::centred, true);
  43559. }
  43560. else
  43561. {
  43562. g.drawText (textToShowWhenEmpty,
  43563. leftIndent, topIndent,
  43564. viewport->getWidth() - leftIndent,
  43565. viewport->getHeight() - topIndent,
  43566. Justification::centredLeft, true);
  43567. }
  43568. }
  43569. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43570. }
  43571. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43572. {
  43573. public:
  43574. TextEditorMenuPerformer (TextEditor* const editor_)
  43575. : editor (editor_)
  43576. {
  43577. }
  43578. void modalStateFinished (int returnValue)
  43579. {
  43580. if (editor != 0 && returnValue != 0)
  43581. editor->performPopupMenuAction (returnValue);
  43582. }
  43583. private:
  43584. Component::SafePointer<TextEditor> editor;
  43585. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  43586. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  43587. };
  43588. void TextEditor::mouseDown (const MouseEvent& e)
  43589. {
  43590. beginDragAutoRepeat (100);
  43591. newTransaction();
  43592. if (wasFocused || ! selectAllTextWhenFocused)
  43593. {
  43594. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43595. {
  43596. moveCursorTo (getTextIndexAt (e.x, e.y),
  43597. e.mods.isShiftDown());
  43598. }
  43599. else
  43600. {
  43601. PopupMenu m;
  43602. m.setLookAndFeel (&getLookAndFeel());
  43603. addPopupMenuItems (m, &e);
  43604. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43605. }
  43606. }
  43607. }
  43608. void TextEditor::mouseDrag (const MouseEvent& e)
  43609. {
  43610. if (wasFocused || ! selectAllTextWhenFocused)
  43611. {
  43612. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43613. {
  43614. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43615. }
  43616. }
  43617. }
  43618. void TextEditor::mouseUp (const MouseEvent& e)
  43619. {
  43620. newTransaction();
  43621. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43622. if (wasFocused || ! selectAllTextWhenFocused)
  43623. {
  43624. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43625. {
  43626. moveCaret (getTextIndexAt (e.x, e.y));
  43627. }
  43628. }
  43629. wasFocused = true;
  43630. }
  43631. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43632. {
  43633. int tokenEnd = getTextIndexAt (e.x, e.y);
  43634. int tokenStart = tokenEnd;
  43635. if (e.getNumberOfClicks() > 3)
  43636. {
  43637. tokenStart = 0;
  43638. tokenEnd = getTotalNumChars();
  43639. }
  43640. else
  43641. {
  43642. const String t (getText());
  43643. const int totalLength = getTotalNumChars();
  43644. while (tokenEnd < totalLength)
  43645. {
  43646. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43647. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43648. ++tokenEnd;
  43649. else
  43650. break;
  43651. }
  43652. tokenStart = tokenEnd;
  43653. while (tokenStart > 0)
  43654. {
  43655. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43656. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43657. --tokenStart;
  43658. else
  43659. break;
  43660. }
  43661. if (e.getNumberOfClicks() > 2)
  43662. {
  43663. while (tokenEnd < totalLength)
  43664. {
  43665. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43666. ++tokenEnd;
  43667. else
  43668. break;
  43669. }
  43670. while (tokenStart > 0)
  43671. {
  43672. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43673. --tokenStart;
  43674. else
  43675. break;
  43676. }
  43677. }
  43678. }
  43679. moveCursorTo (tokenEnd, false);
  43680. moveCursorTo (tokenStart, true);
  43681. }
  43682. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43683. {
  43684. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43685. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43686. }
  43687. bool TextEditor::keyPressed (const KeyPress& key)
  43688. {
  43689. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43690. return false;
  43691. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43692. if (key.isKeyCode (KeyPress::leftKey)
  43693. || key.isKeyCode (KeyPress::upKey))
  43694. {
  43695. newTransaction();
  43696. int newPos;
  43697. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43698. newPos = indexAtPosition (cursorX, cursorY - 1);
  43699. else if (moveInWholeWordSteps)
  43700. newPos = findWordBreakBefore (getCaretPosition());
  43701. else
  43702. newPos = getCaretPosition() - 1;
  43703. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43704. }
  43705. else if (key.isKeyCode (KeyPress::rightKey)
  43706. || key.isKeyCode (KeyPress::downKey))
  43707. {
  43708. newTransaction();
  43709. int newPos;
  43710. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43711. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43712. else if (moveInWholeWordSteps)
  43713. newPos = findWordBreakAfter (getCaretPosition());
  43714. else
  43715. newPos = getCaretPosition() + 1;
  43716. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43717. }
  43718. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43719. {
  43720. newTransaction();
  43721. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43722. key.getModifiers().isShiftDown());
  43723. }
  43724. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43725. {
  43726. newTransaction();
  43727. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43728. key.getModifiers().isShiftDown());
  43729. }
  43730. else if (key.isKeyCode (KeyPress::homeKey))
  43731. {
  43732. newTransaction();
  43733. if (isMultiLine() && ! moveInWholeWordSteps)
  43734. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43735. key.getModifiers().isShiftDown());
  43736. else
  43737. moveCursorTo (0, key.getModifiers().isShiftDown());
  43738. }
  43739. else if (key.isKeyCode (KeyPress::endKey))
  43740. {
  43741. newTransaction();
  43742. if (isMultiLine() && ! moveInWholeWordSteps)
  43743. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43744. key.getModifiers().isShiftDown());
  43745. else
  43746. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43747. }
  43748. else if (key.isKeyCode (KeyPress::backspaceKey))
  43749. {
  43750. if (moveInWholeWordSteps)
  43751. {
  43752. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43753. }
  43754. else
  43755. {
  43756. if (selection.isEmpty() && selection.getStart() > 0)
  43757. selection.setStart (selection.getEnd() - 1);
  43758. }
  43759. cut();
  43760. }
  43761. else if (key.isKeyCode (KeyPress::deleteKey))
  43762. {
  43763. if (key.getModifiers().isShiftDown())
  43764. copy();
  43765. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43766. selection.setEnd (selection.getStart() + 1);
  43767. cut();
  43768. }
  43769. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43770. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43771. {
  43772. newTransaction();
  43773. copy();
  43774. }
  43775. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43776. {
  43777. newTransaction();
  43778. copy();
  43779. cut();
  43780. }
  43781. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43782. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43783. {
  43784. newTransaction();
  43785. paste();
  43786. }
  43787. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43788. {
  43789. newTransaction();
  43790. doUndoRedo (false);
  43791. }
  43792. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43793. {
  43794. newTransaction();
  43795. doUndoRedo (true);
  43796. }
  43797. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43798. {
  43799. newTransaction();
  43800. moveCursorTo (getTotalNumChars(), false);
  43801. moveCursorTo (0, true);
  43802. }
  43803. else if (key == KeyPress::returnKey)
  43804. {
  43805. newTransaction();
  43806. insertTextAtCaret ("\n");
  43807. }
  43808. else if (key.isKeyCode (KeyPress::escapeKey))
  43809. {
  43810. newTransaction();
  43811. moveCursorTo (getCaretPosition(), false);
  43812. escapePressed();
  43813. }
  43814. else if (key.getTextCharacter() >= ' '
  43815. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43816. {
  43817. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43818. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43819. }
  43820. else
  43821. {
  43822. return false;
  43823. }
  43824. return true;
  43825. }
  43826. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43827. {
  43828. if (! isKeyDown)
  43829. return false;
  43830. #if JUCE_WINDOWS
  43831. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43832. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43833. #endif
  43834. // (overridden to avoid forwarding key events to the parent)
  43835. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43836. }
  43837. const int baseMenuItemID = 0x7fff0000;
  43838. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43839. {
  43840. const bool writable = ! isReadOnly();
  43841. if (passwordCharacter == 0)
  43842. {
  43843. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43844. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43845. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43846. }
  43847. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43848. m.addSeparator();
  43849. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43850. m.addSeparator();
  43851. if (getUndoManager() != 0)
  43852. {
  43853. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43854. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43855. }
  43856. }
  43857. void TextEditor::performPopupMenuAction (const int menuItemID)
  43858. {
  43859. switch (menuItemID)
  43860. {
  43861. case baseMenuItemID + 1:
  43862. copy();
  43863. cut();
  43864. break;
  43865. case baseMenuItemID + 2:
  43866. copy();
  43867. break;
  43868. case baseMenuItemID + 3:
  43869. paste();
  43870. break;
  43871. case baseMenuItemID + 4:
  43872. cut();
  43873. break;
  43874. case baseMenuItemID + 5:
  43875. moveCursorTo (getTotalNumChars(), false);
  43876. moveCursorTo (0, true);
  43877. break;
  43878. case baseMenuItemID + 6:
  43879. doUndoRedo (false);
  43880. break;
  43881. case baseMenuItemID + 7:
  43882. doUndoRedo (true);
  43883. break;
  43884. default:
  43885. break;
  43886. }
  43887. }
  43888. void TextEditor::focusGained (FocusChangeType)
  43889. {
  43890. newTransaction();
  43891. caretFlashState = true;
  43892. if (selectAllTextWhenFocused)
  43893. {
  43894. moveCursorTo (0, false);
  43895. moveCursorTo (getTotalNumChars(), true);
  43896. }
  43897. repaint();
  43898. if (caretVisible)
  43899. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43900. ComponentPeer* const peer = getPeer();
  43901. if (peer != 0 && ! isReadOnly())
  43902. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43903. }
  43904. void TextEditor::focusLost (FocusChangeType)
  43905. {
  43906. newTransaction();
  43907. wasFocused = false;
  43908. textHolder->stopTimer();
  43909. caretFlashState = false;
  43910. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43911. repaint();
  43912. }
  43913. void TextEditor::resized()
  43914. {
  43915. viewport->setBoundsInset (borderSize);
  43916. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43917. updateTextHolderSize();
  43918. if (! isMultiLine())
  43919. {
  43920. scrollToMakeSureCursorIsVisible();
  43921. }
  43922. else
  43923. {
  43924. updateCaretPosition();
  43925. }
  43926. }
  43927. void TextEditor::handleCommandMessage (const int commandId)
  43928. {
  43929. Component::BailOutChecker checker (this);
  43930. switch (commandId)
  43931. {
  43932. case TextEditorDefs::textChangeMessageId:
  43933. listeners.callChecked (checker, &TextEditor::Listener::textEditorTextChanged, (TextEditor&) *this);
  43934. break;
  43935. case TextEditorDefs::returnKeyMessageId:
  43936. listeners.callChecked (checker, &TextEditor::Listener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43937. break;
  43938. case TextEditorDefs::escapeKeyMessageId:
  43939. listeners.callChecked (checker, &TextEditor::Listener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43940. break;
  43941. case TextEditorDefs::focusLossMessageId:
  43942. listeners.callChecked (checker, &TextEditor::Listener::textEditorFocusLost, (TextEditor&) *this);
  43943. break;
  43944. default:
  43945. jassertfalse;
  43946. break;
  43947. }
  43948. }
  43949. void TextEditor::enablementChanged()
  43950. {
  43951. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43952. : MouseCursor::IBeamCursor);
  43953. repaint();
  43954. }
  43955. UndoManager* TextEditor::getUndoManager() throw()
  43956. {
  43957. return isReadOnly() ? 0 : &undoManager;
  43958. }
  43959. void TextEditor::clearInternal (UndoManager* const um)
  43960. {
  43961. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43962. }
  43963. void TextEditor::insert (const String& text,
  43964. const int insertIndex,
  43965. const Font& font,
  43966. const Colour& colour,
  43967. UndoManager* const um,
  43968. const int caretPositionToMoveTo)
  43969. {
  43970. if (text.isNotEmpty())
  43971. {
  43972. if (um != 0)
  43973. {
  43974. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43975. newTransaction();
  43976. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43977. caretPosition, caretPositionToMoveTo));
  43978. }
  43979. else
  43980. {
  43981. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43982. // a line gets moved due to word wrap
  43983. int index = 0;
  43984. int nextIndex = 0;
  43985. for (int i = 0; i < sections.size(); ++i)
  43986. {
  43987. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43988. if (insertIndex == index)
  43989. {
  43990. sections.insert (i, new UniformTextSection (text,
  43991. font, colour,
  43992. passwordCharacter));
  43993. break;
  43994. }
  43995. else if (insertIndex > index && insertIndex < nextIndex)
  43996. {
  43997. splitSection (i, insertIndex - index);
  43998. sections.insert (i + 1, new UniformTextSection (text,
  43999. font, colour,
  44000. passwordCharacter));
  44001. break;
  44002. }
  44003. index = nextIndex;
  44004. }
  44005. if (nextIndex == insertIndex)
  44006. sections.add (new UniformTextSection (text,
  44007. font, colour,
  44008. passwordCharacter));
  44009. coalesceSimilarSections();
  44010. totalNumChars = -1;
  44011. valueTextNeedsUpdating = true;
  44012. moveCursorTo (caretPositionToMoveTo, false);
  44013. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  44014. }
  44015. }
  44016. }
  44017. void TextEditor::reinsert (const int insertIndex,
  44018. const Array <UniformTextSection*>& sectionsToInsert)
  44019. {
  44020. int index = 0;
  44021. int nextIndex = 0;
  44022. for (int i = 0; i < sections.size(); ++i)
  44023. {
  44024. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  44025. if (insertIndex == index)
  44026. {
  44027. for (int j = sectionsToInsert.size(); --j >= 0;)
  44028. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44029. break;
  44030. }
  44031. else if (insertIndex > index && insertIndex < nextIndex)
  44032. {
  44033. splitSection (i, insertIndex - index);
  44034. for (int j = sectionsToInsert.size(); --j >= 0;)
  44035. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44036. break;
  44037. }
  44038. index = nextIndex;
  44039. }
  44040. if (nextIndex == insertIndex)
  44041. {
  44042. for (int j = 0; j < sectionsToInsert.size(); ++j)
  44043. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44044. }
  44045. coalesceSimilarSections();
  44046. totalNumChars = -1;
  44047. valueTextNeedsUpdating = true;
  44048. }
  44049. void TextEditor::remove (const Range<int>& range,
  44050. UndoManager* const um,
  44051. const int caretPositionToMoveTo)
  44052. {
  44053. if (! range.isEmpty())
  44054. {
  44055. int index = 0;
  44056. for (int i = 0; i < sections.size(); ++i)
  44057. {
  44058. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  44059. if (range.getStart() > index && range.getStart() < nextIndex)
  44060. {
  44061. splitSection (i, range.getStart() - index);
  44062. --i;
  44063. }
  44064. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  44065. {
  44066. splitSection (i, range.getEnd() - index);
  44067. --i;
  44068. }
  44069. else
  44070. {
  44071. index = nextIndex;
  44072. if (index > range.getEnd())
  44073. break;
  44074. }
  44075. }
  44076. index = 0;
  44077. if (um != 0)
  44078. {
  44079. Array <UniformTextSection*> removedSections;
  44080. for (int i = 0; i < sections.size(); ++i)
  44081. {
  44082. if (range.getEnd() <= range.getStart())
  44083. break;
  44084. UniformTextSection* const section = sections.getUnchecked (i);
  44085. const int nextIndex = index + section->getTotalLength();
  44086. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  44087. removedSections.add (new UniformTextSection (*section));
  44088. index = nextIndex;
  44089. }
  44090. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  44091. newTransaction();
  44092. um->perform (new RemoveAction (*this, range, caretPosition,
  44093. caretPositionToMoveTo, removedSections));
  44094. }
  44095. else
  44096. {
  44097. Range<int> remainingRange (range);
  44098. for (int i = 0; i < sections.size(); ++i)
  44099. {
  44100. UniformTextSection* const section = sections.getUnchecked (i);
  44101. const int nextIndex = index + section->getTotalLength();
  44102. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  44103. {
  44104. sections.remove(i);
  44105. section->clear();
  44106. delete section;
  44107. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  44108. if (remainingRange.isEmpty())
  44109. break;
  44110. --i;
  44111. }
  44112. else
  44113. {
  44114. index = nextIndex;
  44115. }
  44116. }
  44117. coalesceSimilarSections();
  44118. totalNumChars = -1;
  44119. valueTextNeedsUpdating = true;
  44120. moveCursorTo (caretPositionToMoveTo, false);
  44121. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  44122. }
  44123. }
  44124. }
  44125. const String TextEditor::getText() const
  44126. {
  44127. String t;
  44128. t.preallocateStorage (getTotalNumChars());
  44129. String::Concatenator concatenator (t);
  44130. for (int i = 0; i < sections.size(); ++i)
  44131. sections.getUnchecked (i)->appendAllText (concatenator);
  44132. return t;
  44133. }
  44134. const String TextEditor::getTextInRange (const Range<int>& range) const
  44135. {
  44136. String t;
  44137. if (! range.isEmpty())
  44138. {
  44139. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  44140. String::Concatenator concatenator (t);
  44141. int index = 0;
  44142. for (int i = 0; i < sections.size(); ++i)
  44143. {
  44144. const UniformTextSection* const s = sections.getUnchecked (i);
  44145. const int nextIndex = index + s->getTotalLength();
  44146. if (range.getStart() < nextIndex)
  44147. {
  44148. if (range.getEnd() <= index)
  44149. break;
  44150. s->appendSubstring (concatenator, range - index);
  44151. }
  44152. index = nextIndex;
  44153. }
  44154. }
  44155. return t;
  44156. }
  44157. const String TextEditor::getHighlightedText() const
  44158. {
  44159. return getTextInRange (selection);
  44160. }
  44161. int TextEditor::getTotalNumChars() const
  44162. {
  44163. if (totalNumChars < 0)
  44164. {
  44165. totalNumChars = 0;
  44166. for (int i = sections.size(); --i >= 0;)
  44167. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  44168. }
  44169. return totalNumChars;
  44170. }
  44171. bool TextEditor::isEmpty() const
  44172. {
  44173. return getTotalNumChars() == 0;
  44174. }
  44175. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  44176. {
  44177. const float wordWrapWidth = getWordWrapWidth();
  44178. if (wordWrapWidth > 0 && sections.size() > 0)
  44179. {
  44180. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44181. i.getCharPosition (index, cx, cy, lineHeight);
  44182. }
  44183. else
  44184. {
  44185. cx = cy = 0;
  44186. lineHeight = currentFont.getHeight();
  44187. }
  44188. }
  44189. int TextEditor::indexAtPosition (const float x, const float y)
  44190. {
  44191. const float wordWrapWidth = getWordWrapWidth();
  44192. if (wordWrapWidth > 0)
  44193. {
  44194. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44195. while (i.next())
  44196. {
  44197. if (i.lineY + i.lineHeight > y)
  44198. {
  44199. if (i.lineY > y)
  44200. return jmax (0, i.indexInText - 1);
  44201. if (i.atomX >= x)
  44202. return i.indexInText;
  44203. if (x < i.atomRight)
  44204. return i.xToIndex (x);
  44205. }
  44206. }
  44207. }
  44208. return getTotalNumChars();
  44209. }
  44210. int TextEditor::findWordBreakAfter (const int position) const
  44211. {
  44212. const String t (getTextInRange (Range<int> (position, position + 512)));
  44213. const int totalLength = t.length();
  44214. int i = 0;
  44215. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44216. ++i;
  44217. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  44218. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  44219. ++i;
  44220. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44221. ++i;
  44222. return position + i;
  44223. }
  44224. int TextEditor::findWordBreakBefore (const int position) const
  44225. {
  44226. if (position <= 0)
  44227. return 0;
  44228. const int startOfBuffer = jmax (0, position - 512);
  44229. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  44230. int i = position - startOfBuffer;
  44231. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  44232. --i;
  44233. if (i > 0)
  44234. {
  44235. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  44236. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  44237. --i;
  44238. }
  44239. jassert (startOfBuffer + i >= 0);
  44240. return startOfBuffer + i;
  44241. }
  44242. void TextEditor::splitSection (const int sectionIndex,
  44243. const int charToSplitAt)
  44244. {
  44245. jassert (sections[sectionIndex] != 0);
  44246. sections.insert (sectionIndex + 1,
  44247. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  44248. }
  44249. void TextEditor::coalesceSimilarSections()
  44250. {
  44251. for (int i = 0; i < sections.size() - 1; ++i)
  44252. {
  44253. UniformTextSection* const s1 = sections.getUnchecked (i);
  44254. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44255. if (s1->font == s2->font
  44256. && s1->colour == s2->colour)
  44257. {
  44258. s1->append (*s2, passwordCharacter);
  44259. sections.remove (i + 1);
  44260. delete s2;
  44261. --i;
  44262. }
  44263. }
  44264. }
  44265. END_JUCE_NAMESPACE
  44266. /*** End of inlined file: juce_TextEditor.cpp ***/
  44267. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44268. BEGIN_JUCE_NAMESPACE
  44269. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44270. class ToolbarSpacerComp : public ToolbarItemComponent
  44271. {
  44272. public:
  44273. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44274. : ToolbarItemComponent (itemId_, String::empty, false),
  44275. fixedSize (fixedSize_),
  44276. drawBar (drawBar_)
  44277. {
  44278. }
  44279. ~ToolbarSpacerComp()
  44280. {
  44281. }
  44282. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44283. int& preferredSize, int& minSize, int& maxSize)
  44284. {
  44285. if (fixedSize <= 0)
  44286. {
  44287. preferredSize = toolbarThickness * 2;
  44288. minSize = 4;
  44289. maxSize = 32768;
  44290. }
  44291. else
  44292. {
  44293. maxSize = roundToInt (toolbarThickness * fixedSize);
  44294. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44295. preferredSize = maxSize;
  44296. if (getEditingMode() == editableOnPalette)
  44297. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44298. }
  44299. return true;
  44300. }
  44301. void paintButtonArea (Graphics&, int, int, bool, bool)
  44302. {
  44303. }
  44304. void contentAreaChanged (const Rectangle<int>&)
  44305. {
  44306. }
  44307. int getResizeOrder() const throw()
  44308. {
  44309. return fixedSize <= 0 ? 0 : 1;
  44310. }
  44311. void paint (Graphics& g)
  44312. {
  44313. const int w = getWidth();
  44314. const int h = getHeight();
  44315. if (drawBar)
  44316. {
  44317. g.setColour (findColour (Toolbar::separatorColourId, true));
  44318. const float thickness = 0.2f;
  44319. if (isToolbarVertical())
  44320. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44321. else
  44322. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44323. }
  44324. if (getEditingMode() != normalMode && ! drawBar)
  44325. {
  44326. g.setColour (findColour (Toolbar::separatorColourId, true));
  44327. const int indentX = jmin (2, (w - 3) / 2);
  44328. const int indentY = jmin (2, (h - 3) / 2);
  44329. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44330. if (fixedSize <= 0)
  44331. {
  44332. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44333. if (isToolbarVertical())
  44334. {
  44335. x1 = w * 0.5f;
  44336. y1 = h * 0.4f;
  44337. x2 = x1;
  44338. y2 = indentX * 2.0f;
  44339. x3 = x1;
  44340. y3 = h * 0.6f;
  44341. x4 = x1;
  44342. y4 = h - y2;
  44343. hw = w * 0.15f;
  44344. hl = w * 0.2f;
  44345. }
  44346. else
  44347. {
  44348. x1 = w * 0.4f;
  44349. y1 = h * 0.5f;
  44350. x2 = indentX * 2.0f;
  44351. y2 = y1;
  44352. x3 = w * 0.6f;
  44353. y3 = y1;
  44354. x4 = w - x2;
  44355. y4 = y1;
  44356. hw = h * 0.15f;
  44357. hl = h * 0.2f;
  44358. }
  44359. Path p;
  44360. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44361. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44362. g.fillPath (p);
  44363. }
  44364. }
  44365. }
  44366. juce_UseDebuggingNewOperator
  44367. private:
  44368. const float fixedSize;
  44369. const bool drawBar;
  44370. ToolbarSpacerComp (const ToolbarSpacerComp&);
  44371. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  44372. };
  44373. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  44374. {
  44375. public:
  44376. MissingItemsComponent (Toolbar& owner_, const int height_)
  44377. : PopupMenuCustomComponent (true),
  44378. owner (owner_),
  44379. height (height_)
  44380. {
  44381. for (int i = owner_.items.size(); --i >= 0;)
  44382. {
  44383. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44384. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44385. {
  44386. oldIndexes.insert (0, i);
  44387. addAndMakeVisible (tc, 0);
  44388. }
  44389. }
  44390. layout (400);
  44391. }
  44392. ~MissingItemsComponent()
  44393. {
  44394. // deleting the toolbar while its menu it open??
  44395. jassert (owner.isValidComponent());
  44396. for (int i = 0; i < getNumChildComponents(); ++i)
  44397. {
  44398. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44399. if (tc != 0)
  44400. {
  44401. tc->setVisible (false);
  44402. const int index = oldIndexes.remove (i);
  44403. owner.addChildComponent (tc, index);
  44404. --i;
  44405. }
  44406. }
  44407. owner.resized();
  44408. }
  44409. void layout (const int preferredWidth)
  44410. {
  44411. const int indent = 8;
  44412. int x = indent;
  44413. int y = indent;
  44414. int maxX = 0;
  44415. for (int i = 0; i < getNumChildComponents(); ++i)
  44416. {
  44417. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44418. if (tc != 0)
  44419. {
  44420. int preferredSize = 1, minSize = 1, maxSize = 1;
  44421. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44422. {
  44423. if (x + preferredSize > preferredWidth && x > indent)
  44424. {
  44425. x = indent;
  44426. y += height;
  44427. }
  44428. tc->setBounds (x, y, preferredSize, height);
  44429. x += preferredSize;
  44430. maxX = jmax (maxX, x);
  44431. }
  44432. }
  44433. }
  44434. setSize (maxX + 8, y + height + 8);
  44435. }
  44436. void getIdealSize (int& idealWidth, int& idealHeight)
  44437. {
  44438. idealWidth = getWidth();
  44439. idealHeight = getHeight();
  44440. }
  44441. juce_UseDebuggingNewOperator
  44442. private:
  44443. Toolbar& owner;
  44444. const int height;
  44445. Array <int> oldIndexes;
  44446. MissingItemsComponent (const MissingItemsComponent&);
  44447. MissingItemsComponent& operator= (const MissingItemsComponent&);
  44448. };
  44449. Toolbar::Toolbar()
  44450. : vertical (false),
  44451. isEditingActive (false),
  44452. toolbarStyle (Toolbar::iconsOnly)
  44453. {
  44454. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44455. missingItemsButton->setAlwaysOnTop (true);
  44456. missingItemsButton->addButtonListener (this);
  44457. }
  44458. Toolbar::~Toolbar()
  44459. {
  44460. animator.cancelAllAnimations (true);
  44461. deleteAllChildren();
  44462. }
  44463. void Toolbar::setVertical (const bool shouldBeVertical)
  44464. {
  44465. if (vertical != shouldBeVertical)
  44466. {
  44467. vertical = shouldBeVertical;
  44468. resized();
  44469. }
  44470. }
  44471. void Toolbar::clear()
  44472. {
  44473. for (int i = items.size(); --i >= 0;)
  44474. {
  44475. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44476. items.remove (i);
  44477. delete tc;
  44478. }
  44479. resized();
  44480. }
  44481. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44482. {
  44483. if (itemId == ToolbarItemFactory::separatorBarId)
  44484. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44485. else if (itemId == ToolbarItemFactory::spacerId)
  44486. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44487. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44488. return new ToolbarSpacerComp (itemId, 0, false);
  44489. return factory.createItem (itemId);
  44490. }
  44491. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44492. const int itemId,
  44493. const int insertIndex)
  44494. {
  44495. // An ID can't be zero - this might indicate a mistake somewhere?
  44496. jassert (itemId != 0);
  44497. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44498. if (tc != 0)
  44499. {
  44500. #if JUCE_DEBUG
  44501. Array <int> allowedIds;
  44502. factory.getAllToolbarItemIds (allowedIds);
  44503. // If your factory can create an item for a given ID, it must also return
  44504. // that ID from its getAllToolbarItemIds() method!
  44505. jassert (allowedIds.contains (itemId));
  44506. #endif
  44507. items.insert (insertIndex, tc);
  44508. addAndMakeVisible (tc, insertIndex);
  44509. }
  44510. }
  44511. void Toolbar::addItem (ToolbarItemFactory& factory,
  44512. const int itemId,
  44513. const int insertIndex)
  44514. {
  44515. addItemInternal (factory, itemId, insertIndex);
  44516. resized();
  44517. }
  44518. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44519. {
  44520. Array <int> ids;
  44521. factoryToUse.getDefaultItemSet (ids);
  44522. clear();
  44523. for (int i = 0; i < ids.size(); ++i)
  44524. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44525. resized();
  44526. }
  44527. void Toolbar::removeToolbarItem (const int itemIndex)
  44528. {
  44529. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44530. if (tc != 0)
  44531. {
  44532. items.removeValue (tc);
  44533. delete tc;
  44534. resized();
  44535. }
  44536. }
  44537. int Toolbar::getNumItems() const throw()
  44538. {
  44539. return items.size();
  44540. }
  44541. int Toolbar::getItemId (const int itemIndex) const throw()
  44542. {
  44543. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44544. return tc != 0 ? tc->getItemId() : 0;
  44545. }
  44546. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44547. {
  44548. return items [itemIndex];
  44549. }
  44550. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44551. {
  44552. for (;;)
  44553. {
  44554. index += delta;
  44555. ToolbarItemComponent* const tc = getItemComponent (index);
  44556. if (tc == 0)
  44557. break;
  44558. if (tc->isActive)
  44559. return tc;
  44560. }
  44561. return 0;
  44562. }
  44563. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44564. {
  44565. if (toolbarStyle != newStyle)
  44566. {
  44567. toolbarStyle = newStyle;
  44568. updateAllItemPositions (false);
  44569. }
  44570. }
  44571. const String Toolbar::toString() const
  44572. {
  44573. String s ("TB:");
  44574. for (int i = 0; i < getNumItems(); ++i)
  44575. s << getItemId(i) << ' ';
  44576. return s.trimEnd();
  44577. }
  44578. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44579. const String& savedVersion)
  44580. {
  44581. if (! savedVersion.startsWith ("TB:"))
  44582. return false;
  44583. StringArray tokens;
  44584. tokens.addTokens (savedVersion.substring (3), false);
  44585. clear();
  44586. for (int i = 0; i < tokens.size(); ++i)
  44587. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44588. resized();
  44589. return true;
  44590. }
  44591. void Toolbar::paint (Graphics& g)
  44592. {
  44593. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44594. }
  44595. int Toolbar::getThickness() const throw()
  44596. {
  44597. return vertical ? getWidth() : getHeight();
  44598. }
  44599. int Toolbar::getLength() const throw()
  44600. {
  44601. return vertical ? getHeight() : getWidth();
  44602. }
  44603. void Toolbar::setEditingActive (const bool active)
  44604. {
  44605. if (isEditingActive != active)
  44606. {
  44607. isEditingActive = active;
  44608. updateAllItemPositions (false);
  44609. }
  44610. }
  44611. void Toolbar::resized()
  44612. {
  44613. updateAllItemPositions (false);
  44614. }
  44615. void Toolbar::updateAllItemPositions (const bool animate)
  44616. {
  44617. if (getWidth() > 0 && getHeight() > 0)
  44618. {
  44619. StretchableObjectResizer resizer;
  44620. int i;
  44621. for (i = 0; i < items.size(); ++i)
  44622. {
  44623. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44624. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44625. : ToolbarItemComponent::normalMode);
  44626. tc->setStyle (toolbarStyle);
  44627. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44628. int preferredSize = 1, minSize = 1, maxSize = 1;
  44629. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44630. preferredSize, minSize, maxSize))
  44631. {
  44632. tc->isActive = true;
  44633. resizer.addItem (preferredSize, minSize, maxSize,
  44634. spacer != 0 ? spacer->getResizeOrder() : 2);
  44635. }
  44636. else
  44637. {
  44638. tc->isActive = false;
  44639. tc->setVisible (false);
  44640. }
  44641. }
  44642. resizer.resizeToFit (getLength());
  44643. int totalLength = 0;
  44644. for (i = 0; i < resizer.getNumItems(); ++i)
  44645. totalLength += (int) resizer.getItemSize (i);
  44646. const bool itemsOffTheEnd = totalLength > getLength();
  44647. const int extrasButtonSize = getThickness() / 2;
  44648. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44649. missingItemsButton->setVisible (itemsOffTheEnd);
  44650. missingItemsButton->setEnabled (! isEditingActive);
  44651. if (vertical)
  44652. missingItemsButton->setCentrePosition (getWidth() / 2,
  44653. getHeight() - 4 - extrasButtonSize / 2);
  44654. else
  44655. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44656. getHeight() / 2);
  44657. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44658. : missingItemsButton->getX()) - 4
  44659. : getLength();
  44660. int pos = 0, activeIndex = 0;
  44661. for (i = 0; i < items.size(); ++i)
  44662. {
  44663. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44664. if (tc->isActive)
  44665. {
  44666. const int size = (int) resizer.getItemSize (activeIndex++);
  44667. Rectangle<int> newBounds;
  44668. if (vertical)
  44669. newBounds.setBounds (0, pos, getWidth(), size);
  44670. else
  44671. newBounds.setBounds (pos, 0, size, getHeight());
  44672. if (animate)
  44673. {
  44674. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  44675. }
  44676. else
  44677. {
  44678. animator.cancelAnimation (tc, false);
  44679. tc->setBounds (newBounds);
  44680. }
  44681. pos += size;
  44682. tc->setVisible (pos <= maxLength
  44683. && ((! tc->isBeingDragged)
  44684. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44685. }
  44686. }
  44687. }
  44688. }
  44689. void Toolbar::buttonClicked (Button*)
  44690. {
  44691. jassert (missingItemsButton->isShowing());
  44692. if (missingItemsButton->isShowing())
  44693. {
  44694. PopupMenu m;
  44695. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44696. m.showAt (missingItemsButton);
  44697. }
  44698. }
  44699. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44700. Component* /*sourceComponent*/)
  44701. {
  44702. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44703. }
  44704. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44705. {
  44706. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44707. if (tc != 0)
  44708. {
  44709. if (getNumItems() == 0)
  44710. {
  44711. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44712. {
  44713. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44714. if (palette != 0)
  44715. palette->replaceComponent (tc);
  44716. }
  44717. else
  44718. {
  44719. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44720. }
  44721. items.add (tc);
  44722. addChildComponent (tc);
  44723. updateAllItemPositions (false);
  44724. }
  44725. else
  44726. {
  44727. for (int i = getNumItems(); --i >= 0;)
  44728. {
  44729. int currentIndex = getIndexOfChildComponent (tc);
  44730. if (currentIndex < 0)
  44731. {
  44732. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44733. {
  44734. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44735. if (palette != 0)
  44736. palette->replaceComponent (tc);
  44737. }
  44738. else
  44739. {
  44740. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44741. }
  44742. items.add (tc);
  44743. addChildComponent (tc);
  44744. currentIndex = getIndexOfChildComponent (tc);
  44745. updateAllItemPositions (true);
  44746. }
  44747. int newIndex = currentIndex;
  44748. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44749. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44750. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  44751. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44752. if (prev != 0)
  44753. {
  44754. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  44755. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44756. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44757. {
  44758. newIndex = getIndexOfChildComponent (prev);
  44759. }
  44760. }
  44761. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44762. if (next != 0)
  44763. {
  44764. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  44765. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44766. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44767. {
  44768. newIndex = getIndexOfChildComponent (next) + 1;
  44769. }
  44770. }
  44771. if (newIndex != currentIndex)
  44772. {
  44773. items.removeValue (tc);
  44774. removeChildComponent (tc);
  44775. addChildComponent (tc, newIndex);
  44776. items.insert (newIndex, tc);
  44777. updateAllItemPositions (true);
  44778. }
  44779. else
  44780. {
  44781. break;
  44782. }
  44783. }
  44784. }
  44785. }
  44786. }
  44787. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44788. {
  44789. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44790. if (tc != 0)
  44791. {
  44792. if (isParentOf (tc))
  44793. {
  44794. items.removeValue (tc);
  44795. removeChildComponent (tc);
  44796. updateAllItemPositions (true);
  44797. }
  44798. }
  44799. }
  44800. void Toolbar::itemDropped (const String&, Component*, int, int)
  44801. {
  44802. }
  44803. void Toolbar::mouseDown (const MouseEvent& e)
  44804. {
  44805. if (e.mods.isPopupMenu())
  44806. {
  44807. }
  44808. }
  44809. class ToolbarCustomisationDialog : public DialogWindow
  44810. {
  44811. public:
  44812. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44813. Toolbar* const toolbar_,
  44814. const int optionFlags)
  44815. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44816. toolbar (toolbar_)
  44817. {
  44818. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44819. setResizable (true, true);
  44820. setResizeLimits (400, 300, 1500, 1000);
  44821. positionNearBar();
  44822. }
  44823. ~ToolbarCustomisationDialog()
  44824. {
  44825. setContentComponent (0, true);
  44826. }
  44827. void closeButtonPressed()
  44828. {
  44829. setVisible (false);
  44830. }
  44831. bool canModalEventBeSentToComponent (const Component* comp)
  44832. {
  44833. return toolbar->isParentOf (comp);
  44834. }
  44835. void positionNearBar()
  44836. {
  44837. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44838. const int tbx = toolbar->getScreenX();
  44839. const int tby = toolbar->getScreenY();
  44840. const int gap = 8;
  44841. int x, y;
  44842. if (toolbar->isVertical())
  44843. {
  44844. y = tby;
  44845. if (tbx > screenSize.getCentreX())
  44846. x = tbx - getWidth() - gap;
  44847. else
  44848. x = tbx + toolbar->getWidth() + gap;
  44849. }
  44850. else
  44851. {
  44852. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44853. if (tby > screenSize.getCentreY())
  44854. y = tby - getHeight() - gap;
  44855. else
  44856. y = tby + toolbar->getHeight() + gap;
  44857. }
  44858. setTopLeftPosition (x, y);
  44859. }
  44860. private:
  44861. Toolbar* const toolbar;
  44862. class CustomiserPanel : public Component,
  44863. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44864. private ButtonListener
  44865. {
  44866. public:
  44867. CustomiserPanel (ToolbarItemFactory& factory_,
  44868. Toolbar* const toolbar_,
  44869. const int optionFlags)
  44870. : factory (factory_),
  44871. toolbar (toolbar_),
  44872. styleBox (0),
  44873. defaultButton (0)
  44874. {
  44875. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  44876. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44877. | Toolbar::allowIconsWithTextChoice
  44878. | Toolbar::allowTextOnlyChoice)) != 0)
  44879. {
  44880. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  44881. styleBox->setEditableText (false);
  44882. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  44883. styleBox->addItem (TRANS("Show icons only"), 1);
  44884. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  44885. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  44886. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  44887. styleBox->addItem (TRANS("Show descriptions only"), 3);
  44888. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  44889. styleBox->setSelectedId (1);
  44890. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  44891. styleBox->setSelectedId (2);
  44892. else if (toolbar_->getStyle() == Toolbar::textOnly)
  44893. styleBox->setSelectedId (3);
  44894. styleBox->addListener (this);
  44895. }
  44896. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44897. {
  44898. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  44899. defaultButton->addButtonListener (this);
  44900. }
  44901. addAndMakeVisible (instructions = new Label (String::empty,
  44902. 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.")));
  44903. instructions->setFont (Font (13.0f));
  44904. setSize (500, 300);
  44905. }
  44906. ~CustomiserPanel()
  44907. {
  44908. deleteAllChildren();
  44909. }
  44910. void comboBoxChanged (ComboBox*)
  44911. {
  44912. if (styleBox->getSelectedId() == 1)
  44913. toolbar->setStyle (Toolbar::iconsOnly);
  44914. else if (styleBox->getSelectedId() == 2)
  44915. toolbar->setStyle (Toolbar::iconsWithText);
  44916. else if (styleBox->getSelectedId() == 3)
  44917. toolbar->setStyle (Toolbar::textOnly);
  44918. palette->resized(); // to make it update the styles
  44919. }
  44920. void buttonClicked (Button*)
  44921. {
  44922. toolbar->addDefaultItems (factory);
  44923. }
  44924. void paint (Graphics& g)
  44925. {
  44926. Colour background;
  44927. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44928. if (dw != 0)
  44929. background = dw->getBackgroundColour();
  44930. g.setColour (background.contrasting().withAlpha (0.3f));
  44931. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  44932. }
  44933. void resized()
  44934. {
  44935. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  44936. if (styleBox != 0)
  44937. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  44938. if (defaultButton != 0)
  44939. {
  44940. defaultButton->changeWidthToFitText (22);
  44941. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  44942. }
  44943. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44944. }
  44945. private:
  44946. ToolbarItemFactory& factory;
  44947. Toolbar* const toolbar;
  44948. Label* instructions;
  44949. ToolbarItemPalette* palette;
  44950. ComboBox* styleBox;
  44951. TextButton* defaultButton;
  44952. };
  44953. };
  44954. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44955. {
  44956. setEditingActive (true);
  44957. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44958. dw.runModalLoop();
  44959. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  44960. setEditingActive (false);
  44961. }
  44962. END_JUCE_NAMESPACE
  44963. /*** End of inlined file: juce_Toolbar.cpp ***/
  44964. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44965. BEGIN_JUCE_NAMESPACE
  44966. ToolbarItemFactory::ToolbarItemFactory()
  44967. {
  44968. }
  44969. ToolbarItemFactory::~ToolbarItemFactory()
  44970. {
  44971. }
  44972. class ItemDragAndDropOverlayComponent : public Component
  44973. {
  44974. public:
  44975. ItemDragAndDropOverlayComponent()
  44976. : isDragging (false)
  44977. {
  44978. setAlwaysOnTop (true);
  44979. setRepaintsOnMouseActivity (true);
  44980. setMouseCursor (MouseCursor::DraggingHandCursor);
  44981. }
  44982. ~ItemDragAndDropOverlayComponent()
  44983. {
  44984. }
  44985. void paint (Graphics& g)
  44986. {
  44987. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44988. if (isMouseOverOrDragging()
  44989. && tc != 0
  44990. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44991. {
  44992. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44993. g.drawRect (0, 0, getWidth(), getHeight(),
  44994. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44995. }
  44996. }
  44997. void mouseDown (const MouseEvent& e)
  44998. {
  44999. isDragging = false;
  45000. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45001. if (tc != 0)
  45002. {
  45003. tc->dragOffsetX = e.x;
  45004. tc->dragOffsetY = e.y;
  45005. }
  45006. }
  45007. void mouseDrag (const MouseEvent& e)
  45008. {
  45009. if (! (isDragging || e.mouseWasClicked()))
  45010. {
  45011. isDragging = true;
  45012. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  45013. if (dnd != 0)
  45014. {
  45015. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  45016. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45017. if (tc != 0)
  45018. {
  45019. tc->isBeingDragged = true;
  45020. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45021. tc->setVisible (false);
  45022. }
  45023. }
  45024. }
  45025. }
  45026. void mouseUp (const MouseEvent&)
  45027. {
  45028. isDragging = false;
  45029. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45030. if (tc != 0)
  45031. {
  45032. tc->isBeingDragged = false;
  45033. Toolbar* const tb = tc->getToolbar();
  45034. if (tb != 0)
  45035. tb->updateAllItemPositions (true);
  45036. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45037. delete tc;
  45038. }
  45039. }
  45040. void parentSizeChanged()
  45041. {
  45042. setBounds (0, 0, getParentWidth(), getParentHeight());
  45043. }
  45044. juce_UseDebuggingNewOperator
  45045. private:
  45046. bool isDragging;
  45047. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  45048. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  45049. };
  45050. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  45051. const String& labelText,
  45052. const bool isBeingUsedAsAButton_)
  45053. : Button (labelText),
  45054. itemId (itemId_),
  45055. mode (normalMode),
  45056. toolbarStyle (Toolbar::iconsOnly),
  45057. dragOffsetX (0),
  45058. dragOffsetY (0),
  45059. isActive (true),
  45060. isBeingDragged (false),
  45061. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  45062. {
  45063. // Your item ID can't be 0!
  45064. jassert (itemId_ != 0);
  45065. }
  45066. ToolbarItemComponent::~ToolbarItemComponent()
  45067. {
  45068. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45069. overlayComp = 0;
  45070. }
  45071. Toolbar* ToolbarItemComponent::getToolbar() const
  45072. {
  45073. return dynamic_cast <Toolbar*> (getParentComponent());
  45074. }
  45075. bool ToolbarItemComponent::isToolbarVertical() const
  45076. {
  45077. const Toolbar* const t = getToolbar();
  45078. return t != 0 && t->isVertical();
  45079. }
  45080. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  45081. {
  45082. if (toolbarStyle != newStyle)
  45083. {
  45084. toolbarStyle = newStyle;
  45085. repaint();
  45086. resized();
  45087. }
  45088. }
  45089. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  45090. {
  45091. if (isBeingUsedAsAButton)
  45092. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  45093. over, down, *this);
  45094. if (toolbarStyle != Toolbar::iconsOnly)
  45095. {
  45096. const int indent = contentArea.getX();
  45097. int y = indent;
  45098. int h = getHeight() - indent * 2;
  45099. if (toolbarStyle == Toolbar::iconsWithText)
  45100. {
  45101. y = contentArea.getBottom() + indent / 2;
  45102. h -= contentArea.getHeight();
  45103. }
  45104. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  45105. getButtonText(), *this);
  45106. }
  45107. if (! contentArea.isEmpty())
  45108. {
  45109. g.saveState();
  45110. g.setOrigin (contentArea.getX(), contentArea.getY());
  45111. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  45112. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  45113. g.restoreState();
  45114. }
  45115. }
  45116. void ToolbarItemComponent::resized()
  45117. {
  45118. if (toolbarStyle != Toolbar::textOnly)
  45119. {
  45120. const int indent = jmin (proportionOfWidth (0.08f),
  45121. proportionOfHeight (0.08f));
  45122. contentArea = Rectangle<int> (indent, indent,
  45123. getWidth() - indent * 2,
  45124. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  45125. : (getHeight() - indent * 2));
  45126. }
  45127. else
  45128. {
  45129. contentArea = Rectangle<int>();
  45130. }
  45131. contentAreaChanged (contentArea);
  45132. }
  45133. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  45134. {
  45135. if (mode != newMode)
  45136. {
  45137. mode = newMode;
  45138. repaint();
  45139. if (mode == normalMode)
  45140. {
  45141. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45142. overlayComp = 0;
  45143. }
  45144. else if (overlayComp == 0)
  45145. {
  45146. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  45147. overlayComp->parentSizeChanged();
  45148. }
  45149. resized();
  45150. }
  45151. }
  45152. END_JUCE_NAMESPACE
  45153. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  45154. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  45155. BEGIN_JUCE_NAMESPACE
  45156. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  45157. Toolbar* const toolbar_)
  45158. : factory (factory_),
  45159. toolbar (toolbar_)
  45160. {
  45161. Component* const itemHolder = new Component();
  45162. Array <int> allIds;
  45163. factory_.getAllToolbarItemIds (allIds);
  45164. for (int i = 0; i < allIds.size(); ++i)
  45165. {
  45166. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  45167. jassert (tc != 0);
  45168. if (tc != 0)
  45169. {
  45170. itemHolder->addAndMakeVisible (tc);
  45171. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  45172. }
  45173. }
  45174. viewport = new Viewport();
  45175. viewport->setViewedComponent (itemHolder);
  45176. addAndMakeVisible (viewport);
  45177. }
  45178. ToolbarItemPalette::~ToolbarItemPalette()
  45179. {
  45180. viewport->getViewedComponent()->deleteAllChildren();
  45181. deleteAllChildren();
  45182. }
  45183. void ToolbarItemPalette::resized()
  45184. {
  45185. viewport->setBoundsInset (BorderSize (1));
  45186. Component* const itemHolder = viewport->getViewedComponent();
  45187. const int indent = 8;
  45188. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  45189. const int height = toolbar->getThickness();
  45190. int x = indent;
  45191. int y = indent;
  45192. int maxX = 0;
  45193. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  45194. {
  45195. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  45196. if (tc != 0)
  45197. {
  45198. tc->setStyle (toolbar->getStyle());
  45199. int preferredSize = 1, minSize = 1, maxSize = 1;
  45200. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  45201. {
  45202. if (x + preferredSize > preferredWidth && x > indent)
  45203. {
  45204. x = indent;
  45205. y += height;
  45206. }
  45207. tc->setBounds (x, y, preferredSize, height);
  45208. x += preferredSize + 8;
  45209. maxX = jmax (maxX, x);
  45210. }
  45211. }
  45212. }
  45213. itemHolder->setSize (maxX, y + height + 8);
  45214. }
  45215. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  45216. {
  45217. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  45218. jassert (tc != 0);
  45219. if (tc != 0)
  45220. {
  45221. tc->setBounds (comp->getBounds());
  45222. tc->setStyle (toolbar->getStyle());
  45223. tc->setEditingMode (comp->getEditingMode());
  45224. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  45225. }
  45226. }
  45227. END_JUCE_NAMESPACE
  45228. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  45229. /*** Start of inlined file: juce_TreeView.cpp ***/
  45230. BEGIN_JUCE_NAMESPACE
  45231. class TreeViewContentComponent : public Component,
  45232. public TooltipClient
  45233. {
  45234. public:
  45235. TreeViewContentComponent (TreeView& owner_)
  45236. : owner (owner_),
  45237. buttonUnderMouse (0),
  45238. isDragging (false)
  45239. {
  45240. }
  45241. ~TreeViewContentComponent()
  45242. {
  45243. deleteAllChildren();
  45244. }
  45245. void mouseDown (const MouseEvent& e)
  45246. {
  45247. updateButtonUnderMouse (e);
  45248. isDragging = false;
  45249. needSelectionOnMouseUp = false;
  45250. Rectangle<int> pos;
  45251. TreeViewItem* const item = findItemAt (e.y, pos);
  45252. if (item == 0)
  45253. return;
  45254. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  45255. // as selection clicks)
  45256. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  45257. {
  45258. if (e.x >= pos.getX() - owner.getIndentSize())
  45259. item->setOpen (! item->isOpen());
  45260. // (clicks to the left of an open/close button are ignored)
  45261. }
  45262. else
  45263. {
  45264. // mouse-down inside the body of the item..
  45265. if (! owner.isMultiSelectEnabled())
  45266. item->setSelected (true, true);
  45267. else if (item->isSelected())
  45268. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  45269. else
  45270. selectBasedOnModifiers (item, e.mods);
  45271. if (e.x >= pos.getX())
  45272. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45273. }
  45274. }
  45275. void mouseUp (const MouseEvent& e)
  45276. {
  45277. updateButtonUnderMouse (e);
  45278. if (needSelectionOnMouseUp && e.mouseWasClicked())
  45279. {
  45280. Rectangle<int> pos;
  45281. TreeViewItem* const item = findItemAt (e.y, pos);
  45282. if (item != 0)
  45283. selectBasedOnModifiers (item, e.mods);
  45284. }
  45285. }
  45286. void mouseDoubleClick (const MouseEvent& e)
  45287. {
  45288. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  45289. {
  45290. Rectangle<int> pos;
  45291. TreeViewItem* const item = findItemAt (e.y, pos);
  45292. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  45293. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45294. }
  45295. }
  45296. void mouseDrag (const MouseEvent& e)
  45297. {
  45298. if (isEnabled()
  45299. && ! (isDragging || e.mouseWasClicked()
  45300. || e.getDistanceFromDragStart() < 5
  45301. || e.mods.isPopupMenu()))
  45302. {
  45303. isDragging = true;
  45304. Rectangle<int> pos;
  45305. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  45306. if (item != 0 && e.getMouseDownX() >= pos.getX())
  45307. {
  45308. const String dragDescription (item->getDragSourceDescription());
  45309. if (dragDescription.isNotEmpty())
  45310. {
  45311. DragAndDropContainer* const dragContainer
  45312. = DragAndDropContainer::findParentDragContainerFor (this);
  45313. if (dragContainer != 0)
  45314. {
  45315. pos.setSize (pos.getWidth(), item->itemHeight);
  45316. Image dragImage (Component::createComponentSnapshot (pos, true));
  45317. dragImage.multiplyAllAlphas (0.6f);
  45318. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45319. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45320. }
  45321. else
  45322. {
  45323. // to be able to do a drag-and-drop operation, the treeview needs to
  45324. // be inside a component which is also a DragAndDropContainer.
  45325. jassertfalse;
  45326. }
  45327. }
  45328. }
  45329. }
  45330. }
  45331. void mouseMove (const MouseEvent& e)
  45332. {
  45333. updateButtonUnderMouse (e);
  45334. }
  45335. void mouseExit (const MouseEvent& e)
  45336. {
  45337. updateButtonUnderMouse (e);
  45338. }
  45339. void paint (Graphics& g)
  45340. {
  45341. if (owner.rootItem != 0)
  45342. {
  45343. owner.handleAsyncUpdate();
  45344. if (! owner.rootItemVisible)
  45345. g.setOrigin (0, -owner.rootItem->itemHeight);
  45346. owner.rootItem->paintRecursively (g, getWidth());
  45347. }
  45348. }
  45349. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45350. {
  45351. if (owner.rootItem != 0)
  45352. {
  45353. owner.handleAsyncUpdate();
  45354. if (! owner.rootItemVisible)
  45355. y += owner.rootItem->itemHeight;
  45356. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45357. if (ti != 0)
  45358. itemPosition = ti->getItemPosition (false);
  45359. return ti;
  45360. }
  45361. return 0;
  45362. }
  45363. void updateComponents()
  45364. {
  45365. const int visibleTop = -getY();
  45366. const int visibleBottom = visibleTop + getParentHeight();
  45367. BigInteger itemsToKeep;
  45368. {
  45369. TreeViewItem* item = owner.rootItem;
  45370. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45371. while (item != 0 && y < visibleBottom)
  45372. {
  45373. y += item->itemHeight;
  45374. if (y >= visibleTop)
  45375. {
  45376. const int index = rowComponentIds.indexOf (item->uid);
  45377. if (index < 0)
  45378. {
  45379. Component* const comp = item->createItemComponent();
  45380. if (comp != 0)
  45381. {
  45382. addAndMakeVisible (comp);
  45383. itemsToKeep.setBit (rowComponentItems.size());
  45384. rowComponentItems.add (item);
  45385. rowComponentIds.add (item->uid);
  45386. rowComponents.add (comp);
  45387. }
  45388. }
  45389. else
  45390. {
  45391. itemsToKeep.setBit (index);
  45392. }
  45393. }
  45394. item = item->getNextVisibleItem (true);
  45395. }
  45396. }
  45397. for (int i = rowComponentItems.size(); --i >= 0;)
  45398. {
  45399. Component* const comp = rowComponents.getUnchecked(i);
  45400. bool keep = false;
  45401. if (isParentOf (comp))
  45402. {
  45403. if (itemsToKeep[i])
  45404. {
  45405. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  45406. Rectangle<int> pos (item->getItemPosition (false));
  45407. pos.setSize (pos.getWidth(), item->itemHeight);
  45408. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45409. {
  45410. keep = true;
  45411. comp->setBounds (pos);
  45412. }
  45413. }
  45414. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  45415. {
  45416. keep = true;
  45417. comp->setSize (0, 0);
  45418. }
  45419. }
  45420. if (! keep)
  45421. {
  45422. delete comp;
  45423. rowComponents.remove (i);
  45424. rowComponentIds.remove (i);
  45425. rowComponentItems.remove (i);
  45426. }
  45427. }
  45428. }
  45429. void updateButtonUnderMouse (const MouseEvent& e)
  45430. {
  45431. TreeViewItem* newItem = 0;
  45432. if (owner.openCloseButtonsVisible)
  45433. {
  45434. Rectangle<int> pos;
  45435. TreeViewItem* item = findItemAt (e.y, pos);
  45436. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45437. {
  45438. newItem = item;
  45439. if (! newItem->mightContainSubItems())
  45440. newItem = 0;
  45441. }
  45442. }
  45443. if (buttonUnderMouse != newItem)
  45444. {
  45445. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45446. {
  45447. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45448. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45449. }
  45450. buttonUnderMouse = newItem;
  45451. if (buttonUnderMouse != 0)
  45452. {
  45453. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45454. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45455. }
  45456. }
  45457. }
  45458. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45459. {
  45460. return item == buttonUnderMouse;
  45461. }
  45462. void resized()
  45463. {
  45464. owner.itemsChanged();
  45465. }
  45466. const String getTooltip()
  45467. {
  45468. Rectangle<int> pos;
  45469. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45470. if (item != 0)
  45471. return item->getTooltip();
  45472. return owner.getTooltip();
  45473. }
  45474. juce_UseDebuggingNewOperator
  45475. private:
  45476. TreeView& owner;
  45477. Array <TreeViewItem*> rowComponentItems;
  45478. Array <int> rowComponentIds;
  45479. Array <Component*> rowComponents;
  45480. TreeViewItem* buttonUnderMouse;
  45481. bool isDragging, needSelectionOnMouseUp;
  45482. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45483. {
  45484. TreeViewItem* firstSelected = 0;
  45485. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45486. {
  45487. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45488. jassert (lastSelected != 0);
  45489. int rowStart = firstSelected->getRowNumberInTree();
  45490. int rowEnd = lastSelected->getRowNumberInTree();
  45491. if (rowStart > rowEnd)
  45492. swapVariables (rowStart, rowEnd);
  45493. int ourRow = item->getRowNumberInTree();
  45494. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45495. if (ourRow > otherEnd)
  45496. swapVariables (ourRow, otherEnd);
  45497. for (int i = ourRow; i <= otherEnd; ++i)
  45498. owner.getItemOnRow (i)->setSelected (true, false);
  45499. }
  45500. else
  45501. {
  45502. const bool cmd = modifiers.isCommandDown();
  45503. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45504. }
  45505. }
  45506. bool containsItem (TreeViewItem* const item) const
  45507. {
  45508. for (int i = rowComponentItems.size(); --i >= 0;)
  45509. if (rowComponentItems.getUnchecked(i) == item)
  45510. return true;
  45511. return false;
  45512. }
  45513. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45514. {
  45515. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45516. {
  45517. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45518. if (source->isDragging())
  45519. {
  45520. Component* const underMouse = source->getComponentUnderMouse();
  45521. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45522. return true;
  45523. }
  45524. }
  45525. return false;
  45526. }
  45527. TreeViewContentComponent (const TreeViewContentComponent&);
  45528. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  45529. };
  45530. class TreeView::TreeViewport : public Viewport
  45531. {
  45532. public:
  45533. TreeViewport() throw() : lastX (-1) {}
  45534. ~TreeViewport() throw() {}
  45535. void updateComponents (const bool triggerResize = false)
  45536. {
  45537. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45538. if (tvc != 0)
  45539. {
  45540. if (triggerResize)
  45541. tvc->resized();
  45542. else
  45543. tvc->updateComponents();
  45544. }
  45545. repaint();
  45546. }
  45547. void visibleAreaChanged (int x, int, int, int)
  45548. {
  45549. const bool hasScrolledSideways = (x != lastX);
  45550. lastX = x;
  45551. updateComponents (hasScrolledSideways);
  45552. }
  45553. juce_UseDebuggingNewOperator
  45554. private:
  45555. int lastX;
  45556. TreeViewport (const TreeViewport&);
  45557. TreeViewport& operator= (const TreeViewport&);
  45558. };
  45559. TreeView::TreeView (const String& componentName)
  45560. : Component (componentName),
  45561. rootItem (0),
  45562. indentSize (24),
  45563. defaultOpenness (false),
  45564. needsRecalculating (true),
  45565. rootItemVisible (true),
  45566. multiSelectEnabled (false),
  45567. openCloseButtonsVisible (true)
  45568. {
  45569. addAndMakeVisible (viewport = new TreeViewport());
  45570. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45571. viewport->setWantsKeyboardFocus (false);
  45572. setWantsKeyboardFocus (true);
  45573. }
  45574. TreeView::~TreeView()
  45575. {
  45576. if (rootItem != 0)
  45577. rootItem->setOwnerView (0);
  45578. }
  45579. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45580. {
  45581. if (rootItem != newRootItem)
  45582. {
  45583. if (newRootItem != 0)
  45584. {
  45585. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45586. if (newRootItem->ownerView != 0)
  45587. newRootItem->ownerView->setRootItem (0);
  45588. }
  45589. if (rootItem != 0)
  45590. rootItem->setOwnerView (0);
  45591. rootItem = newRootItem;
  45592. if (newRootItem != 0)
  45593. newRootItem->setOwnerView (this);
  45594. needsRecalculating = true;
  45595. handleAsyncUpdate();
  45596. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45597. {
  45598. rootItem->setOpen (false); // force a re-open
  45599. rootItem->setOpen (true);
  45600. }
  45601. }
  45602. }
  45603. void TreeView::deleteRootItem()
  45604. {
  45605. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45606. setRootItem (0);
  45607. }
  45608. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45609. {
  45610. rootItemVisible = shouldBeVisible;
  45611. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45612. {
  45613. rootItem->setOpen (false); // force a re-open
  45614. rootItem->setOpen (true);
  45615. }
  45616. itemsChanged();
  45617. }
  45618. void TreeView::colourChanged()
  45619. {
  45620. setOpaque (findColour (backgroundColourId).isOpaque());
  45621. repaint();
  45622. }
  45623. void TreeView::setIndentSize (const int newIndentSize)
  45624. {
  45625. if (indentSize != newIndentSize)
  45626. {
  45627. indentSize = newIndentSize;
  45628. resized();
  45629. }
  45630. }
  45631. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45632. {
  45633. if (defaultOpenness != isOpenByDefault)
  45634. {
  45635. defaultOpenness = isOpenByDefault;
  45636. itemsChanged();
  45637. }
  45638. }
  45639. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45640. {
  45641. multiSelectEnabled = canMultiSelect;
  45642. }
  45643. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45644. {
  45645. if (openCloseButtonsVisible != shouldBeVisible)
  45646. {
  45647. openCloseButtonsVisible = shouldBeVisible;
  45648. itemsChanged();
  45649. }
  45650. }
  45651. Viewport* TreeView::getViewport() const throw()
  45652. {
  45653. return viewport;
  45654. }
  45655. void TreeView::clearSelectedItems()
  45656. {
  45657. if (rootItem != 0)
  45658. rootItem->deselectAllRecursively();
  45659. }
  45660. int TreeView::getNumSelectedItems() const throw()
  45661. {
  45662. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  45663. }
  45664. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45665. {
  45666. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45667. }
  45668. int TreeView::getNumRowsInTree() const
  45669. {
  45670. if (rootItem != 0)
  45671. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45672. return 0;
  45673. }
  45674. TreeViewItem* TreeView::getItemOnRow (int index) const
  45675. {
  45676. if (! rootItemVisible)
  45677. ++index;
  45678. if (rootItem != 0 && index >= 0)
  45679. return rootItem->getItemOnRow (index);
  45680. return 0;
  45681. }
  45682. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45683. {
  45684. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45685. Rectangle<int> pos;
  45686. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  45687. }
  45688. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45689. {
  45690. if (rootItem == 0)
  45691. return 0;
  45692. return rootItem->findItemFromIdentifierString (identifierString);
  45693. }
  45694. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45695. {
  45696. XmlElement* e = 0;
  45697. if (rootItem != 0)
  45698. {
  45699. e = rootItem->getOpennessState();
  45700. if (e != 0 && alsoIncludeScrollPosition)
  45701. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45702. }
  45703. return e;
  45704. }
  45705. void TreeView::restoreOpennessState (const XmlElement& newState)
  45706. {
  45707. if (rootItem != 0)
  45708. {
  45709. rootItem->restoreOpennessState (newState);
  45710. if (newState.hasAttribute ("scrollPos"))
  45711. viewport->setViewPosition (viewport->getViewPositionX(),
  45712. newState.getIntAttribute ("scrollPos"));
  45713. }
  45714. }
  45715. void TreeView::paint (Graphics& g)
  45716. {
  45717. g.fillAll (findColour (backgroundColourId));
  45718. }
  45719. void TreeView::resized()
  45720. {
  45721. viewport->setBounds (getLocalBounds());
  45722. itemsChanged();
  45723. handleAsyncUpdate();
  45724. }
  45725. void TreeView::enablementChanged()
  45726. {
  45727. repaint();
  45728. }
  45729. void TreeView::moveSelectedRow (int delta)
  45730. {
  45731. if (delta == 0)
  45732. return;
  45733. int rowSelected = 0;
  45734. TreeViewItem* const firstSelected = getSelectedItem (0);
  45735. if (firstSelected != 0)
  45736. rowSelected = firstSelected->getRowNumberInTree();
  45737. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45738. for (;;)
  45739. {
  45740. TreeViewItem* item = getItemOnRow (rowSelected);
  45741. if (item != 0)
  45742. {
  45743. if (! item->canBeSelected())
  45744. {
  45745. // if the row we want to highlight doesn't allow it, try skipping
  45746. // to the next item..
  45747. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45748. rowSelected + (delta < 0 ? -1 : 1));
  45749. if (rowSelected != nextRowToTry)
  45750. {
  45751. rowSelected = nextRowToTry;
  45752. continue;
  45753. }
  45754. else
  45755. {
  45756. break;
  45757. }
  45758. }
  45759. item->setSelected (true, true);
  45760. scrollToKeepItemVisible (item);
  45761. }
  45762. break;
  45763. }
  45764. }
  45765. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45766. {
  45767. if (item != 0 && item->ownerView == this)
  45768. {
  45769. handleAsyncUpdate();
  45770. item = item->getDeepestOpenParentItem();
  45771. int y = item->y;
  45772. int viewTop = viewport->getViewPositionY();
  45773. if (y < viewTop)
  45774. {
  45775. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45776. }
  45777. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45778. {
  45779. viewport->setViewPosition (viewport->getViewPositionX(),
  45780. (y + item->itemHeight) - viewport->getViewHeight());
  45781. }
  45782. }
  45783. }
  45784. bool TreeView::keyPressed (const KeyPress& key)
  45785. {
  45786. if (key.isKeyCode (KeyPress::upKey))
  45787. {
  45788. moveSelectedRow (-1);
  45789. }
  45790. else if (key.isKeyCode (KeyPress::downKey))
  45791. {
  45792. moveSelectedRow (1);
  45793. }
  45794. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45795. {
  45796. if (rootItem != 0)
  45797. {
  45798. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45799. if (key.isKeyCode (KeyPress::pageUpKey))
  45800. rowsOnScreen = -rowsOnScreen;
  45801. moveSelectedRow (rowsOnScreen);
  45802. }
  45803. }
  45804. else if (key.isKeyCode (KeyPress::homeKey))
  45805. {
  45806. moveSelectedRow (-0x3fffffff);
  45807. }
  45808. else if (key.isKeyCode (KeyPress::endKey))
  45809. {
  45810. moveSelectedRow (0x3fffffff);
  45811. }
  45812. else if (key.isKeyCode (KeyPress::returnKey))
  45813. {
  45814. TreeViewItem* const firstSelected = getSelectedItem (0);
  45815. if (firstSelected != 0)
  45816. firstSelected->setOpen (! firstSelected->isOpen());
  45817. }
  45818. else if (key.isKeyCode (KeyPress::leftKey))
  45819. {
  45820. TreeViewItem* const firstSelected = getSelectedItem (0);
  45821. if (firstSelected != 0)
  45822. {
  45823. if (firstSelected->isOpen())
  45824. {
  45825. firstSelected->setOpen (false);
  45826. }
  45827. else
  45828. {
  45829. TreeViewItem* parent = firstSelected->parentItem;
  45830. if ((! rootItemVisible) && parent == rootItem)
  45831. parent = 0;
  45832. if (parent != 0)
  45833. {
  45834. parent->setSelected (true, true);
  45835. scrollToKeepItemVisible (parent);
  45836. }
  45837. }
  45838. }
  45839. }
  45840. else if (key.isKeyCode (KeyPress::rightKey))
  45841. {
  45842. TreeViewItem* const firstSelected = getSelectedItem (0);
  45843. if (firstSelected != 0)
  45844. {
  45845. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45846. moveSelectedRow (1);
  45847. else
  45848. firstSelected->setOpen (true);
  45849. }
  45850. }
  45851. else
  45852. {
  45853. return false;
  45854. }
  45855. return true;
  45856. }
  45857. void TreeView::itemsChanged() throw()
  45858. {
  45859. needsRecalculating = true;
  45860. repaint();
  45861. triggerAsyncUpdate();
  45862. }
  45863. void TreeView::handleAsyncUpdate()
  45864. {
  45865. if (needsRecalculating)
  45866. {
  45867. needsRecalculating = false;
  45868. const ScopedLock sl (nodeAlterationLock);
  45869. if (rootItem != 0)
  45870. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45871. viewport->updateComponents();
  45872. if (rootItem != 0)
  45873. {
  45874. viewport->getViewedComponent()
  45875. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45876. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45877. }
  45878. else
  45879. {
  45880. viewport->getViewedComponent()->setSize (0, 0);
  45881. }
  45882. }
  45883. }
  45884. class TreeView::InsertPointHighlight : public Component
  45885. {
  45886. public:
  45887. InsertPointHighlight()
  45888. : lastItem (0)
  45889. {
  45890. setSize (100, 12);
  45891. setAlwaysOnTop (true);
  45892. setInterceptsMouseClicks (false, false);
  45893. }
  45894. ~InsertPointHighlight() {}
  45895. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45896. {
  45897. lastItem = item;
  45898. lastIndex = insertIndex;
  45899. const int offset = getHeight() / 2;
  45900. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45901. }
  45902. void paint (Graphics& g)
  45903. {
  45904. Path p;
  45905. const float h = (float) getHeight();
  45906. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45907. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45908. p.lineTo ((float) getWidth(), h / 2.0f);
  45909. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45910. g.strokePath (p, PathStrokeType (2.0f));
  45911. }
  45912. TreeViewItem* lastItem;
  45913. int lastIndex;
  45914. private:
  45915. InsertPointHighlight (const InsertPointHighlight&);
  45916. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45917. };
  45918. class TreeView::TargetGroupHighlight : public Component
  45919. {
  45920. public:
  45921. TargetGroupHighlight()
  45922. {
  45923. setAlwaysOnTop (true);
  45924. setInterceptsMouseClicks (false, false);
  45925. }
  45926. ~TargetGroupHighlight() {}
  45927. void setTargetPosition (TreeViewItem* const item) throw()
  45928. {
  45929. Rectangle<int> r (item->getItemPosition (true));
  45930. r.setHeight (item->getItemHeight());
  45931. setBounds (r);
  45932. }
  45933. void paint (Graphics& g)
  45934. {
  45935. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45936. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45937. }
  45938. private:
  45939. TargetGroupHighlight (const TargetGroupHighlight&);
  45940. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45941. };
  45942. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45943. {
  45944. beginDragAutoRepeat (100);
  45945. if (dragInsertPointHighlight == 0)
  45946. {
  45947. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45948. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45949. }
  45950. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45951. dragTargetGroupHighlight->setTargetPosition (item);
  45952. }
  45953. void TreeView::hideDragHighlight() throw()
  45954. {
  45955. dragInsertPointHighlight = 0;
  45956. dragTargetGroupHighlight = 0;
  45957. }
  45958. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45959. const StringArray& files, const String& sourceDescription,
  45960. Component* sourceComponent) const throw()
  45961. {
  45962. insertIndex = 0;
  45963. TreeViewItem* item = getItemAt (y);
  45964. if (item == 0)
  45965. return 0;
  45966. Rectangle<int> itemPos (item->getItemPosition (true));
  45967. insertIndex = item->getIndexInParent();
  45968. const int oldY = y;
  45969. y = itemPos.getY();
  45970. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45971. {
  45972. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45973. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45974. {
  45975. // Check if we're trying to drag into an empty group item..
  45976. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45977. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45978. {
  45979. insertIndex = 0;
  45980. x = itemPos.getX() + getIndentSize();
  45981. y = itemPos.getBottom();
  45982. return item;
  45983. }
  45984. }
  45985. }
  45986. if (oldY > itemPos.getCentreY())
  45987. {
  45988. y += item->getItemHeight();
  45989. while (item->isLastOfSiblings() && item->parentItem != 0
  45990. && item->parentItem->parentItem != 0)
  45991. {
  45992. if (x > itemPos.getX())
  45993. break;
  45994. item = item->parentItem;
  45995. itemPos = item->getItemPosition (true);
  45996. insertIndex = item->getIndexInParent();
  45997. }
  45998. ++insertIndex;
  45999. }
  46000. x = itemPos.getX();
  46001. return item->parentItem;
  46002. }
  46003. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  46004. {
  46005. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  46006. int insertIndex;
  46007. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  46008. if (item != 0)
  46009. {
  46010. if (scrolled || dragInsertPointHighlight == 0
  46011. || dragInsertPointHighlight->lastItem != item
  46012. || dragInsertPointHighlight->lastIndex != insertIndex)
  46013. {
  46014. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  46015. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46016. showDragHighlight (item, insertIndex, x, y);
  46017. else
  46018. hideDragHighlight();
  46019. }
  46020. }
  46021. else
  46022. {
  46023. hideDragHighlight();
  46024. }
  46025. }
  46026. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  46027. {
  46028. hideDragHighlight();
  46029. int insertIndex;
  46030. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  46031. if (item != 0)
  46032. {
  46033. if (files.size() > 0)
  46034. {
  46035. if (item->isInterestedInFileDrag (files))
  46036. item->filesDropped (files, insertIndex);
  46037. }
  46038. else
  46039. {
  46040. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46041. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  46042. }
  46043. }
  46044. }
  46045. bool TreeView::isInterestedInFileDrag (const StringArray&)
  46046. {
  46047. return true;
  46048. }
  46049. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  46050. {
  46051. fileDragMove (files, x, y);
  46052. }
  46053. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  46054. {
  46055. handleDrag (files, String::empty, 0, x, y);
  46056. }
  46057. void TreeView::fileDragExit (const StringArray&)
  46058. {
  46059. hideDragHighlight();
  46060. }
  46061. void TreeView::filesDropped (const StringArray& files, int x, int y)
  46062. {
  46063. handleDrop (files, String::empty, 0, x, y);
  46064. }
  46065. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46066. {
  46067. return true;
  46068. }
  46069. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46070. {
  46071. itemDragMove (sourceDescription, sourceComponent, x, y);
  46072. }
  46073. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46074. {
  46075. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  46076. }
  46077. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46078. {
  46079. hideDragHighlight();
  46080. }
  46081. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46082. {
  46083. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  46084. }
  46085. enum TreeViewOpenness
  46086. {
  46087. opennessDefault = 0,
  46088. opennessClosed = 1,
  46089. opennessOpen = 2
  46090. };
  46091. TreeViewItem::TreeViewItem()
  46092. : ownerView (0),
  46093. parentItem (0),
  46094. y (0),
  46095. itemHeight (0),
  46096. totalHeight (0),
  46097. selected (false),
  46098. redrawNeeded (true),
  46099. drawLinesInside (true),
  46100. drawsInLeftMargin (false),
  46101. openness (opennessDefault)
  46102. {
  46103. static int nextUID = 0;
  46104. uid = nextUID++;
  46105. }
  46106. TreeViewItem::~TreeViewItem()
  46107. {
  46108. }
  46109. const String TreeViewItem::getUniqueName() const
  46110. {
  46111. return String::empty;
  46112. }
  46113. void TreeViewItem::itemOpennessChanged (bool)
  46114. {
  46115. }
  46116. int TreeViewItem::getNumSubItems() const throw()
  46117. {
  46118. return subItems.size();
  46119. }
  46120. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  46121. {
  46122. return subItems [index];
  46123. }
  46124. void TreeViewItem::clearSubItems()
  46125. {
  46126. if (subItems.size() > 0)
  46127. {
  46128. if (ownerView != 0)
  46129. {
  46130. const ScopedLock sl (ownerView->nodeAlterationLock);
  46131. subItems.clear();
  46132. treeHasChanged();
  46133. }
  46134. else
  46135. {
  46136. subItems.clear();
  46137. }
  46138. }
  46139. }
  46140. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  46141. {
  46142. if (newItem != 0)
  46143. {
  46144. newItem->parentItem = this;
  46145. newItem->setOwnerView (ownerView);
  46146. newItem->y = 0;
  46147. newItem->itemHeight = newItem->getItemHeight();
  46148. newItem->totalHeight = 0;
  46149. newItem->itemWidth = newItem->getItemWidth();
  46150. newItem->totalWidth = 0;
  46151. if (ownerView != 0)
  46152. {
  46153. const ScopedLock sl (ownerView->nodeAlterationLock);
  46154. subItems.insert (insertPosition, newItem);
  46155. treeHasChanged();
  46156. if (newItem->isOpen())
  46157. newItem->itemOpennessChanged (true);
  46158. }
  46159. else
  46160. {
  46161. subItems.insert (insertPosition, newItem);
  46162. if (newItem->isOpen())
  46163. newItem->itemOpennessChanged (true);
  46164. }
  46165. }
  46166. }
  46167. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  46168. {
  46169. if (ownerView != 0)
  46170. {
  46171. const ScopedLock sl (ownerView->nodeAlterationLock);
  46172. if (((unsigned int) index) < (unsigned int) subItems.size())
  46173. {
  46174. subItems.remove (index, deleteItem);
  46175. treeHasChanged();
  46176. }
  46177. }
  46178. else
  46179. {
  46180. subItems.remove (index, deleteItem);
  46181. }
  46182. }
  46183. bool TreeViewItem::isOpen() const throw()
  46184. {
  46185. if (openness == opennessDefault)
  46186. return ownerView != 0 && ownerView->defaultOpenness;
  46187. else
  46188. return openness == opennessOpen;
  46189. }
  46190. void TreeViewItem::setOpen (const bool shouldBeOpen)
  46191. {
  46192. if (isOpen() != shouldBeOpen)
  46193. {
  46194. openness = shouldBeOpen ? opennessOpen
  46195. : opennessClosed;
  46196. treeHasChanged();
  46197. itemOpennessChanged (isOpen());
  46198. }
  46199. }
  46200. bool TreeViewItem::isSelected() const throw()
  46201. {
  46202. return selected;
  46203. }
  46204. void TreeViewItem::deselectAllRecursively()
  46205. {
  46206. setSelected (false, false);
  46207. for (int i = 0; i < subItems.size(); ++i)
  46208. subItems.getUnchecked(i)->deselectAllRecursively();
  46209. }
  46210. void TreeViewItem::setSelected (const bool shouldBeSelected,
  46211. const bool deselectOtherItemsFirst)
  46212. {
  46213. if (shouldBeSelected && ! canBeSelected())
  46214. return;
  46215. if (deselectOtherItemsFirst)
  46216. getTopLevelItem()->deselectAllRecursively();
  46217. if (shouldBeSelected != selected)
  46218. {
  46219. selected = shouldBeSelected;
  46220. if (ownerView != 0)
  46221. ownerView->repaint();
  46222. itemSelectionChanged (shouldBeSelected);
  46223. }
  46224. }
  46225. void TreeViewItem::paintItem (Graphics&, int, int)
  46226. {
  46227. }
  46228. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  46229. {
  46230. ownerView->getLookAndFeel()
  46231. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  46232. }
  46233. void TreeViewItem::itemClicked (const MouseEvent&)
  46234. {
  46235. }
  46236. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  46237. {
  46238. if (mightContainSubItems())
  46239. setOpen (! isOpen());
  46240. }
  46241. void TreeViewItem::itemSelectionChanged (bool)
  46242. {
  46243. }
  46244. const String TreeViewItem::getTooltip()
  46245. {
  46246. return String::empty;
  46247. }
  46248. const String TreeViewItem::getDragSourceDescription()
  46249. {
  46250. return String::empty;
  46251. }
  46252. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  46253. {
  46254. return false;
  46255. }
  46256. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  46257. {
  46258. }
  46259. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46260. {
  46261. return false;
  46262. }
  46263. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  46264. {
  46265. }
  46266. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  46267. {
  46268. const int indentX = getIndentX();
  46269. int width = itemWidth;
  46270. if (ownerView != 0 && width < 0)
  46271. width = ownerView->viewport->getViewWidth() - indentX;
  46272. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  46273. if (relativeToTreeViewTopLeft)
  46274. r -= ownerView->viewport->getViewPosition();
  46275. return r;
  46276. }
  46277. void TreeViewItem::treeHasChanged() const throw()
  46278. {
  46279. if (ownerView != 0)
  46280. ownerView->itemsChanged();
  46281. }
  46282. void TreeViewItem::repaintItem() const
  46283. {
  46284. if (ownerView != 0 && areAllParentsOpen())
  46285. {
  46286. Rectangle<int> r (getItemPosition (true));
  46287. r.setLeft (0);
  46288. ownerView->viewport->repaint (r);
  46289. }
  46290. }
  46291. bool TreeViewItem::areAllParentsOpen() const throw()
  46292. {
  46293. return parentItem == 0
  46294. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  46295. }
  46296. void TreeViewItem::updatePositions (int newY)
  46297. {
  46298. y = newY;
  46299. itemHeight = getItemHeight();
  46300. totalHeight = itemHeight;
  46301. itemWidth = getItemWidth();
  46302. totalWidth = jmax (itemWidth, 0) + getIndentX();
  46303. if (isOpen())
  46304. {
  46305. newY += totalHeight;
  46306. for (int i = 0; i < subItems.size(); ++i)
  46307. {
  46308. TreeViewItem* const ti = subItems.getUnchecked(i);
  46309. ti->updatePositions (newY);
  46310. newY += ti->totalHeight;
  46311. totalHeight += ti->totalHeight;
  46312. totalWidth = jmax (totalWidth, ti->totalWidth);
  46313. }
  46314. }
  46315. }
  46316. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46317. {
  46318. TreeViewItem* result = this;
  46319. TreeViewItem* item = this;
  46320. while (item->parentItem != 0)
  46321. {
  46322. item = item->parentItem;
  46323. if (! item->isOpen())
  46324. result = item;
  46325. }
  46326. return result;
  46327. }
  46328. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46329. {
  46330. ownerView = newOwner;
  46331. for (int i = subItems.size(); --i >= 0;)
  46332. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46333. }
  46334. int TreeViewItem::getIndentX() const throw()
  46335. {
  46336. const int indentWidth = ownerView->getIndentSize();
  46337. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46338. if (! ownerView->openCloseButtonsVisible)
  46339. x -= indentWidth;
  46340. TreeViewItem* p = parentItem;
  46341. while (p != 0)
  46342. {
  46343. x += indentWidth;
  46344. p = p->parentItem;
  46345. }
  46346. return x;
  46347. }
  46348. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46349. {
  46350. drawsInLeftMargin = canDrawInLeftMargin;
  46351. }
  46352. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46353. {
  46354. jassert (ownerView != 0);
  46355. if (ownerView == 0)
  46356. return;
  46357. const int indent = getIndentX();
  46358. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46359. {
  46360. g.saveState();
  46361. g.setOrigin (indent, 0);
  46362. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46363. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46364. paintItem (g, itemW, itemHeight);
  46365. g.restoreState();
  46366. }
  46367. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46368. const float halfH = itemHeight * 0.5f;
  46369. int depth = 0;
  46370. TreeViewItem* p = parentItem;
  46371. while (p != 0)
  46372. {
  46373. ++depth;
  46374. p = p->parentItem;
  46375. }
  46376. if (! ownerView->rootItemVisible)
  46377. --depth;
  46378. const int indentWidth = ownerView->getIndentSize();
  46379. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46380. {
  46381. float x = (depth + 0.5f) * indentWidth;
  46382. if (depth >= 0)
  46383. {
  46384. if (parentItem != 0 && parentItem->drawLinesInside)
  46385. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46386. if ((parentItem != 0 && parentItem->drawLinesInside)
  46387. || (parentItem == 0 && drawLinesInside))
  46388. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46389. }
  46390. p = parentItem;
  46391. int d = depth;
  46392. while (p != 0 && --d >= 0)
  46393. {
  46394. x -= (float) indentWidth;
  46395. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46396. && ! p->isLastOfSiblings())
  46397. {
  46398. g.drawLine (x, 0, x, (float) itemHeight);
  46399. }
  46400. p = p->parentItem;
  46401. }
  46402. if (mightContainSubItems())
  46403. {
  46404. g.saveState();
  46405. g.setOrigin (depth * indentWidth, 0);
  46406. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46407. paintOpenCloseButton (g, indentWidth, itemHeight,
  46408. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46409. ->isMouseOverButton (this));
  46410. g.restoreState();
  46411. }
  46412. }
  46413. if (isOpen())
  46414. {
  46415. const Rectangle<int> clip (g.getClipBounds());
  46416. for (int i = 0; i < subItems.size(); ++i)
  46417. {
  46418. TreeViewItem* const ti = subItems.getUnchecked(i);
  46419. const int relY = ti->y - y;
  46420. if (relY >= clip.getBottom())
  46421. break;
  46422. if (relY + ti->totalHeight >= clip.getY())
  46423. {
  46424. g.saveState();
  46425. g.setOrigin (0, relY);
  46426. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46427. ti->paintRecursively (g, width);
  46428. g.restoreState();
  46429. }
  46430. }
  46431. }
  46432. }
  46433. bool TreeViewItem::isLastOfSiblings() const throw()
  46434. {
  46435. return parentItem == 0
  46436. || parentItem->subItems.getLast() == this;
  46437. }
  46438. int TreeViewItem::getIndexInParent() const throw()
  46439. {
  46440. if (parentItem == 0)
  46441. return 0;
  46442. return parentItem->subItems.indexOf (this);
  46443. }
  46444. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46445. {
  46446. return (parentItem == 0) ? this
  46447. : parentItem->getTopLevelItem();
  46448. }
  46449. int TreeViewItem::getNumRows() const throw()
  46450. {
  46451. int num = 1;
  46452. if (isOpen())
  46453. {
  46454. for (int i = subItems.size(); --i >= 0;)
  46455. num += subItems.getUnchecked(i)->getNumRows();
  46456. }
  46457. return num;
  46458. }
  46459. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46460. {
  46461. if (index == 0)
  46462. return this;
  46463. if (index > 0 && isOpen())
  46464. {
  46465. --index;
  46466. for (int i = 0; i < subItems.size(); ++i)
  46467. {
  46468. TreeViewItem* const item = subItems.getUnchecked(i);
  46469. if (index == 0)
  46470. return item;
  46471. const int numRows = item->getNumRows();
  46472. if (numRows > index)
  46473. return item->getItemOnRow (index);
  46474. index -= numRows;
  46475. }
  46476. }
  46477. return 0;
  46478. }
  46479. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46480. {
  46481. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  46482. {
  46483. const int h = itemHeight;
  46484. if (targetY < h)
  46485. return this;
  46486. if (isOpen())
  46487. {
  46488. targetY -= h;
  46489. for (int i = 0; i < subItems.size(); ++i)
  46490. {
  46491. TreeViewItem* const ti = subItems.getUnchecked(i);
  46492. if (targetY < ti->totalHeight)
  46493. return ti->findItemRecursively (targetY);
  46494. targetY -= ti->totalHeight;
  46495. }
  46496. }
  46497. }
  46498. return 0;
  46499. }
  46500. int TreeViewItem::countSelectedItemsRecursively() const throw()
  46501. {
  46502. int total = 0;
  46503. if (isSelected())
  46504. ++total;
  46505. for (int i = subItems.size(); --i >= 0;)
  46506. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  46507. return total;
  46508. }
  46509. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46510. {
  46511. if (isSelected())
  46512. {
  46513. if (index == 0)
  46514. return this;
  46515. --index;
  46516. }
  46517. if (index >= 0)
  46518. {
  46519. for (int i = 0; i < subItems.size(); ++i)
  46520. {
  46521. TreeViewItem* const item = subItems.getUnchecked(i);
  46522. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46523. if (found != 0)
  46524. return found;
  46525. index -= item->countSelectedItemsRecursively();
  46526. }
  46527. }
  46528. return 0;
  46529. }
  46530. int TreeViewItem::getRowNumberInTree() const throw()
  46531. {
  46532. if (parentItem != 0 && ownerView != 0)
  46533. {
  46534. int n = 1 + parentItem->getRowNumberInTree();
  46535. int ourIndex = parentItem->subItems.indexOf (this);
  46536. jassert (ourIndex >= 0);
  46537. while (--ourIndex >= 0)
  46538. n += parentItem->subItems [ourIndex]->getNumRows();
  46539. if (parentItem->parentItem == 0
  46540. && ! ownerView->rootItemVisible)
  46541. --n;
  46542. return n;
  46543. }
  46544. else
  46545. {
  46546. return 0;
  46547. }
  46548. }
  46549. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46550. {
  46551. drawLinesInside = drawLines;
  46552. }
  46553. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46554. {
  46555. if (recurse && isOpen() && subItems.size() > 0)
  46556. return subItems [0];
  46557. if (parentItem != 0)
  46558. {
  46559. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46560. if (nextIndex >= parentItem->subItems.size())
  46561. return parentItem->getNextVisibleItem (false);
  46562. return parentItem->subItems [nextIndex];
  46563. }
  46564. return 0;
  46565. }
  46566. const String TreeViewItem::getItemIdentifierString() const
  46567. {
  46568. String s;
  46569. if (parentItem != 0)
  46570. s = parentItem->getItemIdentifierString();
  46571. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46572. }
  46573. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46574. {
  46575. const String thisId (getUniqueName());
  46576. if (thisId == identifierString)
  46577. return this;
  46578. if (identifierString.startsWith (thisId + "/"))
  46579. {
  46580. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46581. bool wasOpen = isOpen();
  46582. setOpen (true);
  46583. for (int i = subItems.size(); --i >= 0;)
  46584. {
  46585. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46586. if (item != 0)
  46587. return item;
  46588. }
  46589. setOpen (wasOpen);
  46590. }
  46591. return 0;
  46592. }
  46593. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46594. {
  46595. if (e.hasTagName ("CLOSED"))
  46596. {
  46597. setOpen (false);
  46598. }
  46599. else if (e.hasTagName ("OPEN"))
  46600. {
  46601. setOpen (true);
  46602. forEachXmlChildElement (e, n)
  46603. {
  46604. const String id (n->getStringAttribute ("id"));
  46605. for (int i = 0; i < subItems.size(); ++i)
  46606. {
  46607. TreeViewItem* const ti = subItems.getUnchecked(i);
  46608. if (ti->getUniqueName() == id)
  46609. {
  46610. ti->restoreOpennessState (*n);
  46611. break;
  46612. }
  46613. }
  46614. }
  46615. }
  46616. }
  46617. XmlElement* TreeViewItem::getOpennessState() const throw()
  46618. {
  46619. const String name (getUniqueName());
  46620. if (name.isNotEmpty())
  46621. {
  46622. XmlElement* e;
  46623. if (isOpen())
  46624. {
  46625. e = new XmlElement ("OPEN");
  46626. for (int i = 0; i < subItems.size(); ++i)
  46627. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46628. }
  46629. else
  46630. {
  46631. e = new XmlElement ("CLOSED");
  46632. }
  46633. e->setAttribute ("id", name);
  46634. return e;
  46635. }
  46636. else
  46637. {
  46638. // trying to save the openness for an element that has no name - this won't
  46639. // work because it needs the names to identify what to open.
  46640. jassertfalse;
  46641. }
  46642. return 0;
  46643. }
  46644. END_JUCE_NAMESPACE
  46645. /*** End of inlined file: juce_TreeView.cpp ***/
  46646. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46647. BEGIN_JUCE_NAMESPACE
  46648. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46649. : fileList (listToShow)
  46650. {
  46651. }
  46652. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46653. {
  46654. }
  46655. FileBrowserListener::~FileBrowserListener()
  46656. {
  46657. }
  46658. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46659. {
  46660. listeners.add (listener);
  46661. }
  46662. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46663. {
  46664. listeners.remove (listener);
  46665. }
  46666. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46667. {
  46668. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46669. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46670. }
  46671. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46672. {
  46673. if (fileList.getDirectory().exists())
  46674. {
  46675. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46676. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46677. }
  46678. }
  46679. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46680. {
  46681. if (fileList.getDirectory().exists())
  46682. {
  46683. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46684. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46685. }
  46686. }
  46687. END_JUCE_NAMESPACE
  46688. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46689. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46690. BEGIN_JUCE_NAMESPACE
  46691. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46692. TimeSliceThread& thread_)
  46693. : fileFilter (fileFilter_),
  46694. thread (thread_),
  46695. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46696. fileFindHandle (0),
  46697. shouldStop (true)
  46698. {
  46699. }
  46700. DirectoryContentsList::~DirectoryContentsList()
  46701. {
  46702. clear();
  46703. }
  46704. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46705. {
  46706. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46707. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46708. }
  46709. bool DirectoryContentsList::ignoresHiddenFiles() const
  46710. {
  46711. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46712. }
  46713. const File& DirectoryContentsList::getDirectory() const
  46714. {
  46715. return root;
  46716. }
  46717. void DirectoryContentsList::setDirectory (const File& directory,
  46718. const bool includeDirectories,
  46719. const bool includeFiles)
  46720. {
  46721. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46722. if (directory != root)
  46723. {
  46724. clear();
  46725. root = directory;
  46726. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46727. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46728. }
  46729. int newFlags = fileTypeFlags;
  46730. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46731. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46732. setTypeFlags (newFlags);
  46733. }
  46734. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46735. {
  46736. if (fileTypeFlags != newFlags)
  46737. {
  46738. fileTypeFlags = newFlags;
  46739. refresh();
  46740. }
  46741. }
  46742. void DirectoryContentsList::clear()
  46743. {
  46744. shouldStop = true;
  46745. thread.removeTimeSliceClient (this);
  46746. fileFindHandle = 0;
  46747. if (files.size() > 0)
  46748. {
  46749. files.clear();
  46750. changed();
  46751. }
  46752. }
  46753. void DirectoryContentsList::refresh()
  46754. {
  46755. clear();
  46756. if (root.isDirectory())
  46757. {
  46758. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46759. shouldStop = false;
  46760. thread.addTimeSliceClient (this);
  46761. }
  46762. }
  46763. int DirectoryContentsList::getNumFiles() const
  46764. {
  46765. return files.size();
  46766. }
  46767. bool DirectoryContentsList::getFileInfo (const int index,
  46768. FileInfo& result) const
  46769. {
  46770. const ScopedLock sl (fileListLock);
  46771. const FileInfo* const info = files [index];
  46772. if (info != 0)
  46773. {
  46774. result = *info;
  46775. return true;
  46776. }
  46777. return false;
  46778. }
  46779. const File DirectoryContentsList::getFile (const int index) const
  46780. {
  46781. const ScopedLock sl (fileListLock);
  46782. const FileInfo* const info = files [index];
  46783. if (info != 0)
  46784. return root.getChildFile (info->filename);
  46785. return File::nonexistent;
  46786. }
  46787. bool DirectoryContentsList::isStillLoading() const
  46788. {
  46789. return fileFindHandle != 0;
  46790. }
  46791. void DirectoryContentsList::changed()
  46792. {
  46793. sendChangeMessage (this);
  46794. }
  46795. bool DirectoryContentsList::useTimeSlice()
  46796. {
  46797. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46798. bool hasChanged = false;
  46799. for (int i = 100; --i >= 0;)
  46800. {
  46801. if (! checkNextFile (hasChanged))
  46802. {
  46803. if (hasChanged)
  46804. changed();
  46805. return false;
  46806. }
  46807. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46808. break;
  46809. }
  46810. if (hasChanged)
  46811. changed();
  46812. return true;
  46813. }
  46814. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46815. {
  46816. if (fileFindHandle != 0)
  46817. {
  46818. bool fileFoundIsDir, isHidden, isReadOnly;
  46819. int64 fileSize;
  46820. Time modTime, creationTime;
  46821. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46822. &modTime, &creationTime, &isReadOnly))
  46823. {
  46824. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46825. fileSize, modTime, creationTime, isReadOnly))
  46826. {
  46827. hasChanged = true;
  46828. }
  46829. return true;
  46830. }
  46831. else
  46832. {
  46833. fileFindHandle = 0;
  46834. }
  46835. }
  46836. return false;
  46837. }
  46838. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46839. const DirectoryContentsList::FileInfo* const second)
  46840. {
  46841. #if JUCE_WINDOWS
  46842. if (first->isDirectory != second->isDirectory)
  46843. return first->isDirectory ? -1 : 1;
  46844. #endif
  46845. return first->filename.compareIgnoreCase (second->filename);
  46846. }
  46847. bool DirectoryContentsList::addFile (const File& file,
  46848. const bool isDir,
  46849. const int64 fileSize,
  46850. const Time& modTime,
  46851. const Time& creationTime,
  46852. const bool isReadOnly)
  46853. {
  46854. if (fileFilter == 0
  46855. || ((! isDir) && fileFilter->isFileSuitable (file))
  46856. || (isDir && fileFilter->isDirectorySuitable (file)))
  46857. {
  46858. ScopedPointer <FileInfo> info (new FileInfo());
  46859. info->filename = file.getFileName();
  46860. info->fileSize = fileSize;
  46861. info->modificationTime = modTime;
  46862. info->creationTime = creationTime;
  46863. info->isDirectory = isDir;
  46864. info->isReadOnly = isReadOnly;
  46865. const ScopedLock sl (fileListLock);
  46866. for (int i = files.size(); --i >= 0;)
  46867. if (files.getUnchecked(i)->filename == info->filename)
  46868. return false;
  46869. files.addSorted (*this, info.release());
  46870. return true;
  46871. }
  46872. return false;
  46873. }
  46874. END_JUCE_NAMESPACE
  46875. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46876. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46877. BEGIN_JUCE_NAMESPACE
  46878. FileBrowserComponent::FileBrowserComponent (int flags_,
  46879. const File& initialFileOrDirectory,
  46880. const FileFilter* fileFilter_,
  46881. FilePreviewComponent* previewComp_)
  46882. : FileFilter (String::empty),
  46883. fileFilter (fileFilter_),
  46884. flags (flags_),
  46885. previewComp (previewComp_),
  46886. thread ("Juce FileBrowser")
  46887. {
  46888. // You need to specify one or other of the open/save flags..
  46889. jassert ((flags & (saveMode | openMode)) != 0);
  46890. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46891. // You need to specify at least one of these flags..
  46892. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46893. String filename;
  46894. if (initialFileOrDirectory == File::nonexistent)
  46895. {
  46896. currentRoot = File::getCurrentWorkingDirectory();
  46897. }
  46898. else if (initialFileOrDirectory.isDirectory())
  46899. {
  46900. currentRoot = initialFileOrDirectory;
  46901. }
  46902. else
  46903. {
  46904. chosenFiles.add (initialFileOrDirectory);
  46905. currentRoot = initialFileOrDirectory.getParentDirectory();
  46906. filename = initialFileOrDirectory.getFileName();
  46907. }
  46908. fileList = new DirectoryContentsList (this, thread);
  46909. if ((flags & useTreeView) != 0)
  46910. {
  46911. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46912. if ((flags & canSelectMultipleItems) != 0)
  46913. tree->setMultiSelectEnabled (true);
  46914. addAndMakeVisible (tree);
  46915. fileListComponent = tree;
  46916. }
  46917. else
  46918. {
  46919. FileListComponent* const list = new FileListComponent (*fileList);
  46920. list->setOutlineThickness (1);
  46921. if ((flags & canSelectMultipleItems) != 0)
  46922. list->setMultipleSelectionEnabled (true);
  46923. addAndMakeVisible (list);
  46924. fileListComponent = list;
  46925. }
  46926. fileListComponent->addListener (this);
  46927. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  46928. currentPathBox->setEditableText (true);
  46929. StringArray rootNames, rootPaths;
  46930. const BigInteger separators (getRoots (rootNames, rootPaths));
  46931. for (int i = 0; i < rootNames.size(); ++i)
  46932. {
  46933. if (separators [i])
  46934. currentPathBox->addSeparator();
  46935. currentPathBox->addItem (rootNames[i], i + 1);
  46936. }
  46937. currentPathBox->addSeparator();
  46938. currentPathBox->addListener (this);
  46939. addAndMakeVisible (filenameBox = new TextEditor());
  46940. filenameBox->setMultiLine (false);
  46941. filenameBox->setSelectAllWhenFocused (true);
  46942. filenameBox->setText (filename, false);
  46943. filenameBox->addListener (this);
  46944. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46945. Label* label = new Label ("f", TRANS("file:"));
  46946. addAndMakeVisible (label);
  46947. label->attachToComponent (filenameBox, true);
  46948. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46949. goUpButton->addButtonListener (this);
  46950. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46951. if (previewComp != 0)
  46952. addAndMakeVisible (previewComp);
  46953. setRoot (currentRoot);
  46954. thread.startThread (4);
  46955. }
  46956. FileBrowserComponent::~FileBrowserComponent()
  46957. {
  46958. if (previewComp != 0)
  46959. removeChildComponent (previewComp);
  46960. deleteAllChildren();
  46961. fileList = 0;
  46962. thread.stopThread (10000);
  46963. }
  46964. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46965. {
  46966. listeners.add (newListener);
  46967. }
  46968. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46969. {
  46970. listeners.remove (listener);
  46971. }
  46972. bool FileBrowserComponent::isSaveMode() const throw()
  46973. {
  46974. return (flags & saveMode) != 0;
  46975. }
  46976. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46977. {
  46978. if (chosenFiles.size() == 0 && currentFileIsValid())
  46979. return 1;
  46980. return chosenFiles.size();
  46981. }
  46982. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46983. {
  46984. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  46985. return currentRoot;
  46986. if (! filenameBox->isReadOnly())
  46987. return currentRoot.getChildFile (filenameBox->getText());
  46988. return chosenFiles[index];
  46989. }
  46990. bool FileBrowserComponent::currentFileIsValid() const
  46991. {
  46992. if (isSaveMode())
  46993. return ! getSelectedFile (0).isDirectory();
  46994. else
  46995. return getSelectedFile (0).exists();
  46996. }
  46997. const File FileBrowserComponent::getHighlightedFile() const throw()
  46998. {
  46999. return fileListComponent->getSelectedFile (0);
  47000. }
  47001. void FileBrowserComponent::deselectAllFiles()
  47002. {
  47003. fileListComponent->deselectAllFiles();
  47004. }
  47005. bool FileBrowserComponent::isFileSuitable (const File& file) const
  47006. {
  47007. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  47008. : false;
  47009. }
  47010. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  47011. {
  47012. return true;
  47013. }
  47014. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  47015. {
  47016. if (f.isDirectory())
  47017. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  47018. return (flags & canSelectFiles) != 0 && f.exists()
  47019. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  47020. }
  47021. const File FileBrowserComponent::getRoot() const
  47022. {
  47023. return currentRoot;
  47024. }
  47025. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  47026. {
  47027. if (currentRoot != newRootDirectory)
  47028. {
  47029. fileListComponent->scrollToTop();
  47030. String path (newRootDirectory.getFullPathName());
  47031. if (path.isEmpty())
  47032. path = File::separatorString;
  47033. StringArray rootNames, rootPaths;
  47034. getRoots (rootNames, rootPaths);
  47035. if (! rootPaths.contains (path, true))
  47036. {
  47037. bool alreadyListed = false;
  47038. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  47039. {
  47040. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  47041. {
  47042. alreadyListed = true;
  47043. break;
  47044. }
  47045. }
  47046. if (! alreadyListed)
  47047. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  47048. }
  47049. }
  47050. currentRoot = newRootDirectory;
  47051. fileList->setDirectory (currentRoot, true, true);
  47052. String currentRootName (currentRoot.getFullPathName());
  47053. if (currentRootName.isEmpty())
  47054. currentRootName = File::separatorString;
  47055. currentPathBox->setText (currentRootName, true);
  47056. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  47057. && currentRoot.getParentDirectory() != currentRoot);
  47058. }
  47059. void FileBrowserComponent::goUp()
  47060. {
  47061. setRoot (getRoot().getParentDirectory());
  47062. }
  47063. void FileBrowserComponent::refresh()
  47064. {
  47065. fileList->refresh();
  47066. }
  47067. const String FileBrowserComponent::getActionVerb() const
  47068. {
  47069. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  47070. }
  47071. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  47072. {
  47073. return previewComp;
  47074. }
  47075. void FileBrowserComponent::resized()
  47076. {
  47077. getLookAndFeel()
  47078. .layoutFileBrowserComponent (*this, fileListComponent,
  47079. previewComp, currentPathBox,
  47080. filenameBox, goUpButton);
  47081. }
  47082. void FileBrowserComponent::sendListenerChangeMessage()
  47083. {
  47084. Component::BailOutChecker checker (this);
  47085. if (previewComp != 0)
  47086. previewComp->selectedFileChanged (getSelectedFile (0));
  47087. // You shouldn't delete the browser when the file gets changed!
  47088. jassert (! checker.shouldBailOut());
  47089. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  47090. }
  47091. void FileBrowserComponent::selectionChanged()
  47092. {
  47093. StringArray newFilenames;
  47094. bool resetChosenFiles = true;
  47095. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  47096. {
  47097. const File f (fileListComponent->getSelectedFile (i));
  47098. if (isFileOrDirSuitable (f))
  47099. {
  47100. if (resetChosenFiles)
  47101. {
  47102. chosenFiles.clear();
  47103. resetChosenFiles = false;
  47104. }
  47105. chosenFiles.add (f);
  47106. newFilenames.add (f.getRelativePathFrom (getRoot()));
  47107. }
  47108. }
  47109. if (newFilenames.size() > 0)
  47110. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  47111. sendListenerChangeMessage();
  47112. }
  47113. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  47114. {
  47115. Component::BailOutChecker checker (this);
  47116. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  47117. }
  47118. void FileBrowserComponent::fileDoubleClicked (const File& f)
  47119. {
  47120. if (f.isDirectory())
  47121. {
  47122. setRoot (f);
  47123. if ((flags & canSelectDirectories) != 0)
  47124. filenameBox->setText (String::empty);
  47125. }
  47126. else
  47127. {
  47128. Component::BailOutChecker checker (this);
  47129. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  47130. }
  47131. }
  47132. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  47133. {
  47134. (void) key;
  47135. #if JUCE_LINUX || JUCE_WINDOWS
  47136. if (key.getModifiers().isCommandDown()
  47137. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  47138. {
  47139. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  47140. fileList->refresh();
  47141. return true;
  47142. }
  47143. #endif
  47144. return false;
  47145. }
  47146. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  47147. {
  47148. sendListenerChangeMessage();
  47149. }
  47150. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  47151. {
  47152. if (filenameBox->getText().containsChar (File::separator))
  47153. {
  47154. const File f (currentRoot.getChildFile (filenameBox->getText()));
  47155. if (f.isDirectory())
  47156. {
  47157. setRoot (f);
  47158. chosenFiles.clear();
  47159. filenameBox->setText (String::empty);
  47160. }
  47161. else
  47162. {
  47163. setRoot (f.getParentDirectory());
  47164. chosenFiles.clear();
  47165. chosenFiles.add (f);
  47166. filenameBox->setText (f.getFileName());
  47167. }
  47168. }
  47169. else
  47170. {
  47171. fileDoubleClicked (getSelectedFile (0));
  47172. }
  47173. }
  47174. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  47175. {
  47176. }
  47177. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  47178. {
  47179. if (! isSaveMode())
  47180. selectionChanged();
  47181. }
  47182. void FileBrowserComponent::buttonClicked (Button*)
  47183. {
  47184. goUp();
  47185. }
  47186. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  47187. {
  47188. const String newText (currentPathBox->getText().trim().unquoted());
  47189. if (newText.isNotEmpty())
  47190. {
  47191. const int index = currentPathBox->getSelectedId() - 1;
  47192. StringArray rootNames, rootPaths;
  47193. getRoots (rootNames, rootPaths);
  47194. if (rootPaths [index].isNotEmpty())
  47195. {
  47196. setRoot (File (rootPaths [index]));
  47197. }
  47198. else
  47199. {
  47200. File f (newText);
  47201. for (;;)
  47202. {
  47203. if (f.isDirectory())
  47204. {
  47205. setRoot (f);
  47206. break;
  47207. }
  47208. if (f.getParentDirectory() == f)
  47209. break;
  47210. f = f.getParentDirectory();
  47211. }
  47212. }
  47213. }
  47214. }
  47215. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  47216. {
  47217. BigInteger separators;
  47218. #if JUCE_WINDOWS
  47219. Array<File> roots;
  47220. File::findFileSystemRoots (roots);
  47221. rootPaths.clear();
  47222. for (int i = 0; i < roots.size(); ++i)
  47223. {
  47224. const File& drive = roots.getReference(i);
  47225. String name (drive.getFullPathName());
  47226. rootPaths.add (name);
  47227. if (drive.isOnHardDisk())
  47228. {
  47229. String volume (drive.getVolumeLabel());
  47230. if (volume.isEmpty())
  47231. volume = TRANS("Hard Drive");
  47232. name << " [" << drive.getVolumeLabel() << ']';
  47233. }
  47234. else if (drive.isOnCDRomDrive())
  47235. {
  47236. name << TRANS(" [CD/DVD drive]");
  47237. }
  47238. rootNames.add (name);
  47239. }
  47240. separators.setBit (rootPaths.size());
  47241. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47242. rootNames.add ("Documents");
  47243. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47244. rootNames.add ("Desktop");
  47245. #endif
  47246. #if JUCE_MAC
  47247. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47248. rootNames.add ("Home folder");
  47249. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47250. rootNames.add ("Documents");
  47251. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47252. rootNames.add ("Desktop");
  47253. separators.setBit (rootPaths.size());
  47254. Array <File> volumes;
  47255. File vol ("/Volumes");
  47256. vol.findChildFiles (volumes, File::findDirectories, false);
  47257. for (int i = 0; i < volumes.size(); ++i)
  47258. {
  47259. const File& volume = volumes.getReference(i);
  47260. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  47261. {
  47262. rootPaths.add (volume.getFullPathName());
  47263. rootNames.add (volume.getFileName());
  47264. }
  47265. }
  47266. #endif
  47267. #if JUCE_LINUX
  47268. rootPaths.add ("/");
  47269. rootNames.add ("/");
  47270. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47271. rootNames.add ("Home folder");
  47272. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47273. rootNames.add ("Desktop");
  47274. #endif
  47275. return separators;
  47276. }
  47277. END_JUCE_NAMESPACE
  47278. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  47279. /*** Start of inlined file: juce_FileChooser.cpp ***/
  47280. BEGIN_JUCE_NAMESPACE
  47281. FileChooser::FileChooser (const String& chooserBoxTitle,
  47282. const File& currentFileOrDirectory,
  47283. const String& fileFilters,
  47284. const bool useNativeDialogBox_)
  47285. : title (chooserBoxTitle),
  47286. filters (fileFilters),
  47287. startingFile (currentFileOrDirectory),
  47288. useNativeDialogBox (useNativeDialogBox_)
  47289. {
  47290. #if JUCE_LINUX
  47291. useNativeDialogBox = false;
  47292. #endif
  47293. if (! fileFilters.containsNonWhitespaceChars())
  47294. filters = "*";
  47295. }
  47296. FileChooser::~FileChooser()
  47297. {
  47298. }
  47299. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47300. {
  47301. return showDialog (false, true, false, false, false, previewComponent);
  47302. }
  47303. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47304. {
  47305. return showDialog (false, true, false, false, true, previewComponent);
  47306. }
  47307. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47308. {
  47309. return showDialog (true, true, false, false, true, previewComponent);
  47310. }
  47311. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47312. {
  47313. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47314. }
  47315. bool FileChooser::browseForDirectory()
  47316. {
  47317. return showDialog (true, false, false, false, false, 0);
  47318. }
  47319. const File FileChooser::getResult() const
  47320. {
  47321. // if you've used a multiple-file select, you should use the getResults() method
  47322. // to retrieve all the files that were chosen.
  47323. jassert (results.size() <= 1);
  47324. return results.getFirst();
  47325. }
  47326. const Array<File>& FileChooser::getResults() const
  47327. {
  47328. return results;
  47329. }
  47330. bool FileChooser::showDialog (const bool selectsDirectories,
  47331. const bool selectsFiles,
  47332. const bool isSave,
  47333. const bool warnAboutOverwritingExistingFiles,
  47334. const bool selectMultipleFiles,
  47335. FilePreviewComponent* const previewComponent)
  47336. {
  47337. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47338. results.clear();
  47339. // the preview component needs to be the right size before you pass it in here..
  47340. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47341. && previewComponent->getHeight() > 10));
  47342. #if JUCE_WINDOWS
  47343. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47344. #elif JUCE_MAC
  47345. if (useNativeDialogBox && (previewComponent == 0))
  47346. #else
  47347. if (false)
  47348. #endif
  47349. {
  47350. showPlatformDialog (results, title, startingFile, filters,
  47351. selectsDirectories, selectsFiles, isSave,
  47352. warnAboutOverwritingExistingFiles,
  47353. selectMultipleFiles,
  47354. previewComponent);
  47355. }
  47356. else
  47357. {
  47358. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47359. selectsDirectories ? "*" : String::empty,
  47360. String::empty);
  47361. int flags = isSave ? FileBrowserComponent::saveMode
  47362. : FileBrowserComponent::openMode;
  47363. if (selectsFiles)
  47364. flags |= FileBrowserComponent::canSelectFiles;
  47365. if (selectsDirectories)
  47366. {
  47367. flags |= FileBrowserComponent::canSelectDirectories;
  47368. if (! isSave)
  47369. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47370. }
  47371. if (selectMultipleFiles)
  47372. flags |= FileBrowserComponent::canSelectMultipleItems;
  47373. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47374. FileChooserDialogBox box (title, String::empty,
  47375. browserComponent,
  47376. warnAboutOverwritingExistingFiles,
  47377. browserComponent.findColour (AlertWindow::backgroundColourId));
  47378. if (box.show())
  47379. {
  47380. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47381. results.add (browserComponent.getSelectedFile (i));
  47382. }
  47383. }
  47384. if (previouslyFocused != 0)
  47385. previouslyFocused->grabKeyboardFocus();
  47386. return results.size() > 0;
  47387. }
  47388. FilePreviewComponent::FilePreviewComponent()
  47389. {
  47390. }
  47391. FilePreviewComponent::~FilePreviewComponent()
  47392. {
  47393. }
  47394. END_JUCE_NAMESPACE
  47395. /*** End of inlined file: juce_FileChooser.cpp ***/
  47396. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47397. BEGIN_JUCE_NAMESPACE
  47398. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47399. const String& instructions,
  47400. FileBrowserComponent& chooserComponent,
  47401. const bool warnAboutOverwritingExistingFiles_,
  47402. const Colour& backgroundColour)
  47403. : ResizableWindow (name, backgroundColour, true),
  47404. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47405. {
  47406. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47407. setResizable (true, true);
  47408. setResizeLimits (300, 300, 1200, 1000);
  47409. content->okButton.addButtonListener (this);
  47410. content->cancelButton.addButtonListener (this);
  47411. content->chooserComponent.addListener (this);
  47412. }
  47413. FileChooserDialogBox::~FileChooserDialogBox()
  47414. {
  47415. content->chooserComponent.removeListener (this);
  47416. }
  47417. bool FileChooserDialogBox::show (int w, int h)
  47418. {
  47419. return showAt (-1, -1, w, h);
  47420. }
  47421. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47422. {
  47423. if (w <= 0)
  47424. {
  47425. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47426. if (previewComp != 0)
  47427. w = 400 + previewComp->getWidth();
  47428. else
  47429. w = 600;
  47430. }
  47431. if (h <= 0)
  47432. h = 500;
  47433. if (x < 0 || y < 0)
  47434. centreWithSize (w, h);
  47435. else
  47436. setBounds (x, y, w, h);
  47437. const bool ok = (runModalLoop() != 0);
  47438. setVisible (false);
  47439. return ok;
  47440. }
  47441. void FileChooserDialogBox::buttonClicked (Button* button)
  47442. {
  47443. if (button == &(content->okButton))
  47444. {
  47445. if (warnAboutOverwritingExistingFiles
  47446. && content->chooserComponent.isSaveMode()
  47447. && content->chooserComponent.getSelectedFile(0).exists())
  47448. {
  47449. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47450. TRANS("File already exists"),
  47451. TRANS("There's already a file called:")
  47452. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47453. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47454. TRANS("overwrite"),
  47455. TRANS("cancel")))
  47456. {
  47457. return;
  47458. }
  47459. }
  47460. exitModalState (1);
  47461. }
  47462. else if (button == &(content->cancelButton))
  47463. {
  47464. closeButtonPressed();
  47465. }
  47466. }
  47467. void FileChooserDialogBox::closeButtonPressed()
  47468. {
  47469. setVisible (false);
  47470. }
  47471. void FileChooserDialogBox::selectionChanged()
  47472. {
  47473. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47474. }
  47475. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47476. {
  47477. }
  47478. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47479. {
  47480. selectionChanged();
  47481. content->okButton.triggerClick();
  47482. }
  47483. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47484. : Component (name), instructions (instructions_),
  47485. chooserComponent (chooserComponent_),
  47486. okButton (chooserComponent_.getActionVerb()),
  47487. cancelButton (TRANS ("Cancel"))
  47488. {
  47489. addAndMakeVisible (&chooserComponent);
  47490. addAndMakeVisible (&okButton);
  47491. okButton.setEnabled (chooserComponent.currentFileIsValid());
  47492. okButton.addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  47493. addAndMakeVisible (&cancelButton);
  47494. cancelButton.addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  47495. setInterceptsMouseClicks (false, true);
  47496. }
  47497. FileChooserDialogBox::ContentComponent::~ContentComponent()
  47498. {
  47499. }
  47500. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47501. {
  47502. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47503. text.draw (g);
  47504. }
  47505. void FileChooserDialogBox::ContentComponent::resized()
  47506. {
  47507. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47508. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47509. const int y = roundToInt (bb.getBottom()) + 10;
  47510. const int buttonHeight = 26;
  47511. const int buttonY = getHeight() - buttonHeight - 8;
  47512. chooserComponent.setBounds (0, y, getWidth(), buttonY - y - 20);
  47513. okButton.setBounds (proportionOfWidth (0.25f), buttonY,
  47514. proportionOfWidth (0.2f), buttonHeight);
  47515. cancelButton.setBounds (proportionOfWidth (0.55f), buttonY,
  47516. proportionOfWidth (0.2f), buttonHeight);
  47517. }
  47518. END_JUCE_NAMESPACE
  47519. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47520. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47521. BEGIN_JUCE_NAMESPACE
  47522. FileFilter::FileFilter (const String& filterDescription)
  47523. : description (filterDescription)
  47524. {
  47525. }
  47526. FileFilter::~FileFilter()
  47527. {
  47528. }
  47529. const String& FileFilter::getDescription() const throw()
  47530. {
  47531. return description;
  47532. }
  47533. END_JUCE_NAMESPACE
  47534. /*** End of inlined file: juce_FileFilter.cpp ***/
  47535. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47536. BEGIN_JUCE_NAMESPACE
  47537. const Image juce_createIconForFile (const File& file);
  47538. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47539. : ListBox (String::empty, 0),
  47540. DirectoryContentsDisplayComponent (listToShow)
  47541. {
  47542. setModel (this);
  47543. fileList.addChangeListener (this);
  47544. }
  47545. FileListComponent::~FileListComponent()
  47546. {
  47547. fileList.removeChangeListener (this);
  47548. }
  47549. int FileListComponent::getNumSelectedFiles() const
  47550. {
  47551. return getNumSelectedRows();
  47552. }
  47553. const File FileListComponent::getSelectedFile (int index) const
  47554. {
  47555. return fileList.getFile (getSelectedRow (index));
  47556. }
  47557. void FileListComponent::deselectAllFiles()
  47558. {
  47559. deselectAllRows();
  47560. }
  47561. void FileListComponent::scrollToTop()
  47562. {
  47563. getVerticalScrollBar()->setCurrentRangeStart (0);
  47564. }
  47565. void FileListComponent::changeListenerCallback (void*)
  47566. {
  47567. updateContent();
  47568. if (lastDirectory != fileList.getDirectory())
  47569. {
  47570. lastDirectory = fileList.getDirectory();
  47571. deselectAllRows();
  47572. }
  47573. }
  47574. class FileListItemComponent : public Component,
  47575. public TimeSliceClient,
  47576. public AsyncUpdater
  47577. {
  47578. public:
  47579. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47580. : owner (owner_), thread (thread_),
  47581. highlighted (false), index (0), icon (0)
  47582. {
  47583. }
  47584. ~FileListItemComponent()
  47585. {
  47586. thread.removeTimeSliceClient (this);
  47587. clearIcon();
  47588. }
  47589. void paint (Graphics& g)
  47590. {
  47591. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47592. file.getFileName(),
  47593. &icon,
  47594. fileSize, modTime,
  47595. isDirectory, highlighted,
  47596. index, owner);
  47597. }
  47598. void mouseDown (const MouseEvent& e)
  47599. {
  47600. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  47601. owner.sendMouseClickMessage (file, e);
  47602. }
  47603. void mouseDoubleClick (const MouseEvent&)
  47604. {
  47605. owner.sendDoubleClickMessage (file);
  47606. }
  47607. void update (const File& root,
  47608. const DirectoryContentsList::FileInfo* const fileInfo,
  47609. const int index_,
  47610. const bool highlighted_)
  47611. {
  47612. thread.removeTimeSliceClient (this);
  47613. if (highlighted_ != highlighted
  47614. || index_ != index)
  47615. {
  47616. index = index_;
  47617. highlighted = highlighted_;
  47618. repaint();
  47619. }
  47620. File newFile;
  47621. String newFileSize;
  47622. String newModTime;
  47623. if (fileInfo != 0)
  47624. {
  47625. newFile = root.getChildFile (fileInfo->filename);
  47626. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47627. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47628. }
  47629. if (newFile != file
  47630. || fileSize != newFileSize
  47631. || modTime != newModTime)
  47632. {
  47633. file = newFile;
  47634. fileSize = newFileSize;
  47635. modTime = newModTime;
  47636. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47637. repaint();
  47638. clearIcon();
  47639. }
  47640. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47641. {
  47642. updateIcon (true);
  47643. if (! icon.isValid())
  47644. thread.addTimeSliceClient (this);
  47645. }
  47646. }
  47647. bool useTimeSlice()
  47648. {
  47649. updateIcon (false);
  47650. return false;
  47651. }
  47652. void handleAsyncUpdate()
  47653. {
  47654. repaint();
  47655. }
  47656. juce_UseDebuggingNewOperator
  47657. private:
  47658. FileListComponent& owner;
  47659. TimeSliceThread& thread;
  47660. bool highlighted;
  47661. int index;
  47662. File file;
  47663. String fileSize;
  47664. String modTime;
  47665. Image icon;
  47666. bool isDirectory;
  47667. void clearIcon()
  47668. {
  47669. icon = Image::null;
  47670. }
  47671. void updateIcon (const bool onlyUpdateIfCached)
  47672. {
  47673. if (icon.isNull())
  47674. {
  47675. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47676. Image im (ImageCache::getFromHashCode (hashCode));
  47677. if (im.isNull() && ! onlyUpdateIfCached)
  47678. {
  47679. im = juce_createIconForFile (file);
  47680. if (im.isValid())
  47681. ImageCache::addImageToCache (im, hashCode);
  47682. }
  47683. if (im.isValid())
  47684. {
  47685. icon = im;
  47686. triggerAsyncUpdate();
  47687. }
  47688. }
  47689. }
  47690. };
  47691. int FileListComponent::getNumRows()
  47692. {
  47693. return fileList.getNumFiles();
  47694. }
  47695. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47696. {
  47697. }
  47698. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47699. {
  47700. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47701. if (comp == 0)
  47702. {
  47703. delete existingComponentToUpdate;
  47704. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47705. }
  47706. DirectoryContentsList::FileInfo fileInfo;
  47707. if (fileList.getFileInfo (row, fileInfo))
  47708. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47709. else
  47710. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47711. return comp;
  47712. }
  47713. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47714. {
  47715. sendSelectionChangeMessage();
  47716. }
  47717. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47718. {
  47719. }
  47720. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47721. {
  47722. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47723. }
  47724. END_JUCE_NAMESPACE
  47725. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47726. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47727. BEGIN_JUCE_NAMESPACE
  47728. FilenameComponent::FilenameComponent (const String& name,
  47729. const File& currentFile,
  47730. const bool canEditFilename,
  47731. const bool isDirectory,
  47732. const bool isForSaving,
  47733. const String& fileBrowserWildcard,
  47734. const String& enforcedSuffix_,
  47735. const String& textWhenNothingSelected)
  47736. : Component (name),
  47737. maxRecentFiles (30),
  47738. isDir (isDirectory),
  47739. isSaving (isForSaving),
  47740. isFileDragOver (false),
  47741. wildcard (fileBrowserWildcard),
  47742. enforcedSuffix (enforcedSuffix_)
  47743. {
  47744. addAndMakeVisible (&filenameBox);
  47745. filenameBox.setEditableText (canEditFilename);
  47746. filenameBox.addListener (this);
  47747. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47748. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47749. setBrowseButtonText ("...");
  47750. setCurrentFile (currentFile, true);
  47751. }
  47752. FilenameComponent::~FilenameComponent()
  47753. {
  47754. }
  47755. void FilenameComponent::paintOverChildren (Graphics& g)
  47756. {
  47757. if (isFileDragOver)
  47758. {
  47759. g.setColour (Colours::red.withAlpha (0.2f));
  47760. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47761. }
  47762. }
  47763. void FilenameComponent::resized()
  47764. {
  47765. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47766. }
  47767. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47768. {
  47769. browseButtonText = newBrowseButtonText;
  47770. lookAndFeelChanged();
  47771. }
  47772. void FilenameComponent::lookAndFeelChanged()
  47773. {
  47774. browseButton = 0;
  47775. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47776. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47777. resized();
  47778. browseButton->addButtonListener (this);
  47779. }
  47780. void FilenameComponent::setTooltip (const String& newTooltip)
  47781. {
  47782. SettableTooltipClient::setTooltip (newTooltip);
  47783. filenameBox.setTooltip (newTooltip);
  47784. }
  47785. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47786. {
  47787. defaultBrowseFile = newDefaultDirectory;
  47788. }
  47789. void FilenameComponent::buttonClicked (Button*)
  47790. {
  47791. FileChooser fc (TRANS("Choose a new file"),
  47792. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47793. : getCurrentFile(),
  47794. wildcard);
  47795. if (isDir ? fc.browseForDirectory()
  47796. : (isSaving ? fc.browseForFileToSave (false)
  47797. : fc.browseForFileToOpen()))
  47798. {
  47799. setCurrentFile (fc.getResult(), true);
  47800. }
  47801. }
  47802. void FilenameComponent::comboBoxChanged (ComboBox*)
  47803. {
  47804. setCurrentFile (getCurrentFile(), true);
  47805. }
  47806. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47807. {
  47808. return true;
  47809. }
  47810. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47811. {
  47812. isFileDragOver = false;
  47813. repaint();
  47814. const File f (filenames[0]);
  47815. if (f.exists() && (f.isDirectory() == isDir))
  47816. setCurrentFile (f, true);
  47817. }
  47818. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47819. {
  47820. isFileDragOver = true;
  47821. repaint();
  47822. }
  47823. void FilenameComponent::fileDragExit (const StringArray&)
  47824. {
  47825. isFileDragOver = false;
  47826. repaint();
  47827. }
  47828. const File FilenameComponent::getCurrentFile() const
  47829. {
  47830. File f (filenameBox.getText());
  47831. if (enforcedSuffix.isNotEmpty())
  47832. f = f.withFileExtension (enforcedSuffix);
  47833. return f;
  47834. }
  47835. void FilenameComponent::setCurrentFile (File newFile,
  47836. const bool addToRecentlyUsedList,
  47837. const bool sendChangeNotification)
  47838. {
  47839. if (enforcedSuffix.isNotEmpty())
  47840. newFile = newFile.withFileExtension (enforcedSuffix);
  47841. if (newFile.getFullPathName() != lastFilename)
  47842. {
  47843. lastFilename = newFile.getFullPathName();
  47844. if (addToRecentlyUsedList)
  47845. addRecentlyUsedFile (newFile);
  47846. filenameBox.setText (lastFilename, true);
  47847. if (sendChangeNotification)
  47848. triggerAsyncUpdate();
  47849. }
  47850. }
  47851. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47852. {
  47853. filenameBox.setEditableText (shouldBeEditable);
  47854. }
  47855. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47856. {
  47857. StringArray names;
  47858. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47859. names.add (filenameBox.getItemText (i));
  47860. return names;
  47861. }
  47862. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47863. {
  47864. if (filenames != getRecentlyUsedFilenames())
  47865. {
  47866. filenameBox.clear();
  47867. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47868. filenameBox.addItem (filenames[i], i + 1);
  47869. }
  47870. }
  47871. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47872. {
  47873. maxRecentFiles = jmax (1, newMaximum);
  47874. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47875. }
  47876. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47877. {
  47878. StringArray files (getRecentlyUsedFilenames());
  47879. if (file.getFullPathName().isNotEmpty())
  47880. {
  47881. files.removeString (file.getFullPathName(), true);
  47882. files.insert (0, file.getFullPathName());
  47883. setRecentlyUsedFilenames (files);
  47884. }
  47885. }
  47886. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47887. {
  47888. listeners.add (listener);
  47889. }
  47890. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47891. {
  47892. listeners.remove (listener);
  47893. }
  47894. void FilenameComponent::handleAsyncUpdate()
  47895. {
  47896. Component::BailOutChecker checker (this);
  47897. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47898. }
  47899. END_JUCE_NAMESPACE
  47900. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47901. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47902. BEGIN_JUCE_NAMESPACE
  47903. FileSearchPathListComponent::FileSearchPathListComponent()
  47904. {
  47905. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  47906. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47907. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47908. listBox->setOutlineThickness (1);
  47909. addAndMakeVisible (addButton = new TextButton ("+"));
  47910. addButton->addButtonListener (this);
  47911. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47912. addAndMakeVisible (removeButton = new TextButton ("-"));
  47913. removeButton->addButtonListener (this);
  47914. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47915. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  47916. changeButton->addButtonListener (this);
  47917. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47918. upButton->addButtonListener (this);
  47919. {
  47920. Path arrowPath;
  47921. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47922. DrawablePath arrowImage;
  47923. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47924. arrowImage.setPath (arrowPath);
  47925. upButton->setImages (&arrowImage);
  47926. }
  47927. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47928. downButton->addButtonListener (this);
  47929. {
  47930. Path arrowPath;
  47931. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47932. DrawablePath arrowImage;
  47933. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47934. arrowImage.setPath (arrowPath);
  47935. downButton->setImages (&arrowImage);
  47936. }
  47937. updateButtons();
  47938. }
  47939. FileSearchPathListComponent::~FileSearchPathListComponent()
  47940. {
  47941. deleteAllChildren();
  47942. }
  47943. void FileSearchPathListComponent::updateButtons()
  47944. {
  47945. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  47946. removeButton->setEnabled (anythingSelected);
  47947. changeButton->setEnabled (anythingSelected);
  47948. upButton->setEnabled (anythingSelected);
  47949. downButton->setEnabled (anythingSelected);
  47950. }
  47951. void FileSearchPathListComponent::changed()
  47952. {
  47953. listBox->updateContent();
  47954. listBox->repaint();
  47955. updateButtons();
  47956. }
  47957. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47958. {
  47959. if (newPath.toString() != path.toString())
  47960. {
  47961. path = newPath;
  47962. changed();
  47963. }
  47964. }
  47965. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47966. {
  47967. defaultBrowseTarget = newDefaultDirectory;
  47968. }
  47969. int FileSearchPathListComponent::getNumRows()
  47970. {
  47971. return path.getNumPaths();
  47972. }
  47973. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47974. {
  47975. if (rowIsSelected)
  47976. g.fillAll (findColour (TextEditor::highlightColourId));
  47977. g.setColour (findColour (ListBox::textColourId));
  47978. Font f (height * 0.7f);
  47979. f.setHorizontalScale (0.9f);
  47980. g.setFont (f);
  47981. g.drawText (path [rowNumber].getFullPathName(),
  47982. 4, 0, width - 6, height,
  47983. Justification::centredLeft, true);
  47984. }
  47985. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47986. {
  47987. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  47988. {
  47989. path.remove (row);
  47990. changed();
  47991. }
  47992. }
  47993. void FileSearchPathListComponent::returnKeyPressed (int row)
  47994. {
  47995. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47996. if (chooser.browseForDirectory())
  47997. {
  47998. path.remove (row);
  47999. path.add (chooser.getResult(), row);
  48000. changed();
  48001. }
  48002. }
  48003. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  48004. {
  48005. returnKeyPressed (row);
  48006. }
  48007. void FileSearchPathListComponent::selectedRowsChanged (int)
  48008. {
  48009. updateButtons();
  48010. }
  48011. void FileSearchPathListComponent::paint (Graphics& g)
  48012. {
  48013. g.fillAll (findColour (backgroundColourId));
  48014. }
  48015. void FileSearchPathListComponent::resized()
  48016. {
  48017. const int buttonH = 22;
  48018. const int buttonY = getHeight() - buttonH - 4;
  48019. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  48020. addButton->setBounds (2, buttonY, buttonH, buttonH);
  48021. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  48022. changeButton->changeWidthToFitText (buttonH);
  48023. downButton->setSize (buttonH * 2, buttonH);
  48024. upButton->setSize (buttonH * 2, buttonH);
  48025. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  48026. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  48027. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  48028. }
  48029. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  48030. {
  48031. return true;
  48032. }
  48033. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  48034. {
  48035. for (int i = filenames.size(); --i >= 0;)
  48036. {
  48037. const File f (filenames[i]);
  48038. if (f.isDirectory())
  48039. {
  48040. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  48041. path.add (f, row);
  48042. changed();
  48043. }
  48044. }
  48045. }
  48046. void FileSearchPathListComponent::buttonClicked (Button* button)
  48047. {
  48048. const int currentRow = listBox->getSelectedRow();
  48049. if (button == removeButton)
  48050. {
  48051. deleteKeyPressed (currentRow);
  48052. }
  48053. else if (button == addButton)
  48054. {
  48055. File start (defaultBrowseTarget);
  48056. if (start == File::nonexistent)
  48057. start = path [0];
  48058. if (start == File::nonexistent)
  48059. start = File::getCurrentWorkingDirectory();
  48060. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  48061. if (chooser.browseForDirectory())
  48062. {
  48063. path.add (chooser.getResult(), currentRow);
  48064. }
  48065. }
  48066. else if (button == changeButton)
  48067. {
  48068. returnKeyPressed (currentRow);
  48069. }
  48070. else if (button == upButton)
  48071. {
  48072. if (currentRow > 0 && currentRow < path.getNumPaths())
  48073. {
  48074. const File f (path[currentRow]);
  48075. path.remove (currentRow);
  48076. path.add (f, currentRow - 1);
  48077. listBox->selectRow (currentRow - 1);
  48078. }
  48079. }
  48080. else if (button == downButton)
  48081. {
  48082. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  48083. {
  48084. const File f (path[currentRow]);
  48085. path.remove (currentRow);
  48086. path.add (f, currentRow + 1);
  48087. listBox->selectRow (currentRow + 1);
  48088. }
  48089. }
  48090. changed();
  48091. }
  48092. END_JUCE_NAMESPACE
  48093. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  48094. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  48095. BEGIN_JUCE_NAMESPACE
  48096. const Image juce_createIconForFile (const File& file);
  48097. class FileListTreeItem : public TreeViewItem,
  48098. public TimeSliceClient,
  48099. public AsyncUpdater,
  48100. public ChangeListener
  48101. {
  48102. public:
  48103. FileListTreeItem (FileTreeComponent& owner_,
  48104. DirectoryContentsList* const parentContentsList_,
  48105. const int indexInContentsList_,
  48106. const File& file_,
  48107. TimeSliceThread& thread_)
  48108. : file (file_),
  48109. owner (owner_),
  48110. parentContentsList (parentContentsList_),
  48111. indexInContentsList (indexInContentsList_),
  48112. subContentsList (0),
  48113. canDeleteSubContentsList (false),
  48114. thread (thread_),
  48115. icon (0)
  48116. {
  48117. DirectoryContentsList::FileInfo fileInfo;
  48118. if (parentContentsList_ != 0
  48119. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  48120. {
  48121. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  48122. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  48123. isDirectory = fileInfo.isDirectory;
  48124. }
  48125. else
  48126. {
  48127. isDirectory = true;
  48128. }
  48129. }
  48130. ~FileListTreeItem()
  48131. {
  48132. thread.removeTimeSliceClient (this);
  48133. clearSubItems();
  48134. if (canDeleteSubContentsList)
  48135. delete subContentsList;
  48136. }
  48137. bool mightContainSubItems() { return isDirectory; }
  48138. const String getUniqueName() const { return file.getFullPathName(); }
  48139. int getItemHeight() const { return 22; }
  48140. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  48141. void itemOpennessChanged (bool isNowOpen)
  48142. {
  48143. if (isNowOpen)
  48144. {
  48145. clearSubItems();
  48146. isDirectory = file.isDirectory();
  48147. if (isDirectory)
  48148. {
  48149. if (subContentsList == 0)
  48150. {
  48151. jassert (parentContentsList != 0);
  48152. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  48153. l->setDirectory (file, true, true);
  48154. setSubContentsList (l);
  48155. canDeleteSubContentsList = true;
  48156. }
  48157. changeListenerCallback (0);
  48158. }
  48159. }
  48160. }
  48161. void setSubContentsList (DirectoryContentsList* newList)
  48162. {
  48163. jassert (subContentsList == 0);
  48164. subContentsList = newList;
  48165. newList->addChangeListener (this);
  48166. }
  48167. void changeListenerCallback (void*)
  48168. {
  48169. clearSubItems();
  48170. if (isOpen() && subContentsList != 0)
  48171. {
  48172. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  48173. {
  48174. FileListTreeItem* const item
  48175. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  48176. addSubItem (item);
  48177. }
  48178. }
  48179. }
  48180. void paintItem (Graphics& g, int width, int height)
  48181. {
  48182. if (file != File::nonexistent)
  48183. {
  48184. updateIcon (true);
  48185. if (icon.isNull())
  48186. thread.addTimeSliceClient (this);
  48187. }
  48188. owner.getLookAndFeel()
  48189. .drawFileBrowserRow (g, width, height,
  48190. file.getFileName(),
  48191. &icon, fileSize, modTime,
  48192. isDirectory, isSelected(),
  48193. indexInContentsList, owner);
  48194. }
  48195. void itemClicked (const MouseEvent& e)
  48196. {
  48197. owner.sendMouseClickMessage (file, e);
  48198. }
  48199. void itemDoubleClicked (const MouseEvent& e)
  48200. {
  48201. TreeViewItem::itemDoubleClicked (e);
  48202. owner.sendDoubleClickMessage (file);
  48203. }
  48204. void itemSelectionChanged (bool)
  48205. {
  48206. owner.sendSelectionChangeMessage();
  48207. }
  48208. bool useTimeSlice()
  48209. {
  48210. updateIcon (false);
  48211. thread.removeTimeSliceClient (this);
  48212. return false;
  48213. }
  48214. void handleAsyncUpdate()
  48215. {
  48216. owner.repaint();
  48217. }
  48218. const File file;
  48219. juce_UseDebuggingNewOperator
  48220. private:
  48221. FileTreeComponent& owner;
  48222. DirectoryContentsList* parentContentsList;
  48223. int indexInContentsList;
  48224. DirectoryContentsList* subContentsList;
  48225. bool isDirectory, canDeleteSubContentsList;
  48226. TimeSliceThread& thread;
  48227. Image icon;
  48228. String fileSize;
  48229. String modTime;
  48230. void updateIcon (const bool onlyUpdateIfCached)
  48231. {
  48232. if (icon.isNull())
  48233. {
  48234. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48235. Image im (ImageCache::getFromHashCode (hashCode));
  48236. if (im.isNull() && ! onlyUpdateIfCached)
  48237. {
  48238. im = juce_createIconForFile (file);
  48239. if (im.isValid())
  48240. ImageCache::addImageToCache (im, hashCode);
  48241. }
  48242. if (im.isValid())
  48243. {
  48244. icon = im;
  48245. triggerAsyncUpdate();
  48246. }
  48247. }
  48248. }
  48249. };
  48250. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48251. : DirectoryContentsDisplayComponent (listToShow)
  48252. {
  48253. FileListTreeItem* const root
  48254. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48255. listToShow.getTimeSliceThread());
  48256. root->setSubContentsList (&listToShow);
  48257. setRootItemVisible (false);
  48258. setRootItem (root);
  48259. }
  48260. FileTreeComponent::~FileTreeComponent()
  48261. {
  48262. deleteRootItem();
  48263. }
  48264. const File FileTreeComponent::getSelectedFile (const int index) const
  48265. {
  48266. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48267. return item != 0 ? item->file
  48268. : File::nonexistent;
  48269. }
  48270. void FileTreeComponent::deselectAllFiles()
  48271. {
  48272. clearSelectedItems();
  48273. }
  48274. void FileTreeComponent::scrollToTop()
  48275. {
  48276. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48277. }
  48278. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48279. {
  48280. dragAndDropDescription = description;
  48281. }
  48282. END_JUCE_NAMESPACE
  48283. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48284. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48285. BEGIN_JUCE_NAMESPACE
  48286. ImagePreviewComponent::ImagePreviewComponent()
  48287. {
  48288. }
  48289. ImagePreviewComponent::~ImagePreviewComponent()
  48290. {
  48291. }
  48292. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48293. {
  48294. const int availableW = proportionOfWidth (0.97f);
  48295. const int availableH = getHeight() - 13 * 4;
  48296. const double scale = jmin (1.0,
  48297. availableW / (double) w,
  48298. availableH / (double) h);
  48299. w = roundToInt (scale * w);
  48300. h = roundToInt (scale * h);
  48301. }
  48302. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48303. {
  48304. if (fileToLoad != file)
  48305. {
  48306. fileToLoad = file;
  48307. startTimer (100);
  48308. }
  48309. }
  48310. void ImagePreviewComponent::timerCallback()
  48311. {
  48312. stopTimer();
  48313. currentThumbnail = Image::null;
  48314. currentDetails = String::empty;
  48315. repaint();
  48316. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48317. if (in != 0)
  48318. {
  48319. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48320. if (format != 0)
  48321. {
  48322. currentThumbnail = format->decodeImage (*in);
  48323. if (currentThumbnail.isValid())
  48324. {
  48325. int w = currentThumbnail.getWidth();
  48326. int h = currentThumbnail.getHeight();
  48327. currentDetails
  48328. << fileToLoad.getFileName() << "\n"
  48329. << format->getFormatName() << "\n"
  48330. << w << " x " << h << " pixels\n"
  48331. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48332. getThumbSize (w, h);
  48333. currentThumbnail = currentThumbnail.rescaled (w, h);
  48334. }
  48335. }
  48336. }
  48337. }
  48338. void ImagePreviewComponent::paint (Graphics& g)
  48339. {
  48340. if (currentThumbnail.isValid())
  48341. {
  48342. g.setFont (13.0f);
  48343. int w = currentThumbnail.getWidth();
  48344. int h = currentThumbnail.getHeight();
  48345. getThumbSize (w, h);
  48346. const int numLines = 4;
  48347. const int totalH = 13 * numLines + h + 4;
  48348. const int y = (getHeight() - totalH) / 2;
  48349. g.drawImageWithin (currentThumbnail,
  48350. (getWidth() - w) / 2, y, w, h,
  48351. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48352. false);
  48353. g.drawFittedText (currentDetails,
  48354. 0, y + h + 4, getWidth(), 100,
  48355. Justification::centredTop, numLines);
  48356. }
  48357. }
  48358. END_JUCE_NAMESPACE
  48359. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48360. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48361. BEGIN_JUCE_NAMESPACE
  48362. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48363. const String& directoryWildcardPatterns,
  48364. const String& description_)
  48365. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48366. : (description_ + " (" + fileWildcardPatterns + ")"))
  48367. {
  48368. parse (fileWildcardPatterns, fileWildcards);
  48369. parse (directoryWildcardPatterns, directoryWildcards);
  48370. }
  48371. WildcardFileFilter::~WildcardFileFilter()
  48372. {
  48373. }
  48374. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48375. {
  48376. return match (file, fileWildcards);
  48377. }
  48378. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48379. {
  48380. return match (file, directoryWildcards);
  48381. }
  48382. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48383. {
  48384. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48385. result.trim();
  48386. result.removeEmptyStrings();
  48387. // special case for *.*, because people use it to mean "any file", but it
  48388. // would actually ignore files with no extension.
  48389. for (int i = result.size(); --i >= 0;)
  48390. if (result[i] == "*.*")
  48391. result.set (i, "*");
  48392. }
  48393. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48394. {
  48395. const String filename (file.getFileName());
  48396. for (int i = wildcards.size(); --i >= 0;)
  48397. if (filename.matchesWildcard (wildcards[i], true))
  48398. return true;
  48399. return false;
  48400. }
  48401. END_JUCE_NAMESPACE
  48402. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48403. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48404. BEGIN_JUCE_NAMESPACE
  48405. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48406. {
  48407. }
  48408. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48409. {
  48410. }
  48411. namespace KeyboardFocusHelpers
  48412. {
  48413. // This will sort a set of components, so that they are ordered in terms of
  48414. // left-to-right and then top-to-bottom.
  48415. class ScreenPositionComparator
  48416. {
  48417. public:
  48418. ScreenPositionComparator() {}
  48419. static int compareElements (const Component* const first, const Component* const second)
  48420. {
  48421. int explicitOrder1 = first->getExplicitFocusOrder();
  48422. if (explicitOrder1 <= 0)
  48423. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48424. int explicitOrder2 = second->getExplicitFocusOrder();
  48425. if (explicitOrder2 <= 0)
  48426. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48427. if (explicitOrder1 != explicitOrder2)
  48428. return explicitOrder1 - explicitOrder2;
  48429. const int diff = first->getY() - second->getY();
  48430. return (diff == 0) ? first->getX() - second->getX()
  48431. : diff;
  48432. }
  48433. };
  48434. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48435. {
  48436. if (parent->getNumChildComponents() > 0)
  48437. {
  48438. Array <Component*> localComps;
  48439. ScreenPositionComparator comparator;
  48440. int i;
  48441. for (i = parent->getNumChildComponents(); --i >= 0;)
  48442. {
  48443. Component* const c = parent->getChildComponent (i);
  48444. if (c->isVisible() && c->isEnabled())
  48445. localComps.addSorted (comparator, c);
  48446. }
  48447. for (i = 0; i < localComps.size(); ++i)
  48448. {
  48449. Component* const c = localComps.getUnchecked (i);
  48450. if (c->getWantsKeyboardFocus())
  48451. comps.add (c);
  48452. if (! c->isFocusContainer())
  48453. findAllFocusableComponents (c, comps);
  48454. }
  48455. }
  48456. }
  48457. }
  48458. static Component* getIncrementedComponent (Component* const current, const int delta)
  48459. {
  48460. Component* focusContainer = current->getParentComponent();
  48461. if (focusContainer != 0)
  48462. {
  48463. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48464. focusContainer = focusContainer->getParentComponent();
  48465. if (focusContainer != 0)
  48466. {
  48467. Array <Component*> comps;
  48468. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48469. if (comps.size() > 0)
  48470. {
  48471. const int index = comps.indexOf (current);
  48472. return comps [(index + comps.size() + delta) % comps.size()];
  48473. }
  48474. }
  48475. }
  48476. return 0;
  48477. }
  48478. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48479. {
  48480. return getIncrementedComponent (current, 1);
  48481. }
  48482. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48483. {
  48484. return getIncrementedComponent (current, -1);
  48485. }
  48486. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48487. {
  48488. Array <Component*> comps;
  48489. if (parentComponent != 0)
  48490. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48491. return comps.getFirst();
  48492. }
  48493. END_JUCE_NAMESPACE
  48494. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48495. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48496. BEGIN_JUCE_NAMESPACE
  48497. bool KeyListener::keyStateChanged (const bool, Component*)
  48498. {
  48499. return false;
  48500. }
  48501. END_JUCE_NAMESPACE
  48502. /*** End of inlined file: juce_KeyListener.cpp ***/
  48503. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48504. BEGIN_JUCE_NAMESPACE
  48505. // N.B. these two includes are put here deliberately to avoid problems with
  48506. // old GCCs failing on long include paths
  48507. const int maxKeys = 3;
  48508. class KeyMappingChangeButton : public Button
  48509. {
  48510. public:
  48511. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  48512. const CommandID commandID_,
  48513. const String& keyName,
  48514. const int keyNum_)
  48515. : Button (keyName),
  48516. owner (owner_),
  48517. commandID (commandID_),
  48518. keyNum (keyNum_)
  48519. {
  48520. setWantsKeyboardFocus (false);
  48521. setTriggeredOnMouseDown (keyNum >= 0);
  48522. if (keyNum_ < 0)
  48523. setTooltip (TRANS("adds a new key-mapping"));
  48524. else
  48525. setTooltip (TRANS("click to change this key-mapping"));
  48526. }
  48527. ~KeyMappingChangeButton()
  48528. {
  48529. }
  48530. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48531. {
  48532. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48533. keyNum >= 0 ? getName() : String::empty);
  48534. }
  48535. void clicked()
  48536. {
  48537. if (keyNum >= 0)
  48538. {
  48539. // existing key clicked..
  48540. PopupMenu m;
  48541. m.addItem (1, TRANS("change this key-mapping"));
  48542. m.addSeparator();
  48543. m.addItem (2, TRANS("remove this key-mapping"));
  48544. const int res = m.show();
  48545. if (res == 1)
  48546. {
  48547. owner->assignNewKey (commandID, keyNum);
  48548. }
  48549. else if (res == 2)
  48550. {
  48551. owner->getMappings()->removeKeyPress (commandID, keyNum);
  48552. }
  48553. }
  48554. else
  48555. {
  48556. // + button pressed..
  48557. owner->assignNewKey (commandID, -1);
  48558. }
  48559. }
  48560. void fitToContent (const int h) throw()
  48561. {
  48562. if (keyNum < 0)
  48563. {
  48564. setSize (h, h);
  48565. }
  48566. else
  48567. {
  48568. Font f (h * 0.6f);
  48569. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48570. }
  48571. }
  48572. juce_UseDebuggingNewOperator
  48573. private:
  48574. KeyMappingEditorComponent* const owner;
  48575. const CommandID commandID;
  48576. const int keyNum;
  48577. KeyMappingChangeButton (const KeyMappingChangeButton&);
  48578. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  48579. };
  48580. class KeyMappingItemComponent : public Component
  48581. {
  48582. public:
  48583. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  48584. const CommandID commandID_)
  48585. : owner (owner_),
  48586. commandID (commandID_)
  48587. {
  48588. setInterceptsMouseClicks (false, true);
  48589. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  48590. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  48591. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  48592. {
  48593. KeyMappingChangeButton* const kb
  48594. = new KeyMappingChangeButton (owner_, commandID,
  48595. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  48596. kb->setEnabled (! isReadOnly);
  48597. addAndMakeVisible (kb);
  48598. }
  48599. KeyMappingChangeButton* const kb
  48600. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  48601. addChildComponent (kb);
  48602. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  48603. }
  48604. ~KeyMappingItemComponent()
  48605. {
  48606. deleteAllChildren();
  48607. }
  48608. void paint (Graphics& g)
  48609. {
  48610. g.setFont (getHeight() * 0.7f);
  48611. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48612. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  48613. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48614. Justification::centredLeft, true);
  48615. }
  48616. void resized()
  48617. {
  48618. int x = getWidth() - 4;
  48619. for (int i = getNumChildComponents(); --i >= 0;)
  48620. {
  48621. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  48622. kb->fitToContent (getHeight() - 2);
  48623. kb->setTopRightPosition (x, 1);
  48624. x -= kb->getWidth() + 5;
  48625. }
  48626. }
  48627. juce_UseDebuggingNewOperator
  48628. private:
  48629. KeyMappingEditorComponent* const owner;
  48630. const CommandID commandID;
  48631. KeyMappingItemComponent (const KeyMappingItemComponent&);
  48632. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  48633. };
  48634. class KeyMappingTreeViewItem : public TreeViewItem
  48635. {
  48636. public:
  48637. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  48638. const CommandID commandID_)
  48639. : owner (owner_),
  48640. commandID (commandID_)
  48641. {
  48642. }
  48643. ~KeyMappingTreeViewItem()
  48644. {
  48645. }
  48646. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48647. bool mightContainSubItems() { return false; }
  48648. int getItemHeight() const { return 20; }
  48649. Component* createItemComponent()
  48650. {
  48651. return new KeyMappingItemComponent (owner, commandID);
  48652. }
  48653. juce_UseDebuggingNewOperator
  48654. private:
  48655. KeyMappingEditorComponent* const owner;
  48656. const CommandID commandID;
  48657. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  48658. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  48659. };
  48660. class KeyCategoryTreeViewItem : public TreeViewItem
  48661. {
  48662. public:
  48663. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  48664. const String& name)
  48665. : owner (owner_),
  48666. categoryName (name)
  48667. {
  48668. }
  48669. ~KeyCategoryTreeViewItem()
  48670. {
  48671. }
  48672. const String getUniqueName() const { return categoryName + "_cat"; }
  48673. bool mightContainSubItems() { return true; }
  48674. int getItemHeight() const { return 28; }
  48675. void paintItem (Graphics& g, int width, int height)
  48676. {
  48677. g.setFont (height * 0.6f, Font::bold);
  48678. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  48679. g.drawText (categoryName,
  48680. 2, 0, width - 2, height,
  48681. Justification::centredLeft, true);
  48682. }
  48683. void itemOpennessChanged (bool isNowOpen)
  48684. {
  48685. if (isNowOpen)
  48686. {
  48687. if (getNumSubItems() == 0)
  48688. {
  48689. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  48690. for (int i = 0; i < commands.size(); ++i)
  48691. {
  48692. if (owner->shouldCommandBeIncluded (commands[i]))
  48693. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  48694. }
  48695. }
  48696. }
  48697. else
  48698. {
  48699. clearSubItems();
  48700. }
  48701. }
  48702. juce_UseDebuggingNewOperator
  48703. private:
  48704. KeyMappingEditorComponent* owner;
  48705. String categoryName;
  48706. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  48707. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  48708. };
  48709. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  48710. const bool showResetToDefaultButton)
  48711. : mappings (mappingManager)
  48712. {
  48713. jassert (mappingManager != 0); // can't be null!
  48714. mappingManager->addChangeListener (this);
  48715. setLinesDrawnForSubItems (false);
  48716. resetButton = 0;
  48717. if (showResetToDefaultButton)
  48718. {
  48719. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  48720. resetButton->addButtonListener (this);
  48721. }
  48722. addAndMakeVisible (tree = new TreeView());
  48723. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48724. tree->setRootItemVisible (false);
  48725. tree->setDefaultOpenness (true);
  48726. tree->setRootItem (this);
  48727. }
  48728. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48729. {
  48730. mappings->removeChangeListener (this);
  48731. deleteAllChildren();
  48732. }
  48733. bool KeyMappingEditorComponent::mightContainSubItems()
  48734. {
  48735. return true;
  48736. }
  48737. const String KeyMappingEditorComponent::getUniqueName() const
  48738. {
  48739. return "keys";
  48740. }
  48741. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48742. const Colour& textColour)
  48743. {
  48744. setColour (backgroundColourId, mainBackground);
  48745. setColour (textColourId, textColour);
  48746. tree->setColour (TreeView::backgroundColourId, mainBackground);
  48747. }
  48748. void KeyMappingEditorComponent::parentHierarchyChanged()
  48749. {
  48750. changeListenerCallback (0);
  48751. }
  48752. void KeyMappingEditorComponent::resized()
  48753. {
  48754. int h = getHeight();
  48755. if (resetButton != 0)
  48756. {
  48757. const int buttonHeight = 20;
  48758. h -= buttonHeight + 8;
  48759. int x = getWidth() - 8;
  48760. resetButton->changeWidthToFitText (buttonHeight);
  48761. resetButton->setTopRightPosition (x, h + 6);
  48762. }
  48763. tree->setBounds (0, 0, getWidth(), h);
  48764. }
  48765. void KeyMappingEditorComponent::buttonClicked (Button* button)
  48766. {
  48767. if (button == resetButton)
  48768. {
  48769. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48770. TRANS("Reset to defaults"),
  48771. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48772. TRANS("Reset")))
  48773. {
  48774. mappings->resetToDefaultMappings();
  48775. }
  48776. }
  48777. }
  48778. void KeyMappingEditorComponent::changeListenerCallback (void*)
  48779. {
  48780. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  48781. clearSubItems();
  48782. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  48783. for (int i = 0; i < categories.size(); ++i)
  48784. {
  48785. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  48786. int count = 0;
  48787. for (int j = 0; j < commands.size(); ++j)
  48788. if (shouldCommandBeIncluded (commands[j]))
  48789. ++count;
  48790. if (count > 0)
  48791. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  48792. }
  48793. if (oldOpenness != 0)
  48794. tree->restoreOpennessState (*oldOpenness);
  48795. }
  48796. class KeyEntryWindow : public AlertWindow
  48797. {
  48798. public:
  48799. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  48800. : AlertWindow (TRANS("New key-mapping"),
  48801. TRANS("Please press a key combination now..."),
  48802. AlertWindow::NoIcon),
  48803. owner (owner_)
  48804. {
  48805. addButton (TRANS("ok"), 1);
  48806. addButton (TRANS("cancel"), 0);
  48807. // (avoid return + escape keys getting processed by the buttons..)
  48808. for (int i = getNumChildComponents(); --i >= 0;)
  48809. getChildComponent (i)->setWantsKeyboardFocus (false);
  48810. setWantsKeyboardFocus (true);
  48811. grabKeyboardFocus();
  48812. }
  48813. ~KeyEntryWindow()
  48814. {
  48815. }
  48816. bool keyPressed (const KeyPress& key)
  48817. {
  48818. lastPress = key;
  48819. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  48820. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  48821. if (previousCommand != 0)
  48822. {
  48823. message << "\n\n"
  48824. << TRANS("(Currently assigned to \"")
  48825. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  48826. << "\")";
  48827. }
  48828. setMessage (message);
  48829. return true;
  48830. }
  48831. bool keyStateChanged (bool)
  48832. {
  48833. return true;
  48834. }
  48835. KeyPress lastPress;
  48836. juce_UseDebuggingNewOperator
  48837. private:
  48838. KeyMappingEditorComponent* owner;
  48839. KeyEntryWindow (const KeyEntryWindow&);
  48840. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48841. };
  48842. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  48843. {
  48844. KeyEntryWindow entryWindow (this);
  48845. if (entryWindow.runModalLoop() != 0)
  48846. {
  48847. entryWindow.setVisible (false);
  48848. if (entryWindow.lastPress.isValid())
  48849. {
  48850. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  48851. if (previousCommand != 0)
  48852. {
  48853. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48854. TRANS("Change key-mapping"),
  48855. TRANS("This key is already assigned to the command \"")
  48856. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  48857. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48858. TRANS("re-assign"),
  48859. TRANS("cancel")))
  48860. {
  48861. return;
  48862. }
  48863. }
  48864. mappings->removeKeyPress (entryWindow.lastPress);
  48865. if (index >= 0)
  48866. mappings->removeKeyPress (commandID, index);
  48867. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  48868. }
  48869. }
  48870. }
  48871. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48872. {
  48873. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48874. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  48875. }
  48876. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48877. {
  48878. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48879. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  48880. }
  48881. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48882. {
  48883. return key.getTextDescription();
  48884. }
  48885. END_JUCE_NAMESPACE
  48886. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48887. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48888. BEGIN_JUCE_NAMESPACE
  48889. KeyPress::KeyPress() throw()
  48890. : keyCode (0),
  48891. mods (0),
  48892. textCharacter (0)
  48893. {
  48894. }
  48895. KeyPress::KeyPress (const int keyCode_,
  48896. const ModifierKeys& mods_,
  48897. const juce_wchar textCharacter_) throw()
  48898. : keyCode (keyCode_),
  48899. mods (mods_),
  48900. textCharacter (textCharacter_)
  48901. {
  48902. }
  48903. KeyPress::KeyPress (const int keyCode_) throw()
  48904. : keyCode (keyCode_),
  48905. textCharacter (0)
  48906. {
  48907. }
  48908. KeyPress::KeyPress (const KeyPress& other) throw()
  48909. : keyCode (other.keyCode),
  48910. mods (other.mods),
  48911. textCharacter (other.textCharacter)
  48912. {
  48913. }
  48914. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48915. {
  48916. keyCode = other.keyCode;
  48917. mods = other.mods;
  48918. textCharacter = other.textCharacter;
  48919. return *this;
  48920. }
  48921. bool KeyPress::operator== (const KeyPress& other) const throw()
  48922. {
  48923. return mods.getRawFlags() == other.mods.getRawFlags()
  48924. && (textCharacter == other.textCharacter
  48925. || textCharacter == 0
  48926. || other.textCharacter == 0)
  48927. && (keyCode == other.keyCode
  48928. || (keyCode < 256
  48929. && other.keyCode < 256
  48930. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48931. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48932. }
  48933. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48934. {
  48935. return ! operator== (other);
  48936. }
  48937. bool KeyPress::isCurrentlyDown() const
  48938. {
  48939. return isKeyCurrentlyDown (keyCode)
  48940. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48941. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48942. }
  48943. namespace KeyPressHelpers
  48944. {
  48945. struct KeyNameAndCode
  48946. {
  48947. const char* name;
  48948. int code;
  48949. };
  48950. static const KeyNameAndCode translations[] =
  48951. {
  48952. { "spacebar", KeyPress::spaceKey },
  48953. { "return", KeyPress::returnKey },
  48954. { "escape", KeyPress::escapeKey },
  48955. { "backspace", KeyPress::backspaceKey },
  48956. { "cursor left", KeyPress::leftKey },
  48957. { "cursor right", KeyPress::rightKey },
  48958. { "cursor up", KeyPress::upKey },
  48959. { "cursor down", KeyPress::downKey },
  48960. { "page up", KeyPress::pageUpKey },
  48961. { "page down", KeyPress::pageDownKey },
  48962. { "home", KeyPress::homeKey },
  48963. { "end", KeyPress::endKey },
  48964. { "delete", KeyPress::deleteKey },
  48965. { "insert", KeyPress::insertKey },
  48966. { "tab", KeyPress::tabKey },
  48967. { "play", KeyPress::playKey },
  48968. { "stop", KeyPress::stopKey },
  48969. { "fast forward", KeyPress::fastForwardKey },
  48970. { "rewind", KeyPress::rewindKey }
  48971. };
  48972. static const String numberPadPrefix() { return "numpad "; }
  48973. }
  48974. const KeyPress KeyPress::createFromDescription (const String& desc)
  48975. {
  48976. int modifiers = 0;
  48977. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48978. || desc.containsWholeWordIgnoreCase ("control")
  48979. || desc.containsWholeWordIgnoreCase ("ctl"))
  48980. modifiers |= ModifierKeys::ctrlModifier;
  48981. if (desc.containsWholeWordIgnoreCase ("shift")
  48982. || desc.containsWholeWordIgnoreCase ("shft"))
  48983. modifiers |= ModifierKeys::shiftModifier;
  48984. if (desc.containsWholeWordIgnoreCase ("alt")
  48985. || desc.containsWholeWordIgnoreCase ("option"))
  48986. modifiers |= ModifierKeys::altModifier;
  48987. if (desc.containsWholeWordIgnoreCase ("command")
  48988. || desc.containsWholeWordIgnoreCase ("cmd"))
  48989. modifiers |= ModifierKeys::commandModifier;
  48990. int key = 0;
  48991. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48992. {
  48993. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48994. {
  48995. key = KeyPressHelpers::translations[i].code;
  48996. break;
  48997. }
  48998. }
  48999. if (key == 0)
  49000. {
  49001. // see if it's a numpad key..
  49002. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  49003. {
  49004. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  49005. if (lastChar >= '0' && lastChar <= '9')
  49006. key = numberPad0 + lastChar - '0';
  49007. else if (lastChar == '+')
  49008. key = numberPadAdd;
  49009. else if (lastChar == '-')
  49010. key = numberPadSubtract;
  49011. else if (lastChar == '*')
  49012. key = numberPadMultiply;
  49013. else if (lastChar == '/')
  49014. key = numberPadDivide;
  49015. else if (lastChar == '.')
  49016. key = numberPadDecimalPoint;
  49017. else if (lastChar == '=')
  49018. key = numberPadEquals;
  49019. else if (desc.endsWith ("separator"))
  49020. key = numberPadSeparator;
  49021. else if (desc.endsWith ("delete"))
  49022. key = numberPadDelete;
  49023. }
  49024. if (key == 0)
  49025. {
  49026. // see if it's a function key..
  49027. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  49028. for (int i = 1; i <= 12; ++i)
  49029. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  49030. key = F1Key + i - 1;
  49031. if (key == 0)
  49032. {
  49033. // give up and use the hex code..
  49034. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  49035. .toLowerCase()
  49036. .retainCharacters ("0123456789abcdef")
  49037. .getHexValue32();
  49038. if (hexCode > 0)
  49039. key = hexCode;
  49040. else
  49041. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  49042. }
  49043. }
  49044. }
  49045. return KeyPress (key, ModifierKeys (modifiers), 0);
  49046. }
  49047. const String KeyPress::getTextDescription() const
  49048. {
  49049. String desc;
  49050. if (keyCode > 0)
  49051. {
  49052. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  49053. // want to store it as being a slash, not shift+whatever.
  49054. if (textCharacter == '/')
  49055. return "/";
  49056. if (mods.isCtrlDown())
  49057. desc << "ctrl + ";
  49058. if (mods.isShiftDown())
  49059. desc << "shift + ";
  49060. #if JUCE_MAC
  49061. // only do this on the mac, because on Windows ctrl and command are the same,
  49062. // and this would get confusing
  49063. if (mods.isCommandDown())
  49064. desc << "command + ";
  49065. if (mods.isAltDown())
  49066. desc << "option + ";
  49067. #else
  49068. if (mods.isAltDown())
  49069. desc << "alt + ";
  49070. #endif
  49071. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  49072. if (keyCode == KeyPressHelpers::translations[i].code)
  49073. return desc + KeyPressHelpers::translations[i].name;
  49074. if (keyCode >= F1Key && keyCode <= F16Key)
  49075. desc << 'F' << (1 + keyCode - F1Key);
  49076. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  49077. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  49078. else if (keyCode >= 33 && keyCode < 176)
  49079. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  49080. else if (keyCode == numberPadAdd)
  49081. desc << KeyPressHelpers::numberPadPrefix() << '+';
  49082. else if (keyCode == numberPadSubtract)
  49083. desc << KeyPressHelpers::numberPadPrefix() << '-';
  49084. else if (keyCode == numberPadMultiply)
  49085. desc << KeyPressHelpers::numberPadPrefix() << '*';
  49086. else if (keyCode == numberPadDivide)
  49087. desc << KeyPressHelpers::numberPadPrefix() << '/';
  49088. else if (keyCode == numberPadSeparator)
  49089. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  49090. else if (keyCode == numberPadDecimalPoint)
  49091. desc << KeyPressHelpers::numberPadPrefix() << '.';
  49092. else if (keyCode == numberPadDelete)
  49093. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  49094. else
  49095. desc << '#' << String::toHexString (keyCode);
  49096. }
  49097. return desc;
  49098. }
  49099. END_JUCE_NAMESPACE
  49100. /*** End of inlined file: juce_KeyPress.cpp ***/
  49101. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  49102. BEGIN_JUCE_NAMESPACE
  49103. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  49104. : commandManager (commandManager_)
  49105. {
  49106. // A manager is needed to get the descriptions of commands, and will be called when
  49107. // a command is invoked. So you can't leave this null..
  49108. jassert (commandManager_ != 0);
  49109. Desktop::getInstance().addFocusChangeListener (this);
  49110. }
  49111. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  49112. : commandManager (other.commandManager)
  49113. {
  49114. Desktop::getInstance().addFocusChangeListener (this);
  49115. }
  49116. KeyPressMappingSet::~KeyPressMappingSet()
  49117. {
  49118. Desktop::getInstance().removeFocusChangeListener (this);
  49119. }
  49120. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  49121. {
  49122. for (int i = 0; i < mappings.size(); ++i)
  49123. if (mappings.getUnchecked(i)->commandID == commandID)
  49124. return mappings.getUnchecked (i)->keypresses;
  49125. return Array <KeyPress> ();
  49126. }
  49127. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  49128. const KeyPress& newKeyPress,
  49129. int insertIndex)
  49130. {
  49131. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  49132. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  49133. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  49134. && ! newKeyPress.getModifiers().isShiftDown()));
  49135. if (findCommandForKeyPress (newKeyPress) != commandID)
  49136. {
  49137. removeKeyPress (newKeyPress);
  49138. if (newKeyPress.isValid())
  49139. {
  49140. for (int i = mappings.size(); --i >= 0;)
  49141. {
  49142. if (mappings.getUnchecked(i)->commandID == commandID)
  49143. {
  49144. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  49145. sendChangeMessage (this);
  49146. return;
  49147. }
  49148. }
  49149. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49150. if (ci != 0)
  49151. {
  49152. CommandMapping* const cm = new CommandMapping();
  49153. cm->commandID = commandID;
  49154. cm->keypresses.add (newKeyPress);
  49155. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  49156. mappings.add (cm);
  49157. sendChangeMessage (this);
  49158. }
  49159. }
  49160. }
  49161. }
  49162. void KeyPressMappingSet::resetToDefaultMappings()
  49163. {
  49164. mappings.clear();
  49165. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  49166. {
  49167. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  49168. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49169. {
  49170. addKeyPress (ci->commandID,
  49171. ci->defaultKeypresses.getReference (j));
  49172. }
  49173. }
  49174. sendChangeMessage (this);
  49175. }
  49176. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  49177. {
  49178. clearAllKeyPresses (commandID);
  49179. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49180. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49181. {
  49182. addKeyPress (ci->commandID,
  49183. ci->defaultKeypresses.getReference (j));
  49184. }
  49185. }
  49186. void KeyPressMappingSet::clearAllKeyPresses()
  49187. {
  49188. if (mappings.size() > 0)
  49189. {
  49190. sendChangeMessage (this);
  49191. mappings.clear();
  49192. }
  49193. }
  49194. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  49195. {
  49196. for (int i = mappings.size(); --i >= 0;)
  49197. {
  49198. if (mappings.getUnchecked(i)->commandID == commandID)
  49199. {
  49200. mappings.remove (i);
  49201. sendChangeMessage (this);
  49202. }
  49203. }
  49204. }
  49205. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  49206. {
  49207. if (keypress.isValid())
  49208. {
  49209. for (int i = mappings.size(); --i >= 0;)
  49210. {
  49211. CommandMapping* const cm = mappings.getUnchecked(i);
  49212. for (int j = cm->keypresses.size(); --j >= 0;)
  49213. {
  49214. if (keypress == cm->keypresses [j])
  49215. {
  49216. cm->keypresses.remove (j);
  49217. sendChangeMessage (this);
  49218. }
  49219. }
  49220. }
  49221. }
  49222. }
  49223. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  49224. {
  49225. for (int i = mappings.size(); --i >= 0;)
  49226. {
  49227. if (mappings.getUnchecked(i)->commandID == commandID)
  49228. {
  49229. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  49230. sendChangeMessage (this);
  49231. break;
  49232. }
  49233. }
  49234. }
  49235. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  49236. {
  49237. for (int i = 0; i < mappings.size(); ++i)
  49238. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49239. return mappings.getUnchecked(i)->commandID;
  49240. return 0;
  49241. }
  49242. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49243. {
  49244. for (int i = mappings.size(); --i >= 0;)
  49245. if (mappings.getUnchecked(i)->commandID == commandID)
  49246. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49247. return false;
  49248. }
  49249. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49250. const KeyPress& key,
  49251. const bool isKeyDown,
  49252. const int millisecsSinceKeyPressed,
  49253. Component* const originatingComponent) const
  49254. {
  49255. ApplicationCommandTarget::InvocationInfo info (commandID);
  49256. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49257. info.isKeyDown = isKeyDown;
  49258. info.keyPress = key;
  49259. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49260. info.originatingComponent = originatingComponent;
  49261. commandManager->invoke (info, false);
  49262. }
  49263. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49264. {
  49265. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49266. {
  49267. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49268. {
  49269. // if the XML was created as a set of differences from the default mappings,
  49270. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49271. resetToDefaultMappings();
  49272. }
  49273. else
  49274. {
  49275. // if the XML was created calling createXml (false), then we need to clear all
  49276. // the keys and treat the xml as describing the entire set of mappings.
  49277. clearAllKeyPresses();
  49278. }
  49279. forEachXmlChildElement (xmlVersion, map)
  49280. {
  49281. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49282. if (commandId != 0)
  49283. {
  49284. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49285. if (map->hasTagName ("MAPPING"))
  49286. {
  49287. addKeyPress (commandId, key);
  49288. }
  49289. else if (map->hasTagName ("UNMAPPING"))
  49290. {
  49291. if (containsMapping (commandId, key))
  49292. removeKeyPress (key);
  49293. }
  49294. }
  49295. }
  49296. return true;
  49297. }
  49298. return false;
  49299. }
  49300. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49301. {
  49302. ScopedPointer <KeyPressMappingSet> defaultSet;
  49303. if (saveDifferencesFromDefaultSet)
  49304. {
  49305. defaultSet = new KeyPressMappingSet (commandManager);
  49306. defaultSet->resetToDefaultMappings();
  49307. }
  49308. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49309. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49310. int i;
  49311. for (i = 0; i < mappings.size(); ++i)
  49312. {
  49313. const CommandMapping* const cm = mappings.getUnchecked(i);
  49314. for (int j = 0; j < cm->keypresses.size(); ++j)
  49315. {
  49316. if (defaultSet == 0
  49317. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49318. {
  49319. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49320. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49321. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49322. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49323. }
  49324. }
  49325. }
  49326. if (defaultSet != 0)
  49327. {
  49328. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49329. {
  49330. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49331. for (int j = 0; j < cm->keypresses.size(); ++j)
  49332. {
  49333. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49334. {
  49335. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49336. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49337. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49338. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49339. }
  49340. }
  49341. }
  49342. }
  49343. return doc;
  49344. }
  49345. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49346. Component* originatingComponent)
  49347. {
  49348. bool used = false;
  49349. const CommandID commandID = findCommandForKeyPress (key);
  49350. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49351. if (ci != 0
  49352. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49353. {
  49354. ApplicationCommandInfo info (0);
  49355. if (commandManager->getTargetForCommand (commandID, info) != 0
  49356. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49357. {
  49358. invokeCommand (commandID, key, true, 0, originatingComponent);
  49359. used = true;
  49360. }
  49361. else
  49362. {
  49363. if (originatingComponent != 0)
  49364. originatingComponent->getLookAndFeel().playAlertSound();
  49365. }
  49366. }
  49367. return used;
  49368. }
  49369. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49370. {
  49371. bool used = false;
  49372. const uint32 now = Time::getMillisecondCounter();
  49373. for (int i = mappings.size(); --i >= 0;)
  49374. {
  49375. CommandMapping* const cm = mappings.getUnchecked(i);
  49376. if (cm->wantsKeyUpDownCallbacks)
  49377. {
  49378. for (int j = cm->keypresses.size(); --j >= 0;)
  49379. {
  49380. const KeyPress key (cm->keypresses.getReference (j));
  49381. const bool isDown = key.isCurrentlyDown();
  49382. int keyPressEntryIndex = 0;
  49383. bool wasDown = false;
  49384. for (int k = keysDown.size(); --k >= 0;)
  49385. {
  49386. if (key == keysDown.getUnchecked(k)->key)
  49387. {
  49388. keyPressEntryIndex = k;
  49389. wasDown = true;
  49390. used = true;
  49391. break;
  49392. }
  49393. }
  49394. if (isDown != wasDown)
  49395. {
  49396. int millisecs = 0;
  49397. if (isDown)
  49398. {
  49399. KeyPressTime* const k = new KeyPressTime();
  49400. k->key = key;
  49401. k->timeWhenPressed = now;
  49402. keysDown.add (k);
  49403. }
  49404. else
  49405. {
  49406. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49407. if (now > pressTime)
  49408. millisecs = now - pressTime;
  49409. keysDown.remove (keyPressEntryIndex);
  49410. }
  49411. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49412. used = true;
  49413. }
  49414. }
  49415. }
  49416. }
  49417. return used;
  49418. }
  49419. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49420. {
  49421. if (focusedComponent != 0)
  49422. focusedComponent->keyStateChanged (false);
  49423. }
  49424. END_JUCE_NAMESPACE
  49425. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49426. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49427. BEGIN_JUCE_NAMESPACE
  49428. ModifierKeys::ModifierKeys (const int flags_) throw()
  49429. : flags (flags_)
  49430. {
  49431. }
  49432. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49433. : flags (other.flags)
  49434. {
  49435. }
  49436. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49437. {
  49438. flags = other.flags;
  49439. return *this;
  49440. }
  49441. ModifierKeys ModifierKeys::currentModifiers;
  49442. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49443. {
  49444. return currentModifiers;
  49445. }
  49446. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49447. {
  49448. int num = 0;
  49449. if (isLeftButtonDown()) ++num;
  49450. if (isRightButtonDown()) ++num;
  49451. if (isMiddleButtonDown()) ++num;
  49452. return num;
  49453. }
  49454. END_JUCE_NAMESPACE
  49455. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49456. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49457. BEGIN_JUCE_NAMESPACE
  49458. class ComponentAnimator::AnimationTask
  49459. {
  49460. public:
  49461. AnimationTask (Component* const comp)
  49462. : component (comp)
  49463. {
  49464. }
  49465. bool useTimeslice (const int elapsed)
  49466. {
  49467. if (component == 0)
  49468. return false;
  49469. msElapsed += elapsed;
  49470. double newProgress = msElapsed / (double) msTotal;
  49471. if (newProgress >= 0 && newProgress < 1.0)
  49472. {
  49473. newProgress = timeToDistance (newProgress);
  49474. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49475. jassert (newProgress >= lastProgress);
  49476. lastProgress = newProgress;
  49477. left += (destination.getX() - left) * delta;
  49478. top += (destination.getY() - top) * delta;
  49479. right += (destination.getRight() - right) * delta;
  49480. bottom += (destination.getBottom() - bottom) * delta;
  49481. if (delta < 1.0)
  49482. {
  49483. const Rectangle<int> newBounds (roundToInt (left),
  49484. roundToInt (top),
  49485. roundToInt (right - left),
  49486. roundToInt (bottom - top));
  49487. if (newBounds != destination)
  49488. {
  49489. component->setBounds (newBounds);
  49490. return true;
  49491. }
  49492. }
  49493. }
  49494. component->setBounds (destination);
  49495. return false;
  49496. }
  49497. void moveToFinalDestination()
  49498. {
  49499. if (component != 0)
  49500. component->setBounds (destination);
  49501. }
  49502. Component::SafePointer<Component> component;
  49503. Rectangle<int> destination;
  49504. int msElapsed, msTotal;
  49505. double startSpeed, midSpeed, endSpeed, lastProgress;
  49506. double left, top, right, bottom;
  49507. private:
  49508. inline double timeToDistance (const double time) const
  49509. {
  49510. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49511. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49512. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49513. }
  49514. };
  49515. ComponentAnimator::ComponentAnimator()
  49516. : lastTime (0)
  49517. {
  49518. }
  49519. ComponentAnimator::~ComponentAnimator()
  49520. {
  49521. }
  49522. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49523. {
  49524. for (int i = tasks.size(); --i >= 0;)
  49525. if (component == tasks.getUnchecked(i)->component.getComponent())
  49526. return tasks.getUnchecked(i);
  49527. return 0;
  49528. }
  49529. void ComponentAnimator::animateComponent (Component* const component,
  49530. const Rectangle<int>& finalPosition,
  49531. const int millisecondsToSpendMoving,
  49532. const double startSpeed,
  49533. const double endSpeed)
  49534. {
  49535. if (component != 0)
  49536. {
  49537. AnimationTask* at = findTaskFor (component);
  49538. if (at == 0)
  49539. {
  49540. at = new AnimationTask (component);
  49541. tasks.add (at);
  49542. sendChangeMessage (this);
  49543. }
  49544. at->msElapsed = 0;
  49545. at->lastProgress = 0;
  49546. at->msTotal = jmax (1, millisecondsToSpendMoving);
  49547. at->destination = finalPosition;
  49548. // the speeds must be 0 or greater!
  49549. jassert (startSpeed >= 0 && endSpeed >= 0)
  49550. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  49551. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  49552. at->midSpeed = invTotalDistance;
  49553. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  49554. at->left = component->getX();
  49555. at->top = component->getY();
  49556. at->right = component->getRight();
  49557. at->bottom = component->getBottom();
  49558. if (! isTimerRunning())
  49559. {
  49560. lastTime = Time::getMillisecondCounter();
  49561. startTimer (1000 / 50);
  49562. }
  49563. }
  49564. }
  49565. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49566. {
  49567. if (tasks.size() > 0)
  49568. {
  49569. if (moveComponentsToTheirFinalPositions)
  49570. for (int i = tasks.size(); --i >= 0;)
  49571. tasks.getUnchecked(i)->moveToFinalDestination();
  49572. tasks.clear();
  49573. sendChangeMessage (this);
  49574. }
  49575. }
  49576. void ComponentAnimator::cancelAnimation (Component* const component,
  49577. const bool moveComponentToItsFinalPosition)
  49578. {
  49579. AnimationTask* const at = findTaskFor (component);
  49580. if (at != 0)
  49581. {
  49582. if (moveComponentToItsFinalPosition)
  49583. at->moveToFinalDestination();
  49584. tasks.removeObject (at);
  49585. sendChangeMessage (this);
  49586. }
  49587. }
  49588. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49589. {
  49590. AnimationTask* const at = findTaskFor (component);
  49591. if (at != 0)
  49592. return at->destination;
  49593. else if (component != 0)
  49594. return component->getBounds();
  49595. return Rectangle<int>();
  49596. }
  49597. bool ComponentAnimator::isAnimating (Component* component) const
  49598. {
  49599. return findTaskFor (component) != 0;
  49600. }
  49601. void ComponentAnimator::timerCallback()
  49602. {
  49603. const uint32 timeNow = Time::getMillisecondCounter();
  49604. if (lastTime == 0 || lastTime == timeNow)
  49605. lastTime = timeNow;
  49606. const int elapsed = timeNow - lastTime;
  49607. for (int i = tasks.size(); --i >= 0;)
  49608. {
  49609. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49610. {
  49611. tasks.remove (i);
  49612. sendChangeMessage (this);
  49613. }
  49614. }
  49615. lastTime = timeNow;
  49616. if (tasks.size() == 0)
  49617. stopTimer();
  49618. }
  49619. END_JUCE_NAMESPACE
  49620. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49621. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49622. BEGIN_JUCE_NAMESPACE
  49623. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49624. : minW (0),
  49625. maxW (0x3fffffff),
  49626. minH (0),
  49627. maxH (0x3fffffff),
  49628. minOffTop (0),
  49629. minOffLeft (0),
  49630. minOffBottom (0),
  49631. minOffRight (0),
  49632. aspectRatio (0.0)
  49633. {
  49634. }
  49635. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49636. {
  49637. }
  49638. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49639. {
  49640. minW = minimumWidth;
  49641. }
  49642. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49643. {
  49644. maxW = maximumWidth;
  49645. }
  49646. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49647. {
  49648. minH = minimumHeight;
  49649. }
  49650. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49651. {
  49652. maxH = maximumHeight;
  49653. }
  49654. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49655. {
  49656. jassert (maxW >= minimumWidth);
  49657. jassert (maxH >= minimumHeight);
  49658. jassert (minimumWidth > 0 && minimumHeight > 0);
  49659. minW = minimumWidth;
  49660. minH = minimumHeight;
  49661. if (minW > maxW)
  49662. maxW = minW;
  49663. if (minH > maxH)
  49664. maxH = minH;
  49665. }
  49666. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49667. {
  49668. jassert (maximumWidth >= minW);
  49669. jassert (maximumHeight >= minH);
  49670. jassert (maximumWidth > 0 && maximumHeight > 0);
  49671. maxW = jmax (minW, maximumWidth);
  49672. maxH = jmax (minH, maximumHeight);
  49673. }
  49674. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49675. const int minimumHeight,
  49676. const int maximumWidth,
  49677. const int maximumHeight) throw()
  49678. {
  49679. jassert (maximumWidth >= minimumWidth);
  49680. jassert (maximumHeight >= minimumHeight);
  49681. jassert (maximumWidth > 0 && maximumHeight > 0);
  49682. jassert (minimumWidth > 0 && minimumHeight > 0);
  49683. minW = jmax (0, minimumWidth);
  49684. minH = jmax (0, minimumHeight);
  49685. maxW = jmax (minW, maximumWidth);
  49686. maxH = jmax (minH, maximumHeight);
  49687. }
  49688. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49689. const int minimumWhenOffTheLeft,
  49690. const int minimumWhenOffTheBottom,
  49691. const int minimumWhenOffTheRight) throw()
  49692. {
  49693. minOffTop = minimumWhenOffTheTop;
  49694. minOffLeft = minimumWhenOffTheLeft;
  49695. minOffBottom = minimumWhenOffTheBottom;
  49696. minOffRight = minimumWhenOffTheRight;
  49697. }
  49698. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49699. {
  49700. aspectRatio = jmax (0.0, widthOverHeight);
  49701. }
  49702. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49703. {
  49704. return aspectRatio;
  49705. }
  49706. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49707. const Rectangle<int>& targetBounds,
  49708. const bool isStretchingTop,
  49709. const bool isStretchingLeft,
  49710. const bool isStretchingBottom,
  49711. const bool isStretchingRight)
  49712. {
  49713. jassert (component != 0);
  49714. Rectangle<int> limits, bounds (targetBounds);
  49715. BorderSize border;
  49716. Component* const parent = component->getParentComponent();
  49717. if (parent == 0)
  49718. {
  49719. ComponentPeer* peer = component->getPeer();
  49720. if (peer != 0)
  49721. border = peer->getFrameSize();
  49722. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49723. }
  49724. else
  49725. {
  49726. limits.setSize (parent->getWidth(), parent->getHeight());
  49727. }
  49728. border.addTo (bounds);
  49729. checkBounds (bounds,
  49730. border.addedTo (component->getBounds()), limits,
  49731. isStretchingTop, isStretchingLeft,
  49732. isStretchingBottom, isStretchingRight);
  49733. border.subtractFrom (bounds);
  49734. applyBoundsToComponent (component, bounds);
  49735. }
  49736. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49737. {
  49738. setBoundsForComponent (component, component->getBounds(),
  49739. false, false, false, false);
  49740. }
  49741. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49742. const Rectangle<int>& bounds)
  49743. {
  49744. component->setBounds (bounds);
  49745. }
  49746. void ComponentBoundsConstrainer::resizeStart()
  49747. {
  49748. }
  49749. void ComponentBoundsConstrainer::resizeEnd()
  49750. {
  49751. }
  49752. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49753. const Rectangle<int>& old,
  49754. const Rectangle<int>& limits,
  49755. const bool isStretchingTop,
  49756. const bool isStretchingLeft,
  49757. const bool isStretchingBottom,
  49758. const bool isStretchingRight)
  49759. {
  49760. int x = bounds.getX();
  49761. int y = bounds.getY();
  49762. int w = bounds.getWidth();
  49763. int h = bounds.getHeight();
  49764. // constrain the size if it's being stretched..
  49765. if (isStretchingLeft)
  49766. {
  49767. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  49768. w = old.getRight() - x;
  49769. }
  49770. if (isStretchingRight)
  49771. {
  49772. w = jlimit (minW, maxW, w);
  49773. }
  49774. if (isStretchingTop)
  49775. {
  49776. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  49777. h = old.getBottom() - y;
  49778. }
  49779. if (isStretchingBottom)
  49780. {
  49781. h = jlimit (minH, maxH, h);
  49782. }
  49783. // constrain the aspect ratio if one has been specified..
  49784. if (aspectRatio > 0.0 && w > 0 && h > 0)
  49785. {
  49786. bool adjustWidth;
  49787. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49788. {
  49789. adjustWidth = true;
  49790. }
  49791. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49792. {
  49793. adjustWidth = false;
  49794. }
  49795. else
  49796. {
  49797. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49798. const double newRatio = std::abs (w / (double) h);
  49799. adjustWidth = (oldRatio > newRatio);
  49800. }
  49801. if (adjustWidth)
  49802. {
  49803. w = roundToInt (h * aspectRatio);
  49804. if (w > maxW || w < minW)
  49805. {
  49806. w = jlimit (minW, maxW, w);
  49807. h = roundToInt (w / aspectRatio);
  49808. }
  49809. }
  49810. else
  49811. {
  49812. h = roundToInt (w / aspectRatio);
  49813. if (h > maxH || h < minH)
  49814. {
  49815. h = jlimit (minH, maxH, h);
  49816. w = roundToInt (h * aspectRatio);
  49817. }
  49818. }
  49819. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49820. {
  49821. x = old.getX() + (old.getWidth() - w) / 2;
  49822. }
  49823. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49824. {
  49825. y = old.getY() + (old.getHeight() - h) / 2;
  49826. }
  49827. else
  49828. {
  49829. if (isStretchingLeft)
  49830. x = old.getRight() - w;
  49831. if (isStretchingTop)
  49832. y = old.getBottom() - h;
  49833. }
  49834. }
  49835. // ...and constrain the position if limits have been set for that.
  49836. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  49837. {
  49838. if (minOffTop > 0)
  49839. {
  49840. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  49841. if (y < limit)
  49842. {
  49843. if (isStretchingTop)
  49844. h -= (limit - y);
  49845. y = limit;
  49846. }
  49847. }
  49848. if (minOffLeft > 0)
  49849. {
  49850. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  49851. if (x < limit)
  49852. {
  49853. if (isStretchingLeft)
  49854. w -= (limit - x);
  49855. x = limit;
  49856. }
  49857. }
  49858. if (minOffBottom > 0)
  49859. {
  49860. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  49861. if (y > limit)
  49862. {
  49863. if (isStretchingBottom)
  49864. h += (limit - y);
  49865. else
  49866. y = limit;
  49867. }
  49868. }
  49869. if (minOffRight > 0)
  49870. {
  49871. const int limit = limits.getRight() - jmin (minOffRight, w);
  49872. if (x > limit)
  49873. {
  49874. if (isStretchingRight)
  49875. w += (limit - x);
  49876. else
  49877. x = limit;
  49878. }
  49879. }
  49880. }
  49881. jassert (w >= 0 && h >= 0);
  49882. bounds = Rectangle<int> (x, y, w, h);
  49883. }
  49884. END_JUCE_NAMESPACE
  49885. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49886. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49887. BEGIN_JUCE_NAMESPACE
  49888. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49889. : component (component_),
  49890. lastPeer (0),
  49891. reentrant (false)
  49892. {
  49893. jassert (component != 0); // can't use this with a null pointer..
  49894. component->addComponentListener (this);
  49895. registerWithParentComps();
  49896. }
  49897. ComponentMovementWatcher::~ComponentMovementWatcher()
  49898. {
  49899. component->removeComponentListener (this);
  49900. unregister();
  49901. }
  49902. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49903. {
  49904. // agh! don't delete the target component without deleting this object first!
  49905. jassert (component != 0);
  49906. if (! reentrant)
  49907. {
  49908. reentrant = true;
  49909. ComponentPeer* const peer = component->getPeer();
  49910. if (peer != lastPeer)
  49911. {
  49912. componentPeerChanged();
  49913. if (component == 0)
  49914. return;
  49915. lastPeer = peer;
  49916. }
  49917. unregister();
  49918. registerWithParentComps();
  49919. reentrant = false;
  49920. componentMovedOrResized (*component, true, true);
  49921. }
  49922. }
  49923. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49924. {
  49925. // agh! don't delete the target component without deleting this object first!
  49926. jassert (component != 0);
  49927. if (wasMoved)
  49928. {
  49929. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  49930. wasMoved = lastBounds.getPosition() != pos;
  49931. lastBounds.setPosition (pos);
  49932. }
  49933. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49934. lastBounds.setSize (component->getWidth(), component->getHeight());
  49935. if (wasMoved || wasResized)
  49936. componentMovedOrResized (wasMoved, wasResized);
  49937. }
  49938. void ComponentMovementWatcher::registerWithParentComps()
  49939. {
  49940. Component* p = component->getParentComponent();
  49941. while (p != 0)
  49942. {
  49943. p->addComponentListener (this);
  49944. registeredParentComps.add (p);
  49945. p = p->getParentComponent();
  49946. }
  49947. }
  49948. void ComponentMovementWatcher::unregister()
  49949. {
  49950. for (int i = registeredParentComps.size(); --i >= 0;)
  49951. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49952. registeredParentComps.clear();
  49953. }
  49954. END_JUCE_NAMESPACE
  49955. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49956. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49957. BEGIN_JUCE_NAMESPACE
  49958. GroupComponent::GroupComponent (const String& componentName,
  49959. const String& labelText)
  49960. : Component (componentName),
  49961. text (labelText),
  49962. justification (Justification::left)
  49963. {
  49964. setInterceptsMouseClicks (false, true);
  49965. }
  49966. GroupComponent::~GroupComponent()
  49967. {
  49968. }
  49969. void GroupComponent::setText (const String& newText)
  49970. {
  49971. if (text != newText)
  49972. {
  49973. text = newText;
  49974. repaint();
  49975. }
  49976. }
  49977. const String GroupComponent::getText() const
  49978. {
  49979. return text;
  49980. }
  49981. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49982. {
  49983. if (justification != newJustification)
  49984. {
  49985. justification = newJustification;
  49986. repaint();
  49987. }
  49988. }
  49989. void GroupComponent::paint (Graphics& g)
  49990. {
  49991. getLookAndFeel()
  49992. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49993. text, justification,
  49994. *this);
  49995. }
  49996. void GroupComponent::enablementChanged()
  49997. {
  49998. repaint();
  49999. }
  50000. void GroupComponent::colourChanged()
  50001. {
  50002. repaint();
  50003. }
  50004. END_JUCE_NAMESPACE
  50005. /*** End of inlined file: juce_GroupComponent.cpp ***/
  50006. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  50007. BEGIN_JUCE_NAMESPACE
  50008. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  50009. : DocumentWindow (String::empty, backgroundColour,
  50010. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  50011. {
  50012. }
  50013. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  50014. {
  50015. }
  50016. void MultiDocumentPanelWindow::maximiseButtonPressed()
  50017. {
  50018. MultiDocumentPanel* const owner = getOwner();
  50019. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50020. if (owner != 0)
  50021. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  50022. }
  50023. void MultiDocumentPanelWindow::closeButtonPressed()
  50024. {
  50025. MultiDocumentPanel* const owner = getOwner();
  50026. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50027. if (owner != 0)
  50028. owner->closeDocument (getContentComponent(), true);
  50029. }
  50030. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  50031. {
  50032. DocumentWindow::activeWindowStatusChanged();
  50033. updateOrder();
  50034. }
  50035. void MultiDocumentPanelWindow::broughtToFront()
  50036. {
  50037. DocumentWindow::broughtToFront();
  50038. updateOrder();
  50039. }
  50040. void MultiDocumentPanelWindow::updateOrder()
  50041. {
  50042. MultiDocumentPanel* const owner = getOwner();
  50043. if (owner != 0)
  50044. owner->updateOrder();
  50045. }
  50046. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  50047. {
  50048. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50049. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50050. }
  50051. class MDITabbedComponentInternal : public TabbedComponent
  50052. {
  50053. public:
  50054. MDITabbedComponentInternal()
  50055. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  50056. {
  50057. }
  50058. ~MDITabbedComponentInternal()
  50059. {
  50060. }
  50061. void currentTabChanged (int, const String&)
  50062. {
  50063. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50064. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50065. if (owner != 0)
  50066. owner->updateOrder();
  50067. }
  50068. };
  50069. MultiDocumentPanel::MultiDocumentPanel()
  50070. : mode (MaximisedWindowsWithTabs),
  50071. backgroundColour (Colours::lightblue),
  50072. maximumNumDocuments (0),
  50073. numDocsBeforeTabsUsed (0)
  50074. {
  50075. setOpaque (true);
  50076. }
  50077. MultiDocumentPanel::~MultiDocumentPanel()
  50078. {
  50079. closeAllDocuments (false);
  50080. }
  50081. static bool shouldDeleteComp (Component* const c)
  50082. {
  50083. return c->getProperties() ["mdiDocumentDelete_"];
  50084. }
  50085. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  50086. {
  50087. while (components.size() > 0)
  50088. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  50089. return false;
  50090. return true;
  50091. }
  50092. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50093. {
  50094. return new MultiDocumentPanelWindow (backgroundColour);
  50095. }
  50096. void MultiDocumentPanel::addWindow (Component* component)
  50097. {
  50098. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50099. dw->setResizable (true, false);
  50100. dw->setContentComponent (component, false, true);
  50101. dw->setName (component->getName());
  50102. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50103. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50104. int x = 4;
  50105. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50106. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50107. x += 16;
  50108. dw->setTopLeftPosition (x, x);
  50109. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50110. if (pos.toString().isNotEmpty())
  50111. dw->restoreWindowStateFromString (pos.toString());
  50112. addAndMakeVisible (dw);
  50113. dw->toFront (true);
  50114. }
  50115. bool MultiDocumentPanel::addDocument (Component* const component,
  50116. const Colour& docColour,
  50117. const bool deleteWhenRemoved)
  50118. {
  50119. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50120. // with a frame-within-a-frame! Just pass in the bare content component.
  50121. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50122. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50123. return false;
  50124. components.add (component);
  50125. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50126. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50127. component->addComponentListener (this);
  50128. if (mode == FloatingWindows)
  50129. {
  50130. if (isFullscreenWhenOneDocument())
  50131. {
  50132. if (components.size() == 1)
  50133. {
  50134. addAndMakeVisible (component);
  50135. }
  50136. else
  50137. {
  50138. if (components.size() == 2)
  50139. addWindow (components.getFirst());
  50140. addWindow (component);
  50141. }
  50142. }
  50143. else
  50144. {
  50145. addWindow (component);
  50146. }
  50147. }
  50148. else
  50149. {
  50150. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50151. {
  50152. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50153. Array <Component*> temp (components);
  50154. for (int i = 0; i < temp.size(); ++i)
  50155. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50156. resized();
  50157. }
  50158. else
  50159. {
  50160. if (tabComponent != 0)
  50161. tabComponent->addTab (component->getName(), docColour, component, false);
  50162. else
  50163. addAndMakeVisible (component);
  50164. }
  50165. setActiveDocument (component);
  50166. }
  50167. resized();
  50168. activeDocumentChanged();
  50169. return true;
  50170. }
  50171. bool MultiDocumentPanel::closeDocument (Component* component,
  50172. const bool checkItsOkToCloseFirst)
  50173. {
  50174. if (components.contains (component))
  50175. {
  50176. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50177. return false;
  50178. component->removeComponentListener (this);
  50179. const bool shouldDelete = shouldDeleteComp (component);
  50180. component->getProperties().remove ("mdiDocumentDelete_");
  50181. component->getProperties().remove ("mdiDocumentBkg_");
  50182. if (mode == FloatingWindows)
  50183. {
  50184. for (int i = getNumChildComponents(); --i >= 0;)
  50185. {
  50186. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50187. if (dw != 0 && dw->getContentComponent() == component)
  50188. {
  50189. dw->setContentComponent (0, false);
  50190. delete dw;
  50191. break;
  50192. }
  50193. }
  50194. if (shouldDelete)
  50195. delete component;
  50196. components.removeValue (component);
  50197. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50198. {
  50199. for (int i = getNumChildComponents(); --i >= 0;)
  50200. {
  50201. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50202. if (dw != 0)
  50203. {
  50204. dw->setContentComponent (0, false);
  50205. delete dw;
  50206. }
  50207. }
  50208. addAndMakeVisible (components.getFirst());
  50209. }
  50210. }
  50211. else
  50212. {
  50213. jassert (components.indexOf (component) >= 0);
  50214. if (tabComponent != 0)
  50215. {
  50216. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50217. if (tabComponent->getTabContentComponent (i) == component)
  50218. tabComponent->removeTab (i);
  50219. }
  50220. else
  50221. {
  50222. removeChildComponent (component);
  50223. }
  50224. if (shouldDelete)
  50225. delete component;
  50226. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50227. tabComponent = 0;
  50228. components.removeValue (component);
  50229. if (components.size() > 0 && tabComponent == 0)
  50230. addAndMakeVisible (components.getFirst());
  50231. }
  50232. resized();
  50233. activeDocumentChanged();
  50234. }
  50235. else
  50236. {
  50237. jassertfalse;
  50238. }
  50239. return true;
  50240. }
  50241. int MultiDocumentPanel::getNumDocuments() const throw()
  50242. {
  50243. return components.size();
  50244. }
  50245. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50246. {
  50247. return components [index];
  50248. }
  50249. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50250. {
  50251. if (mode == FloatingWindows)
  50252. {
  50253. for (int i = getNumChildComponents(); --i >= 0;)
  50254. {
  50255. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50256. if (dw != 0 && dw->isActiveWindow())
  50257. return dw->getContentComponent();
  50258. }
  50259. }
  50260. return components.getLast();
  50261. }
  50262. void MultiDocumentPanel::setActiveDocument (Component* component)
  50263. {
  50264. if (mode == FloatingWindows)
  50265. {
  50266. component = getContainerComp (component);
  50267. if (component != 0)
  50268. component->toFront (true);
  50269. }
  50270. else if (tabComponent != 0)
  50271. {
  50272. jassert (components.indexOf (component) >= 0);
  50273. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50274. {
  50275. if (tabComponent->getTabContentComponent (i) == component)
  50276. {
  50277. tabComponent->setCurrentTabIndex (i);
  50278. break;
  50279. }
  50280. }
  50281. }
  50282. else
  50283. {
  50284. component->grabKeyboardFocus();
  50285. }
  50286. }
  50287. void MultiDocumentPanel::activeDocumentChanged()
  50288. {
  50289. }
  50290. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50291. {
  50292. maximumNumDocuments = newNumber;
  50293. }
  50294. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50295. {
  50296. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50297. }
  50298. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50299. {
  50300. return numDocsBeforeTabsUsed != 0;
  50301. }
  50302. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50303. {
  50304. if (mode != newLayoutMode)
  50305. {
  50306. mode = newLayoutMode;
  50307. if (mode == FloatingWindows)
  50308. {
  50309. tabComponent = 0;
  50310. }
  50311. else
  50312. {
  50313. for (int i = getNumChildComponents(); --i >= 0;)
  50314. {
  50315. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50316. if (dw != 0)
  50317. {
  50318. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50319. dw->setContentComponent (0, false);
  50320. delete dw;
  50321. }
  50322. }
  50323. }
  50324. resized();
  50325. const Array <Component*> tempComps (components);
  50326. components.clear();
  50327. for (int i = 0; i < tempComps.size(); ++i)
  50328. {
  50329. Component* const c = tempComps.getUnchecked(i);
  50330. addDocument (c,
  50331. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50332. shouldDeleteComp (c));
  50333. }
  50334. }
  50335. }
  50336. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50337. {
  50338. if (backgroundColour != newBackgroundColour)
  50339. {
  50340. backgroundColour = newBackgroundColour;
  50341. setOpaque (newBackgroundColour.isOpaque());
  50342. repaint();
  50343. }
  50344. }
  50345. void MultiDocumentPanel::paint (Graphics& g)
  50346. {
  50347. g.fillAll (backgroundColour);
  50348. }
  50349. void MultiDocumentPanel::resized()
  50350. {
  50351. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50352. {
  50353. for (int i = getNumChildComponents(); --i >= 0;)
  50354. getChildComponent (i)->setBounds (getLocalBounds());
  50355. }
  50356. setWantsKeyboardFocus (components.size() == 0);
  50357. }
  50358. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50359. {
  50360. if (mode == FloatingWindows)
  50361. {
  50362. for (int i = 0; i < getNumChildComponents(); ++i)
  50363. {
  50364. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50365. if (dw != 0 && dw->getContentComponent() == c)
  50366. {
  50367. c = dw;
  50368. break;
  50369. }
  50370. }
  50371. }
  50372. return c;
  50373. }
  50374. void MultiDocumentPanel::componentNameChanged (Component&)
  50375. {
  50376. if (mode == FloatingWindows)
  50377. {
  50378. for (int i = 0; i < getNumChildComponents(); ++i)
  50379. {
  50380. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50381. if (dw != 0)
  50382. dw->setName (dw->getContentComponent()->getName());
  50383. }
  50384. }
  50385. else if (tabComponent != 0)
  50386. {
  50387. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50388. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50389. }
  50390. }
  50391. void MultiDocumentPanel::updateOrder()
  50392. {
  50393. const Array <Component*> oldList (components);
  50394. if (mode == FloatingWindows)
  50395. {
  50396. components.clear();
  50397. for (int i = 0; i < getNumChildComponents(); ++i)
  50398. {
  50399. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50400. if (dw != 0)
  50401. components.add (dw->getContentComponent());
  50402. }
  50403. }
  50404. else
  50405. {
  50406. if (tabComponent != 0)
  50407. {
  50408. Component* const current = tabComponent->getCurrentContentComponent();
  50409. if (current != 0)
  50410. {
  50411. components.removeValue (current);
  50412. components.add (current);
  50413. }
  50414. }
  50415. }
  50416. if (components != oldList)
  50417. activeDocumentChanged();
  50418. }
  50419. END_JUCE_NAMESPACE
  50420. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50421. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50422. BEGIN_JUCE_NAMESPACE
  50423. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  50424. : zone (zoneFlags)
  50425. {
  50426. }
  50427. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  50428. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  50429. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50430. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50431. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50432. const BorderSize& border,
  50433. const Point<int>& position)
  50434. {
  50435. int z = 0;
  50436. if (totalSize.contains (position)
  50437. && ! border.subtractedFrom (totalSize).contains (position))
  50438. {
  50439. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50440. if (position.getX() < jmax (border.getLeft(), minW))
  50441. z |= left;
  50442. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  50443. z |= right;
  50444. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50445. if (position.getY() < jmax (border.getTop(), minH))
  50446. z |= top;
  50447. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  50448. z |= bottom;
  50449. }
  50450. return Zone (z);
  50451. }
  50452. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50453. {
  50454. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50455. switch (zone)
  50456. {
  50457. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50458. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50459. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50460. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50461. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50462. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50463. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50464. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50465. default: break;
  50466. }
  50467. return mc;
  50468. }
  50469. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  50470. {
  50471. if (isDraggingWholeObject())
  50472. return b + offset;
  50473. if (isDraggingLeftEdge())
  50474. b.setLeft (b.getX() + offset.getX());
  50475. if (isDraggingRightEdge())
  50476. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  50477. if (isDraggingTopEdge())
  50478. b.setTop (b.getY() + offset.getY());
  50479. if (isDraggingBottomEdge())
  50480. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  50481. return b;
  50482. }
  50483. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  50484. {
  50485. if (isDraggingWholeObject())
  50486. return b + offset;
  50487. if (isDraggingLeftEdge())
  50488. b.setLeft (b.getX() + offset.getX());
  50489. if (isDraggingRightEdge())
  50490. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  50491. if (isDraggingTopEdge())
  50492. b.setTop (b.getY() + offset.getY());
  50493. if (isDraggingBottomEdge())
  50494. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  50495. return b;
  50496. }
  50497. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50498. ComponentBoundsConstrainer* const constrainer_)
  50499. : component (componentToResize),
  50500. constrainer (constrainer_),
  50501. borderSize (5),
  50502. mouseZone (0)
  50503. {
  50504. }
  50505. ResizableBorderComponent::~ResizableBorderComponent()
  50506. {
  50507. }
  50508. void ResizableBorderComponent::paint (Graphics& g)
  50509. {
  50510. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50511. }
  50512. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50513. {
  50514. updateMouseZone (e);
  50515. }
  50516. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50517. {
  50518. updateMouseZone (e);
  50519. }
  50520. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50521. {
  50522. if (component == 0)
  50523. {
  50524. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50525. return;
  50526. }
  50527. updateMouseZone (e);
  50528. originalBounds = component->getBounds();
  50529. if (constrainer != 0)
  50530. constrainer->resizeStart();
  50531. }
  50532. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50533. {
  50534. if (component == 0)
  50535. {
  50536. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50537. return;
  50538. }
  50539. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50540. if (constrainer != 0)
  50541. constrainer->setBoundsForComponent (component, bounds,
  50542. mouseZone.isDraggingTopEdge(),
  50543. mouseZone.isDraggingLeftEdge(),
  50544. mouseZone.isDraggingBottomEdge(),
  50545. mouseZone.isDraggingRightEdge());
  50546. else
  50547. component->setBounds (bounds);
  50548. }
  50549. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50550. {
  50551. if (constrainer != 0)
  50552. constrainer->resizeEnd();
  50553. }
  50554. bool ResizableBorderComponent::hitTest (int x, int y)
  50555. {
  50556. return x < borderSize.getLeft()
  50557. || x >= getWidth() - borderSize.getRight()
  50558. || y < borderSize.getTop()
  50559. || y >= getHeight() - borderSize.getBottom();
  50560. }
  50561. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50562. {
  50563. if (borderSize != newBorderSize)
  50564. {
  50565. borderSize = newBorderSize;
  50566. repaint();
  50567. }
  50568. }
  50569. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50570. {
  50571. return borderSize;
  50572. }
  50573. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50574. {
  50575. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50576. if (mouseZone != newZone)
  50577. {
  50578. mouseZone = newZone;
  50579. setMouseCursor (newZone.getMouseCursor());
  50580. }
  50581. }
  50582. END_JUCE_NAMESPACE
  50583. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50584. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50585. BEGIN_JUCE_NAMESPACE
  50586. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50587. ComponentBoundsConstrainer* const constrainer_)
  50588. : component (componentToResize),
  50589. constrainer (constrainer_)
  50590. {
  50591. setRepaintsOnMouseActivity (true);
  50592. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50593. }
  50594. ResizableCornerComponent::~ResizableCornerComponent()
  50595. {
  50596. }
  50597. void ResizableCornerComponent::paint (Graphics& g)
  50598. {
  50599. getLookAndFeel()
  50600. .drawCornerResizer (g, getWidth(), getHeight(),
  50601. isMouseOverOrDragging(),
  50602. isMouseButtonDown());
  50603. }
  50604. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50605. {
  50606. if (component == 0)
  50607. {
  50608. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50609. return;
  50610. }
  50611. originalBounds = component->getBounds();
  50612. if (constrainer != 0)
  50613. constrainer->resizeStart();
  50614. }
  50615. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50616. {
  50617. if (component == 0)
  50618. {
  50619. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50620. return;
  50621. }
  50622. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50623. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50624. if (constrainer != 0)
  50625. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50626. else
  50627. component->setBounds (r);
  50628. }
  50629. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50630. {
  50631. if (constrainer != 0)
  50632. constrainer->resizeStart();
  50633. }
  50634. bool ResizableCornerComponent::hitTest (int x, int y)
  50635. {
  50636. if (getWidth() <= 0)
  50637. return false;
  50638. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50639. return y >= yAtX - getHeight() / 4;
  50640. }
  50641. END_JUCE_NAMESPACE
  50642. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50643. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50644. BEGIN_JUCE_NAMESPACE
  50645. class ScrollBar::ScrollbarButton : public Button
  50646. {
  50647. public:
  50648. int direction;
  50649. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50650. : Button (String::empty),
  50651. direction (direction_),
  50652. owner (owner_)
  50653. {
  50654. setWantsKeyboardFocus (false);
  50655. }
  50656. ~ScrollbarButton()
  50657. {
  50658. }
  50659. void paintButton (Graphics& g, bool over, bool down)
  50660. {
  50661. getLookAndFeel()
  50662. .drawScrollbarButton (g, owner,
  50663. getWidth(), getHeight(),
  50664. direction,
  50665. owner.isVertical(),
  50666. over, down);
  50667. }
  50668. void clicked()
  50669. {
  50670. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50671. }
  50672. juce_UseDebuggingNewOperator
  50673. private:
  50674. ScrollBar& owner;
  50675. ScrollbarButton (const ScrollbarButton&);
  50676. ScrollbarButton& operator= (const ScrollbarButton&);
  50677. };
  50678. ScrollBar::ScrollBar (const bool vertical_,
  50679. const bool buttonsAreVisible)
  50680. : totalRange (0.0, 1.0),
  50681. visibleRange (0.0, 0.1),
  50682. singleStepSize (0.1),
  50683. thumbAreaStart (0),
  50684. thumbAreaSize (0),
  50685. thumbStart (0),
  50686. thumbSize (0),
  50687. initialDelayInMillisecs (100),
  50688. repeatDelayInMillisecs (50),
  50689. minimumDelayInMillisecs (10),
  50690. vertical (vertical_),
  50691. isDraggingThumb (false),
  50692. autohides (true)
  50693. {
  50694. setButtonVisibility (buttonsAreVisible);
  50695. setRepaintsOnMouseActivity (true);
  50696. setFocusContainer (true);
  50697. }
  50698. ScrollBar::~ScrollBar()
  50699. {
  50700. upButton = 0;
  50701. downButton = 0;
  50702. }
  50703. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50704. {
  50705. if (totalRange != newRangeLimit)
  50706. {
  50707. totalRange = newRangeLimit;
  50708. setCurrentRange (visibleRange);
  50709. updateThumbPosition();
  50710. }
  50711. }
  50712. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50713. {
  50714. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50715. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50716. }
  50717. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50718. {
  50719. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50720. if (visibleRange != constrainedRange)
  50721. {
  50722. visibleRange = constrainedRange;
  50723. updateThumbPosition();
  50724. triggerAsyncUpdate();
  50725. }
  50726. }
  50727. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50728. {
  50729. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50730. }
  50731. void ScrollBar::setCurrentRangeStart (const double newStart)
  50732. {
  50733. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50734. }
  50735. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50736. {
  50737. singleStepSize = newSingleStepSize;
  50738. }
  50739. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50740. {
  50741. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50742. }
  50743. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50744. {
  50745. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50746. }
  50747. void ScrollBar::scrollToTop()
  50748. {
  50749. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50750. }
  50751. void ScrollBar::scrollToBottom()
  50752. {
  50753. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50754. }
  50755. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50756. const int repeatDelayInMillisecs_,
  50757. const int minimumDelayInMillisecs_)
  50758. {
  50759. initialDelayInMillisecs = initialDelayInMillisecs_;
  50760. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50761. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50762. if (upButton != 0)
  50763. {
  50764. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50765. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50766. }
  50767. }
  50768. void ScrollBar::addListener (Listener* const listener)
  50769. {
  50770. listeners.add (listener);
  50771. }
  50772. void ScrollBar::removeListener (Listener* const listener)
  50773. {
  50774. listeners.remove (listener);
  50775. }
  50776. void ScrollBar::handleAsyncUpdate()
  50777. {
  50778. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50779. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50780. }
  50781. void ScrollBar::updateThumbPosition()
  50782. {
  50783. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50784. : thumbAreaSize);
  50785. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50786. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50787. if (newThumbSize > thumbAreaSize)
  50788. newThumbSize = thumbAreaSize;
  50789. int newThumbStart = thumbAreaStart;
  50790. if (totalRange.getLength() > visibleRange.getLength())
  50791. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50792. / (totalRange.getLength() - visibleRange.getLength()));
  50793. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50794. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50795. {
  50796. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50797. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50798. if (vertical)
  50799. repaint (0, repaintStart, getWidth(), repaintSize);
  50800. else
  50801. repaint (repaintStart, 0, repaintSize, getHeight());
  50802. thumbStart = newThumbStart;
  50803. thumbSize = newThumbSize;
  50804. }
  50805. }
  50806. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50807. {
  50808. if (vertical != shouldBeVertical)
  50809. {
  50810. vertical = shouldBeVertical;
  50811. if (upButton != 0)
  50812. {
  50813. upButton->direction = vertical ? 0 : 3;
  50814. downButton->direction = vertical ? 2 : 1;
  50815. }
  50816. updateThumbPosition();
  50817. }
  50818. }
  50819. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50820. {
  50821. upButton = 0;
  50822. downButton = 0;
  50823. if (buttonsAreVisible)
  50824. {
  50825. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50826. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50827. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50828. }
  50829. updateThumbPosition();
  50830. }
  50831. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50832. {
  50833. autohides = shouldHideWhenFullRange;
  50834. updateThumbPosition();
  50835. }
  50836. bool ScrollBar::autoHides() const throw()
  50837. {
  50838. return autohides;
  50839. }
  50840. void ScrollBar::paint (Graphics& g)
  50841. {
  50842. if (thumbAreaSize > 0)
  50843. {
  50844. LookAndFeel& lf = getLookAndFeel();
  50845. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50846. ? thumbSize : 0;
  50847. if (vertical)
  50848. {
  50849. lf.drawScrollbar (g, *this,
  50850. 0, thumbAreaStart,
  50851. getWidth(), thumbAreaSize,
  50852. vertical,
  50853. thumbStart, thumb,
  50854. isMouseOver(), isMouseButtonDown());
  50855. }
  50856. else
  50857. {
  50858. lf.drawScrollbar (g, *this,
  50859. thumbAreaStart, 0,
  50860. thumbAreaSize, getHeight(),
  50861. vertical,
  50862. thumbStart, thumb,
  50863. isMouseOver(), isMouseButtonDown());
  50864. }
  50865. }
  50866. }
  50867. void ScrollBar::lookAndFeelChanged()
  50868. {
  50869. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50870. }
  50871. void ScrollBar::resized()
  50872. {
  50873. const int length = ((vertical) ? getHeight() : getWidth());
  50874. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50875. : 0;
  50876. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50877. {
  50878. thumbAreaStart = length >> 1;
  50879. thumbAreaSize = 0;
  50880. }
  50881. else
  50882. {
  50883. thumbAreaStart = buttonSize;
  50884. thumbAreaSize = length - (buttonSize << 1);
  50885. }
  50886. if (upButton != 0)
  50887. {
  50888. if (vertical)
  50889. {
  50890. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50891. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50892. }
  50893. else
  50894. {
  50895. upButton->setBounds (0, 0, buttonSize, getHeight());
  50896. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50897. }
  50898. }
  50899. updateThumbPosition();
  50900. }
  50901. void ScrollBar::mouseDown (const MouseEvent& e)
  50902. {
  50903. isDraggingThumb = false;
  50904. lastMousePos = vertical ? e.y : e.x;
  50905. dragStartMousePos = lastMousePos;
  50906. dragStartRange = visibleRange.getStart();
  50907. if (dragStartMousePos < thumbStart)
  50908. {
  50909. moveScrollbarInPages (-1);
  50910. startTimer (400);
  50911. }
  50912. else if (dragStartMousePos >= thumbStart + thumbSize)
  50913. {
  50914. moveScrollbarInPages (1);
  50915. startTimer (400);
  50916. }
  50917. else
  50918. {
  50919. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50920. && (thumbAreaSize > thumbSize);
  50921. }
  50922. }
  50923. void ScrollBar::mouseDrag (const MouseEvent& e)
  50924. {
  50925. if (isDraggingThumb)
  50926. {
  50927. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50928. setCurrentRangeStart (dragStartRange
  50929. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50930. / (thumbAreaSize - thumbSize));
  50931. }
  50932. else
  50933. {
  50934. lastMousePos = (vertical) ? e.y : e.x;
  50935. }
  50936. }
  50937. void ScrollBar::mouseUp (const MouseEvent&)
  50938. {
  50939. isDraggingThumb = false;
  50940. stopTimer();
  50941. repaint();
  50942. }
  50943. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50944. float wheelIncrementX,
  50945. float wheelIncrementY)
  50946. {
  50947. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50948. if (increment < 0)
  50949. increment = jmin (increment * 10.0f, -1.0f);
  50950. else if (increment > 0)
  50951. increment = jmax (increment * 10.0f, 1.0f);
  50952. setCurrentRange (visibleRange - singleStepSize * increment);
  50953. }
  50954. void ScrollBar::timerCallback()
  50955. {
  50956. if (isMouseButtonDown())
  50957. {
  50958. startTimer (40);
  50959. if (lastMousePos < thumbStart)
  50960. setCurrentRange (visibleRange - visibleRange.getLength());
  50961. else if (lastMousePos > thumbStart + thumbSize)
  50962. setCurrentRangeStart (visibleRange.getEnd());
  50963. }
  50964. else
  50965. {
  50966. stopTimer();
  50967. }
  50968. }
  50969. bool ScrollBar::keyPressed (const KeyPress& key)
  50970. {
  50971. if (! isVisible())
  50972. return false;
  50973. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50974. moveScrollbarInSteps (-1);
  50975. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50976. moveScrollbarInSteps (1);
  50977. else if (key.isKeyCode (KeyPress::pageUpKey))
  50978. moveScrollbarInPages (-1);
  50979. else if (key.isKeyCode (KeyPress::pageDownKey))
  50980. moveScrollbarInPages (1);
  50981. else if (key.isKeyCode (KeyPress::homeKey))
  50982. scrollToTop();
  50983. else if (key.isKeyCode (KeyPress::endKey))
  50984. scrollToBottom();
  50985. else
  50986. return false;
  50987. return true;
  50988. }
  50989. END_JUCE_NAMESPACE
  50990. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50991. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50992. BEGIN_JUCE_NAMESPACE
  50993. StretchableLayoutManager::StretchableLayoutManager()
  50994. : totalSize (0)
  50995. {
  50996. }
  50997. StretchableLayoutManager::~StretchableLayoutManager()
  50998. {
  50999. }
  51000. void StretchableLayoutManager::clearAllItems()
  51001. {
  51002. items.clear();
  51003. totalSize = 0;
  51004. }
  51005. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  51006. const double minimumSize,
  51007. const double maximumSize,
  51008. const double preferredSize)
  51009. {
  51010. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  51011. if (layout == 0)
  51012. {
  51013. layout = new ItemLayoutProperties();
  51014. layout->itemIndex = itemIndex;
  51015. int i;
  51016. for (i = 0; i < items.size(); ++i)
  51017. if (items.getUnchecked (i)->itemIndex > itemIndex)
  51018. break;
  51019. items.insert (i, layout);
  51020. }
  51021. layout->minSize = minimumSize;
  51022. layout->maxSize = maximumSize;
  51023. layout->preferredSize = preferredSize;
  51024. layout->currentSize = 0;
  51025. }
  51026. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  51027. double& minimumSize,
  51028. double& maximumSize,
  51029. double& preferredSize) const
  51030. {
  51031. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51032. if (layout != 0)
  51033. {
  51034. minimumSize = layout->minSize;
  51035. maximumSize = layout->maxSize;
  51036. preferredSize = layout->preferredSize;
  51037. return true;
  51038. }
  51039. return false;
  51040. }
  51041. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  51042. {
  51043. totalSize = newTotalSize;
  51044. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  51045. }
  51046. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  51047. {
  51048. int pos = 0;
  51049. for (int i = 0; i < itemIndex; ++i)
  51050. {
  51051. const ItemLayoutProperties* const layout = getInfoFor (i);
  51052. if (layout != 0)
  51053. pos += layout->currentSize;
  51054. }
  51055. return pos;
  51056. }
  51057. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  51058. {
  51059. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51060. if (layout != 0)
  51061. return layout->currentSize;
  51062. return 0;
  51063. }
  51064. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  51065. {
  51066. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51067. if (layout != 0)
  51068. return -layout->currentSize / (double) totalSize;
  51069. return 0;
  51070. }
  51071. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  51072. int newPosition)
  51073. {
  51074. for (int i = items.size(); --i >= 0;)
  51075. {
  51076. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  51077. if (layout->itemIndex == itemIndex)
  51078. {
  51079. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  51080. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  51081. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  51082. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  51083. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  51084. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  51085. endPos += layout->currentSize;
  51086. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  51087. updatePrefSizesToMatchCurrentPositions();
  51088. break;
  51089. }
  51090. }
  51091. }
  51092. void StretchableLayoutManager::layOutComponents (Component** const components,
  51093. int numComponents,
  51094. int x, int y, int w, int h,
  51095. const bool vertically,
  51096. const bool resizeOtherDimension)
  51097. {
  51098. setTotalSize (vertically ? h : w);
  51099. int pos = vertically ? y : x;
  51100. for (int i = 0; i < numComponents; ++i)
  51101. {
  51102. const ItemLayoutProperties* const layout = getInfoFor (i);
  51103. if (layout != 0)
  51104. {
  51105. Component* const c = components[i];
  51106. if (c != 0)
  51107. {
  51108. if (i == numComponents - 1)
  51109. {
  51110. // if it's the last item, crop it to exactly fit the available space..
  51111. if (resizeOtherDimension)
  51112. {
  51113. if (vertically)
  51114. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51115. else
  51116. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51117. }
  51118. else
  51119. {
  51120. if (vertically)
  51121. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51122. else
  51123. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51124. }
  51125. }
  51126. else
  51127. {
  51128. if (resizeOtherDimension)
  51129. {
  51130. if (vertically)
  51131. c->setBounds (x, pos, w, layout->currentSize);
  51132. else
  51133. c->setBounds (pos, y, layout->currentSize, h);
  51134. }
  51135. else
  51136. {
  51137. if (vertically)
  51138. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51139. else
  51140. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51141. }
  51142. }
  51143. }
  51144. pos += layout->currentSize;
  51145. }
  51146. }
  51147. }
  51148. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51149. {
  51150. for (int i = items.size(); --i >= 0;)
  51151. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51152. return items.getUnchecked(i);
  51153. return 0;
  51154. }
  51155. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51156. const int endIndex,
  51157. const int availableSpace,
  51158. int startPos)
  51159. {
  51160. // calculate the total sizes
  51161. int i;
  51162. double totalIdealSize = 0.0;
  51163. int totalMinimums = 0;
  51164. for (i = startIndex; i < endIndex; ++i)
  51165. {
  51166. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51167. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51168. totalMinimums += layout->currentSize;
  51169. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51170. }
  51171. if (totalIdealSize <= 0)
  51172. totalIdealSize = 1.0;
  51173. // now calc the best sizes..
  51174. int extraSpace = availableSpace - totalMinimums;
  51175. while (extraSpace > 0)
  51176. {
  51177. int numWantingMoreSpace = 0;
  51178. int numHavingTakenExtraSpace = 0;
  51179. // first figure out how many comps want a slice of the extra space..
  51180. for (i = startIndex; i < endIndex; ++i)
  51181. {
  51182. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51183. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51184. const int bestSize = jlimit (layout->currentSize,
  51185. jmax (layout->currentSize,
  51186. sizeToRealSize (layout->maxSize, totalSize)),
  51187. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51188. if (bestSize > layout->currentSize)
  51189. ++numWantingMoreSpace;
  51190. }
  51191. // ..share out the extra space..
  51192. for (i = startIndex; i < endIndex; ++i)
  51193. {
  51194. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51195. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51196. int bestSize = jlimit (layout->currentSize,
  51197. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51198. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51199. const int extraWanted = bestSize - layout->currentSize;
  51200. if (extraWanted > 0)
  51201. {
  51202. const int extraAllowed = jmin (extraWanted,
  51203. extraSpace / jmax (1, numWantingMoreSpace));
  51204. if (extraAllowed > 0)
  51205. {
  51206. ++numHavingTakenExtraSpace;
  51207. --numWantingMoreSpace;
  51208. layout->currentSize += extraAllowed;
  51209. extraSpace -= extraAllowed;
  51210. }
  51211. }
  51212. }
  51213. if (numHavingTakenExtraSpace <= 0)
  51214. break;
  51215. }
  51216. // ..and calculate the end position
  51217. for (i = startIndex; i < endIndex; ++i)
  51218. {
  51219. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51220. startPos += layout->currentSize;
  51221. }
  51222. return startPos;
  51223. }
  51224. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51225. const int endIndex) const
  51226. {
  51227. int totalMinimums = 0;
  51228. for (int i = startIndex; i < endIndex; ++i)
  51229. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51230. return totalMinimums;
  51231. }
  51232. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51233. {
  51234. int totalMaximums = 0;
  51235. for (int i = startIndex; i < endIndex; ++i)
  51236. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51237. return totalMaximums;
  51238. }
  51239. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51240. {
  51241. for (int i = 0; i < items.size(); ++i)
  51242. {
  51243. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51244. layout->preferredSize
  51245. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51246. : getItemCurrentAbsoluteSize (i);
  51247. }
  51248. }
  51249. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51250. {
  51251. if (size < 0)
  51252. size *= -totalSpace;
  51253. return roundToInt (size);
  51254. }
  51255. END_JUCE_NAMESPACE
  51256. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51257. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51258. BEGIN_JUCE_NAMESPACE
  51259. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51260. const int itemIndex_,
  51261. const bool isVertical_)
  51262. : layout (layout_),
  51263. itemIndex (itemIndex_),
  51264. isVertical (isVertical_)
  51265. {
  51266. setRepaintsOnMouseActivity (true);
  51267. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51268. : MouseCursor::UpDownResizeCursor));
  51269. }
  51270. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51271. {
  51272. }
  51273. void StretchableLayoutResizerBar::paint (Graphics& g)
  51274. {
  51275. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51276. getWidth(), getHeight(),
  51277. isVertical,
  51278. isMouseOver(),
  51279. isMouseButtonDown());
  51280. }
  51281. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51282. {
  51283. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51284. }
  51285. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51286. {
  51287. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51288. : e.getDistanceFromDragStartY());
  51289. layout->setItemPosition (itemIndex, desiredPos);
  51290. hasBeenMoved();
  51291. }
  51292. void StretchableLayoutResizerBar::hasBeenMoved()
  51293. {
  51294. if (getParentComponent() != 0)
  51295. getParentComponent()->resized();
  51296. }
  51297. END_JUCE_NAMESPACE
  51298. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51299. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51300. BEGIN_JUCE_NAMESPACE
  51301. StretchableObjectResizer::StretchableObjectResizer()
  51302. {
  51303. }
  51304. StretchableObjectResizer::~StretchableObjectResizer()
  51305. {
  51306. }
  51307. void StretchableObjectResizer::addItem (const double size,
  51308. const double minSize, const double maxSize,
  51309. const int order)
  51310. {
  51311. // the order must be >= 0 but less than the maximum integer value.
  51312. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51313. Item* const item = new Item();
  51314. item->size = size;
  51315. item->minSize = minSize;
  51316. item->maxSize = maxSize;
  51317. item->order = order;
  51318. items.add (item);
  51319. }
  51320. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51321. {
  51322. const Item* const it = items [index];
  51323. return it != 0 ? it->size : 0;
  51324. }
  51325. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51326. {
  51327. int order = 0;
  51328. for (;;)
  51329. {
  51330. double currentSize = 0;
  51331. double minSize = 0;
  51332. double maxSize = 0;
  51333. int nextHighestOrder = std::numeric_limits<int>::max();
  51334. for (int i = 0; i < items.size(); ++i)
  51335. {
  51336. const Item* const it = items.getUnchecked(i);
  51337. currentSize += it->size;
  51338. if (it->order <= order)
  51339. {
  51340. minSize += it->minSize;
  51341. maxSize += it->maxSize;
  51342. }
  51343. else
  51344. {
  51345. minSize += it->size;
  51346. maxSize += it->size;
  51347. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51348. }
  51349. }
  51350. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51351. if (thisIterationTarget >= currentSize)
  51352. {
  51353. const double availableExtraSpace = maxSize - currentSize;
  51354. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51355. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51356. for (int i = 0; i < items.size(); ++i)
  51357. {
  51358. Item* const it = items.getUnchecked(i);
  51359. if (it->order <= order)
  51360. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51361. }
  51362. }
  51363. else
  51364. {
  51365. const double amountOfSlack = currentSize - minSize;
  51366. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51367. const double scale = targetAmountOfSlack / amountOfSlack;
  51368. for (int i = 0; i < items.size(); ++i)
  51369. {
  51370. Item* const it = items.getUnchecked(i);
  51371. if (it->order <= order)
  51372. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51373. }
  51374. }
  51375. if (nextHighestOrder < std::numeric_limits<int>::max())
  51376. order = nextHighestOrder;
  51377. else
  51378. break;
  51379. }
  51380. }
  51381. END_JUCE_NAMESPACE
  51382. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51383. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51384. BEGIN_JUCE_NAMESPACE
  51385. TabBarButton::TabBarButton (const String& name,
  51386. TabbedButtonBar* const owner_,
  51387. const int index)
  51388. : Button (name),
  51389. owner (owner_),
  51390. tabIndex (index),
  51391. overlapPixels (0)
  51392. {
  51393. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51394. setComponentEffect (&shadow);
  51395. setWantsKeyboardFocus (false);
  51396. }
  51397. TabBarButton::~TabBarButton()
  51398. {
  51399. }
  51400. void TabBarButton::paintButton (Graphics& g,
  51401. bool isMouseOverButton,
  51402. bool isButtonDown)
  51403. {
  51404. int x, y, w, h;
  51405. getActiveArea (x, y, w, h);
  51406. g.setOrigin (x, y);
  51407. getLookAndFeel()
  51408. .drawTabButton (g, w, h,
  51409. owner->getTabBackgroundColour (tabIndex),
  51410. tabIndex, getButtonText(), *this,
  51411. owner->getOrientation(),
  51412. isMouseOverButton, isButtonDown,
  51413. getToggleState());
  51414. }
  51415. void TabBarButton::clicked (const ModifierKeys& mods)
  51416. {
  51417. if (mods.isPopupMenu())
  51418. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  51419. else
  51420. owner->setCurrentTabIndex (tabIndex);
  51421. }
  51422. bool TabBarButton::hitTest (int mx, int my)
  51423. {
  51424. int x, y, w, h;
  51425. getActiveArea (x, y, w, h);
  51426. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  51427. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  51428. {
  51429. if (((unsigned int) mx) < (unsigned int) getWidth()
  51430. && my >= y + overlapPixels
  51431. && my < y + h - overlapPixels)
  51432. return true;
  51433. }
  51434. else
  51435. {
  51436. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  51437. && ((unsigned int) my) < (unsigned int) getHeight())
  51438. return true;
  51439. }
  51440. Path p;
  51441. getLookAndFeel()
  51442. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  51443. owner->getOrientation(),
  51444. false, false, getToggleState());
  51445. return p.contains ((float) (mx - x),
  51446. (float) (my - y));
  51447. }
  51448. int TabBarButton::getBestTabLength (const int depth)
  51449. {
  51450. return jlimit (depth * 2,
  51451. depth * 7,
  51452. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  51453. }
  51454. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  51455. {
  51456. x = 0;
  51457. y = 0;
  51458. int r = getWidth();
  51459. int b = getHeight();
  51460. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51461. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  51462. r -= spaceAroundImage;
  51463. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  51464. x += spaceAroundImage;
  51465. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  51466. y += spaceAroundImage;
  51467. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  51468. b -= spaceAroundImage;
  51469. w = r - x;
  51470. h = b - y;
  51471. }
  51472. class TabAreaBehindFrontButtonComponent : public Component
  51473. {
  51474. public:
  51475. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  51476. : owner (owner_)
  51477. {
  51478. setInterceptsMouseClicks (false, false);
  51479. }
  51480. ~TabAreaBehindFrontButtonComponent()
  51481. {
  51482. }
  51483. void paint (Graphics& g)
  51484. {
  51485. getLookAndFeel()
  51486. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51487. *owner, owner->getOrientation());
  51488. }
  51489. void enablementChanged()
  51490. {
  51491. repaint();
  51492. }
  51493. private:
  51494. TabbedButtonBar* const owner;
  51495. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  51496. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  51497. };
  51498. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51499. : orientation (orientation_),
  51500. currentTabIndex (-1)
  51501. {
  51502. setInterceptsMouseClicks (false, true);
  51503. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  51504. setFocusContainer (true);
  51505. }
  51506. TabbedButtonBar::~TabbedButtonBar()
  51507. {
  51508. extraTabsButton = 0;
  51509. deleteAllChildren();
  51510. }
  51511. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51512. {
  51513. orientation = newOrientation;
  51514. for (int i = getNumChildComponents(); --i >= 0;)
  51515. getChildComponent (i)->resized();
  51516. resized();
  51517. }
  51518. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  51519. {
  51520. return new TabBarButton (name, this, index);
  51521. }
  51522. void TabbedButtonBar::clearTabs()
  51523. {
  51524. tabs.clear();
  51525. tabColours.clear();
  51526. currentTabIndex = -1;
  51527. extraTabsButton = 0;
  51528. removeChildComponent (behindFrontTab);
  51529. deleteAllChildren();
  51530. addChildComponent (behindFrontTab);
  51531. setCurrentTabIndex (-1);
  51532. }
  51533. void TabbedButtonBar::addTab (const String& tabName,
  51534. const Colour& tabBackgroundColour,
  51535. int insertIndex)
  51536. {
  51537. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51538. if (tabName.isNotEmpty())
  51539. {
  51540. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  51541. insertIndex = tabs.size();
  51542. for (int i = tabs.size(); --i >= insertIndex;)
  51543. {
  51544. TabBarButton* const tb = getTabButton (i);
  51545. if (tb != 0)
  51546. tb->tabIndex++;
  51547. }
  51548. tabs.insert (insertIndex, tabName);
  51549. tabColours.insert (insertIndex, tabBackgroundColour);
  51550. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  51551. jassert (tb != 0); // your createTabButton() mustn't return zero!
  51552. addAndMakeVisible (tb, insertIndex);
  51553. resized();
  51554. if (currentTabIndex < 0)
  51555. setCurrentTabIndex (0);
  51556. }
  51557. }
  51558. void TabbedButtonBar::setTabName (const int tabIndex,
  51559. const String& newName)
  51560. {
  51561. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  51562. && tabs[tabIndex] != newName)
  51563. {
  51564. tabs.set (tabIndex, newName);
  51565. TabBarButton* const tb = getTabButton (tabIndex);
  51566. if (tb != 0)
  51567. tb->setButtonText (newName);
  51568. resized();
  51569. }
  51570. }
  51571. void TabbedButtonBar::removeTab (const int tabIndex)
  51572. {
  51573. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  51574. {
  51575. const int oldTabIndex = currentTabIndex;
  51576. if (currentTabIndex == tabIndex)
  51577. currentTabIndex = -1;
  51578. tabs.remove (tabIndex);
  51579. tabColours.remove (tabIndex);
  51580. delete getTabButton (tabIndex);
  51581. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  51582. {
  51583. TabBarButton* const tb = getTabButton (i);
  51584. if (tb != 0)
  51585. tb->tabIndex--;
  51586. }
  51587. resized();
  51588. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51589. }
  51590. }
  51591. void TabbedButtonBar::moveTab (const int currentIndex,
  51592. const int newIndex)
  51593. {
  51594. tabs.move (currentIndex, newIndex);
  51595. tabColours.move (currentIndex, newIndex);
  51596. resized();
  51597. }
  51598. int TabbedButtonBar::getNumTabs() const
  51599. {
  51600. return tabs.size();
  51601. }
  51602. const StringArray TabbedButtonBar::getTabNames() const
  51603. {
  51604. return tabs;
  51605. }
  51606. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51607. {
  51608. if (currentTabIndex != newIndex)
  51609. {
  51610. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  51611. newIndex = -1;
  51612. currentTabIndex = newIndex;
  51613. for (int i = 0; i < getNumChildComponents(); ++i)
  51614. {
  51615. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51616. if (tb != 0)
  51617. tb->setToggleState (tb->tabIndex == newIndex, false);
  51618. }
  51619. resized();
  51620. if (sendChangeMessage_)
  51621. sendChangeMessage (this);
  51622. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  51623. }
  51624. }
  51625. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51626. {
  51627. for (int i = getNumChildComponents(); --i >= 0;)
  51628. {
  51629. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51630. if (tb != 0 && tb->tabIndex == index)
  51631. return tb;
  51632. }
  51633. return 0;
  51634. }
  51635. void TabbedButtonBar::lookAndFeelChanged()
  51636. {
  51637. extraTabsButton = 0;
  51638. resized();
  51639. }
  51640. void TabbedButtonBar::resized()
  51641. {
  51642. const double minimumScale = 0.7;
  51643. int depth = getWidth();
  51644. int length = getHeight();
  51645. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51646. swapVariables (depth, length);
  51647. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51648. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51649. int i, totalLength = overlap;
  51650. int numVisibleButtons = tabs.size();
  51651. for (i = 0; i < getNumChildComponents(); ++i)
  51652. {
  51653. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51654. if (tb != 0)
  51655. {
  51656. totalLength += tb->getBestTabLength (depth) - overlap;
  51657. tb->overlapPixels = overlap / 2;
  51658. }
  51659. }
  51660. double scale = 1.0;
  51661. if (totalLength > length)
  51662. scale = jmax (minimumScale, length / (double) totalLength);
  51663. const bool isTooBig = totalLength * scale > length;
  51664. int tabsButtonPos = 0;
  51665. if (isTooBig)
  51666. {
  51667. if (extraTabsButton == 0)
  51668. {
  51669. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51670. extraTabsButton->addButtonListener (this);
  51671. extraTabsButton->setAlwaysOnTop (true);
  51672. extraTabsButton->setTriggeredOnMouseDown (true);
  51673. }
  51674. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51675. extraTabsButton->setSize (buttonSize, buttonSize);
  51676. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51677. {
  51678. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51679. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51680. }
  51681. else
  51682. {
  51683. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51684. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51685. }
  51686. totalLength = 0;
  51687. for (i = 0; i < tabs.size(); ++i)
  51688. {
  51689. TabBarButton* const tb = getTabButton (i);
  51690. if (tb != 0)
  51691. {
  51692. const int newLength = totalLength + tb->getBestTabLength (depth);
  51693. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51694. {
  51695. totalLength += overlap;
  51696. break;
  51697. }
  51698. numVisibleButtons = i + 1;
  51699. totalLength = newLength - overlap;
  51700. }
  51701. }
  51702. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51703. }
  51704. else
  51705. {
  51706. extraTabsButton = 0;
  51707. }
  51708. int pos = 0;
  51709. TabBarButton* frontTab = 0;
  51710. for (i = 0; i < tabs.size(); ++i)
  51711. {
  51712. TabBarButton* const tb = getTabButton (i);
  51713. if (tb != 0)
  51714. {
  51715. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51716. if (i < numVisibleButtons)
  51717. {
  51718. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51719. tb->setBounds (pos, 0, bestLength, getHeight());
  51720. else
  51721. tb->setBounds (0, pos, getWidth(), bestLength);
  51722. tb->toBack();
  51723. if (tb->tabIndex == currentTabIndex)
  51724. frontTab = tb;
  51725. tb->setVisible (true);
  51726. }
  51727. else
  51728. {
  51729. tb->setVisible (false);
  51730. }
  51731. pos += bestLength - overlap;
  51732. }
  51733. }
  51734. behindFrontTab->setBounds (getLocalBounds());
  51735. if (frontTab != 0)
  51736. {
  51737. frontTab->toFront (false);
  51738. behindFrontTab->toBehind (frontTab);
  51739. }
  51740. }
  51741. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51742. {
  51743. return tabColours [tabIndex];
  51744. }
  51745. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51746. {
  51747. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  51748. && tabColours [tabIndex] != newColour)
  51749. {
  51750. tabColours.set (tabIndex, newColour);
  51751. repaint();
  51752. }
  51753. }
  51754. void TabbedButtonBar::buttonClicked (Button* button)
  51755. {
  51756. if (button == extraTabsButton)
  51757. {
  51758. PopupMenu m;
  51759. for (int i = 0; i < tabs.size(); ++i)
  51760. {
  51761. TabBarButton* const tb = getTabButton (i);
  51762. if (tb != 0 && ! tb->isVisible())
  51763. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  51764. }
  51765. const int res = m.showAt (extraTabsButton);
  51766. if (res != 0)
  51767. setCurrentTabIndex (res - 1);
  51768. }
  51769. }
  51770. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51771. {
  51772. }
  51773. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51774. {
  51775. }
  51776. END_JUCE_NAMESPACE
  51777. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51778. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51779. BEGIN_JUCE_NAMESPACE
  51780. class TabCompButtonBar : public TabbedButtonBar
  51781. {
  51782. public:
  51783. TabCompButtonBar (TabbedComponent* const owner_,
  51784. const TabbedButtonBar::Orientation orientation_)
  51785. : TabbedButtonBar (orientation_),
  51786. owner (owner_)
  51787. {
  51788. }
  51789. ~TabCompButtonBar()
  51790. {
  51791. }
  51792. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51793. {
  51794. owner->changeCallback (newCurrentTabIndex, newTabName);
  51795. }
  51796. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51797. {
  51798. owner->popupMenuClickOnTab (tabIndex, tabName);
  51799. }
  51800. const Colour getTabBackgroundColour (const int tabIndex)
  51801. {
  51802. return owner->tabs->getTabBackgroundColour (tabIndex);
  51803. }
  51804. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51805. {
  51806. return owner->createTabButton (tabName, tabIndex);
  51807. }
  51808. juce_UseDebuggingNewOperator
  51809. private:
  51810. TabbedComponent* const owner;
  51811. TabCompButtonBar (const TabCompButtonBar&);
  51812. TabCompButtonBar& operator= (const TabCompButtonBar&);
  51813. };
  51814. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51815. : panelComponent (0),
  51816. tabDepth (30),
  51817. outlineThickness (1),
  51818. edgeIndent (0)
  51819. {
  51820. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  51821. }
  51822. TabbedComponent::~TabbedComponent()
  51823. {
  51824. clearTabs();
  51825. delete tabs;
  51826. }
  51827. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51828. {
  51829. tabs->setOrientation (orientation);
  51830. resized();
  51831. }
  51832. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51833. {
  51834. return tabs->getOrientation();
  51835. }
  51836. void TabbedComponent::setTabBarDepth (const int newDepth)
  51837. {
  51838. if (tabDepth != newDepth)
  51839. {
  51840. tabDepth = newDepth;
  51841. resized();
  51842. }
  51843. }
  51844. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  51845. {
  51846. return new TabBarButton (tabName, tabs, tabIndex);
  51847. }
  51848. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51849. void TabbedComponent::clearTabs()
  51850. {
  51851. if (panelComponent != 0)
  51852. {
  51853. panelComponent->setVisible (false);
  51854. removeChildComponent (panelComponent);
  51855. panelComponent = 0;
  51856. }
  51857. tabs->clearTabs();
  51858. for (int i = contentComponents.size(); --i >= 0;)
  51859. {
  51860. Component* const c = contentComponents.getUnchecked(i);
  51861. // be careful not to delete these components until they've been removed from the tab component
  51862. jassert (c == 0 || c->isValidComponent());
  51863. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51864. delete c;
  51865. }
  51866. contentComponents.clear();
  51867. }
  51868. void TabbedComponent::addTab (const String& tabName,
  51869. const Colour& tabBackgroundColour,
  51870. Component* const contentComponent,
  51871. const bool deleteComponentWhenNotNeeded,
  51872. const int insertIndex)
  51873. {
  51874. contentComponents.insert (insertIndex, contentComponent);
  51875. if (contentComponent != 0)
  51876. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51877. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51878. }
  51879. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51880. {
  51881. tabs->setTabName (tabIndex, newName);
  51882. }
  51883. void TabbedComponent::removeTab (const int tabIndex)
  51884. {
  51885. Component* const c = contentComponents [tabIndex];
  51886. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51887. {
  51888. if (c == panelComponent)
  51889. panelComponent = 0;
  51890. delete c;
  51891. }
  51892. contentComponents.remove (tabIndex);
  51893. tabs->removeTab (tabIndex);
  51894. }
  51895. int TabbedComponent::getNumTabs() const
  51896. {
  51897. return tabs->getNumTabs();
  51898. }
  51899. const StringArray TabbedComponent::getTabNames() const
  51900. {
  51901. return tabs->getTabNames();
  51902. }
  51903. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51904. {
  51905. return contentComponents [tabIndex];
  51906. }
  51907. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51908. {
  51909. return tabs->getTabBackgroundColour (tabIndex);
  51910. }
  51911. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51912. {
  51913. tabs->setTabBackgroundColour (tabIndex, newColour);
  51914. if (getCurrentTabIndex() == tabIndex)
  51915. repaint();
  51916. }
  51917. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51918. {
  51919. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51920. }
  51921. int TabbedComponent::getCurrentTabIndex() const
  51922. {
  51923. return tabs->getCurrentTabIndex();
  51924. }
  51925. const String& TabbedComponent::getCurrentTabName() const
  51926. {
  51927. return tabs->getCurrentTabName();
  51928. }
  51929. void TabbedComponent::setOutline (int thickness)
  51930. {
  51931. outlineThickness = thickness;
  51932. repaint();
  51933. }
  51934. void TabbedComponent::setIndent (const int indentThickness)
  51935. {
  51936. edgeIndent = indentThickness;
  51937. }
  51938. void TabbedComponent::paint (Graphics& g)
  51939. {
  51940. g.fillAll (findColour (backgroundColourId));
  51941. const TabbedButtonBar::Orientation o = getOrientation();
  51942. int x = 0;
  51943. int y = 0;
  51944. int r = getWidth();
  51945. int b = getHeight();
  51946. if (o == TabbedButtonBar::TabsAtTop)
  51947. y += tabDepth;
  51948. else if (o == TabbedButtonBar::TabsAtBottom)
  51949. b -= tabDepth;
  51950. else if (o == TabbedButtonBar::TabsAtLeft)
  51951. x += tabDepth;
  51952. else if (o == TabbedButtonBar::TabsAtRight)
  51953. r -= tabDepth;
  51954. g.reduceClipRegion (x, y, r - x, b - y);
  51955. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51956. if (outlineThickness > 0)
  51957. {
  51958. if (o == TabbedButtonBar::TabsAtTop)
  51959. --y;
  51960. else if (o == TabbedButtonBar::TabsAtBottom)
  51961. ++b;
  51962. else if (o == TabbedButtonBar::TabsAtLeft)
  51963. --x;
  51964. else if (o == TabbedButtonBar::TabsAtRight)
  51965. ++r;
  51966. g.setColour (findColour (outlineColourId));
  51967. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51968. }
  51969. }
  51970. void TabbedComponent::resized()
  51971. {
  51972. const TabbedButtonBar::Orientation o = getOrientation();
  51973. const int indent = edgeIndent + outlineThickness;
  51974. BorderSize indents (indent);
  51975. if (o == TabbedButtonBar::TabsAtTop)
  51976. {
  51977. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51978. indents.setTop (tabDepth + edgeIndent);
  51979. }
  51980. else if (o == TabbedButtonBar::TabsAtBottom)
  51981. {
  51982. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51983. indents.setBottom (tabDepth + edgeIndent);
  51984. }
  51985. else if (o == TabbedButtonBar::TabsAtLeft)
  51986. {
  51987. tabs->setBounds (0, 0, tabDepth, getHeight());
  51988. indents.setLeft (tabDepth + edgeIndent);
  51989. }
  51990. else if (o == TabbedButtonBar::TabsAtRight)
  51991. {
  51992. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51993. indents.setRight (tabDepth + edgeIndent);
  51994. }
  51995. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51996. for (int i = contentComponents.size(); --i >= 0;)
  51997. if (contentComponents.getUnchecked (i) != 0)
  51998. contentComponents.getUnchecked (i)->setBounds (bounds);
  51999. }
  52000. void TabbedComponent::lookAndFeelChanged()
  52001. {
  52002. for (int i = contentComponents.size(); --i >= 0;)
  52003. if (contentComponents.getUnchecked (i) != 0)
  52004. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  52005. }
  52006. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  52007. const String& newTabName)
  52008. {
  52009. if (panelComponent != 0)
  52010. {
  52011. panelComponent->setVisible (false);
  52012. removeChildComponent (panelComponent);
  52013. panelComponent = 0;
  52014. }
  52015. if (getCurrentTabIndex() >= 0)
  52016. {
  52017. panelComponent = contentComponents [getCurrentTabIndex()];
  52018. if (panelComponent != 0)
  52019. {
  52020. // do these ops as two stages instead of addAndMakeVisible() so that the
  52021. // component has always got a parent when it gets the visibilityChanged() callback
  52022. addChildComponent (panelComponent);
  52023. panelComponent->setVisible (true);
  52024. panelComponent->toFront (true);
  52025. }
  52026. repaint();
  52027. }
  52028. resized();
  52029. currentTabChanged (newCurrentTabIndex, newTabName);
  52030. }
  52031. void TabbedComponent::currentTabChanged (const int, const String&)
  52032. {
  52033. }
  52034. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  52035. {
  52036. }
  52037. END_JUCE_NAMESPACE
  52038. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  52039. /*** Start of inlined file: juce_Viewport.cpp ***/
  52040. BEGIN_JUCE_NAMESPACE
  52041. Viewport::Viewport (const String& componentName)
  52042. : Component (componentName),
  52043. scrollBarThickness (0),
  52044. singleStepX (16),
  52045. singleStepY (16),
  52046. showHScrollbar (true),
  52047. showVScrollbar (true),
  52048. verticalScrollBar (true),
  52049. horizontalScrollBar (false)
  52050. {
  52051. // content holder is used to clip the contents so they don't overlap the scrollbars
  52052. addAndMakeVisible (&contentHolder);
  52053. contentHolder.setInterceptsMouseClicks (false, true);
  52054. addChildComponent (&verticalScrollBar);
  52055. addChildComponent (&horizontalScrollBar);
  52056. verticalScrollBar.addListener (this);
  52057. horizontalScrollBar.addListener (this);
  52058. setInterceptsMouseClicks (false, true);
  52059. setWantsKeyboardFocus (true);
  52060. }
  52061. Viewport::~Viewport()
  52062. {
  52063. contentHolder.deleteAllChildren();
  52064. }
  52065. void Viewport::visibleAreaChanged (int, int, int, int)
  52066. {
  52067. }
  52068. void Viewport::setViewedComponent (Component* const newViewedComponent)
  52069. {
  52070. if (contentComp.getComponent() != newViewedComponent)
  52071. {
  52072. {
  52073. ScopedPointer<Component> oldCompDeleter (contentComp);
  52074. contentComp = 0;
  52075. }
  52076. contentComp = newViewedComponent;
  52077. if (contentComp != 0)
  52078. {
  52079. contentComp->setTopLeftPosition (0, 0);
  52080. contentHolder.addAndMakeVisible (contentComp);
  52081. contentComp->addComponentListener (this);
  52082. }
  52083. updateVisibleArea();
  52084. }
  52085. }
  52086. int Viewport::getMaximumVisibleWidth() const
  52087. {
  52088. return contentHolder.getWidth();
  52089. }
  52090. int Viewport::getMaximumVisibleHeight() const
  52091. {
  52092. return contentHolder.getHeight();
  52093. }
  52094. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  52095. {
  52096. if (contentComp != 0)
  52097. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  52098. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  52099. }
  52100. void Viewport::setViewPosition (const Point<int>& newPosition)
  52101. {
  52102. setViewPosition (newPosition.getX(), newPosition.getY());
  52103. }
  52104. void Viewport::setViewPositionProportionately (const double x, const double y)
  52105. {
  52106. if (contentComp != 0)
  52107. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  52108. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  52109. }
  52110. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  52111. {
  52112. if (contentComp != 0)
  52113. {
  52114. int dx = 0, dy = 0;
  52115. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  52116. {
  52117. if (mouseX < activeBorderThickness)
  52118. dx = activeBorderThickness - mouseX;
  52119. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  52120. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  52121. if (dx < 0)
  52122. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  52123. else
  52124. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  52125. }
  52126. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  52127. {
  52128. if (mouseY < activeBorderThickness)
  52129. dy = activeBorderThickness - mouseY;
  52130. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  52131. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  52132. if (dy < 0)
  52133. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  52134. else
  52135. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  52136. }
  52137. if (dx != 0 || dy != 0)
  52138. {
  52139. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52140. contentComp->getY() + dy);
  52141. return true;
  52142. }
  52143. }
  52144. return false;
  52145. }
  52146. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52147. {
  52148. updateVisibleArea();
  52149. }
  52150. void Viewport::resized()
  52151. {
  52152. updateVisibleArea();
  52153. }
  52154. void Viewport::updateVisibleArea()
  52155. {
  52156. const int scrollbarWidth = getScrollBarThickness();
  52157. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52158. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52159. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52160. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52161. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52162. Rectangle<int> contentArea (getLocalBounds());
  52163. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52164. {
  52165. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52166. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52167. if (vBarVisible)
  52168. contentArea.setWidth (getWidth() - scrollbarWidth);
  52169. if (hBarVisible)
  52170. contentArea.setHeight (getHeight() - scrollbarWidth);
  52171. if (! contentArea.contains (contentComp->getBounds()))
  52172. {
  52173. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52174. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52175. }
  52176. }
  52177. if (vBarVisible)
  52178. contentArea.setWidth (getWidth() - scrollbarWidth);
  52179. if (hBarVisible)
  52180. contentArea.setHeight (getHeight() - scrollbarWidth);
  52181. contentHolder.setBounds (contentArea);
  52182. Rectangle<int> contentBounds;
  52183. if (contentComp != 0)
  52184. contentBounds = contentComp->getBounds();
  52185. const Point<int> visibleOrigin (-contentBounds.getPosition());
  52186. if (hBarVisible)
  52187. {
  52188. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52189. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52190. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52191. horizontalScrollBar.setSingleStepSize (singleStepX);
  52192. horizontalScrollBar.cancelPendingUpdate();
  52193. }
  52194. if (vBarVisible)
  52195. {
  52196. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52197. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52198. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52199. verticalScrollBar.setSingleStepSize (singleStepY);
  52200. verticalScrollBar.cancelPendingUpdate();
  52201. }
  52202. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52203. horizontalScrollBar.setVisible (hBarVisible);
  52204. verticalScrollBar.setVisible (vBarVisible);
  52205. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52206. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52207. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52208. if (lastVisibleArea != visibleArea)
  52209. {
  52210. lastVisibleArea = visibleArea;
  52211. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  52212. }
  52213. horizontalScrollBar.handleUpdateNowIfNeeded();
  52214. verticalScrollBar.handleUpdateNowIfNeeded();
  52215. }
  52216. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52217. {
  52218. if (singleStepX != stepX || singleStepY != stepY)
  52219. {
  52220. singleStepX = stepX;
  52221. singleStepY = stepY;
  52222. updateVisibleArea();
  52223. }
  52224. }
  52225. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52226. const bool showHorizontalScrollbarIfNeeded)
  52227. {
  52228. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52229. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52230. {
  52231. showVScrollbar = showVerticalScrollbarIfNeeded;
  52232. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52233. updateVisibleArea();
  52234. }
  52235. }
  52236. void Viewport::setScrollBarThickness (const int thickness)
  52237. {
  52238. if (scrollBarThickness != thickness)
  52239. {
  52240. scrollBarThickness = thickness;
  52241. updateVisibleArea();
  52242. }
  52243. }
  52244. int Viewport::getScrollBarThickness() const
  52245. {
  52246. return scrollBarThickness > 0 ? scrollBarThickness
  52247. : getLookAndFeel().getDefaultScrollbarWidth();
  52248. }
  52249. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52250. {
  52251. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52252. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52253. }
  52254. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52255. {
  52256. const int newRangeStartInt = roundToInt (newRangeStart);
  52257. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52258. {
  52259. setViewPosition (newRangeStartInt, getViewPositionY());
  52260. }
  52261. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52262. {
  52263. setViewPosition (getViewPositionX(), newRangeStartInt);
  52264. }
  52265. }
  52266. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52267. {
  52268. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52269. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52270. }
  52271. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52272. {
  52273. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52274. {
  52275. const bool hasVertBar = verticalScrollBar.isVisible();
  52276. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52277. if (hasHorzBar || hasVertBar)
  52278. {
  52279. if (wheelIncrementX != 0)
  52280. {
  52281. wheelIncrementX *= 14.0f * singleStepX;
  52282. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52283. : jmax (wheelIncrementX, 1.0f);
  52284. }
  52285. if (wheelIncrementY != 0)
  52286. {
  52287. wheelIncrementY *= 14.0f * singleStepY;
  52288. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52289. : jmax (wheelIncrementY, 1.0f);
  52290. }
  52291. Point<int> pos (getViewPosition());
  52292. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52293. {
  52294. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52295. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52296. }
  52297. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52298. {
  52299. if (wheelIncrementX == 0 && ! hasVertBar)
  52300. wheelIncrementX = wheelIncrementY;
  52301. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52302. }
  52303. else if (hasVertBar && wheelIncrementY != 0)
  52304. {
  52305. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52306. }
  52307. if (pos != getViewPosition())
  52308. {
  52309. setViewPosition (pos);
  52310. return true;
  52311. }
  52312. }
  52313. }
  52314. return false;
  52315. }
  52316. bool Viewport::keyPressed (const KeyPress& key)
  52317. {
  52318. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52319. || key.isKeyCode (KeyPress::downKey)
  52320. || key.isKeyCode (KeyPress::pageUpKey)
  52321. || key.isKeyCode (KeyPress::pageDownKey)
  52322. || key.isKeyCode (KeyPress::homeKey)
  52323. || key.isKeyCode (KeyPress::endKey);
  52324. if (verticalScrollBar.isVisible() && isUpDownKey)
  52325. return verticalScrollBar.keyPressed (key);
  52326. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52327. || key.isKeyCode (KeyPress::rightKey);
  52328. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52329. return horizontalScrollBar.keyPressed (key);
  52330. return false;
  52331. }
  52332. END_JUCE_NAMESPACE
  52333. /*** End of inlined file: juce_Viewport.cpp ***/
  52334. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52335. BEGIN_JUCE_NAMESPACE
  52336. static const Colour createBaseColour (const Colour& buttonColour,
  52337. const bool hasKeyboardFocus,
  52338. const bool isMouseOverButton,
  52339. const bool isButtonDown) throw()
  52340. {
  52341. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52342. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52343. if (isButtonDown)
  52344. return baseColour.contrasting (0.2f);
  52345. else if (isMouseOverButton)
  52346. return baseColour.contrasting (0.1f);
  52347. return baseColour;
  52348. }
  52349. LookAndFeel::LookAndFeel()
  52350. {
  52351. /* if this fails it means you're trying to create a LookAndFeel object before
  52352. the static Colours have been initialised. That ain't gonna work. It probably
  52353. means that you're using a static LookAndFeel object and that your compiler has
  52354. decided to intialise it before the Colours class.
  52355. */
  52356. jassert (Colours::white == Colour (0xffffffff));
  52357. // set up the standard set of colours..
  52358. const int textButtonColour = 0xffbbbbff;
  52359. const int textHighlightColour = 0x401111ee;
  52360. const int standardOutlineColour = 0xb2808080;
  52361. static const int standardColours[] =
  52362. {
  52363. TextButton::buttonColourId, textButtonColour,
  52364. TextButton::buttonOnColourId, 0xff4444ff,
  52365. TextButton::textColourOnId, 0xff000000,
  52366. TextButton::textColourOffId, 0xff000000,
  52367. ComboBox::buttonColourId, 0xffbbbbff,
  52368. ComboBox::outlineColourId, standardOutlineColour,
  52369. ToggleButton::textColourId, 0xff000000,
  52370. TextEditor::backgroundColourId, 0xffffffff,
  52371. TextEditor::textColourId, 0xff000000,
  52372. TextEditor::highlightColourId, textHighlightColour,
  52373. TextEditor::highlightedTextColourId, 0xff000000,
  52374. TextEditor::caretColourId, 0xff000000,
  52375. TextEditor::outlineColourId, 0x00000000,
  52376. TextEditor::focusedOutlineColourId, textButtonColour,
  52377. TextEditor::shadowColourId, 0x38000000,
  52378. Label::backgroundColourId, 0x00000000,
  52379. Label::textColourId, 0xff000000,
  52380. Label::outlineColourId, 0x00000000,
  52381. ScrollBar::backgroundColourId, 0x00000000,
  52382. ScrollBar::thumbColourId, 0xffffffff,
  52383. ScrollBar::trackColourId, 0xffffffff,
  52384. TreeView::linesColourId, 0x4c000000,
  52385. TreeView::backgroundColourId, 0x00000000,
  52386. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52387. PopupMenu::backgroundColourId, 0xffffffff,
  52388. PopupMenu::textColourId, 0xff000000,
  52389. PopupMenu::headerTextColourId, 0xff000000,
  52390. PopupMenu::highlightedTextColourId, 0xffffffff,
  52391. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52392. ComboBox::textColourId, 0xff000000,
  52393. ComboBox::backgroundColourId, 0xffffffff,
  52394. ComboBox::arrowColourId, 0x99000000,
  52395. ListBox::backgroundColourId, 0xffffffff,
  52396. ListBox::outlineColourId, standardOutlineColour,
  52397. ListBox::textColourId, 0xff000000,
  52398. Slider::backgroundColourId, 0x00000000,
  52399. Slider::thumbColourId, textButtonColour,
  52400. Slider::trackColourId, 0x7fffffff,
  52401. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52402. Slider::rotarySliderOutlineColourId, 0x66000000,
  52403. Slider::textBoxTextColourId, 0xff000000,
  52404. Slider::textBoxBackgroundColourId, 0xffffffff,
  52405. Slider::textBoxHighlightColourId, textHighlightColour,
  52406. Slider::textBoxOutlineColourId, standardOutlineColour,
  52407. ResizableWindow::backgroundColourId, 0xff777777,
  52408. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52409. AlertWindow::backgroundColourId, 0xffededed,
  52410. AlertWindow::textColourId, 0xff000000,
  52411. AlertWindow::outlineColourId, 0xff666666,
  52412. ProgressBar::backgroundColourId, 0xffeeeeee,
  52413. ProgressBar::foregroundColourId, 0xffaaaaee,
  52414. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52415. TooltipWindow::textColourId, 0xff000000,
  52416. TooltipWindow::outlineColourId, 0x4c000000,
  52417. TabbedComponent::backgroundColourId, 0x00000000,
  52418. TabbedComponent::outlineColourId, 0xff777777,
  52419. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52420. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52421. Toolbar::backgroundColourId, 0xfff6f8f9,
  52422. Toolbar::separatorColourId, 0x4c000000,
  52423. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52424. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52425. Toolbar::labelTextColourId, 0xff000000,
  52426. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52427. HyperlinkButton::textColourId, 0xcc1111ee,
  52428. GroupComponent::outlineColourId, 0x66000000,
  52429. GroupComponent::textColourId, 0xff000000,
  52430. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52431. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52432. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52433. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52434. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52435. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52436. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52437. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52438. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52439. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52440. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52441. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52442. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52443. CodeEditorComponent::caretColourId, 0xff000000,
  52444. CodeEditorComponent::highlightColourId, textHighlightColour,
  52445. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52446. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52447. ColourSelector::labelTextColourId, 0xff000000,
  52448. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52449. KeyMappingEditorComponent::textColourId, 0xff000000,
  52450. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52451. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52452. DrawableButton::textColourId, 0xff000000,
  52453. };
  52454. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52455. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52456. static String defaultSansName, defaultSerifName, defaultFixedName;
  52457. if (defaultSansName.isEmpty())
  52458. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  52459. defaultSans = defaultSansName;
  52460. defaultSerif = defaultSerifName;
  52461. defaultFixed = defaultFixedName;
  52462. }
  52463. LookAndFeel::~LookAndFeel()
  52464. {
  52465. }
  52466. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52467. {
  52468. const int index = colourIds.indexOf (colourId);
  52469. if (index >= 0)
  52470. return colours [index];
  52471. jassertfalse;
  52472. return Colours::black;
  52473. }
  52474. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52475. {
  52476. const int index = colourIds.indexOf (colourId);
  52477. if (index >= 0)
  52478. {
  52479. colours.set (index, colour);
  52480. }
  52481. else
  52482. {
  52483. colourIds.add (colourId);
  52484. colours.add (colour);
  52485. }
  52486. }
  52487. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52488. {
  52489. return colourIds.contains (colourId);
  52490. }
  52491. static LookAndFeel* defaultLF = 0;
  52492. static LookAndFeel* currentDefaultLF = 0;
  52493. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52494. {
  52495. // if this happens, your app hasn't initialised itself properly.. if you're
  52496. // trying to hack your own main() function, have a look at
  52497. // JUCEApplication::initialiseForGUI()
  52498. jassert (currentDefaultLF != 0);
  52499. return *currentDefaultLF;
  52500. }
  52501. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52502. {
  52503. if (newDefaultLookAndFeel == 0)
  52504. {
  52505. if (defaultLF == 0)
  52506. defaultLF = new LookAndFeel();
  52507. newDefaultLookAndFeel = defaultLF;
  52508. }
  52509. currentDefaultLF = newDefaultLookAndFeel;
  52510. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52511. {
  52512. Component* const c = Desktop::getInstance().getComponent (i);
  52513. if (c != 0)
  52514. c->sendLookAndFeelChange();
  52515. }
  52516. }
  52517. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52518. {
  52519. if (currentDefaultLF == defaultLF)
  52520. currentDefaultLF = 0;
  52521. deleteAndZero (defaultLF);
  52522. }
  52523. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52524. {
  52525. String faceName (font.getTypefaceName());
  52526. if (faceName == Font::getDefaultSansSerifFontName())
  52527. faceName = defaultSans;
  52528. else if (faceName == Font::getDefaultSerifFontName())
  52529. faceName = defaultSerif;
  52530. else if (faceName == Font::getDefaultMonospacedFontName())
  52531. faceName = defaultFixed;
  52532. Font f (font);
  52533. f.setTypefaceName (faceName);
  52534. return Typeface::createSystemTypefaceFor (f);
  52535. }
  52536. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52537. {
  52538. defaultSans = newName;
  52539. }
  52540. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52541. {
  52542. return component.getMouseCursor();
  52543. }
  52544. void LookAndFeel::drawButtonBackground (Graphics& g,
  52545. Button& button,
  52546. const Colour& backgroundColour,
  52547. bool isMouseOverButton,
  52548. bool isButtonDown)
  52549. {
  52550. const int width = button.getWidth();
  52551. const int height = button.getHeight();
  52552. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52553. const float halfThickness = outlineThickness * 0.5f;
  52554. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52555. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52556. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52557. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52558. const Colour baseColour (createBaseColour (backgroundColour,
  52559. button.hasKeyboardFocus (true),
  52560. isMouseOverButton, isButtonDown)
  52561. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52562. drawGlassLozenge (g,
  52563. indentL,
  52564. indentT,
  52565. width - indentL - indentR,
  52566. height - indentT - indentB,
  52567. baseColour, outlineThickness, -1.0f,
  52568. button.isConnectedOnLeft(),
  52569. button.isConnectedOnRight(),
  52570. button.isConnectedOnTop(),
  52571. button.isConnectedOnBottom());
  52572. }
  52573. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52574. {
  52575. return button.getFont();
  52576. }
  52577. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52578. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52579. {
  52580. Font font (getFontForTextButton (button));
  52581. g.setFont (font);
  52582. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52583. : TextButton::textColourOffId)
  52584. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52585. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52586. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52587. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52588. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52589. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52590. g.drawFittedText (button.getButtonText(),
  52591. leftIndent,
  52592. yIndent,
  52593. button.getWidth() - leftIndent - rightIndent,
  52594. button.getHeight() - yIndent * 2,
  52595. Justification::centred, 2);
  52596. }
  52597. void LookAndFeel::drawTickBox (Graphics& g,
  52598. Component& component,
  52599. float x, float y, float w, float h,
  52600. const bool ticked,
  52601. const bool isEnabled,
  52602. const bool isMouseOverButton,
  52603. const bool isButtonDown)
  52604. {
  52605. const float boxSize = w * 0.7f;
  52606. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52607. createBaseColour (component.findColour (TextButton::buttonColourId)
  52608. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52609. true,
  52610. isMouseOverButton,
  52611. isButtonDown),
  52612. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52613. if (ticked)
  52614. {
  52615. Path tick;
  52616. tick.startNewSubPath (1.5f, 3.0f);
  52617. tick.lineTo (3.0f, 6.0f);
  52618. tick.lineTo (6.0f, 0.0f);
  52619. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52620. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52621. .translated (x, y));
  52622. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52623. }
  52624. }
  52625. void LookAndFeel::drawToggleButton (Graphics& g,
  52626. ToggleButton& button,
  52627. bool isMouseOverButton,
  52628. bool isButtonDown)
  52629. {
  52630. if (button.hasKeyboardFocus (true))
  52631. {
  52632. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52633. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52634. }
  52635. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52636. const float tickWidth = fontSize * 1.1f;
  52637. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52638. tickWidth, tickWidth,
  52639. button.getToggleState(),
  52640. button.isEnabled(),
  52641. isMouseOverButton,
  52642. isButtonDown);
  52643. g.setColour (button.findColour (ToggleButton::textColourId));
  52644. g.setFont (fontSize);
  52645. if (! button.isEnabled())
  52646. g.setOpacity (0.5f);
  52647. const int textX = (int) tickWidth + 5;
  52648. g.drawFittedText (button.getButtonText(),
  52649. textX, 0,
  52650. button.getWidth() - textX - 2, button.getHeight(),
  52651. Justification::centredLeft, 10);
  52652. }
  52653. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52654. {
  52655. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52656. const int tickWidth = jmin (24, button.getHeight());
  52657. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52658. button.getHeight());
  52659. }
  52660. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52661. const String& message,
  52662. const String& button1,
  52663. const String& button2,
  52664. const String& button3,
  52665. AlertWindow::AlertIconType iconType,
  52666. int numButtons,
  52667. Component* associatedComponent)
  52668. {
  52669. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52670. if (numButtons == 1)
  52671. {
  52672. aw->addButton (button1, 0,
  52673. KeyPress (KeyPress::escapeKey, 0, 0),
  52674. KeyPress (KeyPress::returnKey, 0, 0));
  52675. }
  52676. else
  52677. {
  52678. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52679. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52680. if (button1ShortCut == button2ShortCut)
  52681. button2ShortCut = KeyPress();
  52682. if (numButtons == 2)
  52683. {
  52684. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52685. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52686. }
  52687. else if (numButtons == 3)
  52688. {
  52689. aw->addButton (button1, 1, button1ShortCut);
  52690. aw->addButton (button2, 2, button2ShortCut);
  52691. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52692. }
  52693. }
  52694. return aw;
  52695. }
  52696. void LookAndFeel::drawAlertBox (Graphics& g,
  52697. AlertWindow& alert,
  52698. const Rectangle<int>& textArea,
  52699. TextLayout& textLayout)
  52700. {
  52701. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52702. int iconSpaceUsed = 0;
  52703. Justification alignment (Justification::horizontallyCentred);
  52704. const int iconWidth = 80;
  52705. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52706. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52707. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52708. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52709. iconSize, iconSize);
  52710. if (alert.getAlertType() != AlertWindow::NoIcon)
  52711. {
  52712. Path icon;
  52713. uint32 colour;
  52714. char character;
  52715. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52716. {
  52717. colour = 0x55ff5555;
  52718. character = '!';
  52719. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52720. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52721. (float) iconRect.getX(), (float) iconRect.getBottom());
  52722. icon = icon.createPathWithRoundedCorners (5.0f);
  52723. }
  52724. else
  52725. {
  52726. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52727. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52728. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52729. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52730. }
  52731. GlyphArrangement ga;
  52732. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52733. String::charToString (character),
  52734. (float) iconRect.getX(), (float) iconRect.getY(),
  52735. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52736. Justification::centred, false);
  52737. ga.createPath (icon);
  52738. icon.setUsingNonZeroWinding (false);
  52739. g.setColour (Colour (colour));
  52740. g.fillPath (icon);
  52741. iconSpaceUsed = iconWidth;
  52742. alignment = Justification::left;
  52743. }
  52744. g.setColour (alert.findColour (AlertWindow::textColourId));
  52745. textLayout.drawWithin (g,
  52746. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52747. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52748. alignment.getFlags() | Justification::top);
  52749. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52750. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52751. }
  52752. int LookAndFeel::getAlertBoxWindowFlags()
  52753. {
  52754. return ComponentPeer::windowAppearsOnTaskbar
  52755. | ComponentPeer::windowHasDropShadow;
  52756. }
  52757. int LookAndFeel::getAlertWindowButtonHeight()
  52758. {
  52759. return 28;
  52760. }
  52761. const Font LookAndFeel::getAlertWindowFont()
  52762. {
  52763. return Font (12.0f);
  52764. }
  52765. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52766. int width, int height,
  52767. double progress, const String& textToShow)
  52768. {
  52769. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52770. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52771. g.fillAll (background);
  52772. if (progress >= 0.0f && progress < 1.0f)
  52773. {
  52774. drawGlassLozenge (g, 1.0f, 1.0f,
  52775. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52776. (float) (height - 2),
  52777. foreground,
  52778. 0.5f, 0.0f,
  52779. true, true, true, true);
  52780. }
  52781. else
  52782. {
  52783. // spinning bar..
  52784. g.setColour (foreground);
  52785. const int stripeWidth = height * 2;
  52786. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52787. Path p;
  52788. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52789. p.addQuadrilateral (x, 0.0f,
  52790. x + stripeWidth * 0.5f, 0.0f,
  52791. x, (float) height,
  52792. x - stripeWidth * 0.5f, (float) height);
  52793. Image im (Image::ARGB, width, height, true);
  52794. {
  52795. Graphics g2 (im);
  52796. drawGlassLozenge (g2, 1.0f, 1.0f,
  52797. (float) (width - 2),
  52798. (float) (height - 2),
  52799. foreground,
  52800. 0.5f, 0.0f,
  52801. true, true, true, true);
  52802. }
  52803. g.setTiledImageFill (im, 0, 0, 0.85f);
  52804. g.fillPath (p);
  52805. }
  52806. if (textToShow.isNotEmpty())
  52807. {
  52808. g.setColour (Colour::contrasting (background, foreground));
  52809. g.setFont (height * 0.6f);
  52810. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52811. }
  52812. }
  52813. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52814. {
  52815. const float radius = jmin (w, h) * 0.4f;
  52816. const float thickness = radius * 0.15f;
  52817. Path p;
  52818. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52819. radius * 0.6f, thickness,
  52820. thickness * 0.5f);
  52821. const float cx = x + w * 0.5f;
  52822. const float cy = y + h * 0.5f;
  52823. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52824. for (int i = 0; i < 12; ++i)
  52825. {
  52826. const int n = (i + 12 - animationIndex) % 12;
  52827. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52828. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52829. .translated (cx, cy));
  52830. }
  52831. }
  52832. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52833. ScrollBar& scrollbar,
  52834. int width, int height,
  52835. int buttonDirection,
  52836. bool /*isScrollbarVertical*/,
  52837. bool /*isMouseOverButton*/,
  52838. bool isButtonDown)
  52839. {
  52840. Path p;
  52841. if (buttonDirection == 0)
  52842. p.addTriangle (width * 0.5f, height * 0.2f,
  52843. width * 0.1f, height * 0.7f,
  52844. width * 0.9f, height * 0.7f);
  52845. else if (buttonDirection == 1)
  52846. p.addTriangle (width * 0.8f, height * 0.5f,
  52847. width * 0.3f, height * 0.1f,
  52848. width * 0.3f, height * 0.9f);
  52849. else if (buttonDirection == 2)
  52850. p.addTriangle (width * 0.5f, height * 0.8f,
  52851. width * 0.1f, height * 0.3f,
  52852. width * 0.9f, height * 0.3f);
  52853. else if (buttonDirection == 3)
  52854. p.addTriangle (width * 0.2f, height * 0.5f,
  52855. width * 0.7f, height * 0.1f,
  52856. width * 0.7f, height * 0.9f);
  52857. if (isButtonDown)
  52858. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52859. else
  52860. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52861. g.fillPath (p);
  52862. g.setColour (Colour (0x80000000));
  52863. g.strokePath (p, PathStrokeType (0.5f));
  52864. }
  52865. void LookAndFeel::drawScrollbar (Graphics& g,
  52866. ScrollBar& scrollbar,
  52867. int x, int y,
  52868. int width, int height,
  52869. bool isScrollbarVertical,
  52870. int thumbStartPosition,
  52871. int thumbSize,
  52872. bool /*isMouseOver*/,
  52873. bool /*isMouseDown*/)
  52874. {
  52875. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52876. Path slotPath, thumbPath;
  52877. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52878. const float slotIndentx2 = slotIndent * 2.0f;
  52879. const float thumbIndent = slotIndent + 1.0f;
  52880. const float thumbIndentx2 = thumbIndent * 2.0f;
  52881. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52882. if (isScrollbarVertical)
  52883. {
  52884. slotPath.addRoundedRectangle (x + slotIndent,
  52885. y + slotIndent,
  52886. width - slotIndentx2,
  52887. height - slotIndentx2,
  52888. (width - slotIndentx2) * 0.5f);
  52889. if (thumbSize > 0)
  52890. thumbPath.addRoundedRectangle (x + thumbIndent,
  52891. thumbStartPosition + thumbIndent,
  52892. width - thumbIndentx2,
  52893. thumbSize - thumbIndentx2,
  52894. (width - thumbIndentx2) * 0.5f);
  52895. gx1 = (float) x;
  52896. gx2 = x + width * 0.7f;
  52897. }
  52898. else
  52899. {
  52900. slotPath.addRoundedRectangle (x + slotIndent,
  52901. y + slotIndent,
  52902. width - slotIndentx2,
  52903. height - slotIndentx2,
  52904. (height - slotIndentx2) * 0.5f);
  52905. if (thumbSize > 0)
  52906. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52907. y + thumbIndent,
  52908. thumbSize - thumbIndentx2,
  52909. height - thumbIndentx2,
  52910. (height - thumbIndentx2) * 0.5f);
  52911. gy1 = (float) y;
  52912. gy2 = y + height * 0.7f;
  52913. }
  52914. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52915. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52916. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52917. g.fillPath (slotPath);
  52918. if (isScrollbarVertical)
  52919. {
  52920. gx1 = x + width * 0.6f;
  52921. gx2 = (float) x + width;
  52922. }
  52923. else
  52924. {
  52925. gy1 = y + height * 0.6f;
  52926. gy2 = (float) y + height;
  52927. }
  52928. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52929. Colour (0x19000000), gx2, gy2, false));
  52930. g.fillPath (slotPath);
  52931. g.setColour (thumbColour);
  52932. g.fillPath (thumbPath);
  52933. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52934. Colours::transparentBlack, gx2, gy2, false));
  52935. g.saveState();
  52936. if (isScrollbarVertical)
  52937. g.reduceClipRegion (x + width / 2, y, width, height);
  52938. else
  52939. g.reduceClipRegion (x, y + height / 2, width, height);
  52940. g.fillPath (thumbPath);
  52941. g.restoreState();
  52942. g.setColour (Colour (0x4c000000));
  52943. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52944. }
  52945. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52946. {
  52947. return 0;
  52948. }
  52949. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52950. {
  52951. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52952. }
  52953. int LookAndFeel::getDefaultScrollbarWidth()
  52954. {
  52955. return 18;
  52956. }
  52957. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52958. {
  52959. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52960. : scrollbar.getHeight());
  52961. }
  52962. const Path LookAndFeel::getTickShape (const float height)
  52963. {
  52964. static const unsigned char tickShapeData[] =
  52965. {
  52966. 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,
  52967. 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,
  52968. 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,
  52969. 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,
  52970. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52971. };
  52972. Path p;
  52973. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52974. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52975. return p;
  52976. }
  52977. const Path LookAndFeel::getCrossShape (const float height)
  52978. {
  52979. static const unsigned char crossShapeData[] =
  52980. {
  52981. 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,
  52982. 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,
  52983. 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,
  52984. 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,
  52985. 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,
  52986. 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,
  52987. 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
  52988. };
  52989. Path p;
  52990. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52991. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52992. return p;
  52993. }
  52994. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52995. {
  52996. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52997. x += (w - boxSize) >> 1;
  52998. y += (h - boxSize) >> 1;
  52999. w = boxSize;
  53000. h = boxSize;
  53001. g.setColour (Colour (0xe5ffffff));
  53002. g.fillRect (x, y, w, h);
  53003. g.setColour (Colour (0x80000000));
  53004. g.drawRect (x, y, w, h);
  53005. const float size = boxSize / 2 + 1.0f;
  53006. const float centre = (float) (boxSize / 2);
  53007. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  53008. if (isPlus)
  53009. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  53010. }
  53011. void LookAndFeel::drawBubble (Graphics& g,
  53012. float tipX, float tipY,
  53013. float boxX, float boxY,
  53014. float boxW, float boxH)
  53015. {
  53016. int side = 0;
  53017. if (tipX < boxX)
  53018. side = 1;
  53019. else if (tipX > boxX + boxW)
  53020. side = 3;
  53021. else if (tipY > boxY + boxH)
  53022. side = 2;
  53023. const float indent = 2.0f;
  53024. Path p;
  53025. p.addBubble (boxX + indent,
  53026. boxY + indent,
  53027. boxW - indent * 2.0f,
  53028. boxH - indent * 2.0f,
  53029. 5.0f,
  53030. tipX, tipY,
  53031. side,
  53032. 0.5f,
  53033. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  53034. //xxx need to take comp as param for colour
  53035. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  53036. g.fillPath (p);
  53037. //xxx as above
  53038. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  53039. g.strokePath (p, PathStrokeType (1.33f));
  53040. }
  53041. const Font LookAndFeel::getPopupMenuFont()
  53042. {
  53043. return Font (17.0f);
  53044. }
  53045. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  53046. const bool isSeparator,
  53047. int standardMenuItemHeight,
  53048. int& idealWidth,
  53049. int& idealHeight)
  53050. {
  53051. if (isSeparator)
  53052. {
  53053. idealWidth = 50;
  53054. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  53055. }
  53056. else
  53057. {
  53058. Font font (getPopupMenuFont());
  53059. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  53060. font.setHeight (standardMenuItemHeight / 1.3f);
  53061. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  53062. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  53063. }
  53064. }
  53065. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53066. {
  53067. const Colour background (findColour (PopupMenu::backgroundColourId));
  53068. g.fillAll (background);
  53069. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  53070. for (int i = 0; i < height; i += 3)
  53071. g.fillRect (0, i, width, 1);
  53072. #if ! JUCE_MAC
  53073. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  53074. g.drawRect (0, 0, width, height);
  53075. #endif
  53076. }
  53077. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  53078. int width, int height,
  53079. bool isScrollUpArrow)
  53080. {
  53081. const Colour background (findColour (PopupMenu::backgroundColourId));
  53082. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  53083. background.withAlpha (0.0f),
  53084. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53085. false));
  53086. g.fillRect (1, 1, width - 2, height - 2);
  53087. const float hw = width * 0.5f;
  53088. const float arrowW = height * 0.3f;
  53089. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53090. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53091. Path p;
  53092. p.addTriangle (hw - arrowW, y1,
  53093. hw + arrowW, y1,
  53094. hw, y2);
  53095. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53096. g.fillPath (p);
  53097. }
  53098. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53099. int width, int height,
  53100. const bool isSeparator,
  53101. const bool isActive,
  53102. const bool isHighlighted,
  53103. const bool isTicked,
  53104. const bool hasSubMenu,
  53105. const String& text,
  53106. const String& shortcutKeyText,
  53107. Image* image,
  53108. const Colour* const textColourToUse)
  53109. {
  53110. const float halfH = height * 0.5f;
  53111. if (isSeparator)
  53112. {
  53113. const float separatorIndent = 5.5f;
  53114. g.setColour (Colour (0x33000000));
  53115. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53116. g.setColour (Colour (0x66ffffff));
  53117. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53118. }
  53119. else
  53120. {
  53121. Colour textColour (findColour (PopupMenu::textColourId));
  53122. if (textColourToUse != 0)
  53123. textColour = *textColourToUse;
  53124. if (isHighlighted)
  53125. {
  53126. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53127. g.fillRect (1, 1, width - 2, height - 2);
  53128. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53129. }
  53130. else
  53131. {
  53132. g.setColour (textColour);
  53133. }
  53134. if (! isActive)
  53135. g.setOpacity (0.3f);
  53136. Font font (getPopupMenuFont());
  53137. if (font.getHeight() > height / 1.3f)
  53138. font.setHeight (height / 1.3f);
  53139. g.setFont (font);
  53140. const int leftBorder = (height * 5) / 4;
  53141. const int rightBorder = 4;
  53142. if (image != 0)
  53143. {
  53144. g.drawImageWithin (*image,
  53145. 2, 1, leftBorder - 4, height - 2,
  53146. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53147. }
  53148. else if (isTicked)
  53149. {
  53150. const Path tick (getTickShape (1.0f));
  53151. const float th = font.getAscent();
  53152. const float ty = halfH - th * 0.5f;
  53153. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53154. th, true));
  53155. }
  53156. g.drawFittedText (text,
  53157. leftBorder, 0,
  53158. width - (leftBorder + rightBorder), height,
  53159. Justification::centredLeft, 1);
  53160. if (shortcutKeyText.isNotEmpty())
  53161. {
  53162. Font f2 (font);
  53163. f2.setHeight (f2.getHeight() * 0.75f);
  53164. f2.setHorizontalScale (0.95f);
  53165. g.setFont (f2);
  53166. g.drawText (shortcutKeyText,
  53167. leftBorder,
  53168. 0,
  53169. width - (leftBorder + rightBorder + 4),
  53170. height,
  53171. Justification::centredRight,
  53172. true);
  53173. }
  53174. if (hasSubMenu)
  53175. {
  53176. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53177. const float x = width - height * 0.6f;
  53178. Path p;
  53179. p.addTriangle (x, halfH - arrowH * 0.5f,
  53180. x, halfH + arrowH * 0.5f,
  53181. x + arrowH * 0.6f, halfH);
  53182. g.fillPath (p);
  53183. }
  53184. }
  53185. }
  53186. int LookAndFeel::getMenuWindowFlags()
  53187. {
  53188. return ComponentPeer::windowHasDropShadow;
  53189. }
  53190. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53191. bool, MenuBarComponent& menuBar)
  53192. {
  53193. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53194. if (menuBar.isEnabled())
  53195. {
  53196. drawShinyButtonShape (g,
  53197. -4.0f, 0.0f,
  53198. width + 8.0f, (float) height,
  53199. 0.0f,
  53200. baseColour,
  53201. 0.4f,
  53202. true, true, true, true);
  53203. }
  53204. else
  53205. {
  53206. g.fillAll (baseColour);
  53207. }
  53208. }
  53209. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53210. {
  53211. return Font (menuBar.getHeight() * 0.7f);
  53212. }
  53213. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53214. {
  53215. return getMenuBarFont (menuBar, itemIndex, itemText)
  53216. .getStringWidth (itemText) + menuBar.getHeight();
  53217. }
  53218. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53219. int width, int height,
  53220. int itemIndex,
  53221. const String& itemText,
  53222. bool isMouseOverItem,
  53223. bool isMenuOpen,
  53224. bool /*isMouseOverBar*/,
  53225. MenuBarComponent& menuBar)
  53226. {
  53227. if (! menuBar.isEnabled())
  53228. {
  53229. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53230. .withMultipliedAlpha (0.5f));
  53231. }
  53232. else if (isMenuOpen || isMouseOverItem)
  53233. {
  53234. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53235. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53236. }
  53237. else
  53238. {
  53239. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53240. }
  53241. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53242. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53243. }
  53244. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53245. TextEditor& textEditor)
  53246. {
  53247. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53248. }
  53249. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53250. {
  53251. if (textEditor.isEnabled())
  53252. {
  53253. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53254. {
  53255. const int border = 2;
  53256. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53257. g.drawRect (0, 0, width, height, border);
  53258. g.setOpacity (1.0f);
  53259. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53260. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53261. }
  53262. else
  53263. {
  53264. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53265. g.drawRect (0, 0, width, height);
  53266. g.setOpacity (1.0f);
  53267. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53268. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53269. }
  53270. }
  53271. }
  53272. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53273. const bool isButtonDown,
  53274. int buttonX, int buttonY,
  53275. int buttonW, int buttonH,
  53276. ComboBox& box)
  53277. {
  53278. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53279. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53280. {
  53281. g.setColour (box.findColour (TextButton::buttonColourId));
  53282. g.drawRect (0, 0, width, height, 2);
  53283. }
  53284. else
  53285. {
  53286. g.setColour (box.findColour (ComboBox::outlineColourId));
  53287. g.drawRect (0, 0, width, height);
  53288. }
  53289. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53290. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  53291. box.hasKeyboardFocus (true),
  53292. false, isButtonDown)
  53293. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53294. drawGlassLozenge (g,
  53295. buttonX + outlineThickness, buttonY + outlineThickness,
  53296. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53297. baseColour, outlineThickness, -1.0f,
  53298. true, true, true, true);
  53299. if (box.isEnabled())
  53300. {
  53301. const float arrowX = 0.3f;
  53302. const float arrowH = 0.2f;
  53303. Path p;
  53304. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53305. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53306. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53307. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53308. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53309. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53310. g.setColour (box.findColour (ComboBox::arrowColourId));
  53311. g.fillPath (p);
  53312. }
  53313. }
  53314. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53315. {
  53316. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53317. }
  53318. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53319. {
  53320. return new Label (String::empty, String::empty);
  53321. }
  53322. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53323. {
  53324. label.setBounds (1, 1,
  53325. box.getWidth() + 3 - box.getHeight(),
  53326. box.getHeight() - 2);
  53327. label.setFont (getComboBoxFont (box));
  53328. }
  53329. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53330. {
  53331. g.fillAll (label.findColour (Label::backgroundColourId));
  53332. if (! label.isBeingEdited())
  53333. {
  53334. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53335. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53336. g.setFont (label.getFont());
  53337. g.drawFittedText (label.getText(),
  53338. label.getHorizontalBorderSize(),
  53339. label.getVerticalBorderSize(),
  53340. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53341. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53342. label.getJustificationType(),
  53343. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53344. label.getMinimumHorizontalScale());
  53345. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53346. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53347. }
  53348. else if (label.isEnabled())
  53349. {
  53350. g.setColour (label.findColour (Label::outlineColourId));
  53351. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53352. }
  53353. }
  53354. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53355. int x, int y,
  53356. int width, int height,
  53357. float /*sliderPos*/,
  53358. float /*minSliderPos*/,
  53359. float /*maxSliderPos*/,
  53360. const Slider::SliderStyle /*style*/,
  53361. Slider& slider)
  53362. {
  53363. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53364. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53365. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53366. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53367. Path indent;
  53368. if (slider.isHorizontal())
  53369. {
  53370. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53371. const float ih = sliderRadius;
  53372. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53373. gradCol2, 0.0f, iy + ih, false));
  53374. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53375. width + sliderRadius, ih,
  53376. 5.0f);
  53377. g.fillPath (indent);
  53378. }
  53379. else
  53380. {
  53381. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53382. const float iw = sliderRadius;
  53383. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53384. gradCol2, ix + iw, 0.0f, false));
  53385. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53386. iw, height + sliderRadius,
  53387. 5.0f);
  53388. g.fillPath (indent);
  53389. }
  53390. g.setColour (Colour (0x4c000000));
  53391. g.strokePath (indent, PathStrokeType (0.5f));
  53392. }
  53393. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53394. int x, int y,
  53395. int width, int height,
  53396. float sliderPos,
  53397. float minSliderPos,
  53398. float maxSliderPos,
  53399. const Slider::SliderStyle style,
  53400. Slider& slider)
  53401. {
  53402. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53403. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  53404. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53405. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53406. slider.isMouseButtonDown() && slider.isEnabled()));
  53407. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53408. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53409. {
  53410. float kx, ky;
  53411. if (style == Slider::LinearVertical)
  53412. {
  53413. kx = x + width * 0.5f;
  53414. ky = sliderPos;
  53415. }
  53416. else
  53417. {
  53418. kx = sliderPos;
  53419. ky = y + height * 0.5f;
  53420. }
  53421. drawGlassSphere (g,
  53422. kx - sliderRadius,
  53423. ky - sliderRadius,
  53424. sliderRadius * 2.0f,
  53425. knobColour, outlineThickness);
  53426. }
  53427. else
  53428. {
  53429. if (style == Slider::ThreeValueVertical)
  53430. {
  53431. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53432. sliderPos - sliderRadius,
  53433. sliderRadius * 2.0f,
  53434. knobColour, outlineThickness);
  53435. }
  53436. else if (style == Slider::ThreeValueHorizontal)
  53437. {
  53438. drawGlassSphere (g,sliderPos - sliderRadius,
  53439. y + height * 0.5f - sliderRadius,
  53440. sliderRadius * 2.0f,
  53441. knobColour, outlineThickness);
  53442. }
  53443. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53444. {
  53445. const float sr = jmin (sliderRadius, width * 0.4f);
  53446. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53447. minSliderPos - sliderRadius,
  53448. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53449. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53450. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53451. }
  53452. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53453. {
  53454. const float sr = jmin (sliderRadius, height * 0.4f);
  53455. drawGlassPointer (g, minSliderPos - sr,
  53456. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53457. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53458. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53459. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53460. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53461. }
  53462. }
  53463. }
  53464. void LookAndFeel::drawLinearSlider (Graphics& g,
  53465. int x, int y,
  53466. int width, int height,
  53467. float sliderPos,
  53468. float minSliderPos,
  53469. float maxSliderPos,
  53470. const Slider::SliderStyle style,
  53471. Slider& slider)
  53472. {
  53473. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53474. if (style == Slider::LinearBar)
  53475. {
  53476. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53477. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  53478. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53479. false,
  53480. isMouseOver,
  53481. isMouseOver || slider.isMouseButtonDown()));
  53482. drawShinyButtonShape (g,
  53483. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53484. baseColour,
  53485. slider.isEnabled() ? 0.9f : 0.3f,
  53486. true, true, true, true);
  53487. }
  53488. else
  53489. {
  53490. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53491. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53492. }
  53493. }
  53494. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53495. {
  53496. return jmin (7,
  53497. slider.getHeight() / 2,
  53498. slider.getWidth() / 2) + 2;
  53499. }
  53500. void LookAndFeel::drawRotarySlider (Graphics& g,
  53501. int x, int y,
  53502. int width, int height,
  53503. float sliderPos,
  53504. const float rotaryStartAngle,
  53505. const float rotaryEndAngle,
  53506. Slider& slider)
  53507. {
  53508. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53509. const float centreX = x + width * 0.5f;
  53510. const float centreY = y + height * 0.5f;
  53511. const float rx = centreX - radius;
  53512. const float ry = centreY - radius;
  53513. const float rw = radius * 2.0f;
  53514. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53515. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53516. if (radius > 12.0f)
  53517. {
  53518. if (slider.isEnabled())
  53519. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53520. else
  53521. g.setColour (Colour (0x80808080));
  53522. const float thickness = 0.7f;
  53523. {
  53524. Path filledArc;
  53525. filledArc.addPieSegment (rx, ry, rw, rw,
  53526. rotaryStartAngle,
  53527. angle,
  53528. thickness);
  53529. g.fillPath (filledArc);
  53530. }
  53531. if (thickness > 0)
  53532. {
  53533. const float innerRadius = radius * 0.2f;
  53534. Path p;
  53535. p.addTriangle (-innerRadius, 0.0f,
  53536. 0.0f, -radius * thickness * 1.1f,
  53537. innerRadius, 0.0f);
  53538. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53539. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53540. }
  53541. if (slider.isEnabled())
  53542. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53543. else
  53544. g.setColour (Colour (0x80808080));
  53545. Path outlineArc;
  53546. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53547. outlineArc.closeSubPath();
  53548. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53549. }
  53550. else
  53551. {
  53552. if (slider.isEnabled())
  53553. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53554. else
  53555. g.setColour (Colour (0x80808080));
  53556. Path p;
  53557. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53558. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53559. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53560. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53561. }
  53562. }
  53563. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53564. {
  53565. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53566. }
  53567. class SliderLabelComp : public Label
  53568. {
  53569. public:
  53570. SliderLabelComp() : Label (String::empty, String::empty) {}
  53571. ~SliderLabelComp() {}
  53572. void mouseWheelMove (const MouseEvent&, float, float) {}
  53573. };
  53574. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53575. {
  53576. Label* const l = new SliderLabelComp();
  53577. l->setJustificationType (Justification::centred);
  53578. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53579. l->setColour (Label::backgroundColourId,
  53580. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53581. : slider.findColour (Slider::textBoxBackgroundColourId));
  53582. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53583. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53584. l->setColour (TextEditor::backgroundColourId,
  53585. slider.findColour (Slider::textBoxBackgroundColourId)
  53586. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53587. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53588. return l;
  53589. }
  53590. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53591. {
  53592. return 0;
  53593. }
  53594. static const TextLayout layoutTooltipText (const String& text) throw()
  53595. {
  53596. const float tooltipFontSize = 12.0f;
  53597. const int maxToolTipWidth = 400;
  53598. const Font f (tooltipFontSize, Font::bold);
  53599. TextLayout tl (text, f);
  53600. tl.layout (maxToolTipWidth, Justification::left, true);
  53601. return tl;
  53602. }
  53603. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53604. {
  53605. const TextLayout tl (layoutTooltipText (tipText));
  53606. width = tl.getWidth() + 14;
  53607. height = tl.getHeight() + 6;
  53608. }
  53609. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53610. {
  53611. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53612. const Colour textCol (findColour (TooltipWindow::textColourId));
  53613. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53614. g.setColour (findColour (TooltipWindow::outlineColourId));
  53615. g.drawRect (0, 0, width, height, 1);
  53616. #endif
  53617. const TextLayout tl (layoutTooltipText (text));
  53618. g.setColour (findColour (TooltipWindow::textColourId));
  53619. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53620. }
  53621. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53622. {
  53623. return new TextButton (text, TRANS("click to browse for a different file"));
  53624. }
  53625. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53626. ComboBox* filenameBox,
  53627. Button* browseButton)
  53628. {
  53629. browseButton->setSize (80, filenameComp.getHeight());
  53630. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53631. if (tb != 0)
  53632. tb->changeWidthToFitText();
  53633. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53634. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53635. }
  53636. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53637. int imageX, int imageY, int imageW, int imageH,
  53638. const Colour& overlayColour,
  53639. float imageOpacity,
  53640. ImageButton& button)
  53641. {
  53642. if (! button.isEnabled())
  53643. imageOpacity *= 0.3f;
  53644. if (! overlayColour.isOpaque())
  53645. {
  53646. g.setOpacity (imageOpacity);
  53647. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53648. 0, 0, image->getWidth(), image->getHeight(), false);
  53649. }
  53650. if (! overlayColour.isTransparent())
  53651. {
  53652. g.setColour (overlayColour);
  53653. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53654. 0, 0, image->getWidth(), image->getHeight(), true);
  53655. }
  53656. }
  53657. void LookAndFeel::drawCornerResizer (Graphics& g,
  53658. int w, int h,
  53659. bool /*isMouseOver*/,
  53660. bool /*isMouseDragging*/)
  53661. {
  53662. const float lineThickness = jmin (w, h) * 0.075f;
  53663. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53664. {
  53665. g.setColour (Colours::lightgrey);
  53666. g.drawLine (w * i,
  53667. h + 1.0f,
  53668. w + 1.0f,
  53669. h * i,
  53670. lineThickness);
  53671. g.setColour (Colours::darkgrey);
  53672. g.drawLine (w * i + lineThickness,
  53673. h + 1.0f,
  53674. w + 1.0f,
  53675. h * i + lineThickness,
  53676. lineThickness);
  53677. }
  53678. }
  53679. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize& border)
  53680. {
  53681. if (! border.isEmpty())
  53682. {
  53683. const Rectangle<int> fullSize (0, 0, w, h);
  53684. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53685. g.saveState();
  53686. g.excludeClipRegion (centreArea);
  53687. g.setColour (Colour (0x50000000));
  53688. g.drawRect (fullSize);
  53689. g.setColour (Colour (0x19000000));
  53690. g.drawRect (centreArea.expanded (1, 1));
  53691. g.restoreState();
  53692. }
  53693. }
  53694. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53695. const BorderSize& /*border*/, ResizableWindow& window)
  53696. {
  53697. g.fillAll (window.getBackgroundColour());
  53698. }
  53699. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53700. const BorderSize& /*border*/, ResizableWindow&)
  53701. {
  53702. }
  53703. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53704. Graphics& g, int w, int h,
  53705. int titleSpaceX, int titleSpaceW,
  53706. const Image* icon,
  53707. bool drawTitleTextOnLeft)
  53708. {
  53709. const bool isActive = window.isActiveWindow();
  53710. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53711. 0.0f, 0.0f,
  53712. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53713. 0.0f, (float) h, false));
  53714. g.fillAll();
  53715. Font font (h * 0.65f, Font::bold);
  53716. g.setFont (font);
  53717. int textW = font.getStringWidth (window.getName());
  53718. int iconW = 0;
  53719. int iconH = 0;
  53720. if (icon != 0)
  53721. {
  53722. iconH = (int) font.getHeight();
  53723. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53724. }
  53725. textW = jmin (titleSpaceW, textW + iconW);
  53726. int textX = drawTitleTextOnLeft ? titleSpaceX
  53727. : jmax (titleSpaceX, (w - textW) / 2);
  53728. if (textX + textW > titleSpaceX + titleSpaceW)
  53729. textX = titleSpaceX + titleSpaceW - textW;
  53730. if (icon != 0)
  53731. {
  53732. g.setOpacity (isActive ? 1.0f : 0.6f);
  53733. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53734. RectanglePlacement::centred, false);
  53735. textX += iconW;
  53736. textW -= iconW;
  53737. }
  53738. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53739. g.setColour (findColour (DocumentWindow::textColourId));
  53740. else
  53741. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53742. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53743. }
  53744. class GlassWindowButton : public Button
  53745. {
  53746. public:
  53747. GlassWindowButton (const String& name, const Colour& col,
  53748. const Path& normalShape_,
  53749. const Path& toggledShape_) throw()
  53750. : Button (name),
  53751. colour (col),
  53752. normalShape (normalShape_),
  53753. toggledShape (toggledShape_)
  53754. {
  53755. }
  53756. ~GlassWindowButton()
  53757. {
  53758. }
  53759. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53760. {
  53761. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53762. if (! isEnabled())
  53763. alpha *= 0.5f;
  53764. float x = 0, y = 0, diam;
  53765. if (getWidth() < getHeight())
  53766. {
  53767. diam = (float) getWidth();
  53768. y = (getHeight() - getWidth()) * 0.5f;
  53769. }
  53770. else
  53771. {
  53772. diam = (float) getHeight();
  53773. y = (getWidth() - getHeight()) * 0.5f;
  53774. }
  53775. x += diam * 0.05f;
  53776. y += diam * 0.05f;
  53777. diam *= 0.9f;
  53778. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53779. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53780. g.fillEllipse (x, y, diam, diam);
  53781. x += 2.0f;
  53782. y += 2.0f;
  53783. diam -= 4.0f;
  53784. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53785. Path& p = getToggleState() ? toggledShape : normalShape;
  53786. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53787. diam * 0.4f, diam * 0.4f, true));
  53788. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53789. g.fillPath (p, t);
  53790. }
  53791. juce_UseDebuggingNewOperator
  53792. private:
  53793. Colour colour;
  53794. Path normalShape, toggledShape;
  53795. GlassWindowButton (const GlassWindowButton&);
  53796. GlassWindowButton& operator= (const GlassWindowButton&);
  53797. };
  53798. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53799. {
  53800. Path shape;
  53801. const float crossThickness = 0.25f;
  53802. if (buttonType == DocumentWindow::closeButton)
  53803. {
  53804. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53805. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53806. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53807. }
  53808. else if (buttonType == DocumentWindow::minimiseButton)
  53809. {
  53810. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53811. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53812. }
  53813. else if (buttonType == DocumentWindow::maximiseButton)
  53814. {
  53815. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53816. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53817. Path fullscreenShape;
  53818. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53819. fullscreenShape.lineTo (0.0f, 100.0f);
  53820. fullscreenShape.lineTo (0.0f, 0.0f);
  53821. fullscreenShape.lineTo (100.0f, 0.0f);
  53822. fullscreenShape.lineTo (100.0f, 45.0f);
  53823. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53824. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53825. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53826. }
  53827. jassertfalse;
  53828. return 0;
  53829. }
  53830. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53831. int titleBarX,
  53832. int titleBarY,
  53833. int titleBarW,
  53834. int titleBarH,
  53835. Button* minimiseButton,
  53836. Button* maximiseButton,
  53837. Button* closeButton,
  53838. bool positionTitleBarButtonsOnLeft)
  53839. {
  53840. const int buttonW = titleBarH - titleBarH / 8;
  53841. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53842. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53843. if (closeButton != 0)
  53844. {
  53845. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53846. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53847. }
  53848. if (positionTitleBarButtonsOnLeft)
  53849. swapVariables (minimiseButton, maximiseButton);
  53850. if (maximiseButton != 0)
  53851. {
  53852. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53853. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53854. }
  53855. if (minimiseButton != 0)
  53856. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53857. }
  53858. int LookAndFeel::getDefaultMenuBarHeight()
  53859. {
  53860. return 24;
  53861. }
  53862. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53863. {
  53864. return new DropShadower (0.4f, 1, 5, 10);
  53865. }
  53866. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53867. int w, int h,
  53868. bool /*isVerticalBar*/,
  53869. bool isMouseOver,
  53870. bool isMouseDragging)
  53871. {
  53872. float alpha = 0.5f;
  53873. if (isMouseOver || isMouseDragging)
  53874. {
  53875. g.fillAll (Colour (0x190000ff));
  53876. alpha = 1.0f;
  53877. }
  53878. const float cx = w * 0.5f;
  53879. const float cy = h * 0.5f;
  53880. const float cr = jmin (w, h) * 0.4f;
  53881. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53882. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53883. true));
  53884. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53885. }
  53886. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53887. const String& text,
  53888. const Justification& position,
  53889. GroupComponent& group)
  53890. {
  53891. const float textH = 15.0f;
  53892. const float indent = 3.0f;
  53893. const float textEdgeGap = 4.0f;
  53894. float cs = 5.0f;
  53895. Font f (textH);
  53896. Path p;
  53897. float x = indent;
  53898. float y = f.getAscent() - 3.0f;
  53899. float w = jmax (0.0f, width - x * 2.0f);
  53900. float h = jmax (0.0f, height - y - indent);
  53901. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53902. const float cs2 = 2.0f * cs;
  53903. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53904. float textX = cs + textEdgeGap;
  53905. if (position.testFlags (Justification::horizontallyCentred))
  53906. textX = cs + (w - cs2 - textW) * 0.5f;
  53907. else if (position.testFlags (Justification::right))
  53908. textX = w - cs - textW - textEdgeGap;
  53909. p.startNewSubPath (x + textX + textW, y);
  53910. p.lineTo (x + w - cs, y);
  53911. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53912. p.lineTo (x + w, y + h - cs);
  53913. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53914. p.lineTo (x + cs, y + h);
  53915. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53916. p.lineTo (x, y + cs);
  53917. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53918. p.lineTo (x + textX, y);
  53919. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53920. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53921. .withMultipliedAlpha (alpha));
  53922. g.strokePath (p, PathStrokeType (2.0f));
  53923. g.setColour (group.findColour (GroupComponent::textColourId)
  53924. .withMultipliedAlpha (alpha));
  53925. g.setFont (f);
  53926. g.drawText (text,
  53927. roundToInt (x + textX), 0,
  53928. roundToInt (textW),
  53929. roundToInt (textH),
  53930. Justification::centred, true);
  53931. }
  53932. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53933. {
  53934. return 1 + tabDepth / 3;
  53935. }
  53936. int LookAndFeel::getTabButtonSpaceAroundImage()
  53937. {
  53938. return 4;
  53939. }
  53940. void LookAndFeel::createTabButtonShape (Path& p,
  53941. int width, int height,
  53942. int /*tabIndex*/,
  53943. const String& /*text*/,
  53944. Button& /*button*/,
  53945. TabbedButtonBar::Orientation orientation,
  53946. const bool /*isMouseOver*/,
  53947. const bool /*isMouseDown*/,
  53948. const bool /*isFrontTab*/)
  53949. {
  53950. const float w = (float) width;
  53951. const float h = (float) height;
  53952. float length = w;
  53953. float depth = h;
  53954. if (orientation == TabbedButtonBar::TabsAtLeft
  53955. || orientation == TabbedButtonBar::TabsAtRight)
  53956. {
  53957. swapVariables (length, depth);
  53958. }
  53959. const float indent = (float) getTabButtonOverlap ((int) depth);
  53960. const float overhang = 4.0f;
  53961. if (orientation == TabbedButtonBar::TabsAtLeft)
  53962. {
  53963. p.startNewSubPath (w, 0.0f);
  53964. p.lineTo (0.0f, indent);
  53965. p.lineTo (0.0f, h - indent);
  53966. p.lineTo (w, h);
  53967. p.lineTo (w + overhang, h + overhang);
  53968. p.lineTo (w + overhang, -overhang);
  53969. }
  53970. else if (orientation == TabbedButtonBar::TabsAtRight)
  53971. {
  53972. p.startNewSubPath (0.0f, 0.0f);
  53973. p.lineTo (w, indent);
  53974. p.lineTo (w, h - indent);
  53975. p.lineTo (0.0f, h);
  53976. p.lineTo (-overhang, h + overhang);
  53977. p.lineTo (-overhang, -overhang);
  53978. }
  53979. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53980. {
  53981. p.startNewSubPath (0.0f, 0.0f);
  53982. p.lineTo (indent, h);
  53983. p.lineTo (w - indent, h);
  53984. p.lineTo (w, 0.0f);
  53985. p.lineTo (w + overhang, -overhang);
  53986. p.lineTo (-overhang, -overhang);
  53987. }
  53988. else
  53989. {
  53990. p.startNewSubPath (0.0f, h);
  53991. p.lineTo (indent, 0.0f);
  53992. p.lineTo (w - indent, 0.0f);
  53993. p.lineTo (w, h);
  53994. p.lineTo (w + overhang, h + overhang);
  53995. p.lineTo (-overhang, h + overhang);
  53996. }
  53997. p.closeSubPath();
  53998. p = p.createPathWithRoundedCorners (3.0f);
  53999. }
  54000. void LookAndFeel::fillTabButtonShape (Graphics& g,
  54001. const Path& path,
  54002. const Colour& preferredColour,
  54003. int /*tabIndex*/,
  54004. const String& /*text*/,
  54005. Button& button,
  54006. TabbedButtonBar::Orientation /*orientation*/,
  54007. const bool /*isMouseOver*/,
  54008. const bool /*isMouseDown*/,
  54009. const bool isFrontTab)
  54010. {
  54011. g.setColour (isFrontTab ? preferredColour
  54012. : preferredColour.withMultipliedAlpha (0.9f));
  54013. g.fillPath (path);
  54014. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  54015. : TabbedButtonBar::tabOutlineColourId, false)
  54016. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  54017. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  54018. }
  54019. void LookAndFeel::drawTabButtonText (Graphics& g,
  54020. int x, int y, int w, int h,
  54021. const Colour& preferredBackgroundColour,
  54022. int /*tabIndex*/,
  54023. const String& text,
  54024. Button& button,
  54025. TabbedButtonBar::Orientation orientation,
  54026. const bool isMouseOver,
  54027. const bool isMouseDown,
  54028. const bool isFrontTab)
  54029. {
  54030. int length = w;
  54031. int depth = h;
  54032. if (orientation == TabbedButtonBar::TabsAtLeft
  54033. || orientation == TabbedButtonBar::TabsAtRight)
  54034. {
  54035. swapVariables (length, depth);
  54036. }
  54037. Font font (depth * 0.6f);
  54038. font.setUnderline (button.hasKeyboardFocus (false));
  54039. GlyphArrangement textLayout;
  54040. textLayout.addFittedText (font, text.trim(),
  54041. 0.0f, 0.0f, (float) length, (float) depth,
  54042. Justification::centred,
  54043. jmax (1, depth / 12));
  54044. AffineTransform transform;
  54045. if (orientation == TabbedButtonBar::TabsAtLeft)
  54046. {
  54047. transform = transform.rotated (float_Pi * -0.5f)
  54048. .translated ((float) x, (float) (y + h));
  54049. }
  54050. else if (orientation == TabbedButtonBar::TabsAtRight)
  54051. {
  54052. transform = transform.rotated (float_Pi * 0.5f)
  54053. .translated ((float) (x + w), (float) y);
  54054. }
  54055. else
  54056. {
  54057. transform = transform.translated ((float) x, (float) y);
  54058. }
  54059. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  54060. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  54061. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  54062. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  54063. else
  54064. g.setColour (preferredBackgroundColour.contrasting());
  54065. if (! (isMouseOver || isMouseDown))
  54066. g.setOpacity (0.8f);
  54067. if (! button.isEnabled())
  54068. g.setOpacity (0.3f);
  54069. textLayout.draw (g, transform);
  54070. }
  54071. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  54072. const String& text,
  54073. int tabDepth,
  54074. Button&)
  54075. {
  54076. Font f (tabDepth * 0.6f);
  54077. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  54078. }
  54079. void LookAndFeel::drawTabButton (Graphics& g,
  54080. int w, int h,
  54081. const Colour& preferredColour,
  54082. int tabIndex,
  54083. const String& text,
  54084. Button& button,
  54085. TabbedButtonBar::Orientation orientation,
  54086. const bool isMouseOver,
  54087. const bool isMouseDown,
  54088. const bool isFrontTab)
  54089. {
  54090. int length = w;
  54091. int depth = h;
  54092. if (orientation == TabbedButtonBar::TabsAtLeft
  54093. || orientation == TabbedButtonBar::TabsAtRight)
  54094. {
  54095. swapVariables (length, depth);
  54096. }
  54097. Path tabShape;
  54098. createTabButtonShape (tabShape, w, h,
  54099. tabIndex, text, button, orientation,
  54100. isMouseOver, isMouseDown, isFrontTab);
  54101. fillTabButtonShape (g, tabShape, preferredColour,
  54102. tabIndex, text, button, orientation,
  54103. isMouseOver, isMouseDown, isFrontTab);
  54104. const int indent = getTabButtonOverlap (depth);
  54105. int x = 0, y = 0;
  54106. if (orientation == TabbedButtonBar::TabsAtLeft
  54107. || orientation == TabbedButtonBar::TabsAtRight)
  54108. {
  54109. y += indent;
  54110. h -= indent * 2;
  54111. }
  54112. else
  54113. {
  54114. x += indent;
  54115. w -= indent * 2;
  54116. }
  54117. drawTabButtonText (g, x, y, w, h, preferredColour,
  54118. tabIndex, text, button, orientation,
  54119. isMouseOver, isMouseDown, isFrontTab);
  54120. }
  54121. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54122. int w, int h,
  54123. TabbedButtonBar& tabBar,
  54124. TabbedButtonBar::Orientation orientation)
  54125. {
  54126. const float shadowSize = 0.2f;
  54127. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54128. Rectangle<int> shadowRect;
  54129. if (orientation == TabbedButtonBar::TabsAtLeft)
  54130. {
  54131. x1 = (float) w;
  54132. x2 = w * (1.0f - shadowSize);
  54133. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54134. }
  54135. else if (orientation == TabbedButtonBar::TabsAtRight)
  54136. {
  54137. x2 = w * shadowSize;
  54138. shadowRect.setBounds (0, 0, (int) x2, h);
  54139. }
  54140. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54141. {
  54142. y2 = h * shadowSize;
  54143. shadowRect.setBounds (0, 0, w, (int) y2);
  54144. }
  54145. else
  54146. {
  54147. y1 = (float) h;
  54148. y2 = h * (1.0f - shadowSize);
  54149. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54150. }
  54151. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54152. Colours::transparentBlack, x2, y2, false));
  54153. shadowRect.expand (2, 2);
  54154. g.fillRect (shadowRect);
  54155. g.setColour (Colour (0x80000000));
  54156. if (orientation == TabbedButtonBar::TabsAtLeft)
  54157. {
  54158. g.fillRect (w - 1, 0, 1, h);
  54159. }
  54160. else if (orientation == TabbedButtonBar::TabsAtRight)
  54161. {
  54162. g.fillRect (0, 0, 1, h);
  54163. }
  54164. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54165. {
  54166. g.fillRect (0, 0, w, 1);
  54167. }
  54168. else
  54169. {
  54170. g.fillRect (0, h - 1, w, 1);
  54171. }
  54172. }
  54173. Button* LookAndFeel::createTabBarExtrasButton()
  54174. {
  54175. const float thickness = 7.0f;
  54176. const float indent = 22.0f;
  54177. Path p;
  54178. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54179. DrawablePath ellipse;
  54180. ellipse.setPath (p);
  54181. ellipse.setFill (Colour (0x99ffffff));
  54182. p.clear();
  54183. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54184. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54185. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54186. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54187. p.setUsingNonZeroWinding (false);
  54188. DrawablePath dp;
  54189. dp.setPath (p);
  54190. dp.setFill (Colour (0x59000000));
  54191. DrawableComposite normalImage;
  54192. normalImage.insertDrawable (ellipse);
  54193. normalImage.insertDrawable (dp);
  54194. dp.setFill (Colour (0xcc000000));
  54195. DrawableComposite overImage;
  54196. overImage.insertDrawable (ellipse);
  54197. overImage.insertDrawable (dp);
  54198. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54199. db->setImages (&normalImage, &overImage, 0);
  54200. return db;
  54201. }
  54202. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54203. {
  54204. g.fillAll (Colours::white);
  54205. const int w = header.getWidth();
  54206. const int h = header.getHeight();
  54207. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54208. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54209. false));
  54210. g.fillRect (0, h / 2, w, h);
  54211. g.setColour (Colour (0x33000000));
  54212. g.fillRect (0, h - 1, w, 1);
  54213. for (int i = header.getNumColumns (true); --i >= 0;)
  54214. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54215. }
  54216. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54217. int width, int height,
  54218. bool isMouseOver, bool isMouseDown,
  54219. int columnFlags)
  54220. {
  54221. if (isMouseDown)
  54222. g.fillAll (Colour (0x8899aadd));
  54223. else if (isMouseOver)
  54224. g.fillAll (Colour (0x5599aadd));
  54225. int rightOfText = width - 4;
  54226. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54227. {
  54228. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54229. const float bottom = height - top;
  54230. const float w = height * 0.5f;
  54231. const float x = rightOfText - (w * 1.25f);
  54232. rightOfText = (int) x;
  54233. Path sortArrow;
  54234. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54235. g.setColour (Colour (0x99000000));
  54236. g.fillPath (sortArrow);
  54237. }
  54238. g.setColour (Colours::black);
  54239. g.setFont (height * 0.5f, Font::bold);
  54240. const int textX = 4;
  54241. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54242. }
  54243. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54244. {
  54245. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54246. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54247. background.darker (0.1f),
  54248. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54249. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54250. false));
  54251. g.fillAll();
  54252. }
  54253. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54254. {
  54255. return createTabBarExtrasButton();
  54256. }
  54257. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54258. bool isMouseOver, bool isMouseDown,
  54259. ToolbarItemComponent& component)
  54260. {
  54261. if (isMouseDown)
  54262. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54263. else if (isMouseOver)
  54264. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54265. }
  54266. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54267. const String& text, ToolbarItemComponent& component)
  54268. {
  54269. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54270. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54271. const float fontHeight = jmin (14.0f, height * 0.85f);
  54272. g.setFont (fontHeight);
  54273. g.drawFittedText (text,
  54274. x, y, width, height,
  54275. Justification::centred,
  54276. jmax (1, height / (int) fontHeight));
  54277. }
  54278. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54279. bool isOpen, int width, int height)
  54280. {
  54281. const int buttonSize = (height * 3) / 4;
  54282. const int buttonIndent = (height - buttonSize) / 2;
  54283. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54284. const int textX = buttonIndent * 2 + buttonSize + 2;
  54285. g.setColour (Colours::black);
  54286. g.setFont (height * 0.7f, Font::bold);
  54287. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54288. }
  54289. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54290. PropertyComponent&)
  54291. {
  54292. g.setColour (Colour (0x66ffffff));
  54293. g.fillRect (0, 0, width, height - 1);
  54294. }
  54295. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54296. PropertyComponent& component)
  54297. {
  54298. g.setColour (Colours::black);
  54299. if (! component.isEnabled())
  54300. g.setOpacity (0.6f);
  54301. g.setFont (jmin (height, 24) * 0.65f);
  54302. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54303. g.drawFittedText (component.getName(),
  54304. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54305. Justification::centredLeft, 2);
  54306. }
  54307. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54308. {
  54309. return Rectangle<int> (component.getWidth() / 3, 1,
  54310. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54311. }
  54312. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54313. {
  54314. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54315. {
  54316. Graphics g2 (content);
  54317. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54318. g2.fillPath (path);
  54319. g2.setColour (Colours::white.withAlpha (0.8f));
  54320. g2.strokePath (path, PathStrokeType (2.0f));
  54321. }
  54322. DropShadowEffect shadow;
  54323. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54324. shadow.applyEffect (content, g);
  54325. }
  54326. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54327. const String& instructions,
  54328. GlyphArrangement& text,
  54329. int width)
  54330. {
  54331. text.clear();
  54332. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54333. 8.0f, 22.0f, width - 16.0f,
  54334. Justification::centred);
  54335. text.addJustifiedText (Font (14.0f), instructions,
  54336. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54337. Justification::centred);
  54338. }
  54339. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54340. const String& filename, Image* icon,
  54341. const String& fileSizeDescription,
  54342. const String& fileTimeDescription,
  54343. const bool isDirectory,
  54344. const bool isItemSelected,
  54345. const int /*itemIndex*/,
  54346. DirectoryContentsDisplayComponent&)
  54347. {
  54348. if (isItemSelected)
  54349. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54350. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54351. g.setFont (height * 0.7f);
  54352. Image im;
  54353. if (icon != 0)
  54354. im = *icon;
  54355. if (im.isNull())
  54356. im = isDirectory ? getDefaultFolderImage()
  54357. : getDefaultDocumentFileImage();
  54358. const int x = 32;
  54359. if (im.isValid())
  54360. {
  54361. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  54362. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54363. false);
  54364. }
  54365. if (width > 450 && ! isDirectory)
  54366. {
  54367. const int sizeX = roundToInt (width * 0.7f);
  54368. const int dateX = roundToInt (width * 0.8f);
  54369. g.drawFittedText (filename,
  54370. x, 0, sizeX - x, height,
  54371. Justification::centredLeft, 1);
  54372. g.setFont (height * 0.5f);
  54373. g.setColour (Colours::darkgrey);
  54374. if (! isDirectory)
  54375. {
  54376. g.drawFittedText (fileSizeDescription,
  54377. sizeX, 0, dateX - sizeX - 8, height,
  54378. Justification::centredRight, 1);
  54379. g.drawFittedText (fileTimeDescription,
  54380. dateX, 0, width - 8 - dateX, height,
  54381. Justification::centredRight, 1);
  54382. }
  54383. }
  54384. else
  54385. {
  54386. g.drawFittedText (filename,
  54387. x, 0, width - x, height,
  54388. Justification::centredLeft, 1);
  54389. }
  54390. }
  54391. Button* LookAndFeel::createFileBrowserGoUpButton()
  54392. {
  54393. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54394. Path arrowPath;
  54395. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54396. DrawablePath arrowImage;
  54397. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54398. arrowImage.setPath (arrowPath);
  54399. goUpButton->setImages (&arrowImage);
  54400. return goUpButton;
  54401. }
  54402. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54403. DirectoryContentsDisplayComponent* fileListComponent,
  54404. FilePreviewComponent* previewComp,
  54405. ComboBox* currentPathBox,
  54406. TextEditor* filenameBox,
  54407. Button* goUpButton)
  54408. {
  54409. const int x = 8;
  54410. int w = browserComp.getWidth() - x - x;
  54411. if (previewComp != 0)
  54412. {
  54413. const int previewWidth = w / 3;
  54414. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54415. w -= previewWidth + 4;
  54416. }
  54417. int y = 4;
  54418. const int controlsHeight = 22;
  54419. const int bottomSectionHeight = controlsHeight + 8;
  54420. const int upButtonWidth = 50;
  54421. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54422. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54423. y += controlsHeight + 4;
  54424. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54425. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54426. y = listAsComp->getBottom() + 4;
  54427. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54428. }
  54429. const Image LookAndFeel::getDefaultFolderImage()
  54430. {
  54431. 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,
  54432. 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,
  54433. 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,
  54434. 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,
  54435. 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,
  54436. 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,
  54437. 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,
  54438. 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,
  54439. 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,
  54440. 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,
  54441. 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,
  54442. 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,
  54443. 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,
  54444. 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,
  54445. 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,
  54446. 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,
  54447. 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,
  54448. 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,
  54449. 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,
  54450. 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,
  54451. 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,
  54452. 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,
  54453. 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,
  54454. 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,
  54455. 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,
  54456. 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,
  54457. 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,
  54458. 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,
  54459. 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,
  54460. 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,
  54461. 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,
  54462. 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,
  54463. 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,
  54464. 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,
  54465. 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,
  54466. 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,
  54467. 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,
  54468. 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,
  54469. 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,
  54470. 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,
  54471. 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,
  54472. 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,
  54473. 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,
  54474. 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};
  54475. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  54476. }
  54477. const Image LookAndFeel::getDefaultDocumentFileImage()
  54478. {
  54479. 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,
  54480. 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,
  54481. 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,
  54482. 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,
  54483. 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,
  54484. 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,
  54485. 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,
  54486. 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,
  54487. 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,
  54488. 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,
  54489. 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,
  54490. 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,
  54491. 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,
  54492. 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,
  54493. 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,
  54494. 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,
  54495. 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,
  54496. 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,
  54497. 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,
  54498. 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,
  54499. 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,
  54500. 174,66,96,130,0,0};
  54501. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  54502. }
  54503. void LookAndFeel::playAlertSound()
  54504. {
  54505. PlatformUtilities::beep();
  54506. }
  54507. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54508. {
  54509. g.setColour (Colours::white.withAlpha (0.7f));
  54510. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54511. g.setColour (Colours::black.withAlpha (0.2f));
  54512. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54513. const int totalBlocks = 7;
  54514. const int numBlocks = roundToInt (totalBlocks * level);
  54515. const float w = (width - 6.0f) / (float) totalBlocks;
  54516. for (int i = 0; i < totalBlocks; ++i)
  54517. {
  54518. if (i >= numBlocks)
  54519. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54520. else
  54521. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54522. : Colours::red);
  54523. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54524. }
  54525. }
  54526. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54527. {
  54528. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54529. if (keyDescription.isNotEmpty())
  54530. {
  54531. if (button.isEnabled())
  54532. {
  54533. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54534. g.fillAll (textColour.withAlpha (alpha));
  54535. g.setOpacity (0.3f);
  54536. g.drawBevel (0, 0, width, height, 2);
  54537. }
  54538. g.setColour (textColour);
  54539. g.setFont (height * 0.6f);
  54540. g.drawFittedText (keyDescription,
  54541. 3, 0, width - 6, height,
  54542. Justification::centred, 1);
  54543. }
  54544. else
  54545. {
  54546. const float thickness = 7.0f;
  54547. const float indent = 22.0f;
  54548. Path p;
  54549. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54550. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54551. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54552. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54553. p.setUsingNonZeroWinding (false);
  54554. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54555. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54556. }
  54557. if (button.hasKeyboardFocus (false))
  54558. {
  54559. g.setColour (textColour.withAlpha (0.4f));
  54560. g.drawRect (0, 0, width, height);
  54561. }
  54562. }
  54563. static void createRoundedPath (Path& p,
  54564. const float x, const float y,
  54565. const float w, const float h,
  54566. const float cs,
  54567. const bool curveTopLeft, const bool curveTopRight,
  54568. const bool curveBottomLeft, const bool curveBottomRight) throw()
  54569. {
  54570. const float cs2 = 2.0f * cs;
  54571. if (curveTopLeft)
  54572. {
  54573. p.startNewSubPath (x, y + cs);
  54574. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  54575. }
  54576. else
  54577. {
  54578. p.startNewSubPath (x, y);
  54579. }
  54580. if (curveTopRight)
  54581. {
  54582. p.lineTo (x + w - cs, y);
  54583. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  54584. }
  54585. else
  54586. {
  54587. p.lineTo (x + w, y);
  54588. }
  54589. if (curveBottomRight)
  54590. {
  54591. p.lineTo (x + w, y + h - cs);
  54592. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  54593. }
  54594. else
  54595. {
  54596. p.lineTo (x + w, y + h);
  54597. }
  54598. if (curveBottomLeft)
  54599. {
  54600. p.lineTo (x + cs, y + h);
  54601. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  54602. }
  54603. else
  54604. {
  54605. p.lineTo (x, y + h);
  54606. }
  54607. p.closeSubPath();
  54608. }
  54609. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54610. float x, float y, float w, float h,
  54611. float maxCornerSize,
  54612. const Colour& baseColour,
  54613. const float strokeWidth,
  54614. const bool flatOnLeft,
  54615. const bool flatOnRight,
  54616. const bool flatOnTop,
  54617. const bool flatOnBottom) throw()
  54618. {
  54619. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54620. return;
  54621. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54622. Path outline;
  54623. createRoundedPath (outline, x, y, w, h, cs,
  54624. ! (flatOnLeft || flatOnTop),
  54625. ! (flatOnRight || flatOnTop),
  54626. ! (flatOnLeft || flatOnBottom),
  54627. ! (flatOnRight || flatOnBottom));
  54628. ColourGradient cg (baseColour, 0.0f, y,
  54629. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54630. false);
  54631. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54632. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54633. g.setGradientFill (cg);
  54634. g.fillPath (outline);
  54635. g.setColour (Colour (0x80000000));
  54636. g.strokePath (outline, PathStrokeType (strokeWidth));
  54637. }
  54638. void LookAndFeel::drawGlassSphere (Graphics& g,
  54639. const float x, const float y,
  54640. const float diameter,
  54641. const Colour& colour,
  54642. const float outlineThickness) throw()
  54643. {
  54644. if (diameter <= outlineThickness)
  54645. return;
  54646. Path p;
  54647. p.addEllipse (x, y, diameter, diameter);
  54648. {
  54649. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54650. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54651. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54652. g.setGradientFill (cg);
  54653. g.fillPath (p);
  54654. }
  54655. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54656. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54657. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54658. ColourGradient cg (Colours::transparentBlack,
  54659. x + diameter * 0.5f, y + diameter * 0.5f,
  54660. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54661. x, y + diameter * 0.5f, true);
  54662. cg.addColour (0.7, Colours::transparentBlack);
  54663. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54664. g.setGradientFill (cg);
  54665. g.fillPath (p);
  54666. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54667. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54668. }
  54669. void LookAndFeel::drawGlassPointer (Graphics& g,
  54670. const float x, const float y,
  54671. const float diameter,
  54672. const Colour& colour, const float outlineThickness,
  54673. const int direction) throw()
  54674. {
  54675. if (diameter <= outlineThickness)
  54676. return;
  54677. Path p;
  54678. p.startNewSubPath (x + diameter * 0.5f, y);
  54679. p.lineTo (x + diameter, y + diameter * 0.6f);
  54680. p.lineTo (x + diameter, y + diameter);
  54681. p.lineTo (x, y + diameter);
  54682. p.lineTo (x, y + diameter * 0.6f);
  54683. p.closeSubPath();
  54684. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54685. {
  54686. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54687. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54688. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54689. g.setGradientFill (cg);
  54690. g.fillPath (p);
  54691. }
  54692. ColourGradient cg (Colours::transparentBlack,
  54693. x + diameter * 0.5f, y + diameter * 0.5f,
  54694. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54695. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54696. cg.addColour (0.5, Colours::transparentBlack);
  54697. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54698. g.setGradientFill (cg);
  54699. g.fillPath (p);
  54700. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54701. g.strokePath (p, PathStrokeType (outlineThickness));
  54702. }
  54703. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54704. const float x, const float y,
  54705. const float width, const float height,
  54706. const Colour& colour,
  54707. const float outlineThickness,
  54708. const float cornerSize,
  54709. const bool flatOnLeft,
  54710. const bool flatOnRight,
  54711. const bool flatOnTop,
  54712. const bool flatOnBottom) throw()
  54713. {
  54714. if (width <= outlineThickness || height <= outlineThickness)
  54715. return;
  54716. const int intX = (int) x;
  54717. const int intY = (int) y;
  54718. const int intW = (int) width;
  54719. const int intH = (int) height;
  54720. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54721. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54722. const int intEdge = (int) edgeBlurRadius;
  54723. Path outline;
  54724. createRoundedPath (outline, x, y, width, height, cs,
  54725. ! (flatOnLeft || flatOnTop),
  54726. ! (flatOnRight || flatOnTop),
  54727. ! (flatOnLeft || flatOnBottom),
  54728. ! (flatOnRight || flatOnBottom));
  54729. {
  54730. ColourGradient cg (colour.darker (0.2f), 0, y,
  54731. colour.darker (0.2f), 0, y + height, false);
  54732. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54733. cg.addColour (0.4, colour);
  54734. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54735. g.setGradientFill (cg);
  54736. g.fillPath (outline);
  54737. }
  54738. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54739. colour.darker (0.2f), x, y + height * 0.5f, true);
  54740. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54741. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54742. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54743. {
  54744. g.saveState();
  54745. g.setGradientFill (cg);
  54746. g.reduceClipRegion (intX, intY, intEdge, intH);
  54747. g.fillPath (outline);
  54748. g.restoreState();
  54749. }
  54750. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54751. {
  54752. cg.point1.setX (x + width - edgeBlurRadius);
  54753. cg.point2.setX (x + width);
  54754. g.saveState();
  54755. g.setGradientFill (cg);
  54756. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54757. g.fillPath (outline);
  54758. g.restoreState();
  54759. }
  54760. {
  54761. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  54762. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  54763. Path highlight;
  54764. createRoundedPath (highlight,
  54765. x + leftIndent,
  54766. y + cs * 0.1f,
  54767. width - (leftIndent + rightIndent),
  54768. height * 0.4f, cs * 0.4f,
  54769. ! (flatOnLeft || flatOnTop),
  54770. ! (flatOnRight || flatOnTop),
  54771. ! (flatOnLeft || flatOnBottom),
  54772. ! (flatOnRight || flatOnBottom));
  54773. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54774. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54775. g.fillPath (highlight);
  54776. }
  54777. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54778. g.strokePath (outline, PathStrokeType (outlineThickness));
  54779. }
  54780. END_JUCE_NAMESPACE
  54781. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54782. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54783. BEGIN_JUCE_NAMESPACE
  54784. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54785. {
  54786. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54787. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54788. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54789. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54790. setColour (Slider::thumbColourId, Colours::white);
  54791. setColour (Slider::trackColourId, Colour (0x7f000000));
  54792. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54793. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54794. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54795. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54796. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54797. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54798. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54799. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54800. }
  54801. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54802. {
  54803. }
  54804. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54805. Button& button,
  54806. const Colour& backgroundColour,
  54807. bool isMouseOverButton,
  54808. bool isButtonDown)
  54809. {
  54810. const int width = button.getWidth();
  54811. const int height = button.getHeight();
  54812. const float indent = 2.0f;
  54813. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54814. roundToInt (height * 0.4f));
  54815. Path p;
  54816. p.addRoundedRectangle (indent, indent,
  54817. width - indent * 2.0f,
  54818. height - indent * 2.0f,
  54819. (float) cornerSize);
  54820. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54821. if (isMouseOverButton)
  54822. {
  54823. if (isButtonDown)
  54824. bc = bc.brighter();
  54825. else if (bc.getBrightness() > 0.5f)
  54826. bc = bc.darker (0.1f);
  54827. else
  54828. bc = bc.brighter (0.1f);
  54829. }
  54830. g.setColour (bc);
  54831. g.fillPath (p);
  54832. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54833. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54834. }
  54835. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54836. Component& /*component*/,
  54837. float x, float y, float w, float h,
  54838. const bool ticked,
  54839. const bool isEnabled,
  54840. const bool /*isMouseOverButton*/,
  54841. const bool isButtonDown)
  54842. {
  54843. Path box;
  54844. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54845. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54846. : Colours::lightgrey.withAlpha (0.1f));
  54847. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54848. g.fillPath (box, trans);
  54849. g.setColour (Colours::black.withAlpha (0.6f));
  54850. g.strokePath (box, PathStrokeType (0.9f), trans);
  54851. if (ticked)
  54852. {
  54853. Path tick;
  54854. tick.startNewSubPath (1.5f, 3.0f);
  54855. tick.lineTo (3.0f, 6.0f);
  54856. tick.lineTo (6.0f, 0.0f);
  54857. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54858. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54859. }
  54860. }
  54861. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54862. ToggleButton& button,
  54863. bool isMouseOverButton,
  54864. bool isButtonDown)
  54865. {
  54866. if (button.hasKeyboardFocus (true))
  54867. {
  54868. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54869. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54870. }
  54871. const int tickWidth = jmin (20, button.getHeight() - 4);
  54872. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54873. (float) tickWidth, (float) tickWidth,
  54874. button.getToggleState(),
  54875. button.isEnabled(),
  54876. isMouseOverButton,
  54877. isButtonDown);
  54878. g.setColour (button.findColour (ToggleButton::textColourId));
  54879. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54880. if (! button.isEnabled())
  54881. g.setOpacity (0.5f);
  54882. const int textX = tickWidth + 5;
  54883. g.drawFittedText (button.getButtonText(),
  54884. textX, 4,
  54885. button.getWidth() - textX - 2, button.getHeight() - 8,
  54886. Justification::centredLeft, 10);
  54887. }
  54888. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54889. int width, int height,
  54890. double progress, const String& textToShow)
  54891. {
  54892. if (progress < 0 || progress >= 1.0)
  54893. {
  54894. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54895. }
  54896. else
  54897. {
  54898. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54899. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54900. g.fillAll (background);
  54901. g.setColour (foreground);
  54902. g.fillRect (1, 1,
  54903. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54904. height - 2);
  54905. if (textToShow.isNotEmpty())
  54906. {
  54907. g.setColour (Colour::contrasting (background, foreground));
  54908. g.setFont (height * 0.6f);
  54909. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54910. }
  54911. }
  54912. }
  54913. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54914. ScrollBar& bar,
  54915. int width, int height,
  54916. int buttonDirection,
  54917. bool isScrollbarVertical,
  54918. bool isMouseOverButton,
  54919. bool isButtonDown)
  54920. {
  54921. if (isScrollbarVertical)
  54922. width -= 2;
  54923. else
  54924. height -= 2;
  54925. Path p;
  54926. if (buttonDirection == 0)
  54927. p.addTriangle (width * 0.5f, height * 0.2f,
  54928. width * 0.1f, height * 0.7f,
  54929. width * 0.9f, height * 0.7f);
  54930. else if (buttonDirection == 1)
  54931. p.addTriangle (width * 0.8f, height * 0.5f,
  54932. width * 0.3f, height * 0.1f,
  54933. width * 0.3f, height * 0.9f);
  54934. else if (buttonDirection == 2)
  54935. p.addTriangle (width * 0.5f, height * 0.8f,
  54936. width * 0.1f, height * 0.3f,
  54937. width * 0.9f, height * 0.3f);
  54938. else if (buttonDirection == 3)
  54939. p.addTriangle (width * 0.2f, height * 0.5f,
  54940. width * 0.7f, height * 0.1f,
  54941. width * 0.7f, height * 0.9f);
  54942. if (isButtonDown)
  54943. g.setColour (Colours::white);
  54944. else if (isMouseOverButton)
  54945. g.setColour (Colours::white.withAlpha (0.7f));
  54946. else
  54947. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54948. g.fillPath (p);
  54949. g.setColour (Colours::black.withAlpha (0.5f));
  54950. g.strokePath (p, PathStrokeType (0.5f));
  54951. }
  54952. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54953. ScrollBar& bar,
  54954. int x, int y,
  54955. int width, int height,
  54956. bool isScrollbarVertical,
  54957. int thumbStartPosition,
  54958. int thumbSize,
  54959. bool isMouseOver,
  54960. bool isMouseDown)
  54961. {
  54962. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54963. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54964. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54965. if (thumbSize > 0.0f)
  54966. {
  54967. Rectangle<int> thumb;
  54968. if (isScrollbarVertical)
  54969. {
  54970. width -= 2;
  54971. g.fillRect (x + roundToInt (width * 0.35f), y,
  54972. roundToInt (width * 0.3f), height);
  54973. thumb.setBounds (x + 1, thumbStartPosition,
  54974. width - 2, thumbSize);
  54975. }
  54976. else
  54977. {
  54978. height -= 2;
  54979. g.fillRect (x, y + roundToInt (height * 0.35f),
  54980. width, roundToInt (height * 0.3f));
  54981. thumb.setBounds (thumbStartPosition, y + 1,
  54982. thumbSize, height - 2);
  54983. }
  54984. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54985. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54986. g.fillRect (thumb);
  54987. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54988. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54989. if (thumbSize > 16)
  54990. {
  54991. for (int i = 3; --i >= 0;)
  54992. {
  54993. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54994. g.setColour (Colours::black.withAlpha (0.15f));
  54995. if (isScrollbarVertical)
  54996. {
  54997. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54998. g.setColour (Colours::white.withAlpha (0.15f));
  54999. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  55000. }
  55001. else
  55002. {
  55003. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  55004. g.setColour (Colours::white.withAlpha (0.15f));
  55005. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  55006. }
  55007. }
  55008. }
  55009. }
  55010. }
  55011. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  55012. {
  55013. return &scrollbarShadow;
  55014. }
  55015. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  55016. {
  55017. g.fillAll (findColour (PopupMenu::backgroundColourId));
  55018. g.setColour (Colours::black.withAlpha (0.6f));
  55019. g.drawRect (0, 0, width, height);
  55020. }
  55021. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  55022. bool, MenuBarComponent& menuBar)
  55023. {
  55024. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  55025. }
  55026. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  55027. {
  55028. if (textEditor.isEnabled())
  55029. {
  55030. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  55031. g.drawRect (0, 0, width, height);
  55032. }
  55033. }
  55034. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  55035. const bool isButtonDown,
  55036. int buttonX, int buttonY,
  55037. int buttonW, int buttonH,
  55038. ComboBox& box)
  55039. {
  55040. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  55041. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  55042. : ComboBox::backgroundColourId));
  55043. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  55044. g.setColour (box.findColour (ComboBox::outlineColourId));
  55045. g.drawRect (0, 0, width, height);
  55046. const float arrowX = 0.2f;
  55047. const float arrowH = 0.3f;
  55048. if (box.isEnabled())
  55049. {
  55050. Path p;
  55051. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  55052. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  55053. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  55054. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  55055. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  55056. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  55057. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  55058. : ComboBox::buttonColourId));
  55059. g.fillPath (p);
  55060. }
  55061. }
  55062. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  55063. {
  55064. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  55065. f.setHorizontalScale (0.9f);
  55066. return f;
  55067. }
  55068. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  55069. {
  55070. Path p;
  55071. p.addTriangle (x1, y1, x2, y2, x3, y3);
  55072. g.setColour (fill);
  55073. g.fillPath (p);
  55074. g.setColour (outline);
  55075. g.strokePath (p, PathStrokeType (0.3f));
  55076. }
  55077. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  55078. int x, int y,
  55079. int w, int h,
  55080. float sliderPos,
  55081. float minSliderPos,
  55082. float maxSliderPos,
  55083. const Slider::SliderStyle style,
  55084. Slider& slider)
  55085. {
  55086. g.fillAll (slider.findColour (Slider::backgroundColourId));
  55087. if (style == Slider::LinearBar)
  55088. {
  55089. g.setColour (slider.findColour (Slider::thumbColourId));
  55090. g.fillRect (x, y, (int) sliderPos - x, h);
  55091. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  55092. g.drawRect (x, y, (int) sliderPos - x, h);
  55093. }
  55094. else
  55095. {
  55096. g.setColour (slider.findColour (Slider::trackColourId)
  55097. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  55098. if (slider.isHorizontal())
  55099. {
  55100. g.fillRect (x, y + roundToInt (h * 0.6f),
  55101. w, roundToInt (h * 0.2f));
  55102. }
  55103. else
  55104. {
  55105. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  55106. jmin (4, roundToInt (w * 0.2f)), h);
  55107. }
  55108. float alpha = 0.35f;
  55109. if (slider.isEnabled())
  55110. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  55111. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  55112. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  55113. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  55114. {
  55115. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  55116. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  55117. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  55118. fill, outline);
  55119. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  55120. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  55121. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55122. fill, outline);
  55123. }
  55124. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55125. {
  55126. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55127. minSliderPos - 7.0f, y + h * 0.9f ,
  55128. minSliderPos, y + h * 0.9f,
  55129. fill, outline);
  55130. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55131. maxSliderPos, y + h * 0.9f,
  55132. maxSliderPos + 7.0f, y + h * 0.9f,
  55133. fill, outline);
  55134. }
  55135. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55136. {
  55137. drawTriangle (g, sliderPos, y + h * 0.9f,
  55138. sliderPos - 7.0f, y + h * 0.2f,
  55139. sliderPos + 7.0f, y + h * 0.2f,
  55140. fill, outline);
  55141. }
  55142. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55143. {
  55144. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55145. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55146. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55147. fill, outline);
  55148. }
  55149. }
  55150. }
  55151. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55152. {
  55153. if (isIncrement)
  55154. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55155. else
  55156. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55157. }
  55158. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55159. {
  55160. return &scrollbarShadow;
  55161. }
  55162. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55163. {
  55164. return 8;
  55165. }
  55166. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55167. int w, int h,
  55168. bool isMouseOver,
  55169. bool isMouseDragging)
  55170. {
  55171. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55172. : Colours::darkgrey);
  55173. const float lineThickness = jmin (w, h) * 0.1f;
  55174. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55175. {
  55176. g.drawLine (w * i,
  55177. h + 1.0f,
  55178. w + 1.0f,
  55179. h * i,
  55180. lineThickness);
  55181. }
  55182. }
  55183. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55184. {
  55185. Path shape;
  55186. if (buttonType == DocumentWindow::closeButton)
  55187. {
  55188. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55189. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55190. ShapeButton* const b = new ShapeButton ("close",
  55191. Colour (0x7fff3333),
  55192. Colour (0xd7ff3333),
  55193. Colour (0xf7ff3333));
  55194. b->setShape (shape, true, true, true);
  55195. return b;
  55196. }
  55197. else if (buttonType == DocumentWindow::minimiseButton)
  55198. {
  55199. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55200. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55201. DrawablePath dp;
  55202. dp.setPath (shape);
  55203. dp.setFill (Colours::black.withAlpha (0.3f));
  55204. b->setImages (&dp);
  55205. return b;
  55206. }
  55207. else if (buttonType == DocumentWindow::maximiseButton)
  55208. {
  55209. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55210. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55211. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55212. DrawablePath dp;
  55213. dp.setPath (shape);
  55214. dp.setFill (Colours::black.withAlpha (0.3f));
  55215. b->setImages (&dp);
  55216. return b;
  55217. }
  55218. jassertfalse;
  55219. return 0;
  55220. }
  55221. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55222. int titleBarX,
  55223. int titleBarY,
  55224. int titleBarW,
  55225. int titleBarH,
  55226. Button* minimiseButton,
  55227. Button* maximiseButton,
  55228. Button* closeButton,
  55229. bool positionTitleBarButtonsOnLeft)
  55230. {
  55231. titleBarY += titleBarH / 8;
  55232. titleBarH -= titleBarH / 4;
  55233. const int buttonW = titleBarH;
  55234. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55235. : titleBarX + titleBarW - buttonW - 4;
  55236. if (closeButton != 0)
  55237. {
  55238. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55239. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55240. : -(buttonW + buttonW / 5);
  55241. }
  55242. if (positionTitleBarButtonsOnLeft)
  55243. swapVariables (minimiseButton, maximiseButton);
  55244. if (maximiseButton != 0)
  55245. {
  55246. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55247. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55248. }
  55249. if (minimiseButton != 0)
  55250. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55251. }
  55252. END_JUCE_NAMESPACE
  55253. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55254. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55255. BEGIN_JUCE_NAMESPACE
  55256. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55257. : model (0),
  55258. itemUnderMouse (-1),
  55259. currentPopupIndex (-1),
  55260. topLevelIndexClicked (0),
  55261. lastMouseX (0),
  55262. lastMouseY (0)
  55263. {
  55264. setRepaintsOnMouseActivity (true);
  55265. setWantsKeyboardFocus (false);
  55266. setMouseClickGrabsKeyboardFocus (false);
  55267. setModel (model_);
  55268. }
  55269. MenuBarComponent::~MenuBarComponent()
  55270. {
  55271. setModel (0);
  55272. Desktop::getInstance().removeGlobalMouseListener (this);
  55273. }
  55274. MenuBarModel* MenuBarComponent::getModel() const throw()
  55275. {
  55276. return model;
  55277. }
  55278. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55279. {
  55280. if (model != newModel)
  55281. {
  55282. if (model != 0)
  55283. model->removeListener (this);
  55284. model = newModel;
  55285. if (model != 0)
  55286. model->addListener (this);
  55287. repaint();
  55288. menuBarItemsChanged (0);
  55289. }
  55290. }
  55291. void MenuBarComponent::paint (Graphics& g)
  55292. {
  55293. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55294. getLookAndFeel().drawMenuBarBackground (g,
  55295. getWidth(),
  55296. getHeight(),
  55297. isMouseOverBar,
  55298. *this);
  55299. if (model != 0)
  55300. {
  55301. for (int i = 0; i < menuNames.size(); ++i)
  55302. {
  55303. g.saveState();
  55304. g.setOrigin (xPositions [i], 0);
  55305. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55306. getLookAndFeel().drawMenuBarItem (g,
  55307. xPositions[i + 1] - xPositions[i],
  55308. getHeight(),
  55309. i,
  55310. menuNames[i],
  55311. i == itemUnderMouse,
  55312. i == currentPopupIndex,
  55313. isMouseOverBar,
  55314. *this);
  55315. g.restoreState();
  55316. }
  55317. }
  55318. }
  55319. void MenuBarComponent::resized()
  55320. {
  55321. xPositions.clear();
  55322. int x = 0;
  55323. xPositions.add (x);
  55324. for (int i = 0; i < menuNames.size(); ++i)
  55325. {
  55326. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55327. xPositions.add (x);
  55328. }
  55329. }
  55330. int MenuBarComponent::getItemAt (const int x, const int y)
  55331. {
  55332. for (int i = 0; i < xPositions.size(); ++i)
  55333. if (x >= xPositions[i] && x < xPositions[i + 1])
  55334. return reallyContains (x, y, true) ? i : -1;
  55335. return -1;
  55336. }
  55337. void MenuBarComponent::repaintMenuItem (int index)
  55338. {
  55339. if (((unsigned int) index) < (unsigned int) xPositions.size())
  55340. {
  55341. const int x1 = xPositions [index];
  55342. const int x2 = xPositions [index + 1];
  55343. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55344. }
  55345. }
  55346. void MenuBarComponent::setItemUnderMouse (const int index)
  55347. {
  55348. if (itemUnderMouse != index)
  55349. {
  55350. repaintMenuItem (itemUnderMouse);
  55351. itemUnderMouse = index;
  55352. repaintMenuItem (itemUnderMouse);
  55353. }
  55354. }
  55355. void MenuBarComponent::setOpenItem (int index)
  55356. {
  55357. if (currentPopupIndex != index)
  55358. {
  55359. repaintMenuItem (currentPopupIndex);
  55360. currentPopupIndex = index;
  55361. repaintMenuItem (currentPopupIndex);
  55362. if (index >= 0)
  55363. Desktop::getInstance().addGlobalMouseListener (this);
  55364. else
  55365. Desktop::getInstance().removeGlobalMouseListener (this);
  55366. }
  55367. }
  55368. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55369. {
  55370. setItemUnderMouse (getItemAt (x, y));
  55371. }
  55372. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55373. {
  55374. public:
  55375. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55376. : bar (bar_), topLevelIndex (topLevelIndex_)
  55377. {
  55378. }
  55379. ~AsyncCallback() {}
  55380. void modalStateFinished (int returnValue)
  55381. {
  55382. if (bar != 0)
  55383. bar->menuDismissed (topLevelIndex, returnValue);
  55384. }
  55385. private:
  55386. Component::SafePointer<MenuBarComponent> bar;
  55387. const int topLevelIndex;
  55388. AsyncCallback (const AsyncCallback&);
  55389. AsyncCallback& operator= (const AsyncCallback&);
  55390. };
  55391. void MenuBarComponent::showMenu (int index)
  55392. {
  55393. if (index != currentPopupIndex)
  55394. {
  55395. PopupMenu::dismissAllActiveMenus();
  55396. menuBarItemsChanged (0);
  55397. setOpenItem (index);
  55398. setItemUnderMouse (index);
  55399. if (index >= 0)
  55400. {
  55401. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55402. menuNames [itemUnderMouse]));
  55403. if (m.lookAndFeel == 0)
  55404. m.setLookAndFeel (&getLookAndFeel());
  55405. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55406. m.showMenu (itemPos + getScreenPosition(),
  55407. 0, itemPos.getWidth(), 0, 0, true, this,
  55408. new AsyncCallback (this, index));
  55409. }
  55410. }
  55411. }
  55412. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55413. {
  55414. topLevelIndexClicked = topLevelIndex;
  55415. postCommandMessage (itemId);
  55416. }
  55417. void MenuBarComponent::handleCommandMessage (int commandId)
  55418. {
  55419. const Point<int> mousePos (getMouseXYRelative());
  55420. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55421. if (currentPopupIndex == topLevelIndexClicked)
  55422. setOpenItem (-1);
  55423. if (commandId != 0 && model != 0)
  55424. model->menuItemSelected (commandId, topLevelIndexClicked);
  55425. }
  55426. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55427. {
  55428. if (e.eventComponent == this)
  55429. updateItemUnderMouse (e.x, e.y);
  55430. }
  55431. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55432. {
  55433. if (e.eventComponent == this)
  55434. updateItemUnderMouse (e.x, e.y);
  55435. }
  55436. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55437. {
  55438. if (currentPopupIndex < 0)
  55439. {
  55440. const MouseEvent e2 (e.getEventRelativeTo (this));
  55441. updateItemUnderMouse (e2.x, e2.y);
  55442. currentPopupIndex = -2;
  55443. showMenu (itemUnderMouse);
  55444. }
  55445. }
  55446. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55447. {
  55448. const MouseEvent e2 (e.getEventRelativeTo (this));
  55449. const int item = getItemAt (e2.x, e2.y);
  55450. if (item >= 0)
  55451. showMenu (item);
  55452. }
  55453. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55454. {
  55455. const MouseEvent e2 (e.getEventRelativeTo (this));
  55456. updateItemUnderMouse (e2.x, e2.y);
  55457. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55458. {
  55459. setOpenItem (-1);
  55460. PopupMenu::dismissAllActiveMenus();
  55461. }
  55462. }
  55463. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55464. {
  55465. const MouseEvent e2 (e.getEventRelativeTo (this));
  55466. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55467. {
  55468. if (currentPopupIndex >= 0)
  55469. {
  55470. const int item = getItemAt (e2.x, e2.y);
  55471. if (item >= 0)
  55472. showMenu (item);
  55473. }
  55474. else
  55475. {
  55476. updateItemUnderMouse (e2.x, e2.y);
  55477. }
  55478. lastMouseX = e2.x;
  55479. lastMouseY = e2.y;
  55480. }
  55481. }
  55482. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55483. {
  55484. bool used = false;
  55485. const int numMenus = menuNames.size();
  55486. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55487. if (key.isKeyCode (KeyPress::leftKey))
  55488. {
  55489. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55490. used = true;
  55491. }
  55492. else if (key.isKeyCode (KeyPress::rightKey))
  55493. {
  55494. showMenu ((currentIndex + 1) % numMenus);
  55495. used = true;
  55496. }
  55497. return used;
  55498. }
  55499. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55500. {
  55501. StringArray newNames;
  55502. if (model != 0)
  55503. newNames = model->getMenuBarNames();
  55504. if (newNames != menuNames)
  55505. {
  55506. menuNames = newNames;
  55507. repaint();
  55508. resized();
  55509. }
  55510. }
  55511. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55512. const ApplicationCommandTarget::InvocationInfo& info)
  55513. {
  55514. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55515. return;
  55516. for (int i = 0; i < menuNames.size(); ++i)
  55517. {
  55518. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55519. if (menu.containsCommandItem (info.commandID))
  55520. {
  55521. setItemUnderMouse (i);
  55522. startTimer (200);
  55523. break;
  55524. }
  55525. }
  55526. }
  55527. void MenuBarComponent::timerCallback()
  55528. {
  55529. stopTimer();
  55530. const Point<int> mousePos (getMouseXYRelative());
  55531. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55532. }
  55533. END_JUCE_NAMESPACE
  55534. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55535. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55536. BEGIN_JUCE_NAMESPACE
  55537. MenuBarModel::MenuBarModel() throw()
  55538. : manager (0)
  55539. {
  55540. }
  55541. MenuBarModel::~MenuBarModel()
  55542. {
  55543. setApplicationCommandManagerToWatch (0);
  55544. }
  55545. void MenuBarModel::menuItemsChanged()
  55546. {
  55547. triggerAsyncUpdate();
  55548. }
  55549. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55550. {
  55551. if (manager != newManager)
  55552. {
  55553. if (manager != 0)
  55554. manager->removeListener (this);
  55555. manager = newManager;
  55556. if (manager != 0)
  55557. manager->addListener (this);
  55558. }
  55559. }
  55560. void MenuBarModel::addListener (Listener* const newListener) throw()
  55561. {
  55562. listeners.add (newListener);
  55563. }
  55564. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55565. {
  55566. // Trying to remove a listener that isn't on the list!
  55567. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55568. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55569. jassert (listeners.contains (listenerToRemove));
  55570. listeners.remove (listenerToRemove);
  55571. }
  55572. void MenuBarModel::handleAsyncUpdate()
  55573. {
  55574. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55575. }
  55576. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55577. {
  55578. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55579. }
  55580. void MenuBarModel::applicationCommandListChanged()
  55581. {
  55582. menuItemsChanged();
  55583. }
  55584. END_JUCE_NAMESPACE
  55585. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55586. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55587. BEGIN_JUCE_NAMESPACE
  55588. class PopupMenu::Item
  55589. {
  55590. public:
  55591. Item()
  55592. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55593. usesColour (false), customComp (0), commandManager (0)
  55594. {
  55595. }
  55596. Item (const int itemId_,
  55597. const String& text_,
  55598. const bool active_,
  55599. const bool isTicked_,
  55600. const Image& im,
  55601. const Colour& textColour_,
  55602. const bool usesColour_,
  55603. PopupMenuCustomComponent* const customComp_,
  55604. const PopupMenu* const subMenu_,
  55605. ApplicationCommandManager* const commandManager_)
  55606. : itemId (itemId_), text (text_), textColour (textColour_),
  55607. active (active_), isSeparator (false), isTicked (isTicked_),
  55608. usesColour (usesColour_), image (im), customComp (customComp_),
  55609. commandManager (commandManager_)
  55610. {
  55611. if (subMenu_ != 0)
  55612. subMenu = new PopupMenu (*subMenu_);
  55613. if (commandManager_ != 0 && itemId_ != 0)
  55614. {
  55615. String shortcutKey;
  55616. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55617. ->getKeyPressesAssignedToCommand (itemId_));
  55618. for (int i = 0; i < keyPresses.size(); ++i)
  55619. {
  55620. const String key (keyPresses.getReference(i).getTextDescription());
  55621. if (shortcutKey.isNotEmpty())
  55622. shortcutKey << ", ";
  55623. if (key.length() == 1)
  55624. shortcutKey << "shortcut: '" << key << '\'';
  55625. else
  55626. shortcutKey << key;
  55627. }
  55628. shortcutKey = shortcutKey.trim();
  55629. if (shortcutKey.isNotEmpty())
  55630. text << "<end>" << shortcutKey;
  55631. }
  55632. }
  55633. Item (const Item& other)
  55634. : itemId (other.itemId),
  55635. text (other.text),
  55636. textColour (other.textColour),
  55637. active (other.active),
  55638. isSeparator (other.isSeparator),
  55639. isTicked (other.isTicked),
  55640. usesColour (other.usesColour),
  55641. image (other.image),
  55642. customComp (other.customComp),
  55643. commandManager (other.commandManager)
  55644. {
  55645. if (other.subMenu != 0)
  55646. subMenu = new PopupMenu (*(other.subMenu));
  55647. }
  55648. ~Item()
  55649. {
  55650. customComp = 0;
  55651. }
  55652. bool canBeTriggered() const throw()
  55653. {
  55654. return active && ! (isSeparator || (subMenu != 0));
  55655. }
  55656. bool hasActiveSubMenu() const throw()
  55657. {
  55658. return active && (subMenu != 0);
  55659. }
  55660. const int itemId;
  55661. String text;
  55662. const Colour textColour;
  55663. const bool active, isSeparator, isTicked, usesColour;
  55664. Image image;
  55665. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  55666. ScopedPointer <PopupMenu> subMenu;
  55667. ApplicationCommandManager* const commandManager;
  55668. juce_UseDebuggingNewOperator
  55669. private:
  55670. Item& operator= (const Item&);
  55671. };
  55672. class PopupMenu::ItemComponent : public Component
  55673. {
  55674. public:
  55675. ItemComponent (const PopupMenu::Item& itemInfo_)
  55676. : itemInfo (itemInfo_),
  55677. isHighlighted (false)
  55678. {
  55679. if (itemInfo.customComp != 0)
  55680. addAndMakeVisible (itemInfo.customComp);
  55681. }
  55682. ~ItemComponent()
  55683. {
  55684. if (itemInfo.customComp != 0)
  55685. removeChildComponent (itemInfo.customComp);
  55686. }
  55687. void getIdealSize (int& idealWidth,
  55688. int& idealHeight,
  55689. const int standardItemHeight)
  55690. {
  55691. if (itemInfo.customComp != 0)
  55692. {
  55693. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55694. }
  55695. else
  55696. {
  55697. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55698. itemInfo.isSeparator,
  55699. standardItemHeight,
  55700. idealWidth,
  55701. idealHeight);
  55702. }
  55703. }
  55704. void paint (Graphics& g)
  55705. {
  55706. if (itemInfo.customComp == 0)
  55707. {
  55708. String mainText (itemInfo.text);
  55709. String endText;
  55710. const int endIndex = mainText.indexOf ("<end>");
  55711. if (endIndex >= 0)
  55712. {
  55713. endText = mainText.substring (endIndex + 5).trim();
  55714. mainText = mainText.substring (0, endIndex);
  55715. }
  55716. getLookAndFeel()
  55717. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55718. itemInfo.isSeparator,
  55719. itemInfo.active,
  55720. isHighlighted,
  55721. itemInfo.isTicked,
  55722. itemInfo.subMenu != 0,
  55723. mainText, endText,
  55724. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55725. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55726. }
  55727. }
  55728. void resized()
  55729. {
  55730. if (getNumChildComponents() > 0)
  55731. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55732. }
  55733. void setHighlighted (bool shouldBeHighlighted)
  55734. {
  55735. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55736. if (isHighlighted != shouldBeHighlighted)
  55737. {
  55738. isHighlighted = shouldBeHighlighted;
  55739. if (itemInfo.customComp != 0)
  55740. {
  55741. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  55742. itemInfo.customComp->repaint();
  55743. }
  55744. repaint();
  55745. }
  55746. }
  55747. PopupMenu::Item itemInfo;
  55748. juce_UseDebuggingNewOperator
  55749. private:
  55750. bool isHighlighted;
  55751. ItemComponent (const ItemComponent&);
  55752. ItemComponent& operator= (const ItemComponent&);
  55753. };
  55754. namespace PopupMenuSettings
  55755. {
  55756. static const int scrollZone = 24;
  55757. static const int borderSize = 2;
  55758. static const int timerInterval = 50;
  55759. static const int dismissCommandId = 0x6287345f;
  55760. }
  55761. class PopupMenu::Window : public Component,
  55762. private Timer
  55763. {
  55764. public:
  55765. Window()
  55766. : Component ("menu"),
  55767. owner (0),
  55768. currentChild (0),
  55769. activeSubMenu (0),
  55770. managerOfChosenCommand (0),
  55771. minimumWidth (0),
  55772. maximumNumColumns (7),
  55773. standardItemHeight (0),
  55774. isOver (false),
  55775. hasBeenOver (false),
  55776. isDown (false),
  55777. needsToScroll (false),
  55778. hideOnExit (false),
  55779. disableMouseMoves (false),
  55780. hasAnyJuceCompHadFocus (false),
  55781. numColumns (0),
  55782. contentHeight (0),
  55783. childYOffset (0),
  55784. timeEnteredCurrentChildComp (0),
  55785. scrollAcceleration (1.0)
  55786. {
  55787. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  55788. setWantsKeyboardFocus (true);
  55789. setMouseClickGrabsKeyboardFocus (false);
  55790. setAlwaysOnTop (true);
  55791. Desktop::getInstance().addGlobalMouseListener (this);
  55792. getActiveWindows().add (this);
  55793. }
  55794. ~Window()
  55795. {
  55796. getActiveWindows().removeValue (this);
  55797. Desktop::getInstance().removeGlobalMouseListener (this);
  55798. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55799. activeSubMenu = 0;
  55800. deleteAllChildren();
  55801. }
  55802. static Window* create (const PopupMenu& menu,
  55803. const bool dismissOnMouseUp,
  55804. Window* const owner_,
  55805. const Rectangle<int>& target,
  55806. const int minimumWidth,
  55807. const int maximumNumColumns,
  55808. const int standardItemHeight,
  55809. const bool alignToRectangle,
  55810. const int itemIdThatMustBeVisible,
  55811. ApplicationCommandManager** managerOfChosenCommand,
  55812. Component* const componentAttachedTo)
  55813. {
  55814. if (menu.items.size() > 0)
  55815. {
  55816. int totalItems = 0;
  55817. ScopedPointer <Window> mw (new Window());
  55818. mw->setLookAndFeel (menu.lookAndFeel);
  55819. mw->setWantsKeyboardFocus (false);
  55820. mw->setOpaque (mw->getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55821. mw->minimumWidth = minimumWidth;
  55822. mw->maximumNumColumns = maximumNumColumns;
  55823. mw->standardItemHeight = standardItemHeight;
  55824. mw->dismissOnMouseUp = dismissOnMouseUp;
  55825. for (int i = 0; i < menu.items.size(); ++i)
  55826. {
  55827. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  55828. mw->addItem (*item);
  55829. ++totalItems;
  55830. }
  55831. if (totalItems > 0)
  55832. {
  55833. mw->owner = owner_;
  55834. mw->managerOfChosenCommand = managerOfChosenCommand;
  55835. mw->componentAttachedTo = componentAttachedTo;
  55836. mw->componentAttachedToOriginal = componentAttachedTo;
  55837. mw->calculateWindowPos (target, alignToRectangle);
  55838. mw->setTopLeftPosition (mw->windowPos.getX(),
  55839. mw->windowPos.getY());
  55840. mw->updateYPositions();
  55841. if (itemIdThatMustBeVisible != 0)
  55842. {
  55843. const int y = target.getY() - mw->windowPos.getY();
  55844. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  55845. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  55846. }
  55847. mw->resizeToBestWindowPos();
  55848. mw->addToDesktop (ComponentPeer::windowIsTemporary
  55849. | mw->getLookAndFeel().getMenuWindowFlags());
  55850. return mw.release();
  55851. }
  55852. }
  55853. return 0;
  55854. }
  55855. void paint (Graphics& g)
  55856. {
  55857. if (isOpaque())
  55858. g.fillAll (Colours::white);
  55859. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55860. }
  55861. void paintOverChildren (Graphics& g)
  55862. {
  55863. if (isScrolling())
  55864. {
  55865. LookAndFeel& lf = getLookAndFeel();
  55866. if (isScrollZoneActive (false))
  55867. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55868. if (isScrollZoneActive (true))
  55869. {
  55870. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55871. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55872. }
  55873. }
  55874. }
  55875. bool isScrollZoneActive (bool bottomOne) const
  55876. {
  55877. return isScrolling()
  55878. && (bottomOne
  55879. ? childYOffset < contentHeight - windowPos.getHeight()
  55880. : childYOffset > 0);
  55881. }
  55882. void addItem (const PopupMenu::Item& item)
  55883. {
  55884. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  55885. addAndMakeVisible (mic);
  55886. int itemW = 80;
  55887. int itemH = 16;
  55888. mic->getIdealSize (itemW, itemH, standardItemHeight);
  55889. mic->setSize (itemW, jlimit (2, 600, itemH));
  55890. mic->addMouseListener (this, false);
  55891. }
  55892. // hide this and all sub-comps
  55893. void hide (const PopupMenu::Item* const item)
  55894. {
  55895. if (isVisible())
  55896. {
  55897. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55898. activeSubMenu = 0;
  55899. currentChild = 0;
  55900. exitModalState (item != 0 ? item->itemId : 0);
  55901. setVisible (false);
  55902. if (item != 0
  55903. && item->commandManager != 0
  55904. && item->itemId != 0)
  55905. {
  55906. *managerOfChosenCommand = item->commandManager;
  55907. }
  55908. }
  55909. }
  55910. void dismissMenu (const PopupMenu::Item* const item)
  55911. {
  55912. if (owner != 0)
  55913. {
  55914. owner->dismissMenu (item);
  55915. }
  55916. else
  55917. {
  55918. if (item != 0)
  55919. {
  55920. // need a copy of this on the stack as the one passed in will get deleted during this call
  55921. const PopupMenu::Item mi (*item);
  55922. hide (&mi);
  55923. }
  55924. else
  55925. {
  55926. hide (0);
  55927. }
  55928. }
  55929. }
  55930. void mouseMove (const MouseEvent&)
  55931. {
  55932. timerCallback();
  55933. }
  55934. void mouseDown (const MouseEvent&)
  55935. {
  55936. timerCallback();
  55937. }
  55938. void mouseDrag (const MouseEvent&)
  55939. {
  55940. timerCallback();
  55941. }
  55942. void mouseUp (const MouseEvent&)
  55943. {
  55944. timerCallback();
  55945. }
  55946. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55947. {
  55948. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55949. lastMouse = Point<int> (-1, -1);
  55950. }
  55951. bool keyPressed (const KeyPress& key)
  55952. {
  55953. if (key.isKeyCode (KeyPress::downKey))
  55954. {
  55955. selectNextItem (1);
  55956. }
  55957. else if (key.isKeyCode (KeyPress::upKey))
  55958. {
  55959. selectNextItem (-1);
  55960. }
  55961. else if (key.isKeyCode (KeyPress::leftKey))
  55962. {
  55963. if (owner != 0)
  55964. {
  55965. Component::SafePointer<Window> parentWindow (owner);
  55966. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55967. hide (0);
  55968. if (parentWindow != 0)
  55969. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55970. disableTimerUntilMouseMoves();
  55971. }
  55972. else if (componentAttachedTo != 0)
  55973. {
  55974. componentAttachedTo->keyPressed (key);
  55975. }
  55976. }
  55977. else if (key.isKeyCode (KeyPress::rightKey))
  55978. {
  55979. disableTimerUntilMouseMoves();
  55980. if (showSubMenuFor (currentChild))
  55981. {
  55982. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55983. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55984. activeSubMenu->selectNextItem (1);
  55985. }
  55986. else if (componentAttachedTo != 0)
  55987. {
  55988. componentAttachedTo->keyPressed (key);
  55989. }
  55990. }
  55991. else if (key.isKeyCode (KeyPress::returnKey))
  55992. {
  55993. triggerCurrentlyHighlightedItem();
  55994. }
  55995. else if (key.isKeyCode (KeyPress::escapeKey))
  55996. {
  55997. dismissMenu (0);
  55998. }
  55999. else
  56000. {
  56001. return false;
  56002. }
  56003. return true;
  56004. }
  56005. void inputAttemptWhenModal()
  56006. {
  56007. Component::SafePointer<Component> deletionChecker (this);
  56008. timerCallback();
  56009. if (deletionChecker != 0 && ! isOverAnyMenu())
  56010. {
  56011. if (componentAttachedTo != 0)
  56012. {
  56013. // we want to dismiss the menu, but if we do it synchronously, then
  56014. // the mouse-click will be allowed to pass through. That's good, except
  56015. // when the user clicks on the button that orginally popped the menu up,
  56016. // as they'll expect the menu to go away, and in fact it'll just
  56017. // come back. So only dismiss synchronously if they're not on the original
  56018. // comp that we're attached to.
  56019. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  56020. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  56021. {
  56022. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  56023. return;
  56024. }
  56025. }
  56026. dismissMenu (0);
  56027. }
  56028. }
  56029. void handleCommandMessage (int commandId)
  56030. {
  56031. Component::handleCommandMessage (commandId);
  56032. if (commandId == PopupMenuSettings::dismissCommandId)
  56033. dismissMenu (0);
  56034. }
  56035. void timerCallback()
  56036. {
  56037. if (! isVisible())
  56038. return;
  56039. if (componentAttachedTo != componentAttachedToOriginal)
  56040. {
  56041. dismissMenu (0);
  56042. return;
  56043. }
  56044. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  56045. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  56046. return;
  56047. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  56048. // move rather than a real timer callback
  56049. const Point<int> globalMousePos (Desktop::getMousePosition());
  56050. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  56051. const uint32 now = Time::getMillisecondCounter();
  56052. if (now > timeEnteredCurrentChildComp + 100
  56053. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  56054. && currentChild->isValidComponent()
  56055. && (! disableMouseMoves)
  56056. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  56057. {
  56058. showSubMenuFor (currentChild);
  56059. }
  56060. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  56061. {
  56062. highlightItemUnderMouse (globalMousePos, localMousePos);
  56063. }
  56064. bool overScrollArea = false;
  56065. if (isScrolling()
  56066. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  56067. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  56068. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  56069. {
  56070. if (now > lastScroll + 20)
  56071. {
  56072. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  56073. int amount = 0;
  56074. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  56075. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  56076. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  56077. lastScroll = now;
  56078. }
  56079. overScrollArea = true;
  56080. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  56081. }
  56082. else
  56083. {
  56084. scrollAcceleration = 1.0;
  56085. }
  56086. const bool wasDown = isDown;
  56087. bool isOverAny = isOverAnyMenu();
  56088. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  56089. {
  56090. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56091. isOverAny = isOverAnyMenu();
  56092. }
  56093. if (hideOnExit && hasBeenOver && ! isOverAny)
  56094. {
  56095. hide (0);
  56096. }
  56097. else
  56098. {
  56099. isDown = hasBeenOver
  56100. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  56101. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  56102. bool anyFocused = Process::isForegroundProcess();
  56103. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  56104. {
  56105. // because no component at all may have focus, our test here will
  56106. // only be triggered when something has focus and then loses it.
  56107. anyFocused = ! hasAnyJuceCompHadFocus;
  56108. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  56109. {
  56110. if (ComponentPeer::getPeer (i)->isFocused())
  56111. {
  56112. anyFocused = true;
  56113. hasAnyJuceCompHadFocus = true;
  56114. break;
  56115. }
  56116. }
  56117. }
  56118. if (! anyFocused)
  56119. {
  56120. if (now > lastFocused + 10)
  56121. {
  56122. wasHiddenBecauseOfAppChange() = true;
  56123. dismissMenu (0);
  56124. return; // may have been deleted by the previous call..
  56125. }
  56126. }
  56127. else if (wasDown && now > menuCreationTime + 250
  56128. && ! (isDown || overScrollArea))
  56129. {
  56130. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56131. if (isOver)
  56132. {
  56133. triggerCurrentlyHighlightedItem();
  56134. }
  56135. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  56136. {
  56137. dismissMenu (0);
  56138. }
  56139. return; // may have been deleted by the previous calls..
  56140. }
  56141. else
  56142. {
  56143. lastFocused = now;
  56144. }
  56145. }
  56146. }
  56147. static Array<Window*>& getActiveWindows()
  56148. {
  56149. static Array<Window*> activeMenuWindows;
  56150. return activeMenuWindows;
  56151. }
  56152. static bool& wasHiddenBecauseOfAppChange() throw()
  56153. {
  56154. static bool b = false;
  56155. return b;
  56156. }
  56157. juce_UseDebuggingNewOperator
  56158. private:
  56159. Window* owner;
  56160. PopupMenu::ItemComponent* currentChild;
  56161. ScopedPointer <Window> activeSubMenu;
  56162. ApplicationCommandManager** managerOfChosenCommand;
  56163. Component::SafePointer<Component> componentAttachedTo;
  56164. Component* componentAttachedToOriginal;
  56165. Rectangle<int> windowPos;
  56166. Point<int> lastMouse;
  56167. int minimumWidth, maximumNumColumns, standardItemHeight;
  56168. bool isOver, hasBeenOver, isDown, needsToScroll;
  56169. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  56170. int numColumns, contentHeight, childYOffset;
  56171. Array <int> columnWidths;
  56172. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  56173. double scrollAcceleration;
  56174. bool overlaps (const Rectangle<int>& r) const
  56175. {
  56176. return r.intersects (getBounds())
  56177. || (owner != 0 && owner->overlaps (r));
  56178. }
  56179. bool isOverAnyMenu() const
  56180. {
  56181. return (owner != 0) ? owner->isOverAnyMenu()
  56182. : isOverChildren();
  56183. }
  56184. bool isOverChildren() const
  56185. {
  56186. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56187. return isVisible()
  56188. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56189. }
  56190. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56191. {
  56192. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  56193. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  56194. if (activeSubMenu != 0)
  56195. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56196. }
  56197. bool treeContains (const Window* const window) const throw()
  56198. {
  56199. const Window* mw = this;
  56200. while (mw->owner != 0)
  56201. mw = mw->owner;
  56202. while (mw != 0)
  56203. {
  56204. if (mw == window)
  56205. return true;
  56206. mw = mw->activeSubMenu;
  56207. }
  56208. return false;
  56209. }
  56210. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56211. {
  56212. const Rectangle<int> mon (Desktop::getInstance()
  56213. .getMonitorAreaContaining (target.getCentre(),
  56214. #if JUCE_MAC
  56215. true));
  56216. #else
  56217. false)); // on windows, don't stop the menu overlapping the taskbar
  56218. #endif
  56219. int x, y, widthToUse, heightToUse;
  56220. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56221. if (alignToRectangle)
  56222. {
  56223. x = target.getX();
  56224. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56225. const int spaceOver = target.getY() - mon.getY();
  56226. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56227. y = target.getBottom();
  56228. else
  56229. y = target.getY() - heightToUse;
  56230. }
  56231. else
  56232. {
  56233. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56234. if (owner != 0)
  56235. {
  56236. if (owner->owner != 0)
  56237. {
  56238. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56239. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56240. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56241. tendTowardsRight = true;
  56242. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56243. tendTowardsRight = false;
  56244. }
  56245. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56246. {
  56247. tendTowardsRight = true;
  56248. }
  56249. }
  56250. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56251. target.getX() - mon.getX()) - 32;
  56252. if (biggestSpace < widthToUse)
  56253. {
  56254. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56255. if (numColumns > 1)
  56256. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56257. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56258. }
  56259. if (tendTowardsRight)
  56260. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56261. else
  56262. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56263. y = target.getY();
  56264. if (target.getCentreY() > mon.getCentreY())
  56265. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56266. }
  56267. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56268. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56269. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56270. // sets this flag if it's big enough to obscure any of its parent menus
  56271. hideOnExit = (owner != 0)
  56272. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56273. }
  56274. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56275. {
  56276. numColumns = 0;
  56277. contentHeight = 0;
  56278. const int maxMenuH = getParentHeight() - 24;
  56279. int totalW;
  56280. do
  56281. {
  56282. ++numColumns;
  56283. totalW = workOutBestSize (maxMenuW);
  56284. if (totalW > maxMenuW)
  56285. {
  56286. numColumns = jmax (1, numColumns - 1);
  56287. totalW = workOutBestSize (maxMenuW); // to update col widths
  56288. break;
  56289. }
  56290. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56291. {
  56292. break;
  56293. }
  56294. } while (numColumns < maximumNumColumns);
  56295. const int actualH = jmin (contentHeight, maxMenuH);
  56296. needsToScroll = contentHeight > actualH;
  56297. width = updateYPositions();
  56298. height = actualH + PopupMenuSettings::borderSize * 2;
  56299. }
  56300. int workOutBestSize (const int maxMenuW)
  56301. {
  56302. int totalW = 0;
  56303. contentHeight = 0;
  56304. int childNum = 0;
  56305. for (int col = 0; col < numColumns; ++col)
  56306. {
  56307. int i, colW = 50, colH = 0;
  56308. const int numChildren = jmin (getNumChildComponents() - childNum,
  56309. (getNumChildComponents() + numColumns - 1) / numColumns);
  56310. for (i = numChildren; --i >= 0;)
  56311. {
  56312. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  56313. colH += getChildComponent (childNum + i)->getHeight();
  56314. }
  56315. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56316. columnWidths.set (col, colW);
  56317. totalW += colW;
  56318. contentHeight = jmax (contentHeight, colH);
  56319. childNum += numChildren;
  56320. }
  56321. if (totalW < minimumWidth)
  56322. {
  56323. totalW = minimumWidth;
  56324. for (int col = 0; col < numColumns; ++col)
  56325. columnWidths.set (0, totalW / numColumns);
  56326. }
  56327. return totalW;
  56328. }
  56329. void ensureItemIsVisible (const int itemId, int wantedY)
  56330. {
  56331. jassert (itemId != 0)
  56332. for (int i = getNumChildComponents(); --i >= 0;)
  56333. {
  56334. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  56335. if (m != 0
  56336. && m->itemInfo.itemId == itemId
  56337. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56338. {
  56339. const int currentY = m->getY();
  56340. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56341. {
  56342. if (wantedY < 0)
  56343. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56344. jmax (PopupMenuSettings::scrollZone,
  56345. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56346. currentY);
  56347. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56348. int deltaY = wantedY - currentY;
  56349. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56350. jmin (windowPos.getHeight(), mon.getHeight()));
  56351. const int newY = jlimit (mon.getY(),
  56352. mon.getBottom() - windowPos.getHeight(),
  56353. windowPos.getY() + deltaY);
  56354. deltaY -= newY - windowPos.getY();
  56355. childYOffset -= deltaY;
  56356. windowPos.setPosition (windowPos.getX(), newY);
  56357. updateYPositions();
  56358. }
  56359. break;
  56360. }
  56361. }
  56362. }
  56363. void resizeToBestWindowPos()
  56364. {
  56365. Rectangle<int> r (windowPos);
  56366. if (childYOffset < 0)
  56367. {
  56368. r.setBounds (r.getX(), r.getY() - childYOffset,
  56369. r.getWidth(), r.getHeight() + childYOffset);
  56370. }
  56371. else if (childYOffset > 0)
  56372. {
  56373. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56374. if (spaceAtBottom > 0)
  56375. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56376. }
  56377. setBounds (r);
  56378. updateYPositions();
  56379. }
  56380. void alterChildYPos (const int delta)
  56381. {
  56382. if (isScrolling())
  56383. {
  56384. childYOffset += delta;
  56385. if (delta < 0)
  56386. {
  56387. childYOffset = jmax (childYOffset, 0);
  56388. }
  56389. else if (delta > 0)
  56390. {
  56391. childYOffset = jmin (childYOffset,
  56392. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56393. }
  56394. updateYPositions();
  56395. }
  56396. else
  56397. {
  56398. childYOffset = 0;
  56399. }
  56400. resizeToBestWindowPos();
  56401. repaint();
  56402. }
  56403. int updateYPositions()
  56404. {
  56405. int x = 0;
  56406. int childNum = 0;
  56407. for (int col = 0; col < numColumns; ++col)
  56408. {
  56409. const int numChildren = jmin (getNumChildComponents() - childNum,
  56410. (getNumChildComponents() + numColumns - 1) / numColumns);
  56411. const int colW = columnWidths [col];
  56412. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56413. for (int i = 0; i < numChildren; ++i)
  56414. {
  56415. Component* const c = getChildComponent (childNum + i);
  56416. c->setBounds (x, y, colW, c->getHeight());
  56417. y += c->getHeight();
  56418. }
  56419. x += colW;
  56420. childNum += numChildren;
  56421. }
  56422. return x;
  56423. }
  56424. bool isScrolling() const throw()
  56425. {
  56426. return childYOffset != 0 || needsToScroll;
  56427. }
  56428. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56429. {
  56430. if (currentChild->isValidComponent())
  56431. currentChild->setHighlighted (false);
  56432. currentChild = child;
  56433. if (currentChild != 0)
  56434. {
  56435. currentChild->setHighlighted (true);
  56436. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56437. }
  56438. }
  56439. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56440. {
  56441. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56442. activeSubMenu = 0;
  56443. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  56444. {
  56445. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56446. dismissOnMouseUp,
  56447. this,
  56448. childComp->getScreenBounds(),
  56449. 0, maximumNumColumns,
  56450. standardItemHeight,
  56451. false, 0, managerOfChosenCommand,
  56452. componentAttachedTo);
  56453. if (activeSubMenu != 0)
  56454. {
  56455. activeSubMenu->setVisible (true);
  56456. activeSubMenu->enterModalState (false);
  56457. activeSubMenu->toFront (false);
  56458. return true;
  56459. }
  56460. }
  56461. return false;
  56462. }
  56463. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56464. {
  56465. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56466. if (isOver)
  56467. hasBeenOver = true;
  56468. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56469. {
  56470. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56471. if (disableMouseMoves && isOver)
  56472. disableMouseMoves = false;
  56473. }
  56474. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56475. return;
  56476. bool isMovingTowardsMenu = false;
  56477. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  56478. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56479. {
  56480. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56481. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56482. // extends from the last mouse pos to the submenu's rectangle..
  56483. float subX = (float) activeSubMenu->getScreenX();
  56484. if (activeSubMenu->getX() > getX())
  56485. {
  56486. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56487. }
  56488. else
  56489. {
  56490. lastMouse += Point<int> (2, 0);
  56491. subX += activeSubMenu->getWidth();
  56492. }
  56493. Path areaTowardsSubMenu;
  56494. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  56495. (float) lastMouse.getY(),
  56496. subX,
  56497. (float) activeSubMenu->getScreenY(),
  56498. subX,
  56499. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56500. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56501. }
  56502. lastMouse = globalMousePos;
  56503. if (! isMovingTowardsMenu)
  56504. {
  56505. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56506. if (c == this)
  56507. c = 0;
  56508. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56509. if (mic == 0 && c != 0)
  56510. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56511. if (mic != currentChild
  56512. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56513. {
  56514. if (isOver && (c != 0) && (activeSubMenu != 0))
  56515. {
  56516. activeSubMenu->hide (0);
  56517. }
  56518. if (! isOver)
  56519. mic = 0;
  56520. setCurrentlyHighlightedChild (mic);
  56521. }
  56522. }
  56523. }
  56524. void triggerCurrentlyHighlightedItem()
  56525. {
  56526. if (currentChild->isValidComponent()
  56527. && currentChild->itemInfo.canBeTriggered()
  56528. && (currentChild->itemInfo.customComp == 0
  56529. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  56530. {
  56531. dismissMenu (&currentChild->itemInfo);
  56532. }
  56533. }
  56534. void selectNextItem (const int delta)
  56535. {
  56536. disableTimerUntilMouseMoves();
  56537. PopupMenu::ItemComponent* mic = 0;
  56538. bool wasLastOne = (currentChild == 0);
  56539. const int numItems = getNumChildComponents();
  56540. for (int i = 0; i < numItems + 1; ++i)
  56541. {
  56542. int index = (delta > 0) ? i : (numItems - 1 - i);
  56543. index = (index + numItems) % numItems;
  56544. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  56545. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56546. && wasLastOne)
  56547. break;
  56548. if (mic == currentChild)
  56549. wasLastOne = true;
  56550. }
  56551. setCurrentlyHighlightedChild (mic);
  56552. }
  56553. void disableTimerUntilMouseMoves()
  56554. {
  56555. disableMouseMoves = true;
  56556. if (owner != 0)
  56557. owner->disableTimerUntilMouseMoves();
  56558. }
  56559. Window (const Window&);
  56560. Window& operator= (const Window&);
  56561. };
  56562. PopupMenu::PopupMenu()
  56563. : lookAndFeel (0),
  56564. separatorPending (false)
  56565. {
  56566. }
  56567. PopupMenu::PopupMenu (const PopupMenu& other)
  56568. : lookAndFeel (other.lookAndFeel),
  56569. separatorPending (false)
  56570. {
  56571. items.addCopiesOf (other.items);
  56572. }
  56573. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56574. {
  56575. if (this != &other)
  56576. {
  56577. lookAndFeel = other.lookAndFeel;
  56578. clear();
  56579. items.addCopiesOf (other.items);
  56580. }
  56581. return *this;
  56582. }
  56583. PopupMenu::~PopupMenu()
  56584. {
  56585. clear();
  56586. }
  56587. void PopupMenu::clear()
  56588. {
  56589. items.clear();
  56590. separatorPending = false;
  56591. }
  56592. void PopupMenu::addSeparatorIfPending()
  56593. {
  56594. if (separatorPending)
  56595. {
  56596. separatorPending = false;
  56597. if (items.size() > 0)
  56598. items.add (new Item());
  56599. }
  56600. }
  56601. void PopupMenu::addItem (const int itemResultId,
  56602. const String& itemText,
  56603. const bool isActive,
  56604. const bool isTicked,
  56605. const Image& iconToUse)
  56606. {
  56607. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56608. // didn't pick anything, so you shouldn't use it as the id
  56609. // for an item..
  56610. addSeparatorIfPending();
  56611. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56612. Colours::black, false, 0, 0, 0));
  56613. }
  56614. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56615. const int commandID,
  56616. const String& displayName)
  56617. {
  56618. jassert (commandManager != 0 && commandID != 0);
  56619. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56620. if (registeredInfo != 0)
  56621. {
  56622. ApplicationCommandInfo info (*registeredInfo);
  56623. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56624. addSeparatorIfPending();
  56625. items.add (new Item (commandID,
  56626. displayName.isNotEmpty() ? displayName
  56627. : info.shortName,
  56628. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56629. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56630. Image::null,
  56631. Colours::black,
  56632. false,
  56633. 0, 0,
  56634. commandManager));
  56635. }
  56636. }
  56637. void PopupMenu::addColouredItem (const int itemResultId,
  56638. const String& itemText,
  56639. const Colour& itemTextColour,
  56640. const bool isActive,
  56641. const bool isTicked,
  56642. const Image& iconToUse)
  56643. {
  56644. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56645. // didn't pick anything, so you shouldn't use it as the id
  56646. // for an item..
  56647. addSeparatorIfPending();
  56648. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56649. itemTextColour, true, 0, 0, 0));
  56650. }
  56651. void PopupMenu::addCustomItem (const int itemResultId,
  56652. PopupMenuCustomComponent* const customComponent)
  56653. {
  56654. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56655. // didn't pick anything, so you shouldn't use it as the id
  56656. // for an item..
  56657. addSeparatorIfPending();
  56658. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56659. Colours::black, false, customComponent, 0, 0));
  56660. }
  56661. class NormalComponentWrapper : public PopupMenuCustomComponent
  56662. {
  56663. public:
  56664. NormalComponentWrapper (Component* const comp,
  56665. const int w, const int h,
  56666. const bool triggerMenuItemAutomaticallyWhenClicked)
  56667. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56668. width (w),
  56669. height (h)
  56670. {
  56671. addAndMakeVisible (comp);
  56672. }
  56673. ~NormalComponentWrapper() {}
  56674. void getIdealSize (int& idealWidth, int& idealHeight)
  56675. {
  56676. idealWidth = width;
  56677. idealHeight = height;
  56678. }
  56679. void resized()
  56680. {
  56681. if (getChildComponent(0) != 0)
  56682. getChildComponent(0)->setBounds (getLocalBounds());
  56683. }
  56684. juce_UseDebuggingNewOperator
  56685. private:
  56686. const int width, height;
  56687. NormalComponentWrapper (const NormalComponentWrapper&);
  56688. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  56689. };
  56690. void PopupMenu::addCustomItem (const int itemResultId,
  56691. Component* customComponent,
  56692. int idealWidth, int idealHeight,
  56693. const bool triggerMenuItemAutomaticallyWhenClicked)
  56694. {
  56695. addCustomItem (itemResultId,
  56696. new NormalComponentWrapper (customComponent,
  56697. idealWidth, idealHeight,
  56698. triggerMenuItemAutomaticallyWhenClicked));
  56699. }
  56700. void PopupMenu::addSubMenu (const String& subMenuName,
  56701. const PopupMenu& subMenu,
  56702. const bool isActive,
  56703. const Image& iconToUse,
  56704. const bool isTicked)
  56705. {
  56706. addSeparatorIfPending();
  56707. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56708. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56709. }
  56710. void PopupMenu::addSeparator()
  56711. {
  56712. separatorPending = true;
  56713. }
  56714. class HeaderItemComponent : public PopupMenuCustomComponent
  56715. {
  56716. public:
  56717. HeaderItemComponent (const String& name)
  56718. : PopupMenuCustomComponent (false)
  56719. {
  56720. setName (name);
  56721. }
  56722. ~HeaderItemComponent()
  56723. {
  56724. }
  56725. void paint (Graphics& g)
  56726. {
  56727. Font f (getLookAndFeel().getPopupMenuFont());
  56728. f.setBold (true);
  56729. g.setFont (f);
  56730. g.setColour (findColour (PopupMenu::headerTextColourId));
  56731. g.drawFittedText (getName(),
  56732. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56733. Justification::bottomLeft, 1);
  56734. }
  56735. void getIdealSize (int& idealWidth,
  56736. int& idealHeight)
  56737. {
  56738. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56739. idealHeight += idealHeight / 2;
  56740. idealWidth += idealWidth / 4;
  56741. }
  56742. juce_UseDebuggingNewOperator
  56743. };
  56744. void PopupMenu::addSectionHeader (const String& title)
  56745. {
  56746. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56747. }
  56748. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56749. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56750. {
  56751. public:
  56752. PopupMenuCompletionCallback()
  56753. : managerOfChosenCommand (0)
  56754. {
  56755. }
  56756. ~PopupMenuCompletionCallback() {}
  56757. void modalStateFinished (int result)
  56758. {
  56759. if (managerOfChosenCommand != 0 && result != 0)
  56760. {
  56761. ApplicationCommandTarget::InvocationInfo info (result);
  56762. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56763. managerOfChosenCommand->invoke (info, true);
  56764. }
  56765. }
  56766. ApplicationCommandManager* managerOfChosenCommand;
  56767. ScopedPointer<Component> component;
  56768. private:
  56769. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  56770. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  56771. };
  56772. int PopupMenu::showMenu (const Rectangle<int>& target,
  56773. const int itemIdThatMustBeVisible,
  56774. const int minimumWidth,
  56775. const int maximumNumColumns,
  56776. const int standardItemHeight,
  56777. const bool alignToRectangle,
  56778. Component* const componentAttachedTo,
  56779. ModalComponentManager::Callback* userCallback)
  56780. {
  56781. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56782. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56783. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56784. Window::wasHiddenBecauseOfAppChange() = false;
  56785. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56786. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56787. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56788. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56789. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  56790. &callback->managerOfChosenCommand, componentAttachedTo);
  56791. if (callback->component == 0)
  56792. return 0;
  56793. callbackDeleter.release();
  56794. callback->component->enterModalState (false, userCallbackDeleter.release());
  56795. callback->component->toFront (false); // need to do this after making it modal, or it could
  56796. // be stuck behind other comps that are already modal..
  56797. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56798. if (userCallback != 0)
  56799. return 0;
  56800. const int result = callback->component->runModalLoop();
  56801. if (! Window::wasHiddenBecauseOfAppChange())
  56802. {
  56803. if (prevTopLevel != 0)
  56804. prevTopLevel->toFront (true);
  56805. if (prevFocused != 0)
  56806. prevFocused->grabKeyboardFocus();
  56807. }
  56808. return result;
  56809. }
  56810. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56811. const int minimumWidth,
  56812. const int maximumNumColumns,
  56813. const int standardItemHeight,
  56814. ModalComponentManager::Callback* callback)
  56815. {
  56816. const Point<int> mousePos (Desktop::getMousePosition());
  56817. return showAt (mousePos.getX(), mousePos.getY(),
  56818. itemIdThatMustBeVisible,
  56819. minimumWidth,
  56820. maximumNumColumns,
  56821. standardItemHeight,
  56822. callback);
  56823. }
  56824. int PopupMenu::showAt (const int screenX,
  56825. const int screenY,
  56826. const int itemIdThatMustBeVisible,
  56827. const int minimumWidth,
  56828. const int maximumNumColumns,
  56829. const int standardItemHeight,
  56830. ModalComponentManager::Callback* callback)
  56831. {
  56832. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56833. itemIdThatMustBeVisible,
  56834. minimumWidth, maximumNumColumns,
  56835. standardItemHeight,
  56836. false, 0, callback);
  56837. }
  56838. int PopupMenu::showAt (Component* componentToAttachTo,
  56839. const int itemIdThatMustBeVisible,
  56840. const int minimumWidth,
  56841. const int maximumNumColumns,
  56842. const int standardItemHeight,
  56843. ModalComponentManager::Callback* callback)
  56844. {
  56845. if (componentToAttachTo != 0)
  56846. {
  56847. return showMenu (componentToAttachTo->getScreenBounds(),
  56848. itemIdThatMustBeVisible,
  56849. minimumWidth,
  56850. maximumNumColumns,
  56851. standardItemHeight,
  56852. true, componentToAttachTo, callback);
  56853. }
  56854. else
  56855. {
  56856. return show (itemIdThatMustBeVisible,
  56857. minimumWidth,
  56858. maximumNumColumns,
  56859. standardItemHeight,
  56860. callback);
  56861. }
  56862. }
  56863. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56864. {
  56865. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56866. {
  56867. Window* const pmw = Window::getActiveWindows()[i];
  56868. if (pmw != 0)
  56869. pmw->dismissMenu (0);
  56870. }
  56871. }
  56872. int PopupMenu::getNumItems() const throw()
  56873. {
  56874. int num = 0;
  56875. for (int i = items.size(); --i >= 0;)
  56876. if (! (items.getUnchecked(i))->isSeparator)
  56877. ++num;
  56878. return num;
  56879. }
  56880. bool PopupMenu::containsCommandItem (const int commandID) const
  56881. {
  56882. for (int i = items.size(); --i >= 0;)
  56883. {
  56884. const Item* mi = items.getUnchecked (i);
  56885. if ((mi->itemId == commandID && mi->commandManager != 0)
  56886. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56887. {
  56888. return true;
  56889. }
  56890. }
  56891. return false;
  56892. }
  56893. bool PopupMenu::containsAnyActiveItems() const throw()
  56894. {
  56895. for (int i = items.size(); --i >= 0;)
  56896. {
  56897. const Item* const mi = items.getUnchecked (i);
  56898. if (mi->subMenu != 0)
  56899. {
  56900. if (mi->subMenu->containsAnyActiveItems())
  56901. return true;
  56902. }
  56903. else if (mi->active)
  56904. {
  56905. return true;
  56906. }
  56907. }
  56908. return false;
  56909. }
  56910. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56911. {
  56912. lookAndFeel = newLookAndFeel;
  56913. }
  56914. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56915. : isHighlighted (false),
  56916. isTriggeredAutomatically (isTriggeredAutomatically_)
  56917. {
  56918. }
  56919. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56920. {
  56921. }
  56922. void PopupMenuCustomComponent::triggerMenuItem()
  56923. {
  56924. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56925. if (mic != 0)
  56926. {
  56927. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56928. if (pmw != 0)
  56929. {
  56930. pmw->dismissMenu (&mic->itemInfo);
  56931. }
  56932. else
  56933. {
  56934. // something must have gone wrong with the component hierarchy if this happens..
  56935. jassertfalse;
  56936. }
  56937. }
  56938. else
  56939. {
  56940. // why isn't this component inside a menu? Not much point triggering the item if
  56941. // there's no menu.
  56942. jassertfalse;
  56943. }
  56944. }
  56945. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56946. : subMenu (0),
  56947. itemId (0),
  56948. isSeparator (false),
  56949. isTicked (false),
  56950. isEnabled (false),
  56951. isCustomComponent (false),
  56952. isSectionHeader (false),
  56953. customColour (0),
  56954. customImage (0),
  56955. menu (menu_),
  56956. index (0)
  56957. {
  56958. }
  56959. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56960. {
  56961. }
  56962. bool PopupMenu::MenuItemIterator::next()
  56963. {
  56964. if (index >= menu.items.size())
  56965. return false;
  56966. const Item* const item = menu.items.getUnchecked (index);
  56967. ++index;
  56968. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56969. subMenu = item->subMenu;
  56970. itemId = item->itemId;
  56971. isSeparator = item->isSeparator;
  56972. isTicked = item->isTicked;
  56973. isEnabled = item->active;
  56974. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  56975. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56976. customColour = item->usesColour ? &(item->textColour) : 0;
  56977. customImage = item->image;
  56978. commandManager = item->commandManager;
  56979. return true;
  56980. }
  56981. END_JUCE_NAMESPACE
  56982. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56983. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56984. BEGIN_JUCE_NAMESPACE
  56985. ComponentDragger::ComponentDragger()
  56986. : constrainer (0)
  56987. {
  56988. }
  56989. ComponentDragger::~ComponentDragger()
  56990. {
  56991. }
  56992. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  56993. ComponentBoundsConstrainer* const constrainer_)
  56994. {
  56995. jassert (componentToDrag->isValidComponent());
  56996. if (componentToDrag != 0)
  56997. {
  56998. constrainer = constrainer_;
  56999. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  57000. }
  57001. }
  57002. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  57003. {
  57004. jassert (componentToDrag->isValidComponent());
  57005. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  57006. if (componentToDrag != 0)
  57007. {
  57008. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  57009. const Component* const parentComp = componentToDrag->getParentComponent();
  57010. if (parentComp != 0)
  57011. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  57012. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  57013. if (constrainer != 0)
  57014. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  57015. else
  57016. componentToDrag->setBounds (bounds);
  57017. }
  57018. }
  57019. END_JUCE_NAMESPACE
  57020. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  57021. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  57022. BEGIN_JUCE_NAMESPACE
  57023. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  57024. bool juce_performDragDropText (const String& text, bool& shouldStop);
  57025. class DragImageComponent : public Component,
  57026. public Timer
  57027. {
  57028. public:
  57029. DragImageComponent (const Image& im,
  57030. const String& desc,
  57031. Component* const sourceComponent,
  57032. Component* const mouseDragSource_,
  57033. DragAndDropContainer* const o,
  57034. const Point<int>& imageOffset_)
  57035. : image (im),
  57036. source (sourceComponent),
  57037. mouseDragSource (mouseDragSource_),
  57038. owner (o),
  57039. dragDesc (desc),
  57040. imageOffset (imageOffset_),
  57041. hasCheckedForExternalDrag (false),
  57042. drawImage (true)
  57043. {
  57044. setSize (im.getWidth(), im.getHeight());
  57045. if (mouseDragSource == 0)
  57046. mouseDragSource = source;
  57047. mouseDragSource->addMouseListener (this, false);
  57048. startTimer (200);
  57049. setInterceptsMouseClicks (false, false);
  57050. setAlwaysOnTop (true);
  57051. }
  57052. ~DragImageComponent()
  57053. {
  57054. if (owner->dragImageComponent == this)
  57055. owner->dragImageComponent.release();
  57056. if (mouseDragSource != 0)
  57057. {
  57058. mouseDragSource->removeMouseListener (this);
  57059. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  57060. getCurrentlyOver()->itemDragExit (dragDesc, source);
  57061. }
  57062. }
  57063. void paint (Graphics& g)
  57064. {
  57065. if (isOpaque())
  57066. g.fillAll (Colours::white);
  57067. if (drawImage)
  57068. {
  57069. g.setOpacity (1.0f);
  57070. g.drawImageAt (image, 0, 0);
  57071. }
  57072. }
  57073. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  57074. {
  57075. Component* hit = getParentComponent();
  57076. if (hit == 0)
  57077. {
  57078. hit = Desktop::getInstance().findComponentAt (screenPos);
  57079. }
  57080. else
  57081. {
  57082. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  57083. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  57084. }
  57085. // (note: use a local copy of the dragDesc member in case the callback runs
  57086. // a modal loop and deletes this object before the method completes)
  57087. const String dragDescLocal (dragDesc);
  57088. while (hit != 0)
  57089. {
  57090. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  57091. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57092. {
  57093. relativePos = hit->globalPositionToRelative (screenPos);
  57094. return ddt;
  57095. }
  57096. hit = hit->getParentComponent();
  57097. }
  57098. return 0;
  57099. }
  57100. void mouseUp (const MouseEvent& e)
  57101. {
  57102. if (e.originalComponent != this)
  57103. {
  57104. if (mouseDragSource != 0)
  57105. mouseDragSource->removeMouseListener (this);
  57106. bool dropAccepted = false;
  57107. DragAndDropTarget* ddt = 0;
  57108. Point<int> relPos;
  57109. if (isVisible())
  57110. {
  57111. setVisible (false);
  57112. ddt = findTarget (e.getScreenPosition(), relPos);
  57113. // fade this component and remove it - it'll be deleted later by the timer callback
  57114. dropAccepted = ddt != 0;
  57115. setVisible (true);
  57116. if (dropAccepted || source == 0)
  57117. {
  57118. fadeOutComponent (120);
  57119. }
  57120. else
  57121. {
  57122. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  57123. source->getHeight() / 2)));
  57124. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  57125. getHeight() / 2)));
  57126. fadeOutComponent (120,
  57127. target.getX() - ourCentre.getX(),
  57128. target.getY() - ourCentre.getY());
  57129. }
  57130. }
  57131. if (getParentComponent() != 0)
  57132. getParentComponent()->removeChildComponent (this);
  57133. if (dropAccepted && ddt != 0)
  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. currentlyOverComp = 0;
  57139. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  57140. }
  57141. // careful - this object could now be deleted..
  57142. }
  57143. }
  57144. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  57145. {
  57146. // (note: use a local copy of the dragDesc member in case the callback runs
  57147. // a modal loop and deletes this object before it returns)
  57148. const String dragDescLocal (dragDesc);
  57149. Point<int> newPos (screenPos + imageOffset);
  57150. if (getParentComponent() != 0)
  57151. newPos = getParentComponent()->globalPositionToRelative (newPos);
  57152. //if (newX != getX() || newY != getY())
  57153. {
  57154. setTopLeftPosition (newPos.getX(), newPos.getY());
  57155. Point<int> relPos;
  57156. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  57157. Component* ddtComp = dynamic_cast <Component*> (ddt);
  57158. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  57159. if (ddtComp != currentlyOverComp)
  57160. {
  57161. if (currentlyOverComp != 0 && source != 0
  57162. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  57163. {
  57164. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  57165. }
  57166. currentlyOverComp = ddtComp;
  57167. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57168. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  57169. }
  57170. DragAndDropTarget* target = getCurrentlyOver();
  57171. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  57172. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  57173. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  57174. {
  57175. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  57176. {
  57177. hasCheckedForExternalDrag = true;
  57178. StringArray files;
  57179. bool canMoveFiles = false;
  57180. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  57181. && files.size() > 0)
  57182. {
  57183. Component::SafePointer<Component> cdw (this);
  57184. setVisible (false);
  57185. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  57186. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  57187. if (cdw != 0)
  57188. delete this;
  57189. return;
  57190. }
  57191. }
  57192. }
  57193. }
  57194. }
  57195. void mouseDrag (const MouseEvent& e)
  57196. {
  57197. if (e.originalComponent != this)
  57198. updateLocation (true, e.getScreenPosition());
  57199. }
  57200. void timerCallback()
  57201. {
  57202. if (source == 0)
  57203. {
  57204. delete this;
  57205. }
  57206. else if (! isMouseButtonDownAnywhere())
  57207. {
  57208. if (mouseDragSource != 0)
  57209. mouseDragSource->removeMouseListener (this);
  57210. delete this;
  57211. }
  57212. }
  57213. private:
  57214. Image image;
  57215. Component::SafePointer<Component> source;
  57216. Component::SafePointer<Component> mouseDragSource;
  57217. DragAndDropContainer* const owner;
  57218. Component::SafePointer<Component> currentlyOverComp;
  57219. DragAndDropTarget* getCurrentlyOver()
  57220. {
  57221. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  57222. }
  57223. String dragDesc;
  57224. const Point<int> imageOffset;
  57225. bool hasCheckedForExternalDrag, drawImage;
  57226. DragImageComponent (const DragImageComponent&);
  57227. DragImageComponent& operator= (const DragImageComponent&);
  57228. };
  57229. DragAndDropContainer::DragAndDropContainer()
  57230. {
  57231. }
  57232. DragAndDropContainer::~DragAndDropContainer()
  57233. {
  57234. dragImageComponent = 0;
  57235. }
  57236. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57237. Component* sourceComponent,
  57238. const Image& dragImage_,
  57239. const bool allowDraggingToExternalWindows,
  57240. const Point<int>* imageOffsetFromMouse)
  57241. {
  57242. Image dragImage (dragImage_);
  57243. if (dragImageComponent == 0)
  57244. {
  57245. Component* const thisComp = dynamic_cast <Component*> (this);
  57246. if (thisComp == 0)
  57247. {
  57248. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57249. return;
  57250. }
  57251. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57252. if (draggingSource == 0 || ! draggingSource->isDragging())
  57253. {
  57254. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57255. return;
  57256. }
  57257. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57258. Point<int> imageOffset;
  57259. if (dragImage.isNull())
  57260. {
  57261. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57262. .convertedToFormat (Image::ARGB);
  57263. dragImage.multiplyAllAlphas (0.6f);
  57264. const int lo = 150;
  57265. const int hi = 400;
  57266. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  57267. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57268. for (int y = dragImage.getHeight(); --y >= 0;)
  57269. {
  57270. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57271. for (int x = dragImage.getWidth(); --x >= 0;)
  57272. {
  57273. const int dx = x - clipped.getX();
  57274. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57275. if (distance > lo)
  57276. {
  57277. const float alpha = (distance > hi) ? 0
  57278. : (hi - distance) / (float) (hi - lo)
  57279. + Random::getSystemRandom().nextFloat() * 0.008f;
  57280. dragImage.multiplyAlphaAt (x, y, alpha);
  57281. }
  57282. }
  57283. }
  57284. imageOffset = -clipped;
  57285. }
  57286. else
  57287. {
  57288. if (imageOffsetFromMouse == 0)
  57289. imageOffset = -dragImage.getBounds().getCentre();
  57290. else
  57291. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57292. }
  57293. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57294. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57295. currentDragDesc = sourceDescription;
  57296. if (allowDraggingToExternalWindows)
  57297. {
  57298. if (! Desktop::canUseSemiTransparentWindows())
  57299. dragImageComponent->setOpaque (true);
  57300. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57301. | ComponentPeer::windowIsTemporary
  57302. | ComponentPeer::windowIgnoresKeyPresses);
  57303. }
  57304. else
  57305. thisComp->addChildComponent (dragImageComponent);
  57306. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57307. dragImageComponent->setVisible (true);
  57308. }
  57309. }
  57310. bool DragAndDropContainer::isDragAndDropActive() const
  57311. {
  57312. return dragImageComponent != 0;
  57313. }
  57314. const String DragAndDropContainer::getCurrentDragDescription() const
  57315. {
  57316. return (dragImageComponent != 0) ? currentDragDesc
  57317. : String::empty;
  57318. }
  57319. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57320. {
  57321. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57322. }
  57323. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57324. {
  57325. return false;
  57326. }
  57327. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57328. {
  57329. }
  57330. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57331. {
  57332. }
  57333. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57334. {
  57335. }
  57336. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57337. {
  57338. return true;
  57339. }
  57340. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57341. {
  57342. }
  57343. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57344. {
  57345. }
  57346. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57347. {
  57348. }
  57349. END_JUCE_NAMESPACE
  57350. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57351. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57352. BEGIN_JUCE_NAMESPACE
  57353. class MouseCursor::SharedCursorHandle
  57354. {
  57355. public:
  57356. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57357. : handle (createStandardMouseCursor (type)),
  57358. refCount (1),
  57359. standardType (type),
  57360. isStandard (true)
  57361. {
  57362. }
  57363. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57364. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57365. refCount (1),
  57366. standardType (MouseCursor::NormalCursor),
  57367. isStandard (false)
  57368. {
  57369. }
  57370. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57371. {
  57372. const ScopedLock sl (getLock());
  57373. for (int i = 0; i < getCursors().size(); ++i)
  57374. {
  57375. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57376. if (sc->standardType == type)
  57377. return sc->retain();
  57378. }
  57379. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57380. getCursors().add (sc);
  57381. return sc;
  57382. }
  57383. SharedCursorHandle* retain() throw()
  57384. {
  57385. ++refCount;
  57386. return this;
  57387. }
  57388. void release()
  57389. {
  57390. if (--refCount == 0)
  57391. {
  57392. if (isStandard)
  57393. {
  57394. const ScopedLock sl (getLock());
  57395. getCursors().removeValue (this);
  57396. }
  57397. delete this;
  57398. }
  57399. }
  57400. void* getHandle() const throw() { return handle; }
  57401. juce_UseDebuggingNewOperator
  57402. private:
  57403. void* const handle;
  57404. Atomic <int> refCount;
  57405. const MouseCursor::StandardCursorType standardType;
  57406. const bool isStandard;
  57407. static CriticalSection& getLock()
  57408. {
  57409. static CriticalSection lock;
  57410. return lock;
  57411. }
  57412. static Array <SharedCursorHandle*>& getCursors()
  57413. {
  57414. static Array <SharedCursorHandle*> cursors;
  57415. return cursors;
  57416. }
  57417. ~SharedCursorHandle()
  57418. {
  57419. deleteMouseCursor (handle, isStandard);
  57420. }
  57421. SharedCursorHandle& operator= (const SharedCursorHandle&);
  57422. };
  57423. MouseCursor::MouseCursor()
  57424. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  57425. {
  57426. jassert (cursorHandle != 0);
  57427. }
  57428. MouseCursor::MouseCursor (const StandardCursorType type)
  57429. : cursorHandle (SharedCursorHandle::createStandard (type))
  57430. {
  57431. jassert (cursorHandle != 0);
  57432. }
  57433. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57434. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57435. {
  57436. }
  57437. MouseCursor::MouseCursor (const MouseCursor& other)
  57438. : cursorHandle (other.cursorHandle->retain())
  57439. {
  57440. }
  57441. MouseCursor::~MouseCursor()
  57442. {
  57443. cursorHandle->release();
  57444. }
  57445. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57446. {
  57447. other.cursorHandle->retain();
  57448. cursorHandle->release();
  57449. cursorHandle = other.cursorHandle;
  57450. return *this;
  57451. }
  57452. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57453. {
  57454. return getHandle() == other.getHandle();
  57455. }
  57456. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57457. {
  57458. return getHandle() != other.getHandle();
  57459. }
  57460. void* MouseCursor::getHandle() const throw()
  57461. {
  57462. return cursorHandle->getHandle();
  57463. }
  57464. void MouseCursor::showWaitCursor()
  57465. {
  57466. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57467. }
  57468. void MouseCursor::hideWaitCursor()
  57469. {
  57470. Desktop::getInstance().getMainMouseSource().revealCursor();
  57471. }
  57472. END_JUCE_NAMESPACE
  57473. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57474. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57475. BEGIN_JUCE_NAMESPACE
  57476. MouseEvent::MouseEvent (MouseInputSource& source_,
  57477. const Point<int>& position,
  57478. const ModifierKeys& mods_,
  57479. Component* const eventComponent_,
  57480. Component* const originator,
  57481. const Time& eventTime_,
  57482. const Point<int> mouseDownPos_,
  57483. const Time& mouseDownTime_,
  57484. const int numberOfClicks_,
  57485. const bool mouseWasDragged) throw()
  57486. : x (position.getX()),
  57487. y (position.getY()),
  57488. mods (mods_),
  57489. eventComponent (eventComponent_),
  57490. originalComponent (originator),
  57491. eventTime (eventTime_),
  57492. source (source_),
  57493. mouseDownPos (mouseDownPos_),
  57494. mouseDownTime (mouseDownTime_),
  57495. numberOfClicks (numberOfClicks_),
  57496. wasMovedSinceMouseDown (mouseWasDragged)
  57497. {
  57498. }
  57499. MouseEvent::~MouseEvent() throw()
  57500. {
  57501. }
  57502. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57503. {
  57504. if (otherComponent == 0)
  57505. {
  57506. jassertfalse;
  57507. return *this;
  57508. }
  57509. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  57510. mods, otherComponent, originalComponent, eventTime,
  57511. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  57512. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57513. }
  57514. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57515. {
  57516. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57517. eventTime, mouseDownPos, mouseDownTime,
  57518. numberOfClicks, wasMovedSinceMouseDown);
  57519. }
  57520. bool MouseEvent::mouseWasClicked() const throw()
  57521. {
  57522. return ! wasMovedSinceMouseDown;
  57523. }
  57524. int MouseEvent::getMouseDownX() const throw()
  57525. {
  57526. return mouseDownPos.getX();
  57527. }
  57528. int MouseEvent::getMouseDownY() const throw()
  57529. {
  57530. return mouseDownPos.getY();
  57531. }
  57532. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57533. {
  57534. return mouseDownPos;
  57535. }
  57536. int MouseEvent::getDistanceFromDragStartX() const throw()
  57537. {
  57538. return x - mouseDownPos.getX();
  57539. }
  57540. int MouseEvent::getDistanceFromDragStartY() const throw()
  57541. {
  57542. return y - mouseDownPos.getY();
  57543. }
  57544. int MouseEvent::getDistanceFromDragStart() const throw()
  57545. {
  57546. return mouseDownPos.getDistanceFrom (getPosition());
  57547. }
  57548. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57549. {
  57550. return getPosition() - mouseDownPos;
  57551. }
  57552. int MouseEvent::getLengthOfMousePress() const throw()
  57553. {
  57554. if (mouseDownTime.toMilliseconds() > 0)
  57555. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57556. return 0;
  57557. }
  57558. const Point<int> MouseEvent::getPosition() const throw()
  57559. {
  57560. return Point<int> (x, y);
  57561. }
  57562. int MouseEvent::getScreenX() const
  57563. {
  57564. return getScreenPosition().getX();
  57565. }
  57566. int MouseEvent::getScreenY() const
  57567. {
  57568. return getScreenPosition().getY();
  57569. }
  57570. const Point<int> MouseEvent::getScreenPosition() const
  57571. {
  57572. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  57573. }
  57574. int MouseEvent::getMouseDownScreenX() const
  57575. {
  57576. return getMouseDownScreenPosition().getX();
  57577. }
  57578. int MouseEvent::getMouseDownScreenY() const
  57579. {
  57580. return getMouseDownScreenPosition().getY();
  57581. }
  57582. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57583. {
  57584. return eventComponent->relativePositionToGlobal (mouseDownPos);
  57585. }
  57586. int MouseEvent::doubleClickTimeOutMs = 400;
  57587. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57588. {
  57589. doubleClickTimeOutMs = newTime;
  57590. }
  57591. int MouseEvent::getDoubleClickTimeout() throw()
  57592. {
  57593. return doubleClickTimeOutMs;
  57594. }
  57595. END_JUCE_NAMESPACE
  57596. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57597. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57598. BEGIN_JUCE_NAMESPACE
  57599. class MouseInputSourceInternal : public AsyncUpdater
  57600. {
  57601. public:
  57602. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57603. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  57604. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57605. mouseEventCounter (0)
  57606. {
  57607. zerostruct (mouseDowns);
  57608. }
  57609. ~MouseInputSourceInternal()
  57610. {
  57611. }
  57612. bool isDragging() const throw()
  57613. {
  57614. return buttonState.isAnyMouseButtonDown();
  57615. }
  57616. Component* getComponentUnderMouse() const
  57617. {
  57618. return static_cast <Component*> (componentUnderMouse);
  57619. }
  57620. const ModifierKeys getCurrentModifiers() const
  57621. {
  57622. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57623. }
  57624. ComponentPeer* getPeer()
  57625. {
  57626. if (! ComponentPeer::isValidPeer (lastPeer))
  57627. lastPeer = 0;
  57628. return lastPeer;
  57629. }
  57630. Component* findComponentAt (const Point<int>& screenPos)
  57631. {
  57632. ComponentPeer* const peer = getPeer();
  57633. if (peer != 0)
  57634. {
  57635. Component* const comp = peer->getComponent();
  57636. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  57637. // (the contains() call is needed to test for overlapping desktop windows)
  57638. if (comp->contains (relativePos.getX(), relativePos.getY()))
  57639. return comp->getComponentAt (relativePos);
  57640. }
  57641. return 0;
  57642. }
  57643. const Point<int> getScreenPosition() const throw()
  57644. {
  57645. return lastScreenPos + unboundedMouseOffset;
  57646. }
  57647. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  57648. {
  57649. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57650. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  57651. }
  57652. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  57653. {
  57654. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57655. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  57656. }
  57657. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  57658. {
  57659. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57660. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  57661. }
  57662. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  57663. {
  57664. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57665. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  57666. }
  57667. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  57668. {
  57669. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57670. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  57671. }
  57672. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  57673. {
  57674. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57675. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  57676. }
  57677. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  57678. {
  57679. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57680. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  57681. }
  57682. // (returns true if the button change caused a modal event loop)
  57683. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  57684. {
  57685. if (buttonState == newButtonState)
  57686. return false;
  57687. setScreenPos (screenPos, time, false);
  57688. // (ignore secondary clicks when there's already a button down)
  57689. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57690. {
  57691. buttonState = newButtonState;
  57692. return false;
  57693. }
  57694. const int lastCounter = mouseEventCounter;
  57695. if (buttonState.isAnyMouseButtonDown())
  57696. {
  57697. Component* const current = getComponentUnderMouse();
  57698. if (current != 0)
  57699. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57700. enableUnboundedMouseMovement (false, false);
  57701. }
  57702. buttonState = newButtonState;
  57703. if (buttonState.isAnyMouseButtonDown())
  57704. {
  57705. Desktop::getInstance().incrementMouseClickCounter();
  57706. Component* const current = getComponentUnderMouse();
  57707. if (current != 0)
  57708. {
  57709. registerMouseDown (screenPos, time, current);
  57710. sendMouseDown (current, screenPos, time);
  57711. }
  57712. }
  57713. return lastCounter != mouseEventCounter;
  57714. }
  57715. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  57716. {
  57717. Component* current = getComponentUnderMouse();
  57718. if (newComponent != current)
  57719. {
  57720. Component::SafePointer<Component> safeNewComp (newComponent);
  57721. const ModifierKeys originalButtonState (buttonState);
  57722. if (current != 0)
  57723. {
  57724. setButtons (screenPos, time, ModifierKeys());
  57725. sendMouseExit (current, screenPos, time);
  57726. buttonState = originalButtonState;
  57727. }
  57728. componentUnderMouse = safeNewComp;
  57729. current = getComponentUnderMouse();
  57730. if (current != 0)
  57731. sendMouseEnter (current, screenPos, time);
  57732. revealCursor (false);
  57733. setButtons (screenPos, time, originalButtonState);
  57734. }
  57735. }
  57736. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  57737. {
  57738. ModifierKeys::updateCurrentModifiers();
  57739. if (newPeer != lastPeer)
  57740. {
  57741. setComponentUnderMouse (0, screenPos, time);
  57742. lastPeer = newPeer;
  57743. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57744. }
  57745. }
  57746. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  57747. {
  57748. if (! isDragging())
  57749. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57750. if (newScreenPos != lastScreenPos || forceUpdate)
  57751. {
  57752. cancelPendingUpdate();
  57753. lastScreenPos = newScreenPos;
  57754. Component* const current = getComponentUnderMouse();
  57755. if (current != 0)
  57756. {
  57757. if (isDragging())
  57758. {
  57759. registerMouseDrag (newScreenPos);
  57760. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57761. if (isUnboundedMouseModeOn)
  57762. handleUnboundedDrag (current);
  57763. }
  57764. else
  57765. {
  57766. sendMouseMove (current, newScreenPos, time);
  57767. }
  57768. }
  57769. revealCursor (false);
  57770. }
  57771. }
  57772. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  57773. {
  57774. jassert (newPeer != 0);
  57775. lastTime = time;
  57776. ++mouseEventCounter;
  57777. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  57778. if (isDragging() && newMods.isAnyMouseButtonDown())
  57779. {
  57780. setScreenPos (screenPos, time, false);
  57781. }
  57782. else
  57783. {
  57784. setPeer (newPeer, screenPos, time);
  57785. ComponentPeer* peer = getPeer();
  57786. if (peer != 0)
  57787. {
  57788. if (setButtons (screenPos, time, newMods))
  57789. return; // some modal events have been dispatched, so the current event is now out-of-date
  57790. peer = getPeer();
  57791. if (peer != 0)
  57792. setScreenPos (screenPos, time, false);
  57793. }
  57794. }
  57795. }
  57796. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  57797. {
  57798. jassert (peer != 0);
  57799. lastTime = time;
  57800. ++mouseEventCounter;
  57801. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  57802. setPeer (peer, screenPos, time);
  57803. setScreenPos (screenPos, time, false);
  57804. triggerFakeMove();
  57805. if (! isDragging())
  57806. {
  57807. Component* current = getComponentUnderMouse();
  57808. if (current != 0)
  57809. sendMouseWheel (current, screenPos, time, x, y);
  57810. }
  57811. }
  57812. const Time getLastMouseDownTime() const throw()
  57813. {
  57814. return Time (mouseDowns[0].time);
  57815. }
  57816. const Point<int> getLastMouseDownPosition() const throw()
  57817. {
  57818. return mouseDowns[0].position;
  57819. }
  57820. int getNumberOfMultipleClicks() const throw()
  57821. {
  57822. int numClicks = 0;
  57823. if (mouseDowns[0].time != 0)
  57824. {
  57825. if (! mouseMovedSignificantlySincePressed)
  57826. ++numClicks;
  57827. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57828. {
  57829. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  57830. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  57831. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8)
  57832. {
  57833. ++numClicks;
  57834. }
  57835. else
  57836. {
  57837. break;
  57838. }
  57839. }
  57840. }
  57841. return numClicks;
  57842. }
  57843. bool hasMouseMovedSignificantlySincePressed() const throw()
  57844. {
  57845. return mouseMovedSignificantlySincePressed
  57846. || lastTime > mouseDowns[0].time + 300;
  57847. }
  57848. void triggerFakeMove()
  57849. {
  57850. triggerAsyncUpdate();
  57851. }
  57852. void handleAsyncUpdate()
  57853. {
  57854. setScreenPos (lastScreenPos, jmax (lastTime, Time::currentTimeMillis()), true);
  57855. }
  57856. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57857. {
  57858. enable = enable && isDragging();
  57859. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57860. if (enable != isUnboundedMouseModeOn)
  57861. {
  57862. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57863. {
  57864. // when released, return the mouse to within the component's bounds
  57865. Component* current = getComponentUnderMouse();
  57866. if (current != 0)
  57867. Desktop::setMousePosition (current->getScreenBounds()
  57868. .getConstrainedPoint (lastScreenPos));
  57869. }
  57870. isUnboundedMouseModeOn = enable;
  57871. unboundedMouseOffset = Point<int>();
  57872. revealCursor (true);
  57873. }
  57874. }
  57875. void handleUnboundedDrag (Component* current)
  57876. {
  57877. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57878. if (! screenArea.contains (lastScreenPos))
  57879. {
  57880. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57881. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57882. Desktop::setMousePosition (componentCentre);
  57883. }
  57884. else if (isCursorVisibleUntilOffscreen
  57885. && (! unboundedMouseOffset.isOrigin())
  57886. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57887. {
  57888. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57889. unboundedMouseOffset = Point<int>();
  57890. }
  57891. }
  57892. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57893. {
  57894. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57895. {
  57896. cursor = MouseCursor::NoCursor;
  57897. forcedUpdate = true;
  57898. }
  57899. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57900. {
  57901. currentCursorHandle = cursor.getHandle();
  57902. cursor.showInWindow (getPeer());
  57903. }
  57904. }
  57905. void hideCursor()
  57906. {
  57907. showMouseCursor (MouseCursor::NoCursor, true);
  57908. }
  57909. void revealCursor (bool forcedUpdate)
  57910. {
  57911. MouseCursor mc (MouseCursor::NormalCursor);
  57912. Component* current = getComponentUnderMouse();
  57913. if (current != 0)
  57914. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57915. showMouseCursor (mc, forcedUpdate);
  57916. }
  57917. int index;
  57918. bool isMouseDevice;
  57919. Point<int> lastScreenPos;
  57920. ModifierKeys buttonState;
  57921. private:
  57922. MouseInputSource& source;
  57923. Component::SafePointer<Component> componentUnderMouse;
  57924. ComponentPeer* lastPeer;
  57925. Point<int> unboundedMouseOffset;
  57926. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57927. void* currentCursorHandle;
  57928. int mouseEventCounter;
  57929. struct RecentMouseDown
  57930. {
  57931. Point<int> position;
  57932. int64 time;
  57933. Component* component;
  57934. };
  57935. RecentMouseDown mouseDowns[4];
  57936. bool mouseMovedSignificantlySincePressed;
  57937. int64 lastTime;
  57938. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  57939. {
  57940. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57941. mouseDowns[i] = mouseDowns[i - 1];
  57942. mouseDowns[0].position = screenPos;
  57943. mouseDowns[0].time = time;
  57944. mouseDowns[0].component = component;
  57945. mouseMovedSignificantlySincePressed = false;
  57946. }
  57947. void registerMouseDrag (const Point<int>& screenPos) throw()
  57948. {
  57949. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57950. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57951. }
  57952. MouseInputSourceInternal (const MouseInputSourceInternal&);
  57953. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  57954. };
  57955. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57956. {
  57957. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57958. }
  57959. MouseInputSource::~MouseInputSource()
  57960. {
  57961. }
  57962. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57963. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57964. bool MouseInputSource::canHover() const { return isMouse(); }
  57965. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57966. int MouseInputSource::getIndex() const { return pimpl->index; }
  57967. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57968. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57969. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57970. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57971. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57972. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57973. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57974. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57975. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57976. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57977. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57978. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57979. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57980. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57981. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57982. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57983. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57984. {
  57985. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57986. }
  57987. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57988. {
  57989. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57990. }
  57991. END_JUCE_NAMESPACE
  57992. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57993. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57994. BEGIN_JUCE_NAMESPACE
  57995. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57996. : source (0),
  57997. hoverTimeMillisecs (hoverTimeMillisecs_),
  57998. hasJustHovered (false)
  57999. {
  58000. internalTimer.owner = this;
  58001. }
  58002. MouseHoverDetector::~MouseHoverDetector()
  58003. {
  58004. setHoverComponent (0);
  58005. }
  58006. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  58007. {
  58008. hoverTimeMillisecs = newTimeInMillisecs;
  58009. }
  58010. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  58011. {
  58012. if (source != newSourceComponent)
  58013. {
  58014. internalTimer.stopTimer();
  58015. hasJustHovered = false;
  58016. if (source != 0)
  58017. {
  58018. // ! you need to delete the hover detector before deleting its component
  58019. jassert (source->isValidComponent());
  58020. source->removeMouseListener (&internalTimer);
  58021. }
  58022. source = newSourceComponent;
  58023. if (newSourceComponent != 0)
  58024. newSourceComponent->addMouseListener (&internalTimer, false);
  58025. }
  58026. }
  58027. void MouseHoverDetector::hoverTimerCallback()
  58028. {
  58029. internalTimer.stopTimer();
  58030. if (source != 0)
  58031. {
  58032. const Point<int> pos (source->getMouseXYRelative());
  58033. if (source->reallyContains (pos.getX(), pos.getY(), false))
  58034. {
  58035. hasJustHovered = true;
  58036. mouseHovered (pos.getX(), pos.getY());
  58037. }
  58038. }
  58039. }
  58040. void MouseHoverDetector::checkJustHoveredCallback()
  58041. {
  58042. if (hasJustHovered)
  58043. {
  58044. hasJustHovered = false;
  58045. mouseMovedAfterHover();
  58046. }
  58047. }
  58048. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  58049. {
  58050. owner->hoverTimerCallback();
  58051. }
  58052. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  58053. {
  58054. stopTimer();
  58055. owner->checkJustHoveredCallback();
  58056. }
  58057. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  58058. {
  58059. stopTimer();
  58060. owner->checkJustHoveredCallback();
  58061. }
  58062. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  58063. {
  58064. stopTimer();
  58065. owner->checkJustHoveredCallback();
  58066. }
  58067. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  58068. {
  58069. stopTimer();
  58070. owner->checkJustHoveredCallback();
  58071. }
  58072. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  58073. {
  58074. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  58075. {
  58076. lastX = e.x;
  58077. lastY = e.y;
  58078. if (owner->source != 0)
  58079. startTimer (owner->hoverTimeMillisecs);
  58080. owner->checkJustHoveredCallback();
  58081. }
  58082. }
  58083. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  58084. {
  58085. stopTimer();
  58086. owner->checkJustHoveredCallback();
  58087. }
  58088. END_JUCE_NAMESPACE
  58089. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  58090. /*** Start of inlined file: juce_MouseListener.cpp ***/
  58091. BEGIN_JUCE_NAMESPACE
  58092. void MouseListener::mouseEnter (const MouseEvent&)
  58093. {
  58094. }
  58095. void MouseListener::mouseExit (const MouseEvent&)
  58096. {
  58097. }
  58098. void MouseListener::mouseDown (const MouseEvent&)
  58099. {
  58100. }
  58101. void MouseListener::mouseUp (const MouseEvent&)
  58102. {
  58103. }
  58104. void MouseListener::mouseDrag (const MouseEvent&)
  58105. {
  58106. }
  58107. void MouseListener::mouseMove (const MouseEvent&)
  58108. {
  58109. }
  58110. void MouseListener::mouseDoubleClick (const MouseEvent&)
  58111. {
  58112. }
  58113. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  58114. {
  58115. }
  58116. END_JUCE_NAMESPACE
  58117. /*** End of inlined file: juce_MouseListener.cpp ***/
  58118. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58119. BEGIN_JUCE_NAMESPACE
  58120. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  58121. const String& buttonTextWhenTrue,
  58122. const String& buttonTextWhenFalse)
  58123. : PropertyComponent (name),
  58124. onText (buttonTextWhenTrue),
  58125. offText (buttonTextWhenFalse)
  58126. {
  58127. addAndMakeVisible (&button);
  58128. button.setClickingTogglesState (false);
  58129. button.addButtonListener (this);
  58130. }
  58131. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  58132. const String& name,
  58133. const String& buttonText)
  58134. : PropertyComponent (name),
  58135. onText (buttonText),
  58136. offText (buttonText)
  58137. {
  58138. addAndMakeVisible (&button);
  58139. button.setClickingTogglesState (false);
  58140. button.setButtonText (buttonText);
  58141. button.getToggleStateValue().referTo (valueToControl);
  58142. button.setClickingTogglesState (true);
  58143. }
  58144. BooleanPropertyComponent::~BooleanPropertyComponent()
  58145. {
  58146. }
  58147. void BooleanPropertyComponent::setState (const bool newState)
  58148. {
  58149. button.setToggleState (newState, true);
  58150. }
  58151. bool BooleanPropertyComponent::getState() const
  58152. {
  58153. return button.getToggleState();
  58154. }
  58155. void BooleanPropertyComponent::paint (Graphics& g)
  58156. {
  58157. PropertyComponent::paint (g);
  58158. g.setColour (Colours::white);
  58159. g.fillRect (button.getBounds());
  58160. g.setColour (findColour (ComboBox::outlineColourId));
  58161. g.drawRect (button.getBounds());
  58162. }
  58163. void BooleanPropertyComponent::refresh()
  58164. {
  58165. button.setToggleState (getState(), false);
  58166. button.setButtonText (button.getToggleState() ? onText : offText);
  58167. }
  58168. void BooleanPropertyComponent::buttonClicked (Button*)
  58169. {
  58170. setState (! getState());
  58171. }
  58172. END_JUCE_NAMESPACE
  58173. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58174. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58175. BEGIN_JUCE_NAMESPACE
  58176. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  58177. const bool triggerOnMouseDown)
  58178. : PropertyComponent (name)
  58179. {
  58180. addAndMakeVisible (&button);
  58181. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  58182. button.addButtonListener (this);
  58183. }
  58184. ButtonPropertyComponent::~ButtonPropertyComponent()
  58185. {
  58186. }
  58187. void ButtonPropertyComponent::refresh()
  58188. {
  58189. button.setButtonText (getButtonText());
  58190. }
  58191. void ButtonPropertyComponent::buttonClicked (Button*)
  58192. {
  58193. buttonClicked();
  58194. }
  58195. END_JUCE_NAMESPACE
  58196. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58197. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58198. BEGIN_JUCE_NAMESPACE
  58199. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  58200. public Value::Listener
  58201. {
  58202. public:
  58203. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  58204. : sourceValue (sourceValue_),
  58205. mappings (mappings_)
  58206. {
  58207. sourceValue.addListener (this);
  58208. }
  58209. ~RemapperValueSource() {}
  58210. const var getValue() const
  58211. {
  58212. return mappings.indexOf (sourceValue.getValue()) + 1;
  58213. }
  58214. void setValue (const var& newValue)
  58215. {
  58216. const var remappedVal (mappings [(int) newValue - 1]);
  58217. if (remappedVal != sourceValue)
  58218. sourceValue = remappedVal;
  58219. }
  58220. void valueChanged (Value&)
  58221. {
  58222. sendChangeMessage (true);
  58223. }
  58224. juce_UseDebuggingNewOperator
  58225. protected:
  58226. Value sourceValue;
  58227. Array<var> mappings;
  58228. RemapperValueSource (const RemapperValueSource&);
  58229. const RemapperValueSource& operator= (const RemapperValueSource&);
  58230. };
  58231. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  58232. : PropertyComponent (name),
  58233. isCustomClass (true)
  58234. {
  58235. }
  58236. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  58237. const String& name,
  58238. const StringArray& choices_,
  58239. const Array <var>& correspondingValues)
  58240. : PropertyComponent (name),
  58241. choices (choices_),
  58242. isCustomClass (false)
  58243. {
  58244. // The array of corresponding values must contain one value for each of the items in
  58245. // the choices array!
  58246. jassert (correspondingValues.size() == choices.size());
  58247. createComboBox();
  58248. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58249. }
  58250. ChoicePropertyComponent::~ChoicePropertyComponent()
  58251. {
  58252. }
  58253. void ChoicePropertyComponent::createComboBox()
  58254. {
  58255. addAndMakeVisible (&comboBox);
  58256. for (int i = 0; i < choices.size(); ++i)
  58257. {
  58258. if (choices[i].isNotEmpty())
  58259. comboBox.addItem (choices[i], i + 1);
  58260. else
  58261. comboBox.addSeparator();
  58262. }
  58263. comboBox.setEditableText (false);
  58264. }
  58265. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58266. {
  58267. jassertfalse; // you need to override this method in your subclass!
  58268. }
  58269. int ChoicePropertyComponent::getIndex() const
  58270. {
  58271. jassertfalse; // you need to override this method in your subclass!
  58272. return -1;
  58273. }
  58274. const StringArray& ChoicePropertyComponent::getChoices() const
  58275. {
  58276. return choices;
  58277. }
  58278. void ChoicePropertyComponent::refresh()
  58279. {
  58280. if (isCustomClass)
  58281. {
  58282. if (! comboBox.isVisible())
  58283. {
  58284. createComboBox();
  58285. comboBox.addListener (this);
  58286. }
  58287. comboBox.setSelectedId (getIndex() + 1, true);
  58288. }
  58289. }
  58290. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58291. {
  58292. if (isCustomClass)
  58293. {
  58294. const int newIndex = comboBox.getSelectedId() - 1;
  58295. if (newIndex != getIndex())
  58296. setIndex (newIndex);
  58297. }
  58298. }
  58299. END_JUCE_NAMESPACE
  58300. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58301. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58302. BEGIN_JUCE_NAMESPACE
  58303. PropertyComponent::PropertyComponent (const String& name,
  58304. const int preferredHeight_)
  58305. : Component (name),
  58306. preferredHeight (preferredHeight_)
  58307. {
  58308. jassert (name.isNotEmpty());
  58309. }
  58310. PropertyComponent::~PropertyComponent()
  58311. {
  58312. }
  58313. void PropertyComponent::paint (Graphics& g)
  58314. {
  58315. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58316. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58317. }
  58318. void PropertyComponent::resized()
  58319. {
  58320. if (getNumChildComponents() > 0)
  58321. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58322. }
  58323. void PropertyComponent::enablementChanged()
  58324. {
  58325. repaint();
  58326. }
  58327. END_JUCE_NAMESPACE
  58328. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58329. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58330. BEGIN_JUCE_NAMESPACE
  58331. class PropertyPanel::PropertyHolderComponent : public Component
  58332. {
  58333. public:
  58334. PropertyHolderComponent()
  58335. {
  58336. }
  58337. ~PropertyHolderComponent()
  58338. {
  58339. deleteAllChildren();
  58340. }
  58341. void paint (Graphics&)
  58342. {
  58343. }
  58344. void updateLayout (int width);
  58345. void refreshAll() const;
  58346. private:
  58347. PropertyHolderComponent (const PropertyHolderComponent&);
  58348. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  58349. };
  58350. class PropertySectionComponent : public Component
  58351. {
  58352. public:
  58353. PropertySectionComponent (const String& sectionTitle,
  58354. const Array <PropertyComponent*>& newProperties,
  58355. const bool open)
  58356. : Component (sectionTitle),
  58357. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58358. isOpen_ (open)
  58359. {
  58360. for (int i = newProperties.size(); --i >= 0;)
  58361. {
  58362. addAndMakeVisible (newProperties.getUnchecked(i));
  58363. newProperties.getUnchecked(i)->refresh();
  58364. }
  58365. }
  58366. ~PropertySectionComponent()
  58367. {
  58368. deleteAllChildren();
  58369. }
  58370. void paint (Graphics& g)
  58371. {
  58372. if (titleHeight > 0)
  58373. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58374. }
  58375. void resized()
  58376. {
  58377. int y = titleHeight;
  58378. for (int i = getNumChildComponents(); --i >= 0;)
  58379. {
  58380. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58381. if (pec != 0)
  58382. {
  58383. const int prefH = pec->getPreferredHeight();
  58384. pec->setBounds (1, y, getWidth() - 2, prefH);
  58385. y += prefH;
  58386. }
  58387. }
  58388. }
  58389. int getPreferredHeight() const
  58390. {
  58391. int y = titleHeight;
  58392. if (isOpen())
  58393. {
  58394. for (int i = 0; i < getNumChildComponents(); ++i)
  58395. {
  58396. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58397. if (pec != 0)
  58398. y += pec->getPreferredHeight();
  58399. }
  58400. }
  58401. return y;
  58402. }
  58403. void setOpen (const bool open)
  58404. {
  58405. if (isOpen_ != open)
  58406. {
  58407. isOpen_ = open;
  58408. for (int i = 0; i < getNumChildComponents(); ++i)
  58409. {
  58410. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58411. if (pec != 0)
  58412. pec->setVisible (open);
  58413. }
  58414. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  58415. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58416. if (pp != 0)
  58417. pp->resized();
  58418. }
  58419. }
  58420. bool isOpen() const
  58421. {
  58422. return isOpen_;
  58423. }
  58424. void refreshAll() const
  58425. {
  58426. for (int i = 0; i < getNumChildComponents(); ++i)
  58427. {
  58428. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58429. if (pec != 0)
  58430. pec->refresh();
  58431. }
  58432. }
  58433. void mouseDown (const MouseEvent&)
  58434. {
  58435. }
  58436. void mouseUp (const MouseEvent& e)
  58437. {
  58438. if (e.getMouseDownX() < titleHeight
  58439. && e.x < titleHeight
  58440. && e.y < titleHeight
  58441. && e.getNumberOfClicks() != 2)
  58442. {
  58443. setOpen (! isOpen());
  58444. }
  58445. }
  58446. void mouseDoubleClick (const MouseEvent& e)
  58447. {
  58448. if (e.y < titleHeight)
  58449. setOpen (! isOpen());
  58450. }
  58451. private:
  58452. int titleHeight;
  58453. bool isOpen_;
  58454. PropertySectionComponent (const PropertySectionComponent&);
  58455. PropertySectionComponent& operator= (const PropertySectionComponent&);
  58456. };
  58457. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  58458. {
  58459. int y = 0;
  58460. for (int i = getNumChildComponents(); --i >= 0;)
  58461. {
  58462. PropertySectionComponent* const section
  58463. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58464. if (section != 0)
  58465. {
  58466. const int prefH = section->getPreferredHeight();
  58467. section->setBounds (0, y, width, prefH);
  58468. y += prefH;
  58469. }
  58470. }
  58471. setSize (width, y);
  58472. repaint();
  58473. }
  58474. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  58475. {
  58476. for (int i = getNumChildComponents(); --i >= 0;)
  58477. {
  58478. PropertySectionComponent* const section
  58479. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58480. if (section != 0)
  58481. section->refreshAll();
  58482. }
  58483. }
  58484. PropertyPanel::PropertyPanel()
  58485. {
  58486. messageWhenEmpty = TRANS("(nothing selected)");
  58487. addAndMakeVisible (&viewport);
  58488. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58489. viewport.setFocusContainer (true);
  58490. }
  58491. PropertyPanel::~PropertyPanel()
  58492. {
  58493. clear();
  58494. }
  58495. void PropertyPanel::paint (Graphics& g)
  58496. {
  58497. if (propertyHolderComponent->getNumChildComponents() == 0)
  58498. {
  58499. g.setColour (Colours::black.withAlpha (0.5f));
  58500. g.setFont (14.0f);
  58501. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58502. Justification::centred, true);
  58503. }
  58504. }
  58505. void PropertyPanel::resized()
  58506. {
  58507. viewport.setBounds (getLocalBounds());
  58508. updatePropHolderLayout();
  58509. }
  58510. void PropertyPanel::clear()
  58511. {
  58512. if (propertyHolderComponent->getNumChildComponents() > 0)
  58513. {
  58514. propertyHolderComponent->deleteAllChildren();
  58515. repaint();
  58516. }
  58517. }
  58518. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58519. {
  58520. if (propertyHolderComponent->getNumChildComponents() == 0)
  58521. repaint();
  58522. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  58523. newProperties,
  58524. true), 0);
  58525. updatePropHolderLayout();
  58526. }
  58527. void PropertyPanel::addSection (const String& sectionTitle,
  58528. const Array <PropertyComponent*>& newProperties,
  58529. const bool shouldBeOpen)
  58530. {
  58531. jassert (sectionTitle.isNotEmpty());
  58532. if (propertyHolderComponent->getNumChildComponents() == 0)
  58533. repaint();
  58534. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  58535. newProperties,
  58536. shouldBeOpen), 0);
  58537. updatePropHolderLayout();
  58538. }
  58539. void PropertyPanel::updatePropHolderLayout() const
  58540. {
  58541. const int maxWidth = viewport.getMaximumVisibleWidth();
  58542. propertyHolderComponent->updateLayout (maxWidth);
  58543. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58544. if (maxWidth != newMaxWidth)
  58545. {
  58546. // need to do this twice because of scrollbars changing the size, etc.
  58547. propertyHolderComponent->updateLayout (newMaxWidth);
  58548. }
  58549. }
  58550. void PropertyPanel::refreshAll() const
  58551. {
  58552. propertyHolderComponent->refreshAll();
  58553. }
  58554. const StringArray PropertyPanel::getSectionNames() const
  58555. {
  58556. StringArray s;
  58557. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58558. {
  58559. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58560. if (section != 0 && section->getName().isNotEmpty())
  58561. s.add (section->getName());
  58562. }
  58563. return s;
  58564. }
  58565. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58566. {
  58567. int index = 0;
  58568. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58569. {
  58570. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58571. if (section != 0 && section->getName().isNotEmpty())
  58572. {
  58573. if (index == sectionIndex)
  58574. return section->isOpen();
  58575. ++index;
  58576. }
  58577. }
  58578. return false;
  58579. }
  58580. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58581. {
  58582. int index = 0;
  58583. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58584. {
  58585. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58586. if (section != 0 && section->getName().isNotEmpty())
  58587. {
  58588. if (index == sectionIndex)
  58589. {
  58590. section->setOpen (shouldBeOpen);
  58591. break;
  58592. }
  58593. ++index;
  58594. }
  58595. }
  58596. }
  58597. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58598. {
  58599. int index = 0;
  58600. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58601. {
  58602. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58603. if (section != 0 && section->getName().isNotEmpty())
  58604. {
  58605. if (index == sectionIndex)
  58606. {
  58607. section->setEnabled (shouldBeEnabled);
  58608. break;
  58609. }
  58610. ++index;
  58611. }
  58612. }
  58613. }
  58614. XmlElement* PropertyPanel::getOpennessState() const
  58615. {
  58616. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58617. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58618. const StringArray sections (getSectionNames());
  58619. for (int i = 0; i < sections.size(); ++i)
  58620. {
  58621. if (sections[i].isNotEmpty())
  58622. {
  58623. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58624. e->setAttribute ("name", sections[i]);
  58625. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58626. }
  58627. }
  58628. return xml;
  58629. }
  58630. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58631. {
  58632. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58633. {
  58634. const StringArray sections (getSectionNames());
  58635. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58636. {
  58637. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58638. e->getBoolAttribute ("open"));
  58639. }
  58640. viewport.setViewPosition (viewport.getViewPositionX(),
  58641. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58642. }
  58643. }
  58644. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58645. {
  58646. if (messageWhenEmpty != newMessage)
  58647. {
  58648. messageWhenEmpty = newMessage;
  58649. repaint();
  58650. }
  58651. }
  58652. const String& PropertyPanel::getMessageWhenEmpty() const
  58653. {
  58654. return messageWhenEmpty;
  58655. }
  58656. END_JUCE_NAMESPACE
  58657. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58658. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58659. BEGIN_JUCE_NAMESPACE
  58660. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58661. const double rangeMin,
  58662. const double rangeMax,
  58663. const double interval,
  58664. const double skewFactor)
  58665. : PropertyComponent (name)
  58666. {
  58667. addAndMakeVisible (&slider);
  58668. slider.setRange (rangeMin, rangeMax, interval);
  58669. slider.setSkewFactor (skewFactor);
  58670. slider.setSliderStyle (Slider::LinearBar);
  58671. slider.addListener (this);
  58672. }
  58673. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58674. const String& name,
  58675. const double rangeMin,
  58676. const double rangeMax,
  58677. const double interval,
  58678. const double skewFactor)
  58679. : PropertyComponent (name)
  58680. {
  58681. addAndMakeVisible (&slider);
  58682. slider.setRange (rangeMin, rangeMax, interval);
  58683. slider.setSkewFactor (skewFactor);
  58684. slider.setSliderStyle (Slider::LinearBar);
  58685. slider.getValueObject().referTo (valueToControl);
  58686. }
  58687. SliderPropertyComponent::~SliderPropertyComponent()
  58688. {
  58689. }
  58690. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58691. {
  58692. }
  58693. double SliderPropertyComponent::getValue() const
  58694. {
  58695. return slider.getValue();
  58696. }
  58697. void SliderPropertyComponent::refresh()
  58698. {
  58699. slider.setValue (getValue(), false);
  58700. }
  58701. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58702. {
  58703. if (getValue() != slider.getValue())
  58704. setValue (slider.getValue());
  58705. }
  58706. END_JUCE_NAMESPACE
  58707. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58708. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58709. BEGIN_JUCE_NAMESPACE
  58710. class TextPropLabel : public Label
  58711. {
  58712. TextPropertyComponent& owner;
  58713. int maxChars;
  58714. bool isMultiline;
  58715. public:
  58716. TextPropLabel (TextPropertyComponent& owner_,
  58717. const int maxChars_, const bool isMultiline_)
  58718. : Label (String::empty, String::empty),
  58719. owner (owner_),
  58720. maxChars (maxChars_),
  58721. isMultiline (isMultiline_)
  58722. {
  58723. setEditable (true, true, false);
  58724. setColour (backgroundColourId, Colours::white);
  58725. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58726. }
  58727. ~TextPropLabel()
  58728. {
  58729. }
  58730. TextEditor* createEditorComponent()
  58731. {
  58732. TextEditor* const textEditor = Label::createEditorComponent();
  58733. textEditor->setInputRestrictions (maxChars);
  58734. if (isMultiline)
  58735. {
  58736. textEditor->setMultiLine (true, true);
  58737. textEditor->setReturnKeyStartsNewLine (true);
  58738. }
  58739. return textEditor;
  58740. }
  58741. void textWasEdited()
  58742. {
  58743. owner.textWasEdited();
  58744. }
  58745. };
  58746. TextPropertyComponent::TextPropertyComponent (const String& name,
  58747. const int maxNumChars,
  58748. const bool isMultiLine)
  58749. : PropertyComponent (name)
  58750. {
  58751. createEditor (maxNumChars, isMultiLine);
  58752. }
  58753. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58754. const String& name,
  58755. const int maxNumChars,
  58756. const bool isMultiLine)
  58757. : PropertyComponent (name)
  58758. {
  58759. createEditor (maxNumChars, isMultiLine);
  58760. textEditor->getTextValue().referTo (valueToControl);
  58761. }
  58762. TextPropertyComponent::~TextPropertyComponent()
  58763. {
  58764. deleteAllChildren();
  58765. }
  58766. void TextPropertyComponent::setText (const String& newText)
  58767. {
  58768. textEditor->setText (newText, true);
  58769. }
  58770. const String TextPropertyComponent::getText() const
  58771. {
  58772. return textEditor->getText();
  58773. }
  58774. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58775. {
  58776. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58777. if (isMultiLine)
  58778. {
  58779. textEditor->setJustificationType (Justification::topLeft);
  58780. preferredHeight = 120;
  58781. }
  58782. }
  58783. void TextPropertyComponent::refresh()
  58784. {
  58785. textEditor->setText (getText(), false);
  58786. }
  58787. void TextPropertyComponent::textWasEdited()
  58788. {
  58789. const String newText (textEditor->getText());
  58790. if (getText() != newText)
  58791. setText (newText);
  58792. }
  58793. END_JUCE_NAMESPACE
  58794. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58795. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58796. BEGIN_JUCE_NAMESPACE
  58797. class SimpleDeviceManagerInputLevelMeter : public Component,
  58798. public Timer
  58799. {
  58800. public:
  58801. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58802. : manager (manager_),
  58803. level (0)
  58804. {
  58805. startTimer (50);
  58806. manager->enableInputLevelMeasurement (true);
  58807. }
  58808. ~SimpleDeviceManagerInputLevelMeter()
  58809. {
  58810. manager->enableInputLevelMeasurement (false);
  58811. }
  58812. void timerCallback()
  58813. {
  58814. const float newLevel = (float) manager->getCurrentInputLevel();
  58815. if (std::abs (level - newLevel) > 0.005f)
  58816. {
  58817. level = newLevel;
  58818. repaint();
  58819. }
  58820. }
  58821. void paint (Graphics& g)
  58822. {
  58823. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58824. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58825. }
  58826. private:
  58827. AudioDeviceManager* const manager;
  58828. float level;
  58829. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58830. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58831. };
  58832. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58833. public ListBoxModel
  58834. {
  58835. public:
  58836. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58837. const String& noItemsMessage_,
  58838. const int minNumber_,
  58839. const int maxNumber_)
  58840. : ListBox (String::empty, 0),
  58841. deviceManager (deviceManager_),
  58842. noItemsMessage (noItemsMessage_),
  58843. minNumber (minNumber_),
  58844. maxNumber (maxNumber_)
  58845. {
  58846. items = MidiInput::getDevices();
  58847. setModel (this);
  58848. setOutlineThickness (1);
  58849. }
  58850. ~MidiInputSelectorComponentListBox()
  58851. {
  58852. }
  58853. int getNumRows()
  58854. {
  58855. return items.size();
  58856. }
  58857. void paintListBoxItem (int row,
  58858. Graphics& g,
  58859. int width, int height,
  58860. bool rowIsSelected)
  58861. {
  58862. if (((unsigned int) row) < (unsigned int) items.size())
  58863. {
  58864. if (rowIsSelected)
  58865. g.fillAll (findColour (TextEditor::highlightColourId)
  58866. .withMultipliedAlpha (0.3f));
  58867. const String item (items [row]);
  58868. bool enabled = deviceManager.isMidiInputEnabled (item);
  58869. const int x = getTickX();
  58870. const float tickW = height * 0.75f;
  58871. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58872. enabled, true, true, false);
  58873. g.setFont (height * 0.6f);
  58874. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58875. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58876. }
  58877. }
  58878. void listBoxItemClicked (int row, const MouseEvent& e)
  58879. {
  58880. selectRow (row);
  58881. if (e.x < getTickX())
  58882. flipEnablement (row);
  58883. }
  58884. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58885. {
  58886. flipEnablement (row);
  58887. }
  58888. void returnKeyPressed (int row)
  58889. {
  58890. flipEnablement (row);
  58891. }
  58892. void paint (Graphics& g)
  58893. {
  58894. ListBox::paint (g);
  58895. if (items.size() == 0)
  58896. {
  58897. g.setColour (Colours::grey);
  58898. g.setFont (13.0f);
  58899. g.drawText (noItemsMessage,
  58900. 0, 0, getWidth(), getHeight() / 2,
  58901. Justification::centred, true);
  58902. }
  58903. }
  58904. int getBestHeight (const int preferredHeight)
  58905. {
  58906. const int extra = getOutlineThickness() * 2;
  58907. return jmax (getRowHeight() * 2 + extra,
  58908. jmin (getRowHeight() * getNumRows() + extra,
  58909. preferredHeight));
  58910. }
  58911. juce_UseDebuggingNewOperator
  58912. private:
  58913. AudioDeviceManager& deviceManager;
  58914. const String noItemsMessage;
  58915. StringArray items;
  58916. int minNumber, maxNumber;
  58917. void flipEnablement (const int row)
  58918. {
  58919. if (((unsigned int) row) < (unsigned int) items.size())
  58920. {
  58921. const String item (items [row]);
  58922. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58923. }
  58924. }
  58925. int getTickX() const
  58926. {
  58927. return getRowHeight() + 5;
  58928. }
  58929. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  58930. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  58931. };
  58932. class AudioDeviceSettingsPanel : public Component,
  58933. public ChangeListener,
  58934. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58935. public ButtonListener
  58936. {
  58937. public:
  58938. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58939. AudioIODeviceType::DeviceSetupDetails& setup_,
  58940. const bool hideAdvancedOptionsWithButton)
  58941. : type (type_),
  58942. setup (setup_)
  58943. {
  58944. if (hideAdvancedOptionsWithButton)
  58945. {
  58946. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58947. showAdvancedSettingsButton->addButtonListener (this);
  58948. }
  58949. type->scanForDevices();
  58950. setup.manager->addChangeListener (this);
  58951. changeListenerCallback (0);
  58952. }
  58953. ~AudioDeviceSettingsPanel()
  58954. {
  58955. setup.manager->removeChangeListener (this);
  58956. }
  58957. void resized()
  58958. {
  58959. const int lx = proportionOfWidth (0.35f);
  58960. const int w = proportionOfWidth (0.4f);
  58961. const int h = 24;
  58962. const int space = 6;
  58963. const int dh = h + space;
  58964. int y = 0;
  58965. if (outputDeviceDropDown != 0)
  58966. {
  58967. outputDeviceDropDown->setBounds (lx, y, w, h);
  58968. if (testButton != 0)
  58969. testButton->setBounds (proportionOfWidth (0.77f),
  58970. outputDeviceDropDown->getY(),
  58971. proportionOfWidth (0.18f),
  58972. h);
  58973. y += dh;
  58974. }
  58975. if (inputDeviceDropDown != 0)
  58976. {
  58977. inputDeviceDropDown->setBounds (lx, y, w, h);
  58978. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58979. inputDeviceDropDown->getY(),
  58980. proportionOfWidth (0.18f),
  58981. h);
  58982. y += dh;
  58983. }
  58984. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58985. if (outputChanList != 0)
  58986. {
  58987. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58988. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58989. y += bh + space;
  58990. }
  58991. if (inputChanList != 0)
  58992. {
  58993. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58994. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58995. y += bh + space;
  58996. }
  58997. y += space * 2;
  58998. if (showAdvancedSettingsButton != 0)
  58999. {
  59000. showAdvancedSettingsButton->changeWidthToFitText (h);
  59001. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  59002. }
  59003. if (sampleRateDropDown != 0)
  59004. {
  59005. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  59006. || ! showAdvancedSettingsButton->isVisible());
  59007. sampleRateDropDown->setBounds (lx, y, w, h);
  59008. y += dh;
  59009. }
  59010. if (bufferSizeDropDown != 0)
  59011. {
  59012. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  59013. || ! showAdvancedSettingsButton->isVisible());
  59014. bufferSizeDropDown->setBounds (lx, y, w, h);
  59015. y += dh;
  59016. }
  59017. if (showUIButton != 0)
  59018. {
  59019. showUIButton->setVisible (showAdvancedSettingsButton == 0
  59020. || ! showAdvancedSettingsButton->isVisible());
  59021. showUIButton->changeWidthToFitText (h);
  59022. showUIButton->setTopLeftPosition (lx, y);
  59023. }
  59024. }
  59025. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59026. {
  59027. if (comboBoxThatHasChanged == 0)
  59028. return;
  59029. AudioDeviceManager::AudioDeviceSetup config;
  59030. setup.manager->getAudioDeviceSetup (config);
  59031. String error;
  59032. if (comboBoxThatHasChanged == outputDeviceDropDown
  59033. || comboBoxThatHasChanged == inputDeviceDropDown)
  59034. {
  59035. if (outputDeviceDropDown != 0)
  59036. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59037. : outputDeviceDropDown->getText();
  59038. if (inputDeviceDropDown != 0)
  59039. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59040. : inputDeviceDropDown->getText();
  59041. if (! type->hasSeparateInputsAndOutputs())
  59042. config.inputDeviceName = config.outputDeviceName;
  59043. if (comboBoxThatHasChanged == inputDeviceDropDown)
  59044. config.useDefaultInputChannels = true;
  59045. else
  59046. config.useDefaultOutputChannels = true;
  59047. error = setup.manager->setAudioDeviceSetup (config, true);
  59048. showCorrectDeviceName (inputDeviceDropDown, true);
  59049. showCorrectDeviceName (outputDeviceDropDown, false);
  59050. updateControlPanelButton();
  59051. resized();
  59052. }
  59053. else if (comboBoxThatHasChanged == sampleRateDropDown)
  59054. {
  59055. if (sampleRateDropDown->getSelectedId() > 0)
  59056. {
  59057. config.sampleRate = sampleRateDropDown->getSelectedId();
  59058. error = setup.manager->setAudioDeviceSetup (config, true);
  59059. }
  59060. }
  59061. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  59062. {
  59063. if (bufferSizeDropDown->getSelectedId() > 0)
  59064. {
  59065. config.bufferSize = bufferSizeDropDown->getSelectedId();
  59066. error = setup.manager->setAudioDeviceSetup (config, true);
  59067. }
  59068. }
  59069. if (error.isNotEmpty())
  59070. {
  59071. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  59072. "Error when trying to open audio device!",
  59073. error);
  59074. }
  59075. }
  59076. void buttonClicked (Button* button)
  59077. {
  59078. if (button == showAdvancedSettingsButton)
  59079. {
  59080. showAdvancedSettingsButton->setVisible (false);
  59081. resized();
  59082. }
  59083. else if (button == showUIButton)
  59084. {
  59085. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  59086. if (device != 0 && device->showControlPanel())
  59087. {
  59088. setup.manager->closeAudioDevice();
  59089. setup.manager->restartLastAudioDevice();
  59090. getTopLevelComponent()->toFront (true);
  59091. }
  59092. }
  59093. else if (button == testButton && testButton != 0)
  59094. {
  59095. setup.manager->playTestSound();
  59096. }
  59097. }
  59098. void updateControlPanelButton()
  59099. {
  59100. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59101. showUIButton = 0;
  59102. if (currentDevice != 0 && currentDevice->hasControlPanel())
  59103. {
  59104. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  59105. TRANS ("opens the device's own control panel")));
  59106. showUIButton->addButtonListener (this);
  59107. }
  59108. resized();
  59109. }
  59110. void changeListenerCallback (void*)
  59111. {
  59112. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59113. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  59114. {
  59115. if (outputDeviceDropDown == 0)
  59116. {
  59117. outputDeviceDropDown = new ComboBox (String::empty);
  59118. outputDeviceDropDown->addListener (this);
  59119. addAndMakeVisible (outputDeviceDropDown);
  59120. outputDeviceLabel = new Label (String::empty,
  59121. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  59122. : TRANS ("device:"));
  59123. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  59124. if (setup.maxNumOutputChannels > 0)
  59125. {
  59126. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  59127. testButton->addButtonListener (this);
  59128. }
  59129. }
  59130. addNamesToDeviceBox (*outputDeviceDropDown, false);
  59131. }
  59132. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  59133. {
  59134. if (inputDeviceDropDown == 0)
  59135. {
  59136. inputDeviceDropDown = new ComboBox (String::empty);
  59137. inputDeviceDropDown->addListener (this);
  59138. addAndMakeVisible (inputDeviceDropDown);
  59139. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  59140. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  59141. addAndMakeVisible (inputLevelMeter
  59142. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  59143. }
  59144. addNamesToDeviceBox (*inputDeviceDropDown, true);
  59145. }
  59146. updateControlPanelButton();
  59147. showCorrectDeviceName (inputDeviceDropDown, true);
  59148. showCorrectDeviceName (outputDeviceDropDown, false);
  59149. if (currentDevice != 0)
  59150. {
  59151. if (setup.maxNumOutputChannels > 0
  59152. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  59153. {
  59154. if (outputChanList == 0)
  59155. {
  59156. addAndMakeVisible (outputChanList
  59157. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  59158. TRANS ("(no audio output channels found)")));
  59159. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  59160. outputChanLabel->attachToComponent (outputChanList, true);
  59161. }
  59162. outputChanList->refresh();
  59163. }
  59164. else
  59165. {
  59166. outputChanLabel = 0;
  59167. outputChanList = 0;
  59168. }
  59169. if (setup.maxNumInputChannels > 0
  59170. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  59171. {
  59172. if (inputChanList == 0)
  59173. {
  59174. addAndMakeVisible (inputChanList
  59175. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  59176. TRANS ("(no audio input channels found)")));
  59177. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  59178. inputChanLabel->attachToComponent (inputChanList, true);
  59179. }
  59180. inputChanList->refresh();
  59181. }
  59182. else
  59183. {
  59184. inputChanLabel = 0;
  59185. inputChanList = 0;
  59186. }
  59187. // sample rate..
  59188. {
  59189. if (sampleRateDropDown == 0)
  59190. {
  59191. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  59192. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  59193. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  59194. }
  59195. else
  59196. {
  59197. sampleRateDropDown->clear();
  59198. sampleRateDropDown->removeListener (this);
  59199. }
  59200. const int numRates = currentDevice->getNumSampleRates();
  59201. for (int i = 0; i < numRates; ++i)
  59202. {
  59203. const int rate = roundToInt (currentDevice->getSampleRate (i));
  59204. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  59205. }
  59206. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  59207. sampleRateDropDown->addListener (this);
  59208. }
  59209. // buffer size
  59210. {
  59211. if (bufferSizeDropDown == 0)
  59212. {
  59213. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  59214. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  59215. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  59216. }
  59217. else
  59218. {
  59219. bufferSizeDropDown->clear();
  59220. bufferSizeDropDown->removeListener (this);
  59221. }
  59222. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  59223. double currentRate = currentDevice->getCurrentSampleRate();
  59224. if (currentRate == 0)
  59225. currentRate = 48000.0;
  59226. for (int i = 0; i < numBufferSizes; ++i)
  59227. {
  59228. const int bs = currentDevice->getBufferSizeSamples (i);
  59229. bufferSizeDropDown->addItem (String (bs)
  59230. + " samples ("
  59231. + String (bs * 1000.0 / currentRate, 1)
  59232. + " ms)",
  59233. bs);
  59234. }
  59235. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  59236. bufferSizeDropDown->addListener (this);
  59237. }
  59238. }
  59239. else
  59240. {
  59241. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  59242. sampleRateLabel = 0;
  59243. bufferSizeLabel = 0;
  59244. sampleRateDropDown = 0;
  59245. bufferSizeDropDown = 0;
  59246. if (outputDeviceDropDown != 0)
  59247. outputDeviceDropDown->setSelectedId (-1, true);
  59248. if (inputDeviceDropDown != 0)
  59249. inputDeviceDropDown->setSelectedId (-1, true);
  59250. }
  59251. resized();
  59252. setSize (getWidth(), getLowestY() + 4);
  59253. }
  59254. private:
  59255. AudioIODeviceType* const type;
  59256. const AudioIODeviceType::DeviceSetupDetails setup;
  59257. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  59258. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  59259. ScopedPointer<TextButton> testButton;
  59260. ScopedPointer<Component> inputLevelMeter;
  59261. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  59262. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  59263. {
  59264. if (box != 0)
  59265. {
  59266. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  59267. const int index = type->getIndexOfDevice (currentDevice, isInput);
  59268. box->setSelectedId (index + 1, true);
  59269. if (testButton != 0 && ! isInput)
  59270. testButton->setEnabled (index >= 0);
  59271. }
  59272. }
  59273. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  59274. {
  59275. const StringArray devs (type->getDeviceNames (isInputs));
  59276. combo.clear (true);
  59277. for (int i = 0; i < devs.size(); ++i)
  59278. combo.addItem (devs[i], i + 1);
  59279. combo.addItem (TRANS("<< none >>"), -1);
  59280. combo.setSelectedId (-1, true);
  59281. }
  59282. int getLowestY() const
  59283. {
  59284. int y = 0;
  59285. for (int i = getNumChildComponents(); --i >= 0;)
  59286. y = jmax (y, getChildComponent (i)->getBottom());
  59287. return y;
  59288. }
  59289. public:
  59290. class ChannelSelectorListBox : public ListBox,
  59291. public ListBoxModel
  59292. {
  59293. public:
  59294. enum BoxType
  59295. {
  59296. audioInputType,
  59297. audioOutputType
  59298. };
  59299. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59300. const BoxType type_,
  59301. const String& noItemsMessage_)
  59302. : ListBox (String::empty, 0),
  59303. setup (setup_),
  59304. type (type_),
  59305. noItemsMessage (noItemsMessage_)
  59306. {
  59307. refresh();
  59308. setModel (this);
  59309. setOutlineThickness (1);
  59310. }
  59311. ~ChannelSelectorListBox()
  59312. {
  59313. }
  59314. void refresh()
  59315. {
  59316. items.clear();
  59317. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59318. if (currentDevice != 0)
  59319. {
  59320. if (type == audioInputType)
  59321. items = currentDevice->getInputChannelNames();
  59322. else if (type == audioOutputType)
  59323. items = currentDevice->getOutputChannelNames();
  59324. if (setup.useStereoPairs)
  59325. {
  59326. StringArray pairs;
  59327. for (int i = 0; i < items.size(); i += 2)
  59328. {
  59329. const String name (items[i]);
  59330. const String name2 (items[i + 1]);
  59331. String commonBit;
  59332. for (int j = 0; j < name.length(); ++j)
  59333. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59334. commonBit = name.substring (0, j);
  59335. // Make sure we only split the name at a space, because otherwise, things
  59336. // like "input 11" + "input 12" would become "input 11 + 2"
  59337. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59338. commonBit = commonBit.dropLastCharacters (1);
  59339. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59340. }
  59341. items = pairs;
  59342. }
  59343. }
  59344. updateContent();
  59345. repaint();
  59346. }
  59347. int getNumRows()
  59348. {
  59349. return items.size();
  59350. }
  59351. void paintListBoxItem (int row,
  59352. Graphics& g,
  59353. int width, int height,
  59354. bool rowIsSelected)
  59355. {
  59356. if (((unsigned int) row) < (unsigned int) items.size())
  59357. {
  59358. if (rowIsSelected)
  59359. g.fillAll (findColour (TextEditor::highlightColourId)
  59360. .withMultipliedAlpha (0.3f));
  59361. const String item (items [row]);
  59362. bool enabled = false;
  59363. AudioDeviceManager::AudioDeviceSetup config;
  59364. setup.manager->getAudioDeviceSetup (config);
  59365. if (setup.useStereoPairs)
  59366. {
  59367. if (type == audioInputType)
  59368. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59369. else if (type == audioOutputType)
  59370. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59371. }
  59372. else
  59373. {
  59374. if (type == audioInputType)
  59375. enabled = config.inputChannels [row];
  59376. else if (type == audioOutputType)
  59377. enabled = config.outputChannels [row];
  59378. }
  59379. const int x = getTickX();
  59380. const float tickW = height * 0.75f;
  59381. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59382. enabled, true, true, false);
  59383. g.setFont (height * 0.6f);
  59384. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59385. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59386. }
  59387. }
  59388. void listBoxItemClicked (int row, const MouseEvent& e)
  59389. {
  59390. selectRow (row);
  59391. if (e.x < getTickX())
  59392. flipEnablement (row);
  59393. }
  59394. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59395. {
  59396. flipEnablement (row);
  59397. }
  59398. void returnKeyPressed (int row)
  59399. {
  59400. flipEnablement (row);
  59401. }
  59402. void paint (Graphics& g)
  59403. {
  59404. ListBox::paint (g);
  59405. if (items.size() == 0)
  59406. {
  59407. g.setColour (Colours::grey);
  59408. g.setFont (13.0f);
  59409. g.drawText (noItemsMessage,
  59410. 0, 0, getWidth(), getHeight() / 2,
  59411. Justification::centred, true);
  59412. }
  59413. }
  59414. int getBestHeight (int maxHeight)
  59415. {
  59416. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59417. getNumRows())
  59418. + getOutlineThickness() * 2;
  59419. }
  59420. juce_UseDebuggingNewOperator
  59421. private:
  59422. const AudioIODeviceType::DeviceSetupDetails setup;
  59423. const BoxType type;
  59424. const String noItemsMessage;
  59425. StringArray items;
  59426. void flipEnablement (const int row)
  59427. {
  59428. jassert (type == audioInputType || type == audioOutputType);
  59429. if (((unsigned int) row) < (unsigned int) items.size())
  59430. {
  59431. AudioDeviceManager::AudioDeviceSetup config;
  59432. setup.manager->getAudioDeviceSetup (config);
  59433. if (setup.useStereoPairs)
  59434. {
  59435. BigInteger bits;
  59436. BigInteger& original = (type == audioInputType ? config.inputChannels
  59437. : config.outputChannels);
  59438. int i;
  59439. for (i = 0; i < 256; i += 2)
  59440. bits.setBit (i / 2, original [i] || original [i + 1]);
  59441. if (type == audioInputType)
  59442. {
  59443. config.useDefaultInputChannels = false;
  59444. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59445. }
  59446. else
  59447. {
  59448. config.useDefaultOutputChannels = false;
  59449. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59450. }
  59451. for (i = 0; i < 256; ++i)
  59452. original.setBit (i, bits [i / 2]);
  59453. }
  59454. else
  59455. {
  59456. if (type == audioInputType)
  59457. {
  59458. config.useDefaultInputChannels = false;
  59459. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59460. }
  59461. else
  59462. {
  59463. config.useDefaultOutputChannels = false;
  59464. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59465. }
  59466. }
  59467. String error (setup.manager->setAudioDeviceSetup (config, true));
  59468. if (! error.isEmpty())
  59469. {
  59470. //xxx
  59471. }
  59472. }
  59473. }
  59474. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59475. {
  59476. const int numActive = chans.countNumberOfSetBits();
  59477. if (chans [index])
  59478. {
  59479. if (numActive > minNumber)
  59480. chans.setBit (index, false);
  59481. }
  59482. else
  59483. {
  59484. if (numActive >= maxNumber)
  59485. {
  59486. const int firstActiveChan = chans.findNextSetBit();
  59487. chans.setBit (index > firstActiveChan
  59488. ? firstActiveChan : chans.getHighestBit(),
  59489. false);
  59490. }
  59491. chans.setBit (index, true);
  59492. }
  59493. }
  59494. int getTickX() const
  59495. {
  59496. return getRowHeight() + 5;
  59497. }
  59498. ChannelSelectorListBox (const ChannelSelectorListBox&);
  59499. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  59500. };
  59501. private:
  59502. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59503. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  59504. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  59505. };
  59506. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59507. const int minInputChannels_,
  59508. const int maxInputChannels_,
  59509. const int minOutputChannels_,
  59510. const int maxOutputChannels_,
  59511. const bool showMidiInputOptions,
  59512. const bool showMidiOutputSelector,
  59513. const bool showChannelsAsStereoPairs_,
  59514. const bool hideAdvancedOptionsWithButton_)
  59515. : deviceManager (deviceManager_),
  59516. deviceTypeDropDown (0),
  59517. deviceTypeDropDownLabel (0),
  59518. minOutputChannels (minOutputChannels_),
  59519. maxOutputChannels (maxOutputChannels_),
  59520. minInputChannels (minInputChannels_),
  59521. maxInputChannels (maxInputChannels_),
  59522. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59523. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59524. {
  59525. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59526. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59527. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59528. {
  59529. deviceTypeDropDown = new ComboBox (String::empty);
  59530. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59531. {
  59532. deviceTypeDropDown
  59533. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59534. i + 1);
  59535. }
  59536. addAndMakeVisible (deviceTypeDropDown);
  59537. deviceTypeDropDown->addListener (this);
  59538. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59539. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59540. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59541. }
  59542. if (showMidiInputOptions)
  59543. {
  59544. addAndMakeVisible (midiInputsList
  59545. = new MidiInputSelectorComponentListBox (deviceManager,
  59546. TRANS("(no midi inputs available)"),
  59547. 0, 0));
  59548. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59549. midiInputsLabel->setJustificationType (Justification::topRight);
  59550. midiInputsLabel->attachToComponent (midiInputsList, true);
  59551. }
  59552. else
  59553. {
  59554. midiInputsList = 0;
  59555. midiInputsLabel = 0;
  59556. }
  59557. if (showMidiOutputSelector)
  59558. {
  59559. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59560. midiOutputSelector->addListener (this);
  59561. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59562. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59563. }
  59564. else
  59565. {
  59566. midiOutputSelector = 0;
  59567. midiOutputLabel = 0;
  59568. }
  59569. deviceManager_.addChangeListener (this);
  59570. changeListenerCallback (0);
  59571. }
  59572. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59573. {
  59574. deviceManager.removeChangeListener (this);
  59575. }
  59576. void AudioDeviceSelectorComponent::resized()
  59577. {
  59578. const int lx = proportionOfWidth (0.35f);
  59579. const int w = proportionOfWidth (0.4f);
  59580. const int h = 24;
  59581. const int space = 6;
  59582. const int dh = h + space;
  59583. int y = 15;
  59584. if (deviceTypeDropDown != 0)
  59585. {
  59586. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59587. y += dh + space * 2;
  59588. }
  59589. if (audioDeviceSettingsComp != 0)
  59590. {
  59591. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59592. y += audioDeviceSettingsComp->getHeight() + space;
  59593. }
  59594. if (midiInputsList != 0)
  59595. {
  59596. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59597. midiInputsList->setBounds (lx, y, w, bh);
  59598. y += bh + space;
  59599. }
  59600. if (midiOutputSelector != 0)
  59601. midiOutputSelector->setBounds (lx, y, w, h);
  59602. }
  59603. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59604. {
  59605. if (child == audioDeviceSettingsComp)
  59606. resized();
  59607. }
  59608. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59609. {
  59610. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59611. if (device != 0 && device->hasControlPanel())
  59612. {
  59613. if (device->showControlPanel())
  59614. deviceManager.restartLastAudioDevice();
  59615. getTopLevelComponent()->toFront (true);
  59616. }
  59617. }
  59618. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59619. {
  59620. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59621. {
  59622. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59623. if (type != 0)
  59624. {
  59625. audioDeviceSettingsComp = 0;
  59626. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59627. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59628. }
  59629. }
  59630. else if (comboBoxThatHasChanged == midiOutputSelector)
  59631. {
  59632. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59633. }
  59634. }
  59635. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  59636. {
  59637. if (deviceTypeDropDown != 0)
  59638. {
  59639. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59640. }
  59641. if (audioDeviceSettingsComp == 0
  59642. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59643. {
  59644. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59645. audioDeviceSettingsComp = 0;
  59646. AudioIODeviceType* const type
  59647. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59648. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59649. if (type != 0)
  59650. {
  59651. AudioIODeviceType::DeviceSetupDetails details;
  59652. details.manager = &deviceManager;
  59653. details.minNumInputChannels = minInputChannels;
  59654. details.maxNumInputChannels = maxInputChannels;
  59655. details.minNumOutputChannels = minOutputChannels;
  59656. details.maxNumOutputChannels = maxOutputChannels;
  59657. details.useStereoPairs = showChannelsAsStereoPairs;
  59658. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59659. if (audioDeviceSettingsComp != 0)
  59660. {
  59661. addAndMakeVisible (audioDeviceSettingsComp);
  59662. audioDeviceSettingsComp->resized();
  59663. }
  59664. }
  59665. }
  59666. if (midiInputsList != 0)
  59667. {
  59668. midiInputsList->updateContent();
  59669. midiInputsList->repaint();
  59670. }
  59671. if (midiOutputSelector != 0)
  59672. {
  59673. midiOutputSelector->clear();
  59674. const StringArray midiOuts (MidiOutput::getDevices());
  59675. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59676. midiOutputSelector->addSeparator();
  59677. for (int i = 0; i < midiOuts.size(); ++i)
  59678. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59679. int current = -1;
  59680. if (deviceManager.getDefaultMidiOutput() != 0)
  59681. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59682. midiOutputSelector->setSelectedId (current, true);
  59683. }
  59684. resized();
  59685. }
  59686. END_JUCE_NAMESPACE
  59687. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59688. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59689. BEGIN_JUCE_NAMESPACE
  59690. BubbleComponent::BubbleComponent()
  59691. : side (0),
  59692. allowablePlacements (above | below | left | right),
  59693. arrowTipX (0.0f),
  59694. arrowTipY (0.0f)
  59695. {
  59696. setInterceptsMouseClicks (false, false);
  59697. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59698. setComponentEffect (&shadow);
  59699. }
  59700. BubbleComponent::~BubbleComponent()
  59701. {
  59702. }
  59703. void BubbleComponent::paint (Graphics& g)
  59704. {
  59705. int x = content.getX();
  59706. int y = content.getY();
  59707. int w = content.getWidth();
  59708. int h = content.getHeight();
  59709. int cw, ch;
  59710. getContentSize (cw, ch);
  59711. if (side == 3)
  59712. x += w - cw;
  59713. else if (side != 1)
  59714. x += (w - cw) / 2;
  59715. w = cw;
  59716. if (side == 2)
  59717. y += h - ch;
  59718. else if (side != 0)
  59719. y += (h - ch) / 2;
  59720. h = ch;
  59721. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59722. (float) x, (float) y,
  59723. (float) w, (float) h);
  59724. const int cx = x + (w - cw) / 2;
  59725. const int cy = y + (h - ch) / 2;
  59726. const int indent = 3;
  59727. g.setOrigin (cx + indent, cy + indent);
  59728. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59729. paintContent (g, cw - indent * 2, ch - indent * 2);
  59730. }
  59731. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59732. {
  59733. allowablePlacements = newPlacement;
  59734. }
  59735. void BubbleComponent::setPosition (Component* componentToPointTo)
  59736. {
  59737. jassert (componentToPointTo->isValidComponent());
  59738. Point<int> pos;
  59739. if (getParentComponent() != 0)
  59740. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  59741. else
  59742. pos = componentToPointTo->relativePositionToGlobal (pos);
  59743. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59744. }
  59745. void BubbleComponent::setPosition (const int arrowTipX_,
  59746. const int arrowTipY_)
  59747. {
  59748. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59749. }
  59750. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59751. {
  59752. Rectangle<int> availableSpace;
  59753. if (getParentComponent() != 0)
  59754. {
  59755. availableSpace.setSize (getParentComponent()->getWidth(),
  59756. getParentComponent()->getHeight());
  59757. }
  59758. else
  59759. {
  59760. availableSpace = getParentMonitorArea();
  59761. }
  59762. int x = 0;
  59763. int y = 0;
  59764. int w = 150;
  59765. int h = 30;
  59766. getContentSize (w, h);
  59767. w += 30;
  59768. h += 30;
  59769. const float edgeIndent = 2.0f;
  59770. const int arrowLength = jmin (10, h / 3, w / 3);
  59771. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59772. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59773. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59774. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59775. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59776. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59777. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59778. {
  59779. spaceLeft = spaceRight = 0;
  59780. }
  59781. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59782. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59783. {
  59784. spaceAbove = spaceBelow = 0;
  59785. }
  59786. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59787. {
  59788. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59789. arrowTipX = w * 0.5f;
  59790. content.setSize (w, h - arrowLength);
  59791. if (spaceAbove >= spaceBelow)
  59792. {
  59793. // above
  59794. y = rectangleToPointTo.getY() - h;
  59795. content.setPosition (0, 0);
  59796. arrowTipY = h - edgeIndent;
  59797. side = 2;
  59798. }
  59799. else
  59800. {
  59801. // below
  59802. y = rectangleToPointTo.getBottom();
  59803. content.setPosition (0, arrowLength);
  59804. arrowTipY = edgeIndent;
  59805. side = 0;
  59806. }
  59807. }
  59808. else
  59809. {
  59810. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59811. arrowTipY = h * 0.5f;
  59812. content.setSize (w - arrowLength, h);
  59813. if (spaceLeft > spaceRight)
  59814. {
  59815. // on the left
  59816. x = rectangleToPointTo.getX() - w;
  59817. content.setPosition (0, 0);
  59818. arrowTipX = w - edgeIndent;
  59819. side = 3;
  59820. }
  59821. else
  59822. {
  59823. // on the right
  59824. x = rectangleToPointTo.getRight();
  59825. content.setPosition (arrowLength, 0);
  59826. arrowTipX = edgeIndent;
  59827. side = 1;
  59828. }
  59829. }
  59830. setBounds (x, y, w, h);
  59831. }
  59832. END_JUCE_NAMESPACE
  59833. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59834. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59835. BEGIN_JUCE_NAMESPACE
  59836. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59837. : fadeOutLength (fadeOutLengthMs),
  59838. deleteAfterUse (false)
  59839. {
  59840. }
  59841. BubbleMessageComponent::~BubbleMessageComponent()
  59842. {
  59843. fadeOutComponent (fadeOutLength);
  59844. }
  59845. void BubbleMessageComponent::showAt (int x, int y,
  59846. const String& text,
  59847. const int numMillisecondsBeforeRemoving,
  59848. const bool removeWhenMouseClicked,
  59849. const bool deleteSelfAfterUse)
  59850. {
  59851. textLayout.clear();
  59852. textLayout.setText (text, Font (14.0f));
  59853. textLayout.layout (256, Justification::centredLeft, true);
  59854. setPosition (x, y);
  59855. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59856. }
  59857. void BubbleMessageComponent::showAt (Component* const component,
  59858. const String& text,
  59859. const int numMillisecondsBeforeRemoving,
  59860. const bool removeWhenMouseClicked,
  59861. const bool deleteSelfAfterUse)
  59862. {
  59863. textLayout.clear();
  59864. textLayout.setText (text, Font (14.0f));
  59865. textLayout.layout (256, Justification::centredLeft, true);
  59866. setPosition (component);
  59867. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59868. }
  59869. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59870. const bool removeWhenMouseClicked,
  59871. const bool deleteSelfAfterUse)
  59872. {
  59873. setVisible (true);
  59874. deleteAfterUse = deleteSelfAfterUse;
  59875. if (numMillisecondsBeforeRemoving > 0)
  59876. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59877. else
  59878. expiryTime = 0;
  59879. startTimer (77);
  59880. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59881. if (! (removeWhenMouseClicked && isShowing()))
  59882. mouseClickCounter += 0xfffff;
  59883. repaint();
  59884. }
  59885. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59886. {
  59887. w = textLayout.getWidth() + 16;
  59888. h = textLayout.getHeight() + 16;
  59889. }
  59890. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59891. {
  59892. g.setColour (findColour (TooltipWindow::textColourId));
  59893. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59894. }
  59895. void BubbleMessageComponent::timerCallback()
  59896. {
  59897. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59898. {
  59899. stopTimer();
  59900. setVisible (false);
  59901. if (deleteAfterUse)
  59902. delete this;
  59903. }
  59904. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59905. {
  59906. stopTimer();
  59907. fadeOutComponent (fadeOutLength);
  59908. if (deleteAfterUse)
  59909. delete this;
  59910. }
  59911. }
  59912. END_JUCE_NAMESPACE
  59913. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59914. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59915. BEGIN_JUCE_NAMESPACE
  59916. class ColourComponentSlider : public Slider
  59917. {
  59918. public:
  59919. ColourComponentSlider (const String& name)
  59920. : Slider (name)
  59921. {
  59922. setRange (0.0, 255.0, 1.0);
  59923. }
  59924. ~ColourComponentSlider()
  59925. {
  59926. }
  59927. const String getTextFromValue (double value)
  59928. {
  59929. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59930. }
  59931. double getValueFromText (const String& text)
  59932. {
  59933. return (double) text.getHexValue32();
  59934. }
  59935. private:
  59936. ColourComponentSlider (const ColourComponentSlider&);
  59937. ColourComponentSlider& operator= (const ColourComponentSlider&);
  59938. };
  59939. class ColourSpaceMarker : public Component
  59940. {
  59941. public:
  59942. ColourSpaceMarker()
  59943. {
  59944. setInterceptsMouseClicks (false, false);
  59945. }
  59946. ~ColourSpaceMarker()
  59947. {
  59948. }
  59949. void paint (Graphics& g)
  59950. {
  59951. g.setColour (Colour::greyLevel (0.1f));
  59952. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59953. g.setColour (Colour::greyLevel (0.9f));
  59954. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59955. }
  59956. private:
  59957. ColourSpaceMarker (const ColourSpaceMarker&);
  59958. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  59959. };
  59960. class ColourSelector::ColourSpaceView : public Component
  59961. {
  59962. public:
  59963. ColourSpaceView (ColourSelector* owner_,
  59964. float& h_, float& s_, float& v_,
  59965. const int edgeSize)
  59966. : owner (owner_),
  59967. h (h_), s (s_), v (v_),
  59968. lastHue (0.0f),
  59969. edge (edgeSize)
  59970. {
  59971. addAndMakeVisible (&marker);
  59972. setMouseCursor (MouseCursor::CrosshairCursor);
  59973. }
  59974. ~ColourSpaceView()
  59975. {
  59976. }
  59977. void paint (Graphics& g)
  59978. {
  59979. if (colours.isNull())
  59980. {
  59981. const int width = getWidth() / 2;
  59982. const int height = getHeight() / 2;
  59983. colours = Image (Image::RGB, width, height, false);
  59984. Image::BitmapData pixels (colours, true);
  59985. for (int y = 0; y < height; ++y)
  59986. {
  59987. const float val = 1.0f - y / (float) height;
  59988. for (int x = 0; x < width; ++x)
  59989. {
  59990. const float sat = x / (float) width;
  59991. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59992. }
  59993. }
  59994. }
  59995. g.setOpacity (1.0f);
  59996. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59997. 0, 0, colours.getWidth(), colours.getHeight());
  59998. }
  59999. void mouseDown (const MouseEvent& e)
  60000. {
  60001. mouseDrag (e);
  60002. }
  60003. void mouseDrag (const MouseEvent& e)
  60004. {
  60005. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  60006. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  60007. owner->setSV (sat, val);
  60008. }
  60009. void updateIfNeeded()
  60010. {
  60011. if (lastHue != h)
  60012. {
  60013. lastHue = h;
  60014. colours = Image::null;
  60015. repaint();
  60016. }
  60017. updateMarker();
  60018. }
  60019. void resized()
  60020. {
  60021. colours = Image::null;
  60022. updateMarker();
  60023. }
  60024. private:
  60025. ColourSelector* const owner;
  60026. float& h;
  60027. float& s;
  60028. float& v;
  60029. float lastHue;
  60030. ColourSpaceMarker marker;
  60031. const int edge;
  60032. Image colours;
  60033. void updateMarker()
  60034. {
  60035. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  60036. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  60037. edge * 2, edge * 2);
  60038. }
  60039. ColourSpaceView (const ColourSpaceView&);
  60040. ColourSpaceView& operator= (const ColourSpaceView&);
  60041. };
  60042. class HueSelectorMarker : public Component
  60043. {
  60044. public:
  60045. HueSelectorMarker()
  60046. {
  60047. setInterceptsMouseClicks (false, false);
  60048. }
  60049. ~HueSelectorMarker()
  60050. {
  60051. }
  60052. void paint (Graphics& g)
  60053. {
  60054. Path p;
  60055. p.addTriangle (1.0f, 1.0f,
  60056. getWidth() * 0.3f, getHeight() * 0.5f,
  60057. 1.0f, getHeight() - 1.0f);
  60058. p.addTriangle (getWidth() - 1.0f, 1.0f,
  60059. getWidth() * 0.7f, getHeight() * 0.5f,
  60060. getWidth() - 1.0f, getHeight() - 1.0f);
  60061. g.setColour (Colours::white.withAlpha (0.75f));
  60062. g.fillPath (p);
  60063. g.setColour (Colours::black.withAlpha (0.75f));
  60064. g.strokePath (p, PathStrokeType (1.2f));
  60065. }
  60066. private:
  60067. HueSelectorMarker (const HueSelectorMarker&);
  60068. HueSelectorMarker& operator= (const HueSelectorMarker&);
  60069. };
  60070. class ColourSelector::HueSelectorComp : public Component
  60071. {
  60072. public:
  60073. HueSelectorComp (ColourSelector* owner_,
  60074. float& h_, float& s_, float& v_,
  60075. const int edgeSize)
  60076. : owner (owner_),
  60077. h (h_), s (s_), v (v_),
  60078. lastHue (0.0f),
  60079. edge (edgeSize)
  60080. {
  60081. addAndMakeVisible (&marker);
  60082. }
  60083. ~HueSelectorComp()
  60084. {
  60085. }
  60086. void paint (Graphics& g)
  60087. {
  60088. const float yScale = 1.0f / (getHeight() - edge * 2);
  60089. const Rectangle<int> clip (g.getClipBounds());
  60090. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  60091. {
  60092. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  60093. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  60094. }
  60095. }
  60096. void resized()
  60097. {
  60098. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  60099. getWidth(), edge * 2);
  60100. }
  60101. void mouseDown (const MouseEvent& e)
  60102. {
  60103. mouseDrag (e);
  60104. }
  60105. void mouseDrag (const MouseEvent& e)
  60106. {
  60107. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  60108. owner->setHue (hue);
  60109. }
  60110. void updateIfNeeded()
  60111. {
  60112. resized();
  60113. }
  60114. private:
  60115. ColourSelector* const owner;
  60116. float& h;
  60117. float& s;
  60118. float& v;
  60119. float lastHue;
  60120. HueSelectorMarker marker;
  60121. const int edge;
  60122. HueSelectorComp (const HueSelectorComp&);
  60123. HueSelectorComp& operator= (const HueSelectorComp&);
  60124. };
  60125. class ColourSelector::SwatchComponent : public Component
  60126. {
  60127. public:
  60128. SwatchComponent (ColourSelector* owner_, int index_)
  60129. : owner (owner_),
  60130. index (index_)
  60131. {
  60132. }
  60133. ~SwatchComponent()
  60134. {
  60135. }
  60136. void paint (Graphics& g)
  60137. {
  60138. const Colour colour (owner->getSwatchColour (index));
  60139. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  60140. Colour (0xffdddddd).overlaidWith (colour),
  60141. Colour (0xffffffff).overlaidWith (colour));
  60142. }
  60143. void mouseDown (const MouseEvent&)
  60144. {
  60145. PopupMenu m;
  60146. m.addItem (1, TRANS("Use this swatch as the current colour"));
  60147. m.addSeparator();
  60148. m.addItem (2, TRANS("Set this swatch to the current colour"));
  60149. const int r = m.showAt (this);
  60150. if (r == 1)
  60151. {
  60152. owner->setCurrentColour (owner->getSwatchColour (index));
  60153. }
  60154. else if (r == 2)
  60155. {
  60156. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  60157. {
  60158. owner->setSwatchColour (index, owner->getCurrentColour());
  60159. repaint();
  60160. }
  60161. }
  60162. }
  60163. private:
  60164. ColourSelector* const owner;
  60165. const int index;
  60166. SwatchComponent (const SwatchComponent&);
  60167. SwatchComponent& operator= (const SwatchComponent&);
  60168. };
  60169. ColourSelector::ColourSelector (const int flags_,
  60170. const int edgeGap_,
  60171. const int gapAroundColourSpaceComponent)
  60172. : colour (Colours::white),
  60173. colourSpace (0),
  60174. hueSelector (0),
  60175. flags (flags_),
  60176. edgeGap (edgeGap_)
  60177. {
  60178. // not much point having a selector with no components in it!
  60179. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  60180. updateHSV();
  60181. if ((flags & showSliders) != 0)
  60182. {
  60183. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  60184. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  60185. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  60186. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  60187. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  60188. for (int i = 4; --i >= 0;)
  60189. sliders[i]->addListener (this);
  60190. }
  60191. else
  60192. {
  60193. zeromem (sliders, sizeof (sliders));
  60194. }
  60195. if ((flags & showColourspace) != 0)
  60196. {
  60197. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  60198. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  60199. }
  60200. update();
  60201. }
  60202. ColourSelector::~ColourSelector()
  60203. {
  60204. dispatchPendingMessages();
  60205. swatchComponents.clear();
  60206. deleteAllChildren();
  60207. }
  60208. const Colour ColourSelector::getCurrentColour() const
  60209. {
  60210. return ((flags & showAlphaChannel) != 0) ? colour
  60211. : colour.withAlpha ((uint8) 0xff);
  60212. }
  60213. void ColourSelector::setCurrentColour (const Colour& c)
  60214. {
  60215. if (c != colour)
  60216. {
  60217. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  60218. updateHSV();
  60219. update();
  60220. }
  60221. }
  60222. void ColourSelector::setHue (float newH)
  60223. {
  60224. newH = jlimit (0.0f, 1.0f, newH);
  60225. if (h != newH)
  60226. {
  60227. h = newH;
  60228. colour = Colour (h, s, v, colour.getFloatAlpha());
  60229. update();
  60230. }
  60231. }
  60232. void ColourSelector::setSV (float newS, float newV)
  60233. {
  60234. newS = jlimit (0.0f, 1.0f, newS);
  60235. newV = jlimit (0.0f, 1.0f, newV);
  60236. if (s != newS || v != newV)
  60237. {
  60238. s = newS;
  60239. v = newV;
  60240. colour = Colour (h, s, v, colour.getFloatAlpha());
  60241. update();
  60242. }
  60243. }
  60244. void ColourSelector::updateHSV()
  60245. {
  60246. colour.getHSB (h, s, v);
  60247. }
  60248. void ColourSelector::update()
  60249. {
  60250. if (sliders[0] != 0)
  60251. {
  60252. sliders[0]->setValue ((int) colour.getRed());
  60253. sliders[1]->setValue ((int) colour.getGreen());
  60254. sliders[2]->setValue ((int) colour.getBlue());
  60255. sliders[3]->setValue ((int) colour.getAlpha());
  60256. }
  60257. if (colourSpace != 0)
  60258. {
  60259. colourSpace->updateIfNeeded();
  60260. hueSelector->updateIfNeeded();
  60261. }
  60262. if ((flags & showColourAtTop) != 0)
  60263. repaint (previewArea);
  60264. sendChangeMessage (this);
  60265. }
  60266. void ColourSelector::paint (Graphics& g)
  60267. {
  60268. g.fillAll (findColour (backgroundColourId));
  60269. if ((flags & showColourAtTop) != 0)
  60270. {
  60271. const Colour currentColour (getCurrentColour());
  60272. g.fillCheckerBoard (previewArea, 10, 10,
  60273. Colour (0xffdddddd).overlaidWith (currentColour),
  60274. Colour (0xffffffff).overlaidWith (currentColour));
  60275. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  60276. g.setFont (14.0f, true);
  60277. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  60278. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  60279. Justification::centred, false);
  60280. }
  60281. if ((flags & showSliders) != 0)
  60282. {
  60283. g.setColour (findColour (labelTextColourId));
  60284. g.setFont (11.0f);
  60285. for (int i = 4; --i >= 0;)
  60286. {
  60287. if (sliders[i]->isVisible())
  60288. g.drawText (sliders[i]->getName() + ":",
  60289. 0, sliders[i]->getY(),
  60290. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  60291. Justification::centredRight, false);
  60292. }
  60293. }
  60294. }
  60295. void ColourSelector::resized()
  60296. {
  60297. const int swatchesPerRow = 8;
  60298. const int swatchHeight = 22;
  60299. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  60300. const int numSwatches = getNumSwatches();
  60301. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  60302. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  60303. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  60304. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  60305. int y = topSpace;
  60306. if ((flags & showColourspace) != 0)
  60307. {
  60308. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  60309. colourSpace->setBounds (edgeGap, y,
  60310. getWidth() - hueWidth - edgeGap - 4,
  60311. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  60312. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  60313. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  60314. colourSpace->getHeight());
  60315. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  60316. }
  60317. if ((flags & showSliders) != 0)
  60318. {
  60319. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  60320. for (int i = 0; i < numSliders; ++i)
  60321. {
  60322. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60323. proportionOfWidth (0.72f), sliderHeight - 2);
  60324. y += sliderHeight;
  60325. }
  60326. }
  60327. if (numSwatches > 0)
  60328. {
  60329. const int startX = 8;
  60330. const int xGap = 4;
  60331. const int yGap = 4;
  60332. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60333. y += edgeGap;
  60334. if (swatchComponents.size() != numSwatches)
  60335. {
  60336. swatchComponents.clear();
  60337. for (int i = 0; i < numSwatches; ++i)
  60338. {
  60339. SwatchComponent* const sc = new SwatchComponent (this, i);
  60340. swatchComponents.add (sc);
  60341. addAndMakeVisible (sc);
  60342. }
  60343. }
  60344. int x = startX;
  60345. for (int i = 0; i < swatchComponents.size(); ++i)
  60346. {
  60347. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60348. sc->setBounds (x + xGap / 2,
  60349. y + yGap / 2,
  60350. swatchWidth - xGap,
  60351. swatchHeight - yGap);
  60352. if (((i + 1) % swatchesPerRow) == 0)
  60353. {
  60354. x = startX;
  60355. y += swatchHeight;
  60356. }
  60357. else
  60358. {
  60359. x += swatchWidth;
  60360. }
  60361. }
  60362. }
  60363. }
  60364. void ColourSelector::sliderValueChanged (Slider*)
  60365. {
  60366. if (sliders[0] != 0)
  60367. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60368. (uint8) sliders[1]->getValue(),
  60369. (uint8) sliders[2]->getValue(),
  60370. (uint8) sliders[3]->getValue()));
  60371. }
  60372. int ColourSelector::getNumSwatches() const
  60373. {
  60374. return 0;
  60375. }
  60376. const Colour ColourSelector::getSwatchColour (const int) const
  60377. {
  60378. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60379. return Colours::black;
  60380. }
  60381. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60382. {
  60383. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60384. }
  60385. END_JUCE_NAMESPACE
  60386. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60387. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60388. BEGIN_JUCE_NAMESPACE
  60389. class ShadowWindow : public Component
  60390. {
  60391. Component* owner;
  60392. Image shadowImageSections [12];
  60393. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60394. public:
  60395. ShadowWindow (Component* const owner_,
  60396. const int type_,
  60397. const Image shadowImageSections_ [12])
  60398. : owner (owner_),
  60399. type (type_)
  60400. {
  60401. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  60402. shadowImageSections [i] = shadowImageSections_ [i];
  60403. setInterceptsMouseClicks (false, false);
  60404. if (owner_->isOnDesktop())
  60405. {
  60406. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60407. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60408. | ComponentPeer::windowIsTemporary
  60409. | ComponentPeer::windowIgnoresKeyPresses);
  60410. }
  60411. else if (owner_->getParentComponent() != 0)
  60412. {
  60413. owner_->getParentComponent()->addChildComponent (this);
  60414. }
  60415. }
  60416. ~ShadowWindow()
  60417. {
  60418. }
  60419. void paint (Graphics& g)
  60420. {
  60421. const Image& topLeft = shadowImageSections [type * 3];
  60422. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  60423. const Image& filler = shadowImageSections [type * 3 + 2];
  60424. g.setOpacity (1.0f);
  60425. if (type < 2)
  60426. {
  60427. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60428. g.drawImage (topLeft,
  60429. 0, 0, topLeft.getWidth(), imH,
  60430. 0, 0, topLeft.getWidth(), imH);
  60431. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60432. g.drawImage (bottomRight,
  60433. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60434. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60435. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60436. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60437. }
  60438. else
  60439. {
  60440. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60441. g.drawImage (topLeft,
  60442. 0, 0, imW, topLeft.getHeight(),
  60443. 0, 0, imW, topLeft.getHeight());
  60444. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60445. g.drawImage (bottomRight,
  60446. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60447. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60448. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60449. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60450. }
  60451. }
  60452. void resized()
  60453. {
  60454. repaint(); // (needed for correct repainting)
  60455. }
  60456. private:
  60457. ShadowWindow (const ShadowWindow&);
  60458. ShadowWindow& operator= (const ShadowWindow&);
  60459. };
  60460. DropShadower::DropShadower (const float alpha_,
  60461. const int xOffset_,
  60462. const int yOffset_,
  60463. const float blurRadius_)
  60464. : owner (0),
  60465. numShadows (0),
  60466. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  60467. xOffset (xOffset_),
  60468. yOffset (yOffset_),
  60469. alpha (alpha_),
  60470. blurRadius (blurRadius_),
  60471. inDestructor (false),
  60472. reentrant (false)
  60473. {
  60474. }
  60475. DropShadower::~DropShadower()
  60476. {
  60477. if (owner != 0)
  60478. owner->removeComponentListener (this);
  60479. inDestructor = true;
  60480. deleteShadowWindows();
  60481. }
  60482. void DropShadower::deleteShadowWindows()
  60483. {
  60484. if (numShadows > 0)
  60485. {
  60486. int i;
  60487. for (i = numShadows; --i >= 0;)
  60488. delete shadowWindows[i];
  60489. numShadows = 0;
  60490. }
  60491. }
  60492. void DropShadower::setOwner (Component* componentToFollow)
  60493. {
  60494. if (componentToFollow != owner)
  60495. {
  60496. if (owner != 0)
  60497. owner->removeComponentListener (this);
  60498. // (the component can't be null)
  60499. jassert (componentToFollow != 0);
  60500. owner = componentToFollow;
  60501. jassert (owner != 0);
  60502. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60503. owner->addComponentListener (this);
  60504. updateShadows();
  60505. }
  60506. }
  60507. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60508. {
  60509. updateShadows();
  60510. }
  60511. void DropShadower::componentBroughtToFront (Component&)
  60512. {
  60513. bringShadowWindowsToFront();
  60514. }
  60515. void DropShadower::componentChildrenChanged (Component&)
  60516. {
  60517. }
  60518. void DropShadower::componentParentHierarchyChanged (Component&)
  60519. {
  60520. deleteShadowWindows();
  60521. updateShadows();
  60522. }
  60523. void DropShadower::componentVisibilityChanged (Component&)
  60524. {
  60525. updateShadows();
  60526. }
  60527. void DropShadower::updateShadows()
  60528. {
  60529. if (reentrant || inDestructor || (owner == 0))
  60530. return;
  60531. reentrant = true;
  60532. ComponentPeer* const nw = owner->getPeer();
  60533. const bool isOwnerVisible = owner->isVisible()
  60534. && (nw == 0 || ! nw->isMinimised());
  60535. const bool createShadowWindows = numShadows == 0
  60536. && owner->getWidth() > 0
  60537. && owner->getHeight() > 0
  60538. && isOwnerVisible
  60539. && (Desktop::canUseSemiTransparentWindows()
  60540. || owner->getParentComponent() != 0);
  60541. if (createShadowWindows)
  60542. {
  60543. // keep a cached version of the image to save doing the gaussian too often
  60544. String imageId;
  60545. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60546. const int hash = imageId.hashCode();
  60547. Image bigIm (ImageCache::getFromHashCode (hash));
  60548. if (bigIm.isNull())
  60549. {
  60550. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60551. Graphics bigG (bigIm);
  60552. bigG.setColour (Colours::black.withAlpha (alpha));
  60553. bigG.fillRect (shadowEdge + xOffset,
  60554. shadowEdge + yOffset,
  60555. bigIm.getWidth() - (shadowEdge * 2),
  60556. bigIm.getHeight() - (shadowEdge * 2));
  60557. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60558. blurKernel.createGaussianBlur (blurRadius);
  60559. blurKernel.applyToImage (bigIm, bigIm,
  60560. Rectangle<int> (xOffset, yOffset,
  60561. bigIm.getWidth(), bigIm.getHeight()));
  60562. ImageCache::addImageToCache (bigIm, hash);
  60563. }
  60564. const int iw = bigIm.getWidth();
  60565. const int ih = bigIm.getHeight();
  60566. const int shadowEdge2 = shadowEdge * 2;
  60567. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60568. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60569. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60570. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60571. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60572. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60573. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60574. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60575. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60576. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60577. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60578. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60579. for (int i = 0; i < 4; ++i)
  60580. {
  60581. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  60582. ++numShadows;
  60583. }
  60584. }
  60585. if (numShadows > 0)
  60586. {
  60587. for (int i = numShadows; --i >= 0;)
  60588. {
  60589. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  60590. shadowWindows[i]->setVisible (isOwnerVisible);
  60591. }
  60592. const int x = owner->getX();
  60593. const int y = owner->getY() - shadowEdge;
  60594. const int w = owner->getWidth();
  60595. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60596. shadowWindows[0]->setBounds (x - shadowEdge,
  60597. y,
  60598. shadowEdge,
  60599. h);
  60600. shadowWindows[1]->setBounds (x + w,
  60601. y,
  60602. shadowEdge,
  60603. h);
  60604. shadowWindows[2]->setBounds (x,
  60605. y,
  60606. w,
  60607. shadowEdge);
  60608. shadowWindows[3]->setBounds (x,
  60609. owner->getBottom(),
  60610. w,
  60611. shadowEdge);
  60612. }
  60613. reentrant = false;
  60614. if (createShadowWindows)
  60615. bringShadowWindowsToFront();
  60616. }
  60617. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60618. const int sx, const int sy)
  60619. {
  60620. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60621. Graphics g (shadowImageSections[num]);
  60622. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60623. }
  60624. void DropShadower::bringShadowWindowsToFront()
  60625. {
  60626. if (! (inDestructor || reentrant))
  60627. {
  60628. updateShadows();
  60629. reentrant = true;
  60630. for (int i = numShadows; --i >= 0;)
  60631. shadowWindows[i]->toBehind (owner);
  60632. reentrant = false;
  60633. }
  60634. }
  60635. END_JUCE_NAMESPACE
  60636. /*** End of inlined file: juce_DropShadower.cpp ***/
  60637. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  60638. BEGIN_JUCE_NAMESPACE
  60639. class MagnifyingPeer : public ComponentPeer
  60640. {
  60641. public:
  60642. MagnifyingPeer (Component* const component_,
  60643. MagnifierComponent* const magnifierComp_)
  60644. : ComponentPeer (component_, 0),
  60645. magnifierComp (magnifierComp_)
  60646. {
  60647. }
  60648. ~MagnifyingPeer()
  60649. {
  60650. }
  60651. void* getNativeHandle() const { return 0; }
  60652. void setVisible (bool) {}
  60653. void setTitle (const String&) {}
  60654. void setPosition (int, int) {}
  60655. void setSize (int, int) {}
  60656. void setBounds (int, int, int, int, bool) {}
  60657. void setMinimised (bool) {}
  60658. bool isMinimised() const { return false; }
  60659. void setFullScreen (bool) {}
  60660. bool isFullScreen() const { return false; }
  60661. const BorderSize getFrameSize() const { return BorderSize (0); }
  60662. bool setAlwaysOnTop (bool) { return true; }
  60663. void toFront (bool) {}
  60664. void toBehind (ComponentPeer*) {}
  60665. void setIcon (const Image&) {}
  60666. bool isFocused() const
  60667. {
  60668. return magnifierComp->hasKeyboardFocus (true);
  60669. }
  60670. void grabFocus()
  60671. {
  60672. ComponentPeer* peer = magnifierComp->getPeer();
  60673. if (peer != 0)
  60674. peer->grabFocus();
  60675. }
  60676. void textInputRequired (const Point<int>& position)
  60677. {
  60678. ComponentPeer* peer = magnifierComp->getPeer();
  60679. if (peer != 0)
  60680. peer->textInputRequired (position);
  60681. }
  60682. const Rectangle<int> getBounds() const
  60683. {
  60684. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  60685. component->getWidth(), component->getHeight());
  60686. }
  60687. const Point<int> getScreenPosition() const
  60688. {
  60689. return magnifierComp->getScreenPosition();
  60690. }
  60691. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  60692. {
  60693. const double zoom = magnifierComp->getScaleFactor();
  60694. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  60695. roundToInt (relativePosition.getY() * zoom)));
  60696. }
  60697. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  60698. {
  60699. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  60700. const double zoom = magnifierComp->getScaleFactor();
  60701. return Point<int> (roundToInt (p.getX() / zoom),
  60702. roundToInt (p.getY() / zoom));
  60703. }
  60704. bool contains (const Point<int>& position, bool) const
  60705. {
  60706. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  60707. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  60708. }
  60709. void repaint (const Rectangle<int>& area)
  60710. {
  60711. const double zoom = magnifierComp->getScaleFactor();
  60712. magnifierComp->repaint ((int) (area.getX() * zoom),
  60713. (int) (area.getY() * zoom),
  60714. roundToInt (area.getWidth() * zoom) + 1,
  60715. roundToInt (area.getHeight() * zoom) + 1);
  60716. }
  60717. void performAnyPendingRepaintsNow()
  60718. {
  60719. }
  60720. juce_UseDebuggingNewOperator
  60721. private:
  60722. MagnifierComponent* const magnifierComp;
  60723. MagnifyingPeer (const MagnifyingPeer&);
  60724. MagnifyingPeer& operator= (const MagnifyingPeer&);
  60725. };
  60726. class PeerHolderComp : public Component
  60727. {
  60728. public:
  60729. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  60730. : magnifierComp (magnifierComp_)
  60731. {
  60732. setVisible (true);
  60733. }
  60734. ~PeerHolderComp()
  60735. {
  60736. }
  60737. ComponentPeer* createNewPeer (int, void*)
  60738. {
  60739. return new MagnifyingPeer (this, magnifierComp);
  60740. }
  60741. void childBoundsChanged (Component* c)
  60742. {
  60743. if (c != 0)
  60744. {
  60745. setSize (c->getWidth(), c->getHeight());
  60746. magnifierComp->childBoundsChanged (this);
  60747. }
  60748. }
  60749. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60750. {
  60751. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  60752. Component* const p = magnifierComp->getParentComponent();
  60753. if (p != 0)
  60754. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  60755. }
  60756. private:
  60757. MagnifierComponent* const magnifierComp;
  60758. PeerHolderComp (const PeerHolderComp&);
  60759. PeerHolderComp& operator= (const PeerHolderComp&);
  60760. };
  60761. MagnifierComponent::MagnifierComponent (Component* const content_,
  60762. const bool deleteContentCompWhenNoLongerNeeded)
  60763. : content (content_),
  60764. scaleFactor (0.0),
  60765. peer (0),
  60766. deleteContent (deleteContentCompWhenNoLongerNeeded),
  60767. quality (Graphics::lowResamplingQuality),
  60768. mouseSource (0, true)
  60769. {
  60770. holderComp = new PeerHolderComp (this);
  60771. setScaleFactor (1.0);
  60772. }
  60773. MagnifierComponent::~MagnifierComponent()
  60774. {
  60775. delete holderComp;
  60776. if (deleteContent)
  60777. delete content;
  60778. }
  60779. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  60780. {
  60781. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  60782. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  60783. if (scaleFactor != newScaleFactor)
  60784. {
  60785. scaleFactor = newScaleFactor;
  60786. if (scaleFactor == 1.0)
  60787. {
  60788. holderComp->removeFromDesktop();
  60789. peer = 0;
  60790. addChildComponent (content);
  60791. childBoundsChanged (content);
  60792. }
  60793. else
  60794. {
  60795. holderComp->addAndMakeVisible (content);
  60796. holderComp->childBoundsChanged (content);
  60797. childBoundsChanged (holderComp);
  60798. holderComp->addToDesktop (0);
  60799. peer = holderComp->getPeer();
  60800. }
  60801. repaint();
  60802. }
  60803. }
  60804. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  60805. {
  60806. quality = newQuality;
  60807. }
  60808. void MagnifierComponent::paint (Graphics& g)
  60809. {
  60810. const int w = holderComp->getWidth();
  60811. const int h = holderComp->getHeight();
  60812. if (w == 0 || h == 0)
  60813. return;
  60814. const Rectangle<int> r (g.getClipBounds());
  60815. const int srcX = (int) (r.getX() / scaleFactor);
  60816. const int srcY = (int) (r.getY() / scaleFactor);
  60817. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60818. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60819. if (scaleFactor >= 1.0)
  60820. {
  60821. ++srcW;
  60822. ++srcH;
  60823. }
  60824. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60825. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  60826. {
  60827. Graphics g2 (temp);
  60828. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  60829. holderComp->paintEntireComponent (g2);
  60830. }
  60831. g.setImageResamplingQuality (quality);
  60832. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60833. }
  60834. void MagnifierComponent::childBoundsChanged (Component* c)
  60835. {
  60836. if (c != 0)
  60837. setSize (roundToInt (c->getWidth() * scaleFactor),
  60838. roundToInt (c->getHeight() * scaleFactor));
  60839. }
  60840. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60841. {
  60842. if (peer != 0)
  60843. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60844. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60845. }
  60846. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60847. {
  60848. passOnMouseEventToPeer (e);
  60849. }
  60850. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60851. {
  60852. passOnMouseEventToPeer (e);
  60853. }
  60854. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60855. {
  60856. passOnMouseEventToPeer (e);
  60857. }
  60858. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60859. {
  60860. passOnMouseEventToPeer (e);
  60861. }
  60862. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60863. {
  60864. passOnMouseEventToPeer (e);
  60865. }
  60866. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60867. {
  60868. passOnMouseEventToPeer (e);
  60869. }
  60870. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60871. {
  60872. if (peer != 0)
  60873. peer->handleMouseWheel (e.source.getIndex(),
  60874. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60875. ix * 256.0f, iy * 256.0f);
  60876. else
  60877. Component::mouseWheelMove (e, ix, iy);
  60878. }
  60879. int MagnifierComponent::scaleInt (const int n) const
  60880. {
  60881. return roundToInt (n / scaleFactor);
  60882. }
  60883. END_JUCE_NAMESPACE
  60884. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60885. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60886. BEGIN_JUCE_NAMESPACE
  60887. class MidiKeyboardUpDownButton : public Button
  60888. {
  60889. public:
  60890. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  60891. const int delta_)
  60892. : Button (String::empty),
  60893. owner (owner_),
  60894. delta (delta_)
  60895. {
  60896. setOpaque (true);
  60897. }
  60898. ~MidiKeyboardUpDownButton()
  60899. {
  60900. }
  60901. void clicked()
  60902. {
  60903. int note = owner->getLowestVisibleKey();
  60904. if (delta < 0)
  60905. note = (note - 1) / 12;
  60906. else
  60907. note = note / 12 + 1;
  60908. owner->setLowestVisibleKey (note * 12);
  60909. }
  60910. void paintButton (Graphics& g,
  60911. bool isMouseOverButton,
  60912. bool isButtonDown)
  60913. {
  60914. owner->drawUpDownButton (g, getWidth(), getHeight(),
  60915. isMouseOverButton, isButtonDown,
  60916. delta > 0);
  60917. }
  60918. private:
  60919. MidiKeyboardComponent* const owner;
  60920. const int delta;
  60921. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  60922. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  60923. };
  60924. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60925. const Orientation orientation_)
  60926. : state (state_),
  60927. xOffset (0),
  60928. blackNoteLength (1),
  60929. keyWidth (16.0f),
  60930. orientation (orientation_),
  60931. midiChannel (1),
  60932. midiInChannelMask (0xffff),
  60933. velocity (1.0f),
  60934. noteUnderMouse (-1),
  60935. mouseDownNote (-1),
  60936. rangeStart (0),
  60937. rangeEnd (127),
  60938. firstKey (12 * 4),
  60939. canScroll (true),
  60940. mouseDragging (false),
  60941. useMousePositionForVelocity (true),
  60942. keyMappingOctave (6),
  60943. octaveNumForMiddleC (3)
  60944. {
  60945. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  60946. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  60947. // initialise with a default set of querty key-mappings..
  60948. const char* const keymap = "awsedftgyhujkolp;";
  60949. for (int i = String (keymap).length(); --i >= 0;)
  60950. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60951. setOpaque (true);
  60952. setWantsKeyboardFocus (true);
  60953. state.addListener (this);
  60954. }
  60955. MidiKeyboardComponent::~MidiKeyboardComponent()
  60956. {
  60957. state.removeListener (this);
  60958. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60959. deleteAllChildren();
  60960. }
  60961. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60962. {
  60963. keyWidth = widthInPixels;
  60964. resized();
  60965. }
  60966. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60967. {
  60968. if (orientation != newOrientation)
  60969. {
  60970. orientation = newOrientation;
  60971. resized();
  60972. }
  60973. }
  60974. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60975. const int highestNote)
  60976. {
  60977. jassert (lowestNote >= 0 && lowestNote <= 127);
  60978. jassert (highestNote >= 0 && highestNote <= 127);
  60979. jassert (lowestNote <= highestNote);
  60980. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60981. {
  60982. rangeStart = jlimit (0, 127, lowestNote);
  60983. rangeEnd = jlimit (0, 127, highestNote);
  60984. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60985. resized();
  60986. }
  60987. }
  60988. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60989. {
  60990. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60991. if (noteNumber != firstKey)
  60992. {
  60993. firstKey = noteNumber;
  60994. sendChangeMessage (this);
  60995. resized();
  60996. }
  60997. }
  60998. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60999. {
  61000. if (canScroll != canScroll_)
  61001. {
  61002. canScroll = canScroll_;
  61003. resized();
  61004. }
  61005. }
  61006. void MidiKeyboardComponent::colourChanged()
  61007. {
  61008. repaint();
  61009. }
  61010. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  61011. {
  61012. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  61013. if (midiChannel != midiChannelNumber)
  61014. {
  61015. resetAnyKeysInUse();
  61016. midiChannel = jlimit (1, 16, midiChannelNumber);
  61017. }
  61018. }
  61019. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  61020. {
  61021. midiInChannelMask = midiChannelMask;
  61022. triggerAsyncUpdate();
  61023. }
  61024. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  61025. {
  61026. velocity = jlimit (0.0f, 1.0f, velocity_);
  61027. useMousePositionForVelocity = useMousePositionForVelocity_;
  61028. }
  61029. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  61030. {
  61031. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  61032. static const float blackNoteWidth = 0.7f;
  61033. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  61034. 1.0f, 2 - blackNoteWidth * 0.4f,
  61035. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  61036. 4.0f, 5 - blackNoteWidth * 0.5f,
  61037. 5.0f, 6 - blackNoteWidth * 0.3f,
  61038. 6.0f };
  61039. static const float widths[] = { 1.0f, blackNoteWidth,
  61040. 1.0f, blackNoteWidth,
  61041. 1.0f, 1.0f, blackNoteWidth,
  61042. 1.0f, blackNoteWidth,
  61043. 1.0f, blackNoteWidth,
  61044. 1.0f };
  61045. const int octave = midiNoteNumber / 12;
  61046. const int note = midiNoteNumber % 12;
  61047. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  61048. w = roundToInt (widths [note] * keyWidth_);
  61049. }
  61050. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  61051. {
  61052. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  61053. int rx, rw;
  61054. getKeyPosition (rangeStart, keyWidth, rx, rw);
  61055. x -= xOffset + rx;
  61056. }
  61057. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  61058. {
  61059. int x, y;
  61060. getKeyPos (midiNoteNumber, x, y);
  61061. return x;
  61062. }
  61063. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  61064. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  61065. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  61066. {
  61067. if (! reallyContains (pos.getX(), pos.getY(), false))
  61068. return -1;
  61069. Point<int> p (pos);
  61070. if (orientation != horizontalKeyboard)
  61071. {
  61072. p = Point<int> (p.getY(), p.getX());
  61073. if (orientation == verticalKeyboardFacingLeft)
  61074. p = Point<int> (p.getX(), getWidth() - p.getY());
  61075. else
  61076. p = Point<int> (getHeight() - p.getX(), p.getY());
  61077. }
  61078. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  61079. }
  61080. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  61081. {
  61082. if (pos.getY() < blackNoteLength)
  61083. {
  61084. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61085. {
  61086. for (int i = 0; i < 5; ++i)
  61087. {
  61088. const int note = octaveStart + blackNotes [i];
  61089. if (note >= rangeStart && note <= rangeEnd)
  61090. {
  61091. int kx, kw;
  61092. getKeyPos (note, kx, kw);
  61093. kx += xOffset;
  61094. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61095. {
  61096. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  61097. return note;
  61098. }
  61099. }
  61100. }
  61101. }
  61102. }
  61103. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61104. {
  61105. for (int i = 0; i < 7; ++i)
  61106. {
  61107. const int note = octaveStart + whiteNotes [i];
  61108. if (note >= rangeStart && note <= rangeEnd)
  61109. {
  61110. int kx, kw;
  61111. getKeyPos (note, kx, kw);
  61112. kx += xOffset;
  61113. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61114. {
  61115. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  61116. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  61117. return note;
  61118. }
  61119. }
  61120. }
  61121. }
  61122. mousePositionVelocity = 0;
  61123. return -1;
  61124. }
  61125. void MidiKeyboardComponent::repaintNote (const int noteNum)
  61126. {
  61127. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61128. {
  61129. int x, w;
  61130. getKeyPos (noteNum, x, w);
  61131. if (orientation == horizontalKeyboard)
  61132. repaint (x, 0, w, getHeight());
  61133. else if (orientation == verticalKeyboardFacingLeft)
  61134. repaint (0, x, getWidth(), w);
  61135. else if (orientation == verticalKeyboardFacingRight)
  61136. repaint (0, getHeight() - x - w, getWidth(), w);
  61137. }
  61138. }
  61139. void MidiKeyboardComponent::paint (Graphics& g)
  61140. {
  61141. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  61142. const Colour lineColour (findColour (keySeparatorLineColourId));
  61143. const Colour textColour (findColour (textLabelColourId));
  61144. int x, w, octave;
  61145. for (octave = 0; octave < 128; octave += 12)
  61146. {
  61147. for (int white = 0; white < 7; ++white)
  61148. {
  61149. const int noteNum = octave + whiteNotes [white];
  61150. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61151. {
  61152. getKeyPos (noteNum, x, w);
  61153. if (orientation == horizontalKeyboard)
  61154. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  61155. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61156. noteUnderMouse == noteNum,
  61157. lineColour, textColour);
  61158. else if (orientation == verticalKeyboardFacingLeft)
  61159. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  61160. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61161. noteUnderMouse == noteNum,
  61162. lineColour, textColour);
  61163. else if (orientation == verticalKeyboardFacingRight)
  61164. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  61165. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61166. noteUnderMouse == noteNum,
  61167. lineColour, textColour);
  61168. }
  61169. }
  61170. }
  61171. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  61172. if (orientation == verticalKeyboardFacingLeft)
  61173. {
  61174. x1 = getWidth() - 1.0f;
  61175. x2 = getWidth() - 5.0f;
  61176. }
  61177. else if (orientation == verticalKeyboardFacingRight)
  61178. x2 = 5.0f;
  61179. else
  61180. y2 = 5.0f;
  61181. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  61182. Colours::transparentBlack, x2, y2, false));
  61183. getKeyPos (rangeEnd, x, w);
  61184. x += w;
  61185. if (orientation == verticalKeyboardFacingLeft)
  61186. g.fillRect (getWidth() - 5, 0, 5, x);
  61187. else if (orientation == verticalKeyboardFacingRight)
  61188. g.fillRect (0, 0, 5, x);
  61189. else
  61190. g.fillRect (0, 0, x, 5);
  61191. g.setColour (lineColour);
  61192. if (orientation == verticalKeyboardFacingLeft)
  61193. g.fillRect (0, 0, 1, x);
  61194. else if (orientation == verticalKeyboardFacingRight)
  61195. g.fillRect (getWidth() - 1, 0, 1, x);
  61196. else
  61197. g.fillRect (0, getHeight() - 1, x, 1);
  61198. const Colour blackNoteColour (findColour (blackNoteColourId));
  61199. for (octave = 0; octave < 128; octave += 12)
  61200. {
  61201. for (int black = 0; black < 5; ++black)
  61202. {
  61203. const int noteNum = octave + blackNotes [black];
  61204. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61205. {
  61206. getKeyPos (noteNum, x, w);
  61207. if (orientation == horizontalKeyboard)
  61208. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  61209. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61210. noteUnderMouse == noteNum,
  61211. blackNoteColour);
  61212. else if (orientation == verticalKeyboardFacingLeft)
  61213. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  61214. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61215. noteUnderMouse == noteNum,
  61216. blackNoteColour);
  61217. else if (orientation == verticalKeyboardFacingRight)
  61218. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  61219. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61220. noteUnderMouse == noteNum,
  61221. blackNoteColour);
  61222. }
  61223. }
  61224. }
  61225. }
  61226. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  61227. Graphics& g, int x, int y, int w, int h,
  61228. bool isDown, bool isOver,
  61229. const Colour& lineColour,
  61230. const Colour& textColour)
  61231. {
  61232. Colour c (Colours::transparentWhite);
  61233. if (isDown)
  61234. c = findColour (keyDownOverlayColourId);
  61235. if (isOver)
  61236. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61237. g.setColour (c);
  61238. g.fillRect (x, y, w, h);
  61239. const String text (getWhiteNoteText (midiNoteNumber));
  61240. if (! text.isEmpty())
  61241. {
  61242. g.setColour (textColour);
  61243. Font f (jmin (12.0f, keyWidth * 0.9f));
  61244. f.setHorizontalScale (0.8f);
  61245. g.setFont (f);
  61246. Justification justification (Justification::centredBottom);
  61247. if (orientation == verticalKeyboardFacingLeft)
  61248. justification = Justification::centredLeft;
  61249. else if (orientation == verticalKeyboardFacingRight)
  61250. justification = Justification::centredRight;
  61251. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  61252. }
  61253. g.setColour (lineColour);
  61254. if (orientation == horizontalKeyboard)
  61255. g.fillRect (x, y, 1, h);
  61256. else if (orientation == verticalKeyboardFacingLeft)
  61257. g.fillRect (x, y, w, 1);
  61258. else if (orientation == verticalKeyboardFacingRight)
  61259. g.fillRect (x, y + h - 1, w, 1);
  61260. if (midiNoteNumber == rangeEnd)
  61261. {
  61262. if (orientation == horizontalKeyboard)
  61263. g.fillRect (x + w, y, 1, h);
  61264. else if (orientation == verticalKeyboardFacingLeft)
  61265. g.fillRect (x, y + h, w, 1);
  61266. else if (orientation == verticalKeyboardFacingRight)
  61267. g.fillRect (x, y - 1, w, 1);
  61268. }
  61269. }
  61270. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  61271. Graphics& g, int x, int y, int w, int h,
  61272. bool isDown, bool isOver,
  61273. const Colour& noteFillColour)
  61274. {
  61275. Colour c (noteFillColour);
  61276. if (isDown)
  61277. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  61278. if (isOver)
  61279. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61280. g.setColour (c);
  61281. g.fillRect (x, y, w, h);
  61282. if (isDown)
  61283. {
  61284. g.setColour (noteFillColour);
  61285. g.drawRect (x, y, w, h);
  61286. }
  61287. else
  61288. {
  61289. const int xIndent = jmax (1, jmin (w, h) / 8);
  61290. g.setColour (c.brighter());
  61291. if (orientation == horizontalKeyboard)
  61292. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  61293. else if (orientation == verticalKeyboardFacingLeft)
  61294. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  61295. else if (orientation == verticalKeyboardFacingRight)
  61296. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  61297. }
  61298. }
  61299. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  61300. {
  61301. octaveNumForMiddleC = octaveNumForMiddleC_;
  61302. repaint();
  61303. }
  61304. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  61305. {
  61306. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  61307. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  61308. return String::empty;
  61309. }
  61310. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  61311. const bool isMouseOver_,
  61312. const bool isButtonDown,
  61313. const bool movesOctavesUp)
  61314. {
  61315. g.fillAll (findColour (upDownButtonBackgroundColourId));
  61316. float angle;
  61317. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  61318. angle = movesOctavesUp ? 0.0f : 0.5f;
  61319. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  61320. angle = movesOctavesUp ? 0.25f : 0.75f;
  61321. else
  61322. angle = movesOctavesUp ? 0.75f : 0.25f;
  61323. Path path;
  61324. path.lineTo (0.0f, 1.0f);
  61325. path.lineTo (1.0f, 0.5f);
  61326. path.closeSubPath();
  61327. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  61328. g.setColour (findColour (upDownButtonArrowColourId)
  61329. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  61330. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  61331. w - 2.0f,
  61332. h - 2.0f,
  61333. true));
  61334. }
  61335. void MidiKeyboardComponent::resized()
  61336. {
  61337. int w = getWidth();
  61338. int h = getHeight();
  61339. if (w > 0 && h > 0)
  61340. {
  61341. if (orientation != horizontalKeyboard)
  61342. swapVariables (w, h);
  61343. blackNoteLength = roundToInt (h * 0.7f);
  61344. int kx2, kw2;
  61345. getKeyPos (rangeEnd, kx2, kw2);
  61346. kx2 += kw2;
  61347. if (firstKey != rangeStart)
  61348. {
  61349. int kx1, kw1;
  61350. getKeyPos (rangeStart, kx1, kw1);
  61351. if (kx2 - kx1 <= w)
  61352. {
  61353. firstKey = rangeStart;
  61354. sendChangeMessage (this);
  61355. repaint();
  61356. }
  61357. }
  61358. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  61359. scrollDown->setVisible (showScrollButtons);
  61360. scrollUp->setVisible (showScrollButtons);
  61361. xOffset = 0;
  61362. if (showScrollButtons)
  61363. {
  61364. const int scrollButtonW = jmin (12, w / 2);
  61365. if (orientation == horizontalKeyboard)
  61366. {
  61367. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  61368. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  61369. }
  61370. else if (orientation == verticalKeyboardFacingLeft)
  61371. {
  61372. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  61373. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61374. }
  61375. else if (orientation == verticalKeyboardFacingRight)
  61376. {
  61377. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61378. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  61379. }
  61380. int endOfLastKey, kw;
  61381. getKeyPos (rangeEnd, endOfLastKey, kw);
  61382. endOfLastKey += kw;
  61383. float mousePositionVelocity;
  61384. const int spaceAvailable = w - scrollButtonW * 2;
  61385. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  61386. if (lastStartKey >= 0 && firstKey > lastStartKey)
  61387. {
  61388. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  61389. sendChangeMessage (this);
  61390. }
  61391. int newOffset = 0;
  61392. getKeyPos (firstKey, newOffset, kw);
  61393. xOffset = newOffset - scrollButtonW;
  61394. }
  61395. else
  61396. {
  61397. firstKey = rangeStart;
  61398. }
  61399. timerCallback();
  61400. repaint();
  61401. }
  61402. }
  61403. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61404. {
  61405. triggerAsyncUpdate();
  61406. }
  61407. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61408. {
  61409. triggerAsyncUpdate();
  61410. }
  61411. void MidiKeyboardComponent::handleAsyncUpdate()
  61412. {
  61413. for (int i = rangeStart; i <= rangeEnd; ++i)
  61414. {
  61415. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61416. {
  61417. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61418. repaintNote (i);
  61419. }
  61420. }
  61421. }
  61422. void MidiKeyboardComponent::resetAnyKeysInUse()
  61423. {
  61424. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61425. {
  61426. state.allNotesOff (midiChannel);
  61427. keysPressed.clear();
  61428. mouseDownNote = -1;
  61429. }
  61430. }
  61431. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61432. {
  61433. float mousePositionVelocity = 0.0f;
  61434. const int newNote = (mouseDragging || isMouseOver())
  61435. ? xyToNote (pos, mousePositionVelocity) : -1;
  61436. if (noteUnderMouse != newNote)
  61437. {
  61438. if (mouseDownNote >= 0)
  61439. {
  61440. state.noteOff (midiChannel, mouseDownNote);
  61441. mouseDownNote = -1;
  61442. }
  61443. if (mouseDragging && newNote >= 0)
  61444. {
  61445. if (! useMousePositionForVelocity)
  61446. mousePositionVelocity = 1.0f;
  61447. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61448. mouseDownNote = newNote;
  61449. }
  61450. repaintNote (noteUnderMouse);
  61451. noteUnderMouse = newNote;
  61452. repaintNote (noteUnderMouse);
  61453. }
  61454. else if (mouseDownNote >= 0 && ! mouseDragging)
  61455. {
  61456. state.noteOff (midiChannel, mouseDownNote);
  61457. mouseDownNote = -1;
  61458. }
  61459. }
  61460. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61461. {
  61462. updateNoteUnderMouse (e.getPosition());
  61463. stopTimer();
  61464. }
  61465. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61466. {
  61467. float mousePositionVelocity;
  61468. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61469. if (newNote >= 0)
  61470. mouseDraggedToKey (newNote, e);
  61471. updateNoteUnderMouse (e.getPosition());
  61472. }
  61473. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61474. {
  61475. return true;
  61476. }
  61477. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61478. {
  61479. }
  61480. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61481. {
  61482. float mousePositionVelocity;
  61483. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61484. mouseDragging = false;
  61485. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61486. {
  61487. repaintNote (noteUnderMouse);
  61488. noteUnderMouse = -1;
  61489. mouseDragging = true;
  61490. updateNoteUnderMouse (e.getPosition());
  61491. startTimer (500);
  61492. }
  61493. }
  61494. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61495. {
  61496. mouseDragging = false;
  61497. updateNoteUnderMouse (e.getPosition());
  61498. stopTimer();
  61499. }
  61500. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61501. {
  61502. updateNoteUnderMouse (e.getPosition());
  61503. }
  61504. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61505. {
  61506. updateNoteUnderMouse (e.getPosition());
  61507. }
  61508. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61509. {
  61510. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61511. }
  61512. void MidiKeyboardComponent::timerCallback()
  61513. {
  61514. updateNoteUnderMouse (getMouseXYRelative());
  61515. }
  61516. void MidiKeyboardComponent::clearKeyMappings()
  61517. {
  61518. resetAnyKeysInUse();
  61519. keyPressNotes.clear();
  61520. keyPresses.clear();
  61521. }
  61522. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61523. const int midiNoteOffsetFromC)
  61524. {
  61525. removeKeyPressForNote (midiNoteOffsetFromC);
  61526. keyPressNotes.add (midiNoteOffsetFromC);
  61527. keyPresses.add (key);
  61528. }
  61529. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61530. {
  61531. for (int i = keyPressNotes.size(); --i >= 0;)
  61532. {
  61533. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61534. {
  61535. keyPressNotes.remove (i);
  61536. keyPresses.remove (i);
  61537. }
  61538. }
  61539. }
  61540. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61541. {
  61542. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61543. keyMappingOctave = newOctaveNumber;
  61544. }
  61545. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61546. {
  61547. bool keyPressUsed = false;
  61548. for (int i = keyPresses.size(); --i >= 0;)
  61549. {
  61550. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61551. if (keyPresses.getReference(i).isCurrentlyDown())
  61552. {
  61553. if (! keysPressed [note])
  61554. {
  61555. keysPressed.setBit (note);
  61556. state.noteOn (midiChannel, note, velocity);
  61557. keyPressUsed = true;
  61558. }
  61559. }
  61560. else
  61561. {
  61562. if (keysPressed [note])
  61563. {
  61564. keysPressed.clearBit (note);
  61565. state.noteOff (midiChannel, note);
  61566. keyPressUsed = true;
  61567. }
  61568. }
  61569. }
  61570. return keyPressUsed;
  61571. }
  61572. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61573. {
  61574. resetAnyKeysInUse();
  61575. }
  61576. END_JUCE_NAMESPACE
  61577. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61578. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61579. #if JUCE_OPENGL
  61580. BEGIN_JUCE_NAMESPACE
  61581. extern void juce_glViewport (const int w, const int h);
  61582. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61583. const int alphaBits_,
  61584. const int depthBufferBits_,
  61585. const int stencilBufferBits_)
  61586. : redBits (bitsPerRGBComponent),
  61587. greenBits (bitsPerRGBComponent),
  61588. blueBits (bitsPerRGBComponent),
  61589. alphaBits (alphaBits_),
  61590. depthBufferBits (depthBufferBits_),
  61591. stencilBufferBits (stencilBufferBits_),
  61592. accumulationBufferRedBits (0),
  61593. accumulationBufferGreenBits (0),
  61594. accumulationBufferBlueBits (0),
  61595. accumulationBufferAlphaBits (0),
  61596. fullSceneAntiAliasingNumSamples (0)
  61597. {
  61598. }
  61599. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61600. : redBits (other.redBits),
  61601. greenBits (other.greenBits),
  61602. blueBits (other.blueBits),
  61603. alphaBits (other.alphaBits),
  61604. depthBufferBits (other.depthBufferBits),
  61605. stencilBufferBits (other.stencilBufferBits),
  61606. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61607. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61608. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61609. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61610. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61611. {
  61612. }
  61613. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61614. {
  61615. redBits = other.redBits;
  61616. greenBits = other.greenBits;
  61617. blueBits = other.blueBits;
  61618. alphaBits = other.alphaBits;
  61619. depthBufferBits = other.depthBufferBits;
  61620. stencilBufferBits = other.stencilBufferBits;
  61621. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61622. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61623. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61624. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61625. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61626. return *this;
  61627. }
  61628. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61629. {
  61630. return redBits == other.redBits
  61631. && greenBits == other.greenBits
  61632. && blueBits == other.blueBits
  61633. && alphaBits == other.alphaBits
  61634. && depthBufferBits == other.depthBufferBits
  61635. && stencilBufferBits == other.stencilBufferBits
  61636. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61637. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61638. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61639. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61640. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61641. }
  61642. static Array<OpenGLContext*> knownContexts;
  61643. OpenGLContext::OpenGLContext() throw()
  61644. {
  61645. knownContexts.add (this);
  61646. }
  61647. OpenGLContext::~OpenGLContext()
  61648. {
  61649. knownContexts.removeValue (this);
  61650. }
  61651. OpenGLContext* OpenGLContext::getCurrentContext()
  61652. {
  61653. for (int i = knownContexts.size(); --i >= 0;)
  61654. {
  61655. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61656. if (oglc->isActive())
  61657. return oglc;
  61658. }
  61659. return 0;
  61660. }
  61661. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61662. {
  61663. public:
  61664. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61665. : ComponentMovementWatcher (owner_),
  61666. owner (owner_),
  61667. wasShowing (false)
  61668. {
  61669. }
  61670. ~OpenGLComponentWatcher() {}
  61671. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61672. {
  61673. owner->updateContextPosition();
  61674. }
  61675. void componentPeerChanged()
  61676. {
  61677. const ScopedLock sl (owner->getContextLock());
  61678. owner->deleteContext();
  61679. }
  61680. void componentVisibilityChanged (Component&)
  61681. {
  61682. const bool isShowingNow = owner->isShowing();
  61683. if (wasShowing != isShowingNow)
  61684. {
  61685. wasShowing = isShowingNow;
  61686. if (! isShowingNow)
  61687. {
  61688. const ScopedLock sl (owner->getContextLock());
  61689. owner->deleteContext();
  61690. }
  61691. }
  61692. }
  61693. juce_UseDebuggingNewOperator
  61694. private:
  61695. OpenGLComponent* const owner;
  61696. bool wasShowing;
  61697. };
  61698. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61699. : type (type_),
  61700. contextToShareListsWith (0),
  61701. needToUpdateViewport (true)
  61702. {
  61703. setOpaque (true);
  61704. componentWatcher = new OpenGLComponentWatcher (this);
  61705. }
  61706. OpenGLComponent::~OpenGLComponent()
  61707. {
  61708. deleteContext();
  61709. componentWatcher = 0;
  61710. }
  61711. void OpenGLComponent::deleteContext()
  61712. {
  61713. const ScopedLock sl (contextLock);
  61714. context = 0;
  61715. }
  61716. void OpenGLComponent::updateContextPosition()
  61717. {
  61718. needToUpdateViewport = true;
  61719. if (getWidth() > 0 && getHeight() > 0)
  61720. {
  61721. Component* const topComp = getTopLevelComponent();
  61722. if (topComp->getPeer() != 0)
  61723. {
  61724. const ScopedLock sl (contextLock);
  61725. if (context != 0)
  61726. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61727. getScreenY() - topComp->getScreenY(),
  61728. getWidth(),
  61729. getHeight(),
  61730. topComp->getHeight());
  61731. }
  61732. }
  61733. }
  61734. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61735. {
  61736. OpenGLPixelFormat pf;
  61737. const ScopedLock sl (contextLock);
  61738. if (context != 0)
  61739. pf = context->getPixelFormat();
  61740. return pf;
  61741. }
  61742. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61743. {
  61744. if (! (preferredPixelFormat == formatToUse))
  61745. {
  61746. const ScopedLock sl (contextLock);
  61747. deleteContext();
  61748. preferredPixelFormat = formatToUse;
  61749. }
  61750. }
  61751. void OpenGLComponent::shareWith (OpenGLContext* c)
  61752. {
  61753. if (contextToShareListsWith != c)
  61754. {
  61755. const ScopedLock sl (contextLock);
  61756. deleteContext();
  61757. contextToShareListsWith = c;
  61758. }
  61759. }
  61760. bool OpenGLComponent::makeCurrentContextActive()
  61761. {
  61762. if (context == 0)
  61763. {
  61764. const ScopedLock sl (contextLock);
  61765. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61766. {
  61767. context = createContext();
  61768. if (context != 0)
  61769. {
  61770. updateContextPosition();
  61771. if (context->makeActive())
  61772. newOpenGLContextCreated();
  61773. }
  61774. }
  61775. }
  61776. return context != 0 && context->makeActive();
  61777. }
  61778. void OpenGLComponent::makeCurrentContextInactive()
  61779. {
  61780. if (context != 0)
  61781. context->makeInactive();
  61782. }
  61783. bool OpenGLComponent::isActiveContext() const throw()
  61784. {
  61785. return context != 0 && context->isActive();
  61786. }
  61787. void OpenGLComponent::swapBuffers()
  61788. {
  61789. if (context != 0)
  61790. context->swapBuffers();
  61791. }
  61792. void OpenGLComponent::paint (Graphics&)
  61793. {
  61794. if (renderAndSwapBuffers())
  61795. {
  61796. ComponentPeer* const peer = getPeer();
  61797. if (peer != 0)
  61798. {
  61799. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61800. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61801. }
  61802. }
  61803. }
  61804. bool OpenGLComponent::renderAndSwapBuffers()
  61805. {
  61806. const ScopedLock sl (contextLock);
  61807. if (! makeCurrentContextActive())
  61808. return false;
  61809. if (needToUpdateViewport)
  61810. {
  61811. needToUpdateViewport = false;
  61812. juce_glViewport (getWidth(), getHeight());
  61813. }
  61814. renderOpenGL();
  61815. swapBuffers();
  61816. return true;
  61817. }
  61818. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61819. {
  61820. Component::internalRepaint (x, y, w, h);
  61821. if (context != 0)
  61822. context->repaint();
  61823. }
  61824. END_JUCE_NAMESPACE
  61825. #endif
  61826. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61827. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61828. BEGIN_JUCE_NAMESPACE
  61829. PreferencesPanel::PreferencesPanel()
  61830. : buttonSize (70)
  61831. {
  61832. }
  61833. PreferencesPanel::~PreferencesPanel()
  61834. {
  61835. currentPage = 0;
  61836. deleteAllChildren();
  61837. }
  61838. void PreferencesPanel::addSettingsPage (const String& title,
  61839. const Drawable* icon,
  61840. const Drawable* overIcon,
  61841. const Drawable* downIcon)
  61842. {
  61843. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61844. button->setImages (icon, overIcon, downIcon);
  61845. button->setRadioGroupId (1);
  61846. button->addButtonListener (this);
  61847. button->setClickingTogglesState (true);
  61848. button->setWantsKeyboardFocus (false);
  61849. addAndMakeVisible (button);
  61850. resized();
  61851. if (currentPage == 0)
  61852. setCurrentPage (title);
  61853. }
  61854. void PreferencesPanel::addSettingsPage (const String& title,
  61855. const void* imageData,
  61856. const int imageDataSize)
  61857. {
  61858. DrawableImage icon, iconOver, iconDown;
  61859. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61860. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61861. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61862. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61863. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61864. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61865. }
  61866. class PrefsDialogWindow : public DialogWindow
  61867. {
  61868. public:
  61869. PrefsDialogWindow (const String& dialogtitle,
  61870. const Colour& backgroundColour)
  61871. : DialogWindow (dialogtitle, backgroundColour, true)
  61872. {
  61873. }
  61874. ~PrefsDialogWindow()
  61875. {
  61876. }
  61877. void closeButtonPressed()
  61878. {
  61879. exitModalState (0);
  61880. }
  61881. private:
  61882. PrefsDialogWindow (const PrefsDialogWindow&);
  61883. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  61884. };
  61885. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  61886. int dialogWidth,
  61887. int dialogHeight,
  61888. const Colour& backgroundColour)
  61889. {
  61890. setSize (dialogWidth, dialogHeight);
  61891. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  61892. dw.setContentComponent (this, true, true);
  61893. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  61894. dw.runModalLoop();
  61895. dw.setContentComponent (0, false, false);
  61896. }
  61897. void PreferencesPanel::resized()
  61898. {
  61899. int x = 0;
  61900. for (int i = 0; i < getNumChildComponents(); ++i)
  61901. {
  61902. Component* c = getChildComponent (i);
  61903. if (dynamic_cast <DrawableButton*> (c) == 0)
  61904. {
  61905. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  61906. }
  61907. else
  61908. {
  61909. c->setBounds (x, 0, buttonSize, buttonSize);
  61910. x += buttonSize;
  61911. }
  61912. }
  61913. }
  61914. void PreferencesPanel::paint (Graphics& g)
  61915. {
  61916. g.setColour (Colours::grey);
  61917. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61918. }
  61919. void PreferencesPanel::setCurrentPage (const String& pageName)
  61920. {
  61921. if (currentPageName != pageName)
  61922. {
  61923. currentPageName = pageName;
  61924. currentPage = 0;
  61925. currentPage = createComponentForPage (pageName);
  61926. if (currentPage != 0)
  61927. {
  61928. addAndMakeVisible (currentPage);
  61929. currentPage->toBack();
  61930. resized();
  61931. }
  61932. for (int i = 0; i < getNumChildComponents(); ++i)
  61933. {
  61934. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61935. if (db != 0 && db->getName() == pageName)
  61936. {
  61937. db->setToggleState (true, false);
  61938. break;
  61939. }
  61940. }
  61941. }
  61942. }
  61943. void PreferencesPanel::buttonClicked (Button*)
  61944. {
  61945. for (int i = 0; i < getNumChildComponents(); ++i)
  61946. {
  61947. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61948. if (db != 0 && db->getToggleState())
  61949. {
  61950. setCurrentPage (db->getName());
  61951. break;
  61952. }
  61953. }
  61954. }
  61955. END_JUCE_NAMESPACE
  61956. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61957. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61958. #if JUCE_WINDOWS || JUCE_LINUX
  61959. BEGIN_JUCE_NAMESPACE
  61960. SystemTrayIconComponent::SystemTrayIconComponent()
  61961. {
  61962. addToDesktop (0);
  61963. }
  61964. SystemTrayIconComponent::~SystemTrayIconComponent()
  61965. {
  61966. }
  61967. END_JUCE_NAMESPACE
  61968. #endif
  61969. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61970. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61971. BEGIN_JUCE_NAMESPACE
  61972. class AlertWindowTextEditor : public TextEditor
  61973. {
  61974. public:
  61975. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61976. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61977. {
  61978. setSelectAllWhenFocused (true);
  61979. }
  61980. ~AlertWindowTextEditor()
  61981. {
  61982. }
  61983. void returnPressed()
  61984. {
  61985. // pass these up the component hierarchy to be trigger the buttons
  61986. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61987. }
  61988. void escapePressed()
  61989. {
  61990. // pass these up the component hierarchy to be trigger the buttons
  61991. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61992. }
  61993. private:
  61994. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61995. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61996. static juce_wchar getDefaultPasswordChar() throw()
  61997. {
  61998. #if JUCE_LINUX
  61999. return 0x2022;
  62000. #else
  62001. return 0x25cf;
  62002. #endif
  62003. }
  62004. };
  62005. AlertWindow::AlertWindow (const String& title,
  62006. const String& message,
  62007. AlertIconType iconType,
  62008. Component* associatedComponent_)
  62009. : TopLevelWindow (title, true),
  62010. alertIconType (iconType),
  62011. associatedComponent (associatedComponent_)
  62012. {
  62013. if (message.isEmpty())
  62014. text = " "; // to force an update if the message is empty
  62015. setMessage (message);
  62016. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  62017. {
  62018. Component* const c = Desktop::getInstance().getComponent (i);
  62019. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  62020. {
  62021. setAlwaysOnTop (true);
  62022. break;
  62023. }
  62024. }
  62025. if (! JUCEApplication::isStandaloneApp())
  62026. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62027. lookAndFeelChanged();
  62028. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  62029. }
  62030. AlertWindow::~AlertWindow()
  62031. {
  62032. for (int i = customComps.size(); --i >= 0;)
  62033. removeChildComponent ((Component*) customComps[i]);
  62034. deleteAllChildren();
  62035. }
  62036. void AlertWindow::userTriedToCloseWindow()
  62037. {
  62038. exitModalState (0);
  62039. }
  62040. void AlertWindow::setMessage (const String& message)
  62041. {
  62042. const String newMessage (message.substring (0, 2048));
  62043. if (text != newMessage)
  62044. {
  62045. text = newMessage;
  62046. font.setHeight (15.0f);
  62047. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  62048. textLayout.setText (getName() + "\n\n", titleFont);
  62049. textLayout.appendText (text, font);
  62050. updateLayout (true);
  62051. repaint();
  62052. }
  62053. }
  62054. void AlertWindow::buttonClicked (Button* button)
  62055. {
  62056. for (int i = 0; i < buttons.size(); i++)
  62057. {
  62058. TextButton* const c = (TextButton*) buttons[i];
  62059. if (button->getName() == c->getName())
  62060. {
  62061. if (c->getParentComponent() != 0)
  62062. c->getParentComponent()->exitModalState (c->getCommandID());
  62063. break;
  62064. }
  62065. }
  62066. }
  62067. void AlertWindow::addButton (const String& name,
  62068. const int returnValue,
  62069. const KeyPress& shortcutKey1,
  62070. const KeyPress& shortcutKey2)
  62071. {
  62072. TextButton* const b = new TextButton (name, String::empty);
  62073. b->setWantsKeyboardFocus (true);
  62074. b->setMouseClickGrabsKeyboardFocus (false);
  62075. b->setCommandToTrigger (0, returnValue, false);
  62076. b->addShortcut (shortcutKey1);
  62077. b->addShortcut (shortcutKey2);
  62078. b->addButtonListener (this);
  62079. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  62080. addAndMakeVisible (b, 0);
  62081. buttons.add (b);
  62082. updateLayout (false);
  62083. }
  62084. int AlertWindow::getNumButtons() const
  62085. {
  62086. return buttons.size();
  62087. }
  62088. void AlertWindow::triggerButtonClick (const String& buttonName)
  62089. {
  62090. for (int i = buttons.size(); --i >= 0;)
  62091. {
  62092. TextButton* const b = (TextButton*) buttons[i];
  62093. if (buttonName == b->getName())
  62094. {
  62095. b->triggerClick();
  62096. break;
  62097. }
  62098. }
  62099. }
  62100. void AlertWindow::addTextEditor (const String& name,
  62101. const String& initialContents,
  62102. const String& onScreenLabel,
  62103. const bool isPasswordBox)
  62104. {
  62105. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  62106. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  62107. tc->setFont (font);
  62108. tc->setText (initialContents);
  62109. tc->setCaretPosition (initialContents.length());
  62110. addAndMakeVisible (tc);
  62111. textBoxes.add (tc);
  62112. allComps.add (tc);
  62113. textboxNames.add (onScreenLabel);
  62114. updateLayout (false);
  62115. }
  62116. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  62117. {
  62118. for (int i = textBoxes.size(); --i >= 0;)
  62119. if (static_cast <TextEditor*> (textBoxes.getUnchecked(i))->getName() == nameOfTextEditor)
  62120. return static_cast <TextEditor*> (textBoxes.getUnchecked(i));
  62121. return 0;
  62122. }
  62123. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  62124. {
  62125. TextEditor* const t = getTextEditor (nameOfTextEditor);
  62126. return t != 0 ? t->getText() : String::empty;
  62127. }
  62128. void AlertWindow::addComboBox (const String& name,
  62129. const StringArray& items,
  62130. const String& onScreenLabel)
  62131. {
  62132. ComboBox* const cb = new ComboBox (name);
  62133. for (int i = 0; i < items.size(); ++i)
  62134. cb->addItem (items[i], i + 1);
  62135. addAndMakeVisible (cb);
  62136. cb->setSelectedItemIndex (0);
  62137. comboBoxes.add (cb);
  62138. allComps.add (cb);
  62139. comboBoxNames.add (onScreenLabel);
  62140. updateLayout (false);
  62141. }
  62142. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  62143. {
  62144. for (int i = comboBoxes.size(); --i >= 0;)
  62145. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  62146. return (ComboBox*) comboBoxes[i];
  62147. return 0;
  62148. }
  62149. class AlertTextComp : public TextEditor
  62150. {
  62151. public:
  62152. AlertTextComp (const String& message,
  62153. const Font& font)
  62154. {
  62155. setReadOnly (true);
  62156. setMultiLine (true, true);
  62157. setCaretVisible (false);
  62158. setScrollbarsShown (true);
  62159. lookAndFeelChanged();
  62160. setWantsKeyboardFocus (false);
  62161. setFont (font);
  62162. setText (message, false);
  62163. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  62164. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  62165. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  62166. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  62167. }
  62168. ~AlertTextComp()
  62169. {
  62170. }
  62171. int getPreferredWidth() const throw() { return bestWidth; }
  62172. void updateLayout (const int width)
  62173. {
  62174. TextLayout text;
  62175. text.appendText (getText(), getFont());
  62176. text.layout (width - 8, Justification::topLeft, true);
  62177. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  62178. }
  62179. private:
  62180. int bestWidth;
  62181. AlertTextComp (const AlertTextComp&);
  62182. AlertTextComp& operator= (const AlertTextComp&);
  62183. };
  62184. void AlertWindow::addTextBlock (const String& textBlock)
  62185. {
  62186. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  62187. textBlocks.add (c);
  62188. allComps.add (c);
  62189. addAndMakeVisible (c);
  62190. updateLayout (false);
  62191. }
  62192. void AlertWindow::addProgressBarComponent (double& progressValue)
  62193. {
  62194. ProgressBar* const pb = new ProgressBar (progressValue);
  62195. progressBars.add (pb);
  62196. allComps.add (pb);
  62197. addAndMakeVisible (pb);
  62198. updateLayout (false);
  62199. }
  62200. void AlertWindow::addCustomComponent (Component* const component)
  62201. {
  62202. customComps.add (component);
  62203. allComps.add (component);
  62204. addAndMakeVisible (component);
  62205. updateLayout (false);
  62206. }
  62207. int AlertWindow::getNumCustomComponents() const
  62208. {
  62209. return customComps.size();
  62210. }
  62211. Component* AlertWindow::getCustomComponent (const int index) const
  62212. {
  62213. return (Component*) customComps [index];
  62214. }
  62215. Component* AlertWindow::removeCustomComponent (const int index)
  62216. {
  62217. Component* const c = getCustomComponent (index);
  62218. if (c != 0)
  62219. {
  62220. customComps.removeValue (c);
  62221. allComps.removeValue (c);
  62222. removeChildComponent (c);
  62223. updateLayout (false);
  62224. }
  62225. return c;
  62226. }
  62227. void AlertWindow::paint (Graphics& g)
  62228. {
  62229. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  62230. g.setColour (findColour (textColourId));
  62231. g.setFont (getLookAndFeel().getAlertWindowFont());
  62232. int i;
  62233. for (i = textBoxes.size(); --i >= 0;)
  62234. {
  62235. const TextEditor* const te = (TextEditor*) textBoxes[i];
  62236. g.drawFittedText (textboxNames[i],
  62237. te->getX(), te->getY() - 14,
  62238. te->getWidth(), 14,
  62239. Justification::centredLeft, 1);
  62240. }
  62241. for (i = comboBoxNames.size(); --i >= 0;)
  62242. {
  62243. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  62244. g.drawFittedText (comboBoxNames[i],
  62245. cb->getX(), cb->getY() - 14,
  62246. cb->getWidth(), 14,
  62247. Justification::centredLeft, 1);
  62248. }
  62249. for (i = customComps.size(); --i >= 0;)
  62250. {
  62251. const Component* const c = (Component*) customComps[i];
  62252. g.drawFittedText (c->getName(),
  62253. c->getX(), c->getY() - 14,
  62254. c->getWidth(), 14,
  62255. Justification::centredLeft, 1);
  62256. }
  62257. }
  62258. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  62259. {
  62260. const int titleH = 24;
  62261. const int iconWidth = 80;
  62262. const int wid = jmax (font.getStringWidth (text),
  62263. font.getStringWidth (getName()));
  62264. const int sw = (int) std::sqrt (font.getHeight() * wid);
  62265. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  62266. const int edgeGap = 10;
  62267. const int labelHeight = 18;
  62268. int iconSpace;
  62269. if (alertIconType == NoIcon)
  62270. {
  62271. textLayout.layout (w, Justification::horizontallyCentred, true);
  62272. iconSpace = 0;
  62273. }
  62274. else
  62275. {
  62276. textLayout.layout (w, Justification::left, true);
  62277. iconSpace = iconWidth;
  62278. }
  62279. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  62280. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62281. const int textLayoutH = textLayout.getHeight();
  62282. const int textBottom = 16 + titleH + textLayoutH;
  62283. int h = textBottom;
  62284. int buttonW = 40;
  62285. int i;
  62286. for (i = 0; i < buttons.size(); ++i)
  62287. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  62288. w = jmax (buttonW, w);
  62289. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  62290. if (buttons.size() > 0)
  62291. h += 20 + ((TextButton*) buttons[0])->getHeight();
  62292. for (i = customComps.size(); --i >= 0;)
  62293. {
  62294. Component* c = (Component*) customComps[i];
  62295. w = jmax (w, (c->getWidth() * 100) / 80);
  62296. h += 10 + c->getHeight();
  62297. if (c->getName().isNotEmpty())
  62298. h += labelHeight;
  62299. }
  62300. for (i = textBlocks.size(); --i >= 0;)
  62301. {
  62302. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62303. w = jmax (w, ac->getPreferredWidth());
  62304. }
  62305. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62306. for (i = textBlocks.size(); --i >= 0;)
  62307. {
  62308. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62309. ac->updateLayout ((int) (w * 0.8f));
  62310. h += ac->getHeight() + 10;
  62311. }
  62312. h = jmin (getParentHeight() - 50, h);
  62313. if (onlyIncreaseSize)
  62314. {
  62315. w = jmax (w, getWidth());
  62316. h = jmax (h, getHeight());
  62317. }
  62318. if (! isVisible())
  62319. {
  62320. centreAroundComponent (associatedComponent, w, h);
  62321. }
  62322. else
  62323. {
  62324. const int cx = getX() + getWidth() / 2;
  62325. const int cy = getY() + getHeight() / 2;
  62326. setBounds (cx - w / 2,
  62327. cy - h / 2,
  62328. w, h);
  62329. }
  62330. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  62331. const int spacer = 16;
  62332. int totalWidth = -spacer;
  62333. for (i = buttons.size(); --i >= 0;)
  62334. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  62335. int x = (w - totalWidth) / 2;
  62336. int y = (int) (getHeight() * 0.95f);
  62337. for (i = 0; i < buttons.size(); ++i)
  62338. {
  62339. TextButton* const c = (TextButton*) buttons[i];
  62340. int ny = proportionOfHeight (0.95f) - c->getHeight();
  62341. c->setTopLeftPosition (x, ny);
  62342. if (ny < y)
  62343. y = ny;
  62344. x += c->getWidth() + spacer;
  62345. c->toFront (false);
  62346. }
  62347. y = textBottom;
  62348. for (i = 0; i < allComps.size(); ++i)
  62349. {
  62350. Component* const c = (Component*) allComps[i];
  62351. h = 22;
  62352. const int comboIndex = comboBoxes.indexOf (c);
  62353. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  62354. y += labelHeight;
  62355. const int tbIndex = textBoxes.indexOf (c);
  62356. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  62357. y += labelHeight;
  62358. if (customComps.contains (c))
  62359. {
  62360. if (c->getName().isNotEmpty())
  62361. y += labelHeight;
  62362. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  62363. h = c->getHeight();
  62364. }
  62365. else if (textBlocks.contains (c))
  62366. {
  62367. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  62368. h = c->getHeight();
  62369. }
  62370. else
  62371. {
  62372. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  62373. }
  62374. y += h + 10;
  62375. }
  62376. setWantsKeyboardFocus (getNumChildComponents() == 0);
  62377. }
  62378. bool AlertWindow::containsAnyExtraComponents() const
  62379. {
  62380. return textBoxes.size()
  62381. + comboBoxes.size()
  62382. + progressBars.size()
  62383. + customComps.size() > 0;
  62384. }
  62385. void AlertWindow::mouseDown (const MouseEvent&)
  62386. {
  62387. dragger.startDraggingComponent (this, &constrainer);
  62388. }
  62389. void AlertWindow::mouseDrag (const MouseEvent& e)
  62390. {
  62391. dragger.dragComponent (this, e);
  62392. }
  62393. bool AlertWindow::keyPressed (const KeyPress& key)
  62394. {
  62395. for (int i = buttons.size(); --i >= 0;)
  62396. {
  62397. TextButton* const b = (TextButton*) buttons[i];
  62398. if (b->isRegisteredForShortcut (key))
  62399. {
  62400. b->triggerClick();
  62401. return true;
  62402. }
  62403. }
  62404. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  62405. {
  62406. exitModalState (0);
  62407. return true;
  62408. }
  62409. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  62410. {
  62411. ((TextButton*) buttons.getFirst())->triggerClick();
  62412. return true;
  62413. }
  62414. return false;
  62415. }
  62416. void AlertWindow::lookAndFeelChanged()
  62417. {
  62418. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  62419. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  62420. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  62421. }
  62422. int AlertWindow::getDesktopWindowStyleFlags() const
  62423. {
  62424. return getLookAndFeel().getAlertBoxWindowFlags();
  62425. }
  62426. struct AlertWindowInfo
  62427. {
  62428. String title, message, button1, button2, button3;
  62429. AlertWindow::AlertIconType iconType;
  62430. int numButtons;
  62431. Component::SafePointer<Component> associatedComponent;
  62432. int run() const
  62433. {
  62434. return (int) (pointer_sized_int)
  62435. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  62436. }
  62437. private:
  62438. int show() const
  62439. {
  62440. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  62441. : LookAndFeel::getDefaultLookAndFeel();
  62442. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  62443. iconType, numButtons, associatedComponent));
  62444. jassert (alertBox != 0); // you have to return one of these!
  62445. return alertBox->runModalLoop();
  62446. }
  62447. static void* showCallback (void* userData)
  62448. {
  62449. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  62450. }
  62451. };
  62452. void AlertWindow::showMessageBox (AlertIconType iconType,
  62453. const String& title,
  62454. const String& message,
  62455. const String& buttonText,
  62456. Component* associatedComponent)
  62457. {
  62458. AlertWindowInfo info;
  62459. info.title = title;
  62460. info.message = message;
  62461. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62462. info.iconType = iconType;
  62463. info.numButtons = 1;
  62464. info.associatedComponent = associatedComponent;
  62465. info.run();
  62466. }
  62467. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62468. const String& title,
  62469. const String& message,
  62470. const String& button1Text,
  62471. const String& button2Text,
  62472. Component* associatedComponent)
  62473. {
  62474. AlertWindowInfo info;
  62475. info.title = title;
  62476. info.message = message;
  62477. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62478. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62479. info.iconType = iconType;
  62480. info.numButtons = 2;
  62481. info.associatedComponent = associatedComponent;
  62482. return info.run() != 0;
  62483. }
  62484. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62485. const String& title,
  62486. const String& message,
  62487. const String& button1Text,
  62488. const String& button2Text,
  62489. const String& button3Text,
  62490. Component* associatedComponent)
  62491. {
  62492. AlertWindowInfo info;
  62493. info.title = title;
  62494. info.message = message;
  62495. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62496. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62497. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62498. info.iconType = iconType;
  62499. info.numButtons = 3;
  62500. info.associatedComponent = associatedComponent;
  62501. return info.run();
  62502. }
  62503. END_JUCE_NAMESPACE
  62504. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62505. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62506. BEGIN_JUCE_NAMESPACE
  62507. CallOutBox::CallOutBox (Component& contentComponent,
  62508. Component& componentToPointTo,
  62509. Component* const parentComponent)
  62510. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62511. {
  62512. addAndMakeVisible (&content);
  62513. if (parentComponent != 0)
  62514. {
  62515. updatePosition (parentComponent->getLocalBounds(),
  62516. componentToPointTo.getLocalBounds()
  62517. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()));
  62518. parentComponent->addAndMakeVisible (this);
  62519. }
  62520. else
  62521. {
  62522. if (! JUCEApplication::isStandaloneApp())
  62523. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62524. updatePosition (componentToPointTo.getScreenBounds(),
  62525. componentToPointTo.getParentMonitorArea());
  62526. addToDesktop (ComponentPeer::windowIsTemporary);
  62527. }
  62528. }
  62529. CallOutBox::~CallOutBox()
  62530. {
  62531. }
  62532. void CallOutBox::setArrowSize (const float newSize)
  62533. {
  62534. arrowSize = newSize;
  62535. borderSpace = jmax (20, (int) arrowSize);
  62536. refreshPath();
  62537. }
  62538. void CallOutBox::paint (Graphics& g)
  62539. {
  62540. if (background.isNull())
  62541. {
  62542. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62543. Graphics g (background);
  62544. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  62545. }
  62546. g.setColour (Colours::black);
  62547. g.drawImageAt (background, 0, 0);
  62548. }
  62549. void CallOutBox::resized()
  62550. {
  62551. content.setTopLeftPosition (borderSpace, borderSpace);
  62552. refreshPath();
  62553. }
  62554. void CallOutBox::moved()
  62555. {
  62556. refreshPath();
  62557. }
  62558. void CallOutBox::childBoundsChanged (Component*)
  62559. {
  62560. updatePosition (targetArea, availableArea);
  62561. }
  62562. bool CallOutBox::hitTest (int x, int y)
  62563. {
  62564. return outline.contains ((float) x, (float) y);
  62565. }
  62566. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62567. void CallOutBox::inputAttemptWhenModal()
  62568. {
  62569. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62570. if (targetArea.contains (mousePos))
  62571. {
  62572. // if you click on the area that originally popped-up the callout, you expect it
  62573. // to get rid of the box, but deleting the box here allows the click to pass through and
  62574. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62575. postCommandMessage (callOutBoxDismissCommandId);
  62576. }
  62577. else
  62578. {
  62579. exitModalState (0);
  62580. setVisible (false);
  62581. }
  62582. }
  62583. void CallOutBox::handleCommandMessage (int commandId)
  62584. {
  62585. Component::handleCommandMessage (commandId);
  62586. if (commandId == callOutBoxDismissCommandId)
  62587. {
  62588. exitModalState (0);
  62589. setVisible (false);
  62590. }
  62591. }
  62592. bool CallOutBox::keyPressed (const KeyPress& key)
  62593. {
  62594. if (key.isKeyCode (KeyPress::escapeKey))
  62595. {
  62596. inputAttemptWhenModal();
  62597. return true;
  62598. }
  62599. return false;
  62600. }
  62601. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62602. {
  62603. targetArea = newAreaToPointTo;
  62604. availableArea = newAreaToFitIn;
  62605. Rectangle<int> bounds (0, 0,
  62606. content.getWidth() + borderSpace * 2,
  62607. content.getHeight() + borderSpace * 2);
  62608. const int hw = bounds.getWidth() / 2;
  62609. const int hh = bounds.getHeight() / 2;
  62610. const float hwReduced = (float) (hw - borderSpace * 3);
  62611. const float hhReduced = (float) (hh - borderSpace * 3);
  62612. const float arrowIndent = borderSpace - arrowSize;
  62613. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62614. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62615. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62616. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62617. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62618. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62619. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62620. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62621. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62622. float nearest = 1.0e9f;
  62623. for (int i = 0; i < 4; ++i)
  62624. {
  62625. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62626. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62627. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62628. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62629. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62630. distanceFromCentre *= 2.0f;
  62631. if (distanceFromCentre < nearest)
  62632. {
  62633. nearest = distanceFromCentre;
  62634. targetPoint = targets[i];
  62635. bounds.setPosition ((int) (centre.getX() - hw),
  62636. (int) (centre.getY() - hh));
  62637. }
  62638. }
  62639. setBounds (bounds);
  62640. }
  62641. void CallOutBox::refreshPath()
  62642. {
  62643. repaint();
  62644. background = Image::null;
  62645. outline.clear();
  62646. const float gap = 4.5f;
  62647. const float cornerSize = 9.0f;
  62648. const float cornerSize2 = 2.0f * cornerSize;
  62649. const float arrowBaseWidth = arrowSize * 0.7f;
  62650. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62651. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62652. outline.startNewSubPath (left + cornerSize, top);
  62653. if (targetY <= top)
  62654. {
  62655. outline.lineTo (targetX - arrowBaseWidth, top);
  62656. outline.lineTo (targetX, targetY);
  62657. outline.lineTo (targetX + arrowBaseWidth, top);
  62658. }
  62659. outline.lineTo (right - cornerSize, top);
  62660. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62661. if (targetX >= right)
  62662. {
  62663. outline.lineTo (right, targetY - arrowBaseWidth);
  62664. outline.lineTo (targetX, targetY);
  62665. outline.lineTo (right, targetY + arrowBaseWidth);
  62666. }
  62667. outline.lineTo (right, bottom - cornerSize);
  62668. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62669. if (targetY >= bottom)
  62670. {
  62671. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62672. outline.lineTo (targetX, targetY);
  62673. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62674. }
  62675. outline.lineTo (left + cornerSize, bottom);
  62676. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62677. if (targetX <= left)
  62678. {
  62679. outline.lineTo (left, targetY + arrowBaseWidth);
  62680. outline.lineTo (targetX, targetY);
  62681. outline.lineTo (left, targetY - arrowBaseWidth);
  62682. }
  62683. outline.lineTo (left, top + cornerSize);
  62684. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62685. outline.closeSubPath();
  62686. }
  62687. END_JUCE_NAMESPACE
  62688. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62689. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62690. BEGIN_JUCE_NAMESPACE
  62691. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62692. static Array <ComponentPeer*> heavyweightPeers;
  62693. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62694. : component (component_),
  62695. styleFlags (styleFlags_),
  62696. lastPaintTime (0),
  62697. constrainer (0),
  62698. lastDragAndDropCompUnderMouse (0),
  62699. fakeMouseMessageSent (false),
  62700. isWindowMinimised (false)
  62701. {
  62702. heavyweightPeers.add (this);
  62703. }
  62704. ComponentPeer::~ComponentPeer()
  62705. {
  62706. heavyweightPeers.removeValue (this);
  62707. Desktop::getInstance().triggerFocusCallback();
  62708. }
  62709. int ComponentPeer::getNumPeers() throw()
  62710. {
  62711. return heavyweightPeers.size();
  62712. }
  62713. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62714. {
  62715. return heavyweightPeers [index];
  62716. }
  62717. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62718. {
  62719. for (int i = heavyweightPeers.size(); --i >= 0;)
  62720. {
  62721. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62722. if (peer->getComponent() == component)
  62723. return peer;
  62724. }
  62725. return 0;
  62726. }
  62727. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62728. {
  62729. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62730. }
  62731. void ComponentPeer::updateCurrentModifiers() throw()
  62732. {
  62733. ModifierKeys::updateCurrentModifiers();
  62734. }
  62735. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62736. {
  62737. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62738. jassert (mouse != 0); // not enough sources!
  62739. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62740. }
  62741. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62742. {
  62743. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62744. jassert (mouse != 0); // not enough sources!
  62745. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62746. }
  62747. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62748. {
  62749. Graphics g (&contextToPaintTo);
  62750. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62751. g.saveState();
  62752. #endif
  62753. JUCE_TRY
  62754. {
  62755. component->paintEntireComponent (g);
  62756. }
  62757. JUCE_CATCH_EXCEPTION
  62758. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62759. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62760. // clearly when things are being repainted.
  62761. {
  62762. g.restoreState();
  62763. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62764. (uint8) Random::getSystemRandom().nextInt (255),
  62765. (uint8) Random::getSystemRandom().nextInt (255),
  62766. (uint8) 0x50));
  62767. }
  62768. #endif
  62769. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62770. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62771. mess up a lot of the calculations that the library needs to do.
  62772. */
  62773. jassert (roundToInt (10.1f) == 10);
  62774. }
  62775. bool ComponentPeer::handleKeyPress (const int keyCode,
  62776. const juce_wchar textCharacter)
  62777. {
  62778. updateCurrentModifiers();
  62779. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62780. ? Component::getCurrentlyFocusedComponent()
  62781. : component;
  62782. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62783. {
  62784. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62785. if (currentModalComp != 0)
  62786. target = currentModalComp;
  62787. }
  62788. const KeyPress keyInfo (keyCode,
  62789. ModifierKeys::getCurrentModifiers().getRawFlags()
  62790. & ModifierKeys::allKeyboardModifiers,
  62791. textCharacter);
  62792. bool keyWasUsed = false;
  62793. while (target != 0)
  62794. {
  62795. const Component::SafePointer<Component> deletionChecker (target);
  62796. if (target->keyListeners_ != 0)
  62797. {
  62798. for (int i = target->keyListeners_->size(); --i >= 0;)
  62799. {
  62800. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  62801. if (keyWasUsed || deletionChecker == 0)
  62802. return keyWasUsed;
  62803. i = jmin (i, target->keyListeners_->size());
  62804. }
  62805. }
  62806. keyWasUsed = target->keyPressed (keyInfo);
  62807. if (keyWasUsed || deletionChecker == 0)
  62808. break;
  62809. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62810. {
  62811. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62812. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62813. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62814. break;
  62815. }
  62816. target = target->parentComponent_;
  62817. }
  62818. return keyWasUsed;
  62819. }
  62820. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62821. {
  62822. updateCurrentModifiers();
  62823. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62824. ? Component::getCurrentlyFocusedComponent()
  62825. : component;
  62826. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62827. {
  62828. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62829. if (currentModalComp != 0)
  62830. target = currentModalComp;
  62831. }
  62832. bool keyWasUsed = false;
  62833. while (target != 0)
  62834. {
  62835. const Component::SafePointer<Component> deletionChecker (target);
  62836. keyWasUsed = target->keyStateChanged (isKeyDown);
  62837. if (keyWasUsed || deletionChecker == 0)
  62838. break;
  62839. if (target->keyListeners_ != 0)
  62840. {
  62841. for (int i = target->keyListeners_->size(); --i >= 0;)
  62842. {
  62843. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62844. if (keyWasUsed || deletionChecker == 0)
  62845. return keyWasUsed;
  62846. i = jmin (i, target->keyListeners_->size());
  62847. }
  62848. }
  62849. target = target->parentComponent_;
  62850. }
  62851. return keyWasUsed;
  62852. }
  62853. void ComponentPeer::handleModifierKeysChange()
  62854. {
  62855. updateCurrentModifiers();
  62856. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62857. if (target == 0)
  62858. target = Component::getCurrentlyFocusedComponent();
  62859. if (target == 0)
  62860. target = component;
  62861. if (target != 0)
  62862. target->internalModifierKeysChanged();
  62863. }
  62864. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62865. {
  62866. Component* const c = Component::getCurrentlyFocusedComponent();
  62867. if (component->isParentOf (c))
  62868. {
  62869. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62870. if (ti != 0 && ti->isTextInputActive())
  62871. return ti;
  62872. }
  62873. return 0;
  62874. }
  62875. void ComponentPeer::handleBroughtToFront()
  62876. {
  62877. updateCurrentModifiers();
  62878. if (component != 0)
  62879. component->internalBroughtToFront();
  62880. }
  62881. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62882. {
  62883. constrainer = newConstrainer;
  62884. }
  62885. void ComponentPeer::handleMovedOrResized()
  62886. {
  62887. jassert (component->isValidComponent());
  62888. updateCurrentModifiers();
  62889. const bool nowMinimised = isMinimised();
  62890. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62891. {
  62892. const Component::SafePointer<Component> deletionChecker (component);
  62893. const Rectangle<int> newBounds (getBounds());
  62894. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62895. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62896. if (wasMoved || wasResized)
  62897. {
  62898. component->bounds_ = newBounds;
  62899. if (wasResized)
  62900. component->repaint();
  62901. component->sendMovedResizedMessages (wasMoved, wasResized);
  62902. if (deletionChecker == 0)
  62903. return;
  62904. }
  62905. }
  62906. if (isWindowMinimised != nowMinimised)
  62907. {
  62908. isWindowMinimised = nowMinimised;
  62909. component->minimisationStateChanged (nowMinimised);
  62910. component->sendVisibilityChangeMessage();
  62911. }
  62912. if (! isFullScreen())
  62913. lastNonFullscreenBounds = component->getBounds();
  62914. }
  62915. void ComponentPeer::handleFocusGain()
  62916. {
  62917. updateCurrentModifiers();
  62918. if (component->isParentOf (lastFocusedComponent))
  62919. {
  62920. Component::currentlyFocusedComponent = lastFocusedComponent;
  62921. Desktop::getInstance().triggerFocusCallback();
  62922. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62923. }
  62924. else
  62925. {
  62926. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62927. component->grabKeyboardFocus();
  62928. else
  62929. Component::bringModalComponentToFront();
  62930. }
  62931. }
  62932. void ComponentPeer::handleFocusLoss()
  62933. {
  62934. updateCurrentModifiers();
  62935. if (component->hasKeyboardFocus (true))
  62936. {
  62937. lastFocusedComponent = Component::currentlyFocusedComponent;
  62938. if (lastFocusedComponent != 0)
  62939. {
  62940. Component::currentlyFocusedComponent = 0;
  62941. Desktop::getInstance().triggerFocusCallback();
  62942. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62943. }
  62944. }
  62945. }
  62946. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62947. {
  62948. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62949. ? static_cast <Component*> (lastFocusedComponent)
  62950. : component;
  62951. }
  62952. void ComponentPeer::handleScreenSizeChange()
  62953. {
  62954. updateCurrentModifiers();
  62955. component->parentSizeChanged();
  62956. handleMovedOrResized();
  62957. }
  62958. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62959. {
  62960. lastNonFullscreenBounds = newBounds;
  62961. }
  62962. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62963. {
  62964. return lastNonFullscreenBounds;
  62965. }
  62966. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62967. const StringArray& files,
  62968. FileDragAndDropTarget* const lastOne)
  62969. {
  62970. while (c != 0)
  62971. {
  62972. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62973. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62974. return t;
  62975. c = c->getParentComponent();
  62976. }
  62977. return 0;
  62978. }
  62979. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62980. {
  62981. updateCurrentModifiers();
  62982. FileDragAndDropTarget* lastTarget
  62983. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62984. FileDragAndDropTarget* newTarget = 0;
  62985. Component* const compUnderMouse = component->getComponentAt (position);
  62986. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62987. {
  62988. lastDragAndDropCompUnderMouse = compUnderMouse;
  62989. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62990. if (newTarget != lastTarget)
  62991. {
  62992. if (lastTarget != 0)
  62993. lastTarget->fileDragExit (files);
  62994. dragAndDropTargetComponent = 0;
  62995. if (newTarget != 0)
  62996. {
  62997. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62998. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  62999. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  63000. }
  63001. }
  63002. }
  63003. else
  63004. {
  63005. newTarget = lastTarget;
  63006. }
  63007. if (newTarget != 0)
  63008. {
  63009. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  63010. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63011. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  63012. }
  63013. }
  63014. void ComponentPeer::handleFileDragExit (const StringArray& files)
  63015. {
  63016. handleFileDragMove (files, Point<int> (-1, -1));
  63017. jassert (dragAndDropTargetComponent == 0);
  63018. lastDragAndDropCompUnderMouse = 0;
  63019. }
  63020. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  63021. {
  63022. handleFileDragMove (files, position);
  63023. if (dragAndDropTargetComponent != 0)
  63024. {
  63025. FileDragAndDropTarget* const target
  63026. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  63027. dragAndDropTargetComponent = 0;
  63028. lastDragAndDropCompUnderMouse = 0;
  63029. if (target != 0)
  63030. {
  63031. Component* const targetComp = dynamic_cast <Component*> (target);
  63032. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63033. {
  63034. targetComp->internalModalInputAttempt();
  63035. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63036. return;
  63037. }
  63038. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63039. target->filesDropped (files, pos.getX(), pos.getY());
  63040. }
  63041. }
  63042. }
  63043. void ComponentPeer::handleUserClosingWindow()
  63044. {
  63045. updateCurrentModifiers();
  63046. component->userTriedToCloseWindow();
  63047. }
  63048. void ComponentPeer::bringModalComponentToFront()
  63049. {
  63050. Component::bringModalComponentToFront();
  63051. }
  63052. void ComponentPeer::clearMaskedRegion()
  63053. {
  63054. maskedRegion.clear();
  63055. }
  63056. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  63057. {
  63058. maskedRegion.add (x, y, w, h);
  63059. }
  63060. const StringArray ComponentPeer::getAvailableRenderingEngines()
  63061. {
  63062. StringArray s;
  63063. s.add ("Software Renderer");
  63064. return s;
  63065. }
  63066. int ComponentPeer::getCurrentRenderingEngine() throw()
  63067. {
  63068. return 0;
  63069. }
  63070. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  63071. {
  63072. }
  63073. END_JUCE_NAMESPACE
  63074. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  63075. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  63076. BEGIN_JUCE_NAMESPACE
  63077. DialogWindow::DialogWindow (const String& name,
  63078. const Colour& backgroundColour_,
  63079. const bool escapeKeyTriggersCloseButton_,
  63080. const bool addToDesktop_)
  63081. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  63082. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  63083. {
  63084. }
  63085. DialogWindow::~DialogWindow()
  63086. {
  63087. }
  63088. void DialogWindow::resized()
  63089. {
  63090. DocumentWindow::resized();
  63091. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  63092. if (escapeKeyTriggersCloseButton
  63093. && getCloseButton() != 0
  63094. && ! getCloseButton()->isRegisteredForShortcut (esc))
  63095. {
  63096. getCloseButton()->addShortcut (esc);
  63097. }
  63098. }
  63099. class TempDialogWindow : public DialogWindow
  63100. {
  63101. public:
  63102. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  63103. : DialogWindow (title, colour, escapeCloses, true)
  63104. {
  63105. if (! JUCEApplication::isStandaloneApp())
  63106. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  63107. }
  63108. ~TempDialogWindow()
  63109. {
  63110. }
  63111. void closeButtonPressed()
  63112. {
  63113. setVisible (false);
  63114. }
  63115. private:
  63116. TempDialogWindow (const TempDialogWindow&);
  63117. TempDialogWindow& operator= (const TempDialogWindow&);
  63118. };
  63119. int DialogWindow::showModalDialog (const String& dialogTitle,
  63120. Component* contentComponent,
  63121. Component* componentToCentreAround,
  63122. const Colour& colour,
  63123. const bool escapeKeyTriggersCloseButton,
  63124. const bool shouldBeResizable,
  63125. const bool useBottomRightCornerResizer)
  63126. {
  63127. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  63128. dw.setContentComponent (contentComponent, true, true);
  63129. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  63130. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63131. const int result = dw.runModalLoop();
  63132. dw.setContentComponent (0, false);
  63133. return result;
  63134. }
  63135. END_JUCE_NAMESPACE
  63136. /*** End of inlined file: juce_DialogWindow.cpp ***/
  63137. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  63138. BEGIN_JUCE_NAMESPACE
  63139. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  63140. {
  63141. public:
  63142. ButtonListenerProxy (DocumentWindow& owner_)
  63143. : owner (owner_)
  63144. {
  63145. }
  63146. void buttonClicked (Button* button)
  63147. {
  63148. if (button == owner.getMinimiseButton())
  63149. owner.minimiseButtonPressed();
  63150. else if (button == owner.getMaximiseButton())
  63151. owner.maximiseButtonPressed();
  63152. else if (button == owner.getCloseButton())
  63153. owner.closeButtonPressed();
  63154. }
  63155. juce_UseDebuggingNewOperator
  63156. private:
  63157. DocumentWindow& owner;
  63158. ButtonListenerProxy (const ButtonListenerProxy&);
  63159. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  63160. };
  63161. DocumentWindow::DocumentWindow (const String& title,
  63162. const Colour& backgroundColour,
  63163. const int requiredButtons_,
  63164. const bool addToDesktop_)
  63165. : ResizableWindow (title, backgroundColour, addToDesktop_),
  63166. titleBarHeight (26),
  63167. menuBarHeight (24),
  63168. requiredButtons (requiredButtons_),
  63169. #if JUCE_MAC
  63170. positionTitleBarButtonsOnLeft (true),
  63171. #else
  63172. positionTitleBarButtonsOnLeft (false),
  63173. #endif
  63174. drawTitleTextCentred (true),
  63175. menuBarModel (0)
  63176. {
  63177. setResizeLimits (128, 128, 32768, 32768);
  63178. lookAndFeelChanged();
  63179. }
  63180. DocumentWindow::~DocumentWindow()
  63181. {
  63182. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63183. titleBarButtons[i] = 0;
  63184. menuBar = 0;
  63185. }
  63186. void DocumentWindow::repaintTitleBar()
  63187. {
  63188. repaint (getTitleBarArea());
  63189. }
  63190. void DocumentWindow::setName (const String& newName)
  63191. {
  63192. if (newName != getName())
  63193. {
  63194. Component::setName (newName);
  63195. repaintTitleBar();
  63196. }
  63197. }
  63198. void DocumentWindow::setIcon (const Image& imageToUse)
  63199. {
  63200. titleBarIcon = imageToUse;
  63201. repaintTitleBar();
  63202. }
  63203. void DocumentWindow::setTitleBarHeight (const int newHeight)
  63204. {
  63205. titleBarHeight = newHeight;
  63206. resized();
  63207. repaintTitleBar();
  63208. }
  63209. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  63210. const bool positionTitleBarButtonsOnLeft_)
  63211. {
  63212. requiredButtons = requiredButtons_;
  63213. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  63214. lookAndFeelChanged();
  63215. }
  63216. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  63217. {
  63218. drawTitleTextCentred = textShouldBeCentred;
  63219. repaintTitleBar();
  63220. }
  63221. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  63222. const int menuBarHeight_)
  63223. {
  63224. if (menuBarModel != menuBarModel_)
  63225. {
  63226. menuBar = 0;
  63227. menuBarModel = menuBarModel_;
  63228. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  63229. : getLookAndFeel().getDefaultMenuBarHeight();
  63230. if (menuBarModel != 0)
  63231. {
  63232. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63233. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  63234. menuBar->setEnabled (isActiveWindow());
  63235. }
  63236. resized();
  63237. }
  63238. }
  63239. void DocumentWindow::closeButtonPressed()
  63240. {
  63241. /* If you've got a close button, you have to override this method to get
  63242. rid of your window!
  63243. If the window is just a pop-up, you should override this method and make
  63244. it delete the window in whatever way is appropriate for your app. E.g. you
  63245. might just want to call "delete this".
  63246. If your app is centred around this window such that the whole app should quit when
  63247. the window is closed, then you will probably want to use this method as an opportunity
  63248. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  63249. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  63250. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  63251. or closing it via the taskbar icon on Windows).
  63252. */
  63253. jassertfalse;
  63254. }
  63255. void DocumentWindow::minimiseButtonPressed()
  63256. {
  63257. setMinimised (true);
  63258. }
  63259. void DocumentWindow::maximiseButtonPressed()
  63260. {
  63261. setFullScreen (! isFullScreen());
  63262. }
  63263. void DocumentWindow::paint (Graphics& g)
  63264. {
  63265. ResizableWindow::paint (g);
  63266. if (resizableBorder == 0)
  63267. {
  63268. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  63269. const BorderSize border (getBorderThickness());
  63270. g.fillRect (0, 0, getWidth(), border.getTop());
  63271. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  63272. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  63273. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  63274. }
  63275. const Rectangle<int> titleBarArea (getTitleBarArea());
  63276. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  63277. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  63278. int titleSpaceX1 = 6;
  63279. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  63280. for (int i = 0; i < 3; ++i)
  63281. {
  63282. if (titleBarButtons[i] != 0)
  63283. {
  63284. if (positionTitleBarButtonsOnLeft)
  63285. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  63286. else
  63287. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  63288. }
  63289. }
  63290. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  63291. titleBarArea.getWidth(),
  63292. titleBarArea.getHeight(),
  63293. titleSpaceX1,
  63294. jmax (1, titleSpaceX2 - titleSpaceX1),
  63295. titleBarIcon.isValid() ? &titleBarIcon : 0,
  63296. ! drawTitleTextCentred);
  63297. }
  63298. void DocumentWindow::resized()
  63299. {
  63300. ResizableWindow::resized();
  63301. if (titleBarButtons[1] != 0)
  63302. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  63303. const Rectangle<int> titleBarArea (getTitleBarArea());
  63304. getLookAndFeel()
  63305. .positionDocumentWindowButtons (*this,
  63306. titleBarArea.getX(), titleBarArea.getY(),
  63307. titleBarArea.getWidth(), titleBarArea.getHeight(),
  63308. titleBarButtons[0],
  63309. titleBarButtons[1],
  63310. titleBarButtons[2],
  63311. positionTitleBarButtonsOnLeft);
  63312. if (menuBar != 0)
  63313. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  63314. titleBarArea.getWidth(), menuBarHeight);
  63315. }
  63316. const BorderSize DocumentWindow::getBorderThickness()
  63317. {
  63318. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  63319. ? 0 : (resizableBorder != 0 ? 4 : 1));
  63320. }
  63321. const BorderSize DocumentWindow::getContentComponentBorder()
  63322. {
  63323. BorderSize border (getBorderThickness());
  63324. border.setTop (border.getTop()
  63325. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  63326. + (menuBar != 0 ? menuBarHeight : 0));
  63327. return border;
  63328. }
  63329. int DocumentWindow::getTitleBarHeight() const
  63330. {
  63331. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  63332. }
  63333. const Rectangle<int> DocumentWindow::getTitleBarArea()
  63334. {
  63335. const BorderSize border (getBorderThickness());
  63336. return Rectangle<int> (border.getLeft(), border.getTop(),
  63337. getWidth() - border.getLeftAndRight(),
  63338. getTitleBarHeight());
  63339. }
  63340. Button* DocumentWindow::getCloseButton() const throw()
  63341. {
  63342. return titleBarButtons[2];
  63343. }
  63344. Button* DocumentWindow::getMinimiseButton() const throw()
  63345. {
  63346. return titleBarButtons[0];
  63347. }
  63348. Button* DocumentWindow::getMaximiseButton() const throw()
  63349. {
  63350. return titleBarButtons[1];
  63351. }
  63352. int DocumentWindow::getDesktopWindowStyleFlags() const
  63353. {
  63354. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  63355. if ((requiredButtons & minimiseButton) != 0)
  63356. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  63357. if ((requiredButtons & maximiseButton) != 0)
  63358. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  63359. if ((requiredButtons & closeButton) != 0)
  63360. styleFlags |= ComponentPeer::windowHasCloseButton;
  63361. return styleFlags;
  63362. }
  63363. void DocumentWindow::lookAndFeelChanged()
  63364. {
  63365. int i;
  63366. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  63367. titleBarButtons[i] = 0;
  63368. if (! isUsingNativeTitleBar())
  63369. {
  63370. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  63371. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  63372. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  63373. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  63374. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  63375. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  63376. for (i = 0; i < 3; ++i)
  63377. {
  63378. if (titleBarButtons[i] != 0)
  63379. {
  63380. if (buttonListener == 0)
  63381. buttonListener = new ButtonListenerProxy (*this);
  63382. titleBarButtons[i]->addButtonListener (buttonListener);
  63383. titleBarButtons[i]->setWantsKeyboardFocus (false);
  63384. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63385. Component::addAndMakeVisible (titleBarButtons[i]);
  63386. }
  63387. }
  63388. if (getCloseButton() != 0)
  63389. {
  63390. #if JUCE_MAC
  63391. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  63392. #else
  63393. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  63394. #endif
  63395. }
  63396. }
  63397. activeWindowStatusChanged();
  63398. ResizableWindow::lookAndFeelChanged();
  63399. }
  63400. void DocumentWindow::parentHierarchyChanged()
  63401. {
  63402. lookAndFeelChanged();
  63403. }
  63404. void DocumentWindow::activeWindowStatusChanged()
  63405. {
  63406. ResizableWindow::activeWindowStatusChanged();
  63407. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63408. if (titleBarButtons[i] != 0)
  63409. titleBarButtons[i]->setEnabled (isActiveWindow());
  63410. if (menuBar != 0)
  63411. menuBar->setEnabled (isActiveWindow());
  63412. }
  63413. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  63414. {
  63415. if (getTitleBarArea().contains (e.x, e.y)
  63416. && getMaximiseButton() != 0)
  63417. {
  63418. getMaximiseButton()->triggerClick();
  63419. }
  63420. }
  63421. void DocumentWindow::userTriedToCloseWindow()
  63422. {
  63423. closeButtonPressed();
  63424. }
  63425. END_JUCE_NAMESPACE
  63426. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63427. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63428. BEGIN_JUCE_NAMESPACE
  63429. ResizableWindow::ResizableWindow (const String& name,
  63430. const bool addToDesktop_)
  63431. : TopLevelWindow (name, addToDesktop_),
  63432. resizeToFitContent (false),
  63433. fullscreen (false),
  63434. lastNonFullScreenPos (50, 50, 256, 256),
  63435. constrainer (0)
  63436. #if JUCE_DEBUG
  63437. , hasBeenResized (false)
  63438. #endif
  63439. {
  63440. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63441. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63442. if (addToDesktop_)
  63443. Component::addToDesktop (getDesktopWindowStyleFlags());
  63444. }
  63445. ResizableWindow::ResizableWindow (const String& name,
  63446. const Colour& backgroundColour_,
  63447. const bool addToDesktop_)
  63448. : TopLevelWindow (name, addToDesktop_),
  63449. resizeToFitContent (false),
  63450. fullscreen (false),
  63451. lastNonFullScreenPos (50, 50, 256, 256),
  63452. constrainer (0)
  63453. #if JUCE_DEBUG
  63454. , hasBeenResized (false)
  63455. #endif
  63456. {
  63457. setBackgroundColour (backgroundColour_);
  63458. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63459. if (addToDesktop_)
  63460. Component::addToDesktop (getDesktopWindowStyleFlags());
  63461. }
  63462. ResizableWindow::~ResizableWindow()
  63463. {
  63464. resizableCorner = 0;
  63465. resizableBorder = 0;
  63466. contentComponent.deleteAndZero();
  63467. // have you been adding your own components directly to this window..? tut tut tut.
  63468. // Read the instructions for using a ResizableWindow!
  63469. jassert (getNumChildComponents() == 0);
  63470. }
  63471. int ResizableWindow::getDesktopWindowStyleFlags() const
  63472. {
  63473. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63474. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63475. styleFlags |= ComponentPeer::windowIsResizable;
  63476. return styleFlags;
  63477. }
  63478. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63479. const bool deleteOldOne,
  63480. const bool resizeToFit)
  63481. {
  63482. resizeToFitContent = resizeToFit;
  63483. if (newContentComponent != static_cast <Component*> (contentComponent))
  63484. {
  63485. if (deleteOldOne)
  63486. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  63487. // external deletion of the content comp)
  63488. else
  63489. removeChildComponent (contentComponent);
  63490. contentComponent = newContentComponent;
  63491. Component::addAndMakeVisible (contentComponent);
  63492. }
  63493. if (resizeToFit)
  63494. childBoundsChanged (contentComponent);
  63495. resized(); // must always be called to position the new content comp
  63496. }
  63497. void ResizableWindow::setContentComponentSize (int width, int height)
  63498. {
  63499. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63500. const BorderSize border (getContentComponentBorder());
  63501. setSize (width + border.getLeftAndRight(),
  63502. height + border.getTopAndBottom());
  63503. }
  63504. const BorderSize ResizableWindow::getBorderThickness()
  63505. {
  63506. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63507. }
  63508. const BorderSize ResizableWindow::getContentComponentBorder()
  63509. {
  63510. return getBorderThickness();
  63511. }
  63512. void ResizableWindow::moved()
  63513. {
  63514. updateLastPos();
  63515. }
  63516. void ResizableWindow::visibilityChanged()
  63517. {
  63518. TopLevelWindow::visibilityChanged();
  63519. updateLastPos();
  63520. }
  63521. void ResizableWindow::resized()
  63522. {
  63523. if (resizableBorder != 0)
  63524. {
  63525. #if JUCE_WINDOWS || JUCE_LINUX
  63526. // hide the resizable border if the OS already provides one..
  63527. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63528. #else
  63529. resizableBorder->setVisible (! isFullScreen());
  63530. #endif
  63531. resizableBorder->setBorderThickness (getBorderThickness());
  63532. resizableBorder->setSize (getWidth(), getHeight());
  63533. resizableBorder->toBack();
  63534. }
  63535. if (resizableCorner != 0)
  63536. {
  63537. #if JUCE_MAC
  63538. // hide the resizable border if the OS already provides one..
  63539. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63540. #else
  63541. resizableCorner->setVisible (! isFullScreen());
  63542. #endif
  63543. const int resizerSize = 18;
  63544. resizableCorner->setBounds (getWidth() - resizerSize,
  63545. getHeight() - resizerSize,
  63546. resizerSize, resizerSize);
  63547. }
  63548. if (contentComponent != 0)
  63549. contentComponent->setBoundsInset (getContentComponentBorder());
  63550. updateLastPos();
  63551. #if JUCE_DEBUG
  63552. hasBeenResized = true;
  63553. #endif
  63554. }
  63555. void ResizableWindow::childBoundsChanged (Component* child)
  63556. {
  63557. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63558. {
  63559. // not going to look very good if this component has a zero size..
  63560. jassert (child->getWidth() > 0);
  63561. jassert (child->getHeight() > 0);
  63562. const BorderSize borders (getContentComponentBorder());
  63563. setSize (child->getWidth() + borders.getLeftAndRight(),
  63564. child->getHeight() + borders.getTopAndBottom());
  63565. }
  63566. }
  63567. void ResizableWindow::activeWindowStatusChanged()
  63568. {
  63569. const BorderSize border (getContentComponentBorder());
  63570. Rectangle<int> area (getLocalBounds());
  63571. repaint (area.removeFromTop (border.getTop()));
  63572. repaint (area.removeFromLeft (border.getLeft()));
  63573. repaint (area.removeFromRight (border.getRight()));
  63574. repaint (area.removeFromBottom (border.getBottom()));
  63575. }
  63576. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63577. const bool useBottomRightCornerResizer)
  63578. {
  63579. if (shouldBeResizable)
  63580. {
  63581. if (useBottomRightCornerResizer)
  63582. {
  63583. resizableBorder = 0;
  63584. if (resizableCorner == 0)
  63585. {
  63586. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63587. resizableCorner->setAlwaysOnTop (true);
  63588. }
  63589. }
  63590. else
  63591. {
  63592. resizableCorner = 0;
  63593. if (resizableBorder == 0)
  63594. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63595. }
  63596. }
  63597. else
  63598. {
  63599. resizableCorner = 0;
  63600. resizableBorder = 0;
  63601. }
  63602. if (isUsingNativeTitleBar())
  63603. recreateDesktopWindow();
  63604. childBoundsChanged (contentComponent);
  63605. resized();
  63606. }
  63607. bool ResizableWindow::isResizable() const throw()
  63608. {
  63609. return resizableCorner != 0
  63610. || resizableBorder != 0;
  63611. }
  63612. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63613. const int newMinimumHeight,
  63614. const int newMaximumWidth,
  63615. const int newMaximumHeight) throw()
  63616. {
  63617. // if you've set up a custom constrainer then these settings won't have any effect..
  63618. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63619. if (constrainer == 0)
  63620. setConstrainer (&defaultConstrainer);
  63621. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63622. newMaximumWidth, newMaximumHeight);
  63623. setBoundsConstrained (getBounds());
  63624. }
  63625. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63626. {
  63627. if (constrainer != newConstrainer)
  63628. {
  63629. constrainer = newConstrainer;
  63630. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63631. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63632. resizableCorner = 0;
  63633. resizableBorder = 0;
  63634. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63635. ComponentPeer* const peer = getPeer();
  63636. if (peer != 0)
  63637. peer->setConstrainer (newConstrainer);
  63638. }
  63639. }
  63640. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63641. {
  63642. if (constrainer != 0)
  63643. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63644. else
  63645. setBounds (bounds);
  63646. }
  63647. void ResizableWindow::paint (Graphics& g)
  63648. {
  63649. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63650. getBorderThickness(), *this);
  63651. if (! isFullScreen())
  63652. {
  63653. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63654. getBorderThickness(), *this);
  63655. }
  63656. #if JUCE_DEBUG
  63657. /* If this fails, then you've probably written a subclass with a resized()
  63658. callback but forgotten to make it call its parent class's resized() method.
  63659. It's important when you override methods like resized(), moved(),
  63660. etc., that you make sure the base class methods also get called.
  63661. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63662. because your content should all be inside the content component - and it's the
  63663. content component's resized() method that you should be using to do your
  63664. layout.
  63665. */
  63666. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63667. #endif
  63668. }
  63669. void ResizableWindow::lookAndFeelChanged()
  63670. {
  63671. resized();
  63672. if (isOnDesktop())
  63673. {
  63674. Component::addToDesktop (getDesktopWindowStyleFlags());
  63675. ComponentPeer* const peer = getPeer();
  63676. if (peer != 0)
  63677. peer->setConstrainer (constrainer);
  63678. }
  63679. }
  63680. const Colour ResizableWindow::getBackgroundColour() const throw()
  63681. {
  63682. return findColour (backgroundColourId, false);
  63683. }
  63684. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63685. {
  63686. Colour backgroundColour (newColour);
  63687. if (! Desktop::canUseSemiTransparentWindows())
  63688. backgroundColour = newColour.withAlpha (1.0f);
  63689. setColour (backgroundColourId, backgroundColour);
  63690. setOpaque (backgroundColour.isOpaque());
  63691. repaint();
  63692. }
  63693. bool ResizableWindow::isFullScreen() const
  63694. {
  63695. if (isOnDesktop())
  63696. {
  63697. ComponentPeer* const peer = getPeer();
  63698. return peer != 0 && peer->isFullScreen();
  63699. }
  63700. return fullscreen;
  63701. }
  63702. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63703. {
  63704. if (shouldBeFullScreen != isFullScreen())
  63705. {
  63706. updateLastPos();
  63707. fullscreen = shouldBeFullScreen;
  63708. if (isOnDesktop())
  63709. {
  63710. ComponentPeer* const peer = getPeer();
  63711. if (peer != 0)
  63712. {
  63713. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63714. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63715. peer->setFullScreen (shouldBeFullScreen);
  63716. if (! shouldBeFullScreen)
  63717. setBounds (lastPos);
  63718. }
  63719. else
  63720. {
  63721. jassertfalse;
  63722. }
  63723. }
  63724. else
  63725. {
  63726. if (shouldBeFullScreen)
  63727. setBounds (0, 0, getParentWidth(), getParentHeight());
  63728. else
  63729. setBounds (lastNonFullScreenPos);
  63730. }
  63731. resized();
  63732. }
  63733. }
  63734. bool ResizableWindow::isMinimised() const
  63735. {
  63736. ComponentPeer* const peer = getPeer();
  63737. return (peer != 0) && peer->isMinimised();
  63738. }
  63739. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63740. {
  63741. if (shouldMinimise != isMinimised())
  63742. {
  63743. ComponentPeer* const peer = getPeer();
  63744. if (peer != 0)
  63745. {
  63746. updateLastPos();
  63747. peer->setMinimised (shouldMinimise);
  63748. }
  63749. else
  63750. {
  63751. jassertfalse;
  63752. }
  63753. }
  63754. }
  63755. void ResizableWindow::updateLastPos()
  63756. {
  63757. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63758. {
  63759. lastNonFullScreenPos = getBounds();
  63760. }
  63761. }
  63762. void ResizableWindow::parentSizeChanged()
  63763. {
  63764. if (isFullScreen() && getParentComponent() != 0)
  63765. {
  63766. setBounds (0, 0, getParentWidth(), getParentHeight());
  63767. }
  63768. }
  63769. const String ResizableWindow::getWindowStateAsString()
  63770. {
  63771. updateLastPos();
  63772. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63773. }
  63774. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63775. {
  63776. StringArray tokens;
  63777. tokens.addTokens (s, false);
  63778. tokens.removeEmptyStrings();
  63779. tokens.trim();
  63780. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63781. const int firstCoord = fs ? 1 : 0;
  63782. if (tokens.size() != firstCoord + 4)
  63783. return false;
  63784. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63785. tokens[firstCoord + 1].getIntValue(),
  63786. tokens[firstCoord + 2].getIntValue(),
  63787. tokens[firstCoord + 3].getIntValue());
  63788. if (newPos.isEmpty())
  63789. return false;
  63790. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63791. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63792. if (peer != 0)
  63793. peer->getFrameSize().addTo (newPos);
  63794. if (! screen.contains (newPos))
  63795. {
  63796. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63797. jmin (newPos.getHeight(), screen.getHeight()));
  63798. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63799. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63800. }
  63801. if (peer != 0)
  63802. {
  63803. peer->getFrameSize().subtractFrom (newPos);
  63804. peer->setNonFullScreenBounds (newPos);
  63805. }
  63806. lastNonFullScreenPos = newPos;
  63807. setFullScreen (fs);
  63808. if (! fs)
  63809. setBoundsConstrained (newPos);
  63810. return true;
  63811. }
  63812. void ResizableWindow::mouseDown (const MouseEvent&)
  63813. {
  63814. if (! isFullScreen())
  63815. dragger.startDraggingComponent (this, constrainer);
  63816. }
  63817. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63818. {
  63819. if (! isFullScreen())
  63820. dragger.dragComponent (this, e);
  63821. }
  63822. #if JUCE_DEBUG
  63823. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63824. {
  63825. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63826. manages its child components automatically, and if you add your own it'll cause
  63827. trouble. Instead, use setContentComponent() to give it a component which
  63828. will be automatically resized and kept in the right place - then you can add
  63829. subcomponents to the content comp. See the notes for the ResizableWindow class
  63830. for more info.
  63831. If you really know what you're doing and want to avoid this assertion, just call
  63832. Component::addChildComponent directly.
  63833. */
  63834. jassertfalse;
  63835. Component::addChildComponent (child, zOrder);
  63836. }
  63837. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63838. {
  63839. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63840. manages its child components automatically, and if you add your own it'll cause
  63841. trouble. Instead, use setContentComponent() to give it a component which
  63842. will be automatically resized and kept in the right place - then you can add
  63843. subcomponents to the content comp. See the notes for the ResizableWindow class
  63844. for more info.
  63845. If you really know what you're doing and want to avoid this assertion, just call
  63846. Component::addAndMakeVisible directly.
  63847. */
  63848. jassertfalse;
  63849. Component::addAndMakeVisible (child, zOrder);
  63850. }
  63851. #endif
  63852. END_JUCE_NAMESPACE
  63853. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63854. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63855. BEGIN_JUCE_NAMESPACE
  63856. SplashScreen::SplashScreen()
  63857. {
  63858. setOpaque (true);
  63859. }
  63860. SplashScreen::~SplashScreen()
  63861. {
  63862. }
  63863. void SplashScreen::show (const String& title,
  63864. const Image& backgroundImage_,
  63865. const int minimumTimeToDisplayFor,
  63866. const bool useDropShadow,
  63867. const bool removeOnMouseClick)
  63868. {
  63869. backgroundImage = backgroundImage_;
  63870. jassert (backgroundImage_.isValid());
  63871. if (backgroundImage_.isValid())
  63872. {
  63873. setOpaque (! backgroundImage_.hasAlphaChannel());
  63874. show (title,
  63875. backgroundImage_.getWidth(),
  63876. backgroundImage_.getHeight(),
  63877. minimumTimeToDisplayFor,
  63878. useDropShadow,
  63879. removeOnMouseClick);
  63880. }
  63881. }
  63882. void SplashScreen::show (const String& title,
  63883. const int width,
  63884. const int height,
  63885. const int minimumTimeToDisplayFor,
  63886. const bool useDropShadow,
  63887. const bool removeOnMouseClick)
  63888. {
  63889. setName (title);
  63890. setAlwaysOnTop (true);
  63891. setVisible (true);
  63892. centreWithSize (width, height);
  63893. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63894. toFront (false);
  63895. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63896. repaint();
  63897. originalClickCounter = removeOnMouseClick
  63898. ? Desktop::getMouseButtonClickCounter()
  63899. : std::numeric_limits<int>::max();
  63900. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63901. startTimer (50);
  63902. }
  63903. void SplashScreen::paint (Graphics& g)
  63904. {
  63905. g.setOpacity (1.0f);
  63906. g.drawImage (backgroundImage,
  63907. 0, 0, getWidth(), getHeight(),
  63908. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63909. }
  63910. void SplashScreen::timerCallback()
  63911. {
  63912. if (Time::getCurrentTime() > earliestTimeToDelete
  63913. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63914. {
  63915. delete this;
  63916. }
  63917. }
  63918. END_JUCE_NAMESPACE
  63919. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63920. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63921. BEGIN_JUCE_NAMESPACE
  63922. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63923. const bool hasProgressBar,
  63924. const bool hasCancelButton,
  63925. const int timeOutMsWhenCancelling_,
  63926. const String& cancelButtonText)
  63927. : Thread ("Juce Progress Window"),
  63928. progress (0.0),
  63929. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63930. {
  63931. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63932. .createAlertWindow (title, String::empty, cancelButtonText,
  63933. String::empty, String::empty,
  63934. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63935. if (hasProgressBar)
  63936. alertWindow->addProgressBarComponent (progress);
  63937. }
  63938. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63939. {
  63940. stopThread (timeOutMsWhenCancelling);
  63941. }
  63942. bool ThreadWithProgressWindow::runThread (const int priority)
  63943. {
  63944. startThread (priority);
  63945. startTimer (100);
  63946. {
  63947. const ScopedLock sl (messageLock);
  63948. alertWindow->setMessage (message);
  63949. }
  63950. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63951. stopThread (timeOutMsWhenCancelling);
  63952. alertWindow->setVisible (false);
  63953. return finishedNaturally;
  63954. }
  63955. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63956. {
  63957. progress = newProgress;
  63958. }
  63959. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63960. {
  63961. const ScopedLock sl (messageLock);
  63962. message = newStatusMessage;
  63963. }
  63964. void ThreadWithProgressWindow::timerCallback()
  63965. {
  63966. if (! isThreadRunning())
  63967. {
  63968. // thread has finished normally..
  63969. alertWindow->exitModalState (1);
  63970. alertWindow->setVisible (false);
  63971. }
  63972. else
  63973. {
  63974. const ScopedLock sl (messageLock);
  63975. alertWindow->setMessage (message);
  63976. }
  63977. }
  63978. END_JUCE_NAMESPACE
  63979. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63980. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63981. BEGIN_JUCE_NAMESPACE
  63982. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63983. const int millisecondsBeforeTipAppears_)
  63984. : Component ("tooltip"),
  63985. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63986. mouseClicks (0),
  63987. lastHideTime (0),
  63988. lastComponentUnderMouse (0),
  63989. changedCompsSinceShown (true)
  63990. {
  63991. if (Desktop::getInstance().getMainMouseSource().canHover())
  63992. startTimer (123);
  63993. setAlwaysOnTop (true);
  63994. setOpaque (true);
  63995. if (parentComponent != 0)
  63996. parentComponent->addChildComponent (this);
  63997. }
  63998. TooltipWindow::~TooltipWindow()
  63999. {
  64000. hide();
  64001. }
  64002. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  64003. {
  64004. millisecondsBeforeTipAppears = newTimeMs;
  64005. }
  64006. void TooltipWindow::paint (Graphics& g)
  64007. {
  64008. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  64009. }
  64010. void TooltipWindow::mouseEnter (const MouseEvent&)
  64011. {
  64012. hide();
  64013. }
  64014. void TooltipWindow::showFor (const String& tip)
  64015. {
  64016. jassert (tip.isNotEmpty());
  64017. if (tipShowing != tip)
  64018. repaint();
  64019. tipShowing = tip;
  64020. Point<int> mousePos (Desktop::getMousePosition());
  64021. if (getParentComponent() != 0)
  64022. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  64023. int x, y, w, h;
  64024. getLookAndFeel().getTooltipSize (tip, w, h);
  64025. if (mousePos.getX() > getParentWidth() / 2)
  64026. x = mousePos.getX() - (w + 12);
  64027. else
  64028. x = mousePos.getX() + 24;
  64029. if (mousePos.getY() > getParentHeight() / 2)
  64030. y = mousePos.getY() - (h + 6);
  64031. else
  64032. y = mousePos.getY() + 6;
  64033. setBounds (x, y, w, h);
  64034. setVisible (true);
  64035. if (getParentComponent() == 0)
  64036. {
  64037. addToDesktop (ComponentPeer::windowHasDropShadow
  64038. | ComponentPeer::windowIsTemporary
  64039. | ComponentPeer::windowIgnoresKeyPresses);
  64040. }
  64041. toFront (false);
  64042. }
  64043. const String TooltipWindow::getTipFor (Component* const c)
  64044. {
  64045. if (c != 0
  64046. && Process::isForegroundProcess()
  64047. && ! Component::isMouseButtonDownAnywhere())
  64048. {
  64049. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  64050. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  64051. return ttc->getTooltip();
  64052. }
  64053. return String::empty;
  64054. }
  64055. void TooltipWindow::hide()
  64056. {
  64057. tipShowing = String::empty;
  64058. removeFromDesktop();
  64059. setVisible (false);
  64060. }
  64061. void TooltipWindow::timerCallback()
  64062. {
  64063. const unsigned int now = Time::getApproximateMillisecondCounter();
  64064. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  64065. const String newTip (getTipFor (newComp));
  64066. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  64067. lastComponentUnderMouse = newComp;
  64068. lastTipUnderMouse = newTip;
  64069. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  64070. const bool mouseWasClicked = clickCount > mouseClicks;
  64071. mouseClicks = clickCount;
  64072. const Point<int> mousePos (Desktop::getMousePosition());
  64073. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  64074. lastMousePos = mousePos;
  64075. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  64076. lastCompChangeTime = now;
  64077. if (isVisible() || now < lastHideTime + 500)
  64078. {
  64079. // if a tip is currently visible (or has just disappeared), update to a new one
  64080. // immediately if needed..
  64081. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  64082. {
  64083. if (isVisible())
  64084. {
  64085. lastHideTime = now;
  64086. hide();
  64087. }
  64088. }
  64089. else if (tipChanged)
  64090. {
  64091. showFor (newTip);
  64092. }
  64093. }
  64094. else
  64095. {
  64096. // if there isn't currently a tip, but one is needed, only let it
  64097. // appear after a timeout..
  64098. if (newTip.isNotEmpty()
  64099. && newTip != tipShowing
  64100. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  64101. {
  64102. showFor (newTip);
  64103. }
  64104. }
  64105. }
  64106. END_JUCE_NAMESPACE
  64107. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  64108. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  64109. BEGIN_JUCE_NAMESPACE
  64110. /** Keeps track of the active top level window.
  64111. */
  64112. class TopLevelWindowManager : public Timer,
  64113. public DeletedAtShutdown
  64114. {
  64115. public:
  64116. TopLevelWindowManager()
  64117. : currentActive (0)
  64118. {
  64119. }
  64120. ~TopLevelWindowManager()
  64121. {
  64122. clearSingletonInstance();
  64123. }
  64124. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  64125. void timerCallback()
  64126. {
  64127. startTimer (jmin (1731, getTimerInterval() * 2));
  64128. TopLevelWindow* active = 0;
  64129. if (Process::isForegroundProcess())
  64130. {
  64131. active = currentActive;
  64132. Component* const c = Component::getCurrentlyFocusedComponent();
  64133. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  64134. if (tlw == 0 && c != 0)
  64135. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  64136. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  64137. if (tlw != 0)
  64138. active = tlw;
  64139. }
  64140. if (active != currentActive)
  64141. {
  64142. currentActive = active;
  64143. for (int i = windows.size(); --i >= 0;)
  64144. {
  64145. TopLevelWindow* const tlw = windows.getUnchecked (i);
  64146. tlw->setWindowActive (isWindowActive (tlw));
  64147. i = jmin (i, windows.size() - 1);
  64148. }
  64149. Desktop::getInstance().triggerFocusCallback();
  64150. }
  64151. }
  64152. bool addWindow (TopLevelWindow* const w)
  64153. {
  64154. windows.add (w);
  64155. startTimer (10);
  64156. return isWindowActive (w);
  64157. }
  64158. void removeWindow (TopLevelWindow* const w)
  64159. {
  64160. startTimer (10);
  64161. if (currentActive == w)
  64162. currentActive = 0;
  64163. windows.removeValue (w);
  64164. if (windows.size() == 0)
  64165. deleteInstance();
  64166. }
  64167. Array <TopLevelWindow*> windows;
  64168. private:
  64169. TopLevelWindow* currentActive;
  64170. bool isWindowActive (TopLevelWindow* const tlw) const
  64171. {
  64172. return (tlw == currentActive
  64173. || tlw->isParentOf (currentActive)
  64174. || tlw->hasKeyboardFocus (true))
  64175. && tlw->isShowing();
  64176. }
  64177. TopLevelWindowManager (const TopLevelWindowManager&);
  64178. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  64179. };
  64180. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  64181. void juce_CheckCurrentlyFocusedTopLevelWindow()
  64182. {
  64183. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  64184. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  64185. }
  64186. TopLevelWindow::TopLevelWindow (const String& name,
  64187. const bool addToDesktop_)
  64188. : Component (name),
  64189. useDropShadow (true),
  64190. useNativeTitleBar (false),
  64191. windowIsActive_ (false)
  64192. {
  64193. setOpaque (true);
  64194. if (addToDesktop_)
  64195. Component::addToDesktop (getDesktopWindowStyleFlags());
  64196. else
  64197. setDropShadowEnabled (true);
  64198. setWantsKeyboardFocus (true);
  64199. setBroughtToFrontOnMouseClick (true);
  64200. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  64201. }
  64202. TopLevelWindow::~TopLevelWindow()
  64203. {
  64204. shadower = 0;
  64205. TopLevelWindowManager::getInstance()->removeWindow (this);
  64206. }
  64207. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  64208. {
  64209. if (hasKeyboardFocus (true))
  64210. TopLevelWindowManager::getInstance()->timerCallback();
  64211. else
  64212. TopLevelWindowManager::getInstance()->startTimer (10);
  64213. }
  64214. void TopLevelWindow::setWindowActive (const bool isNowActive)
  64215. {
  64216. if (windowIsActive_ != isNowActive)
  64217. {
  64218. windowIsActive_ = isNowActive;
  64219. activeWindowStatusChanged();
  64220. }
  64221. }
  64222. void TopLevelWindow::activeWindowStatusChanged()
  64223. {
  64224. }
  64225. void TopLevelWindow::parentHierarchyChanged()
  64226. {
  64227. setDropShadowEnabled (useDropShadow);
  64228. }
  64229. void TopLevelWindow::visibilityChanged()
  64230. {
  64231. if (isShowing())
  64232. toFront (true);
  64233. }
  64234. int TopLevelWindow::getDesktopWindowStyleFlags() const
  64235. {
  64236. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  64237. if (useDropShadow)
  64238. styleFlags |= ComponentPeer::windowHasDropShadow;
  64239. if (useNativeTitleBar)
  64240. styleFlags |= ComponentPeer::windowHasTitleBar;
  64241. return styleFlags;
  64242. }
  64243. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  64244. {
  64245. useDropShadow = useShadow;
  64246. if (isOnDesktop())
  64247. {
  64248. shadower = 0;
  64249. Component::addToDesktop (getDesktopWindowStyleFlags());
  64250. }
  64251. else
  64252. {
  64253. if (useShadow && isOpaque())
  64254. {
  64255. if (shadower == 0)
  64256. {
  64257. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  64258. if (shadower != 0)
  64259. shadower->setOwner (this);
  64260. }
  64261. }
  64262. else
  64263. {
  64264. shadower = 0;
  64265. }
  64266. }
  64267. }
  64268. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  64269. {
  64270. if (useNativeTitleBar != useNativeTitleBar_)
  64271. {
  64272. useNativeTitleBar = useNativeTitleBar_;
  64273. recreateDesktopWindow();
  64274. sendLookAndFeelChange();
  64275. }
  64276. }
  64277. void TopLevelWindow::recreateDesktopWindow()
  64278. {
  64279. if (isOnDesktop())
  64280. {
  64281. Component::addToDesktop (getDesktopWindowStyleFlags());
  64282. toFront (true);
  64283. }
  64284. }
  64285. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  64286. {
  64287. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  64288. because this class needs to make sure its layout corresponds with settings like whether
  64289. it's got a native title bar or not.
  64290. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  64291. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  64292. method, then add or remove whatever flags are necessary from this value before returning it.
  64293. */
  64294. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  64295. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  64296. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  64297. if (windowStyleFlags != getDesktopWindowStyleFlags())
  64298. sendLookAndFeelChange();
  64299. }
  64300. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  64301. {
  64302. if (c == 0)
  64303. c = TopLevelWindow::getActiveTopLevelWindow();
  64304. if (c == 0)
  64305. {
  64306. centreWithSize (width, height);
  64307. }
  64308. else
  64309. {
  64310. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  64311. (c->getHeight() - height) / 2)));
  64312. Rectangle<int> parentArea (c->getParentMonitorArea());
  64313. if (getParentComponent() != 0)
  64314. {
  64315. p = getParentComponent()->globalPositionToRelative (p);
  64316. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  64317. }
  64318. parentArea.reduce (12, 12);
  64319. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  64320. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  64321. width, height);
  64322. }
  64323. }
  64324. int TopLevelWindow::getNumTopLevelWindows() throw()
  64325. {
  64326. return TopLevelWindowManager::getInstance()->windows.size();
  64327. }
  64328. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  64329. {
  64330. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  64331. }
  64332. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  64333. {
  64334. TopLevelWindow* best = 0;
  64335. int bestNumTWLParents = -1;
  64336. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  64337. {
  64338. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  64339. if (tlw->isActiveWindow())
  64340. {
  64341. int numTWLParents = 0;
  64342. const Component* c = tlw->getParentComponent();
  64343. while (c != 0)
  64344. {
  64345. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  64346. ++numTWLParents;
  64347. c = c->getParentComponent();
  64348. }
  64349. if (bestNumTWLParents < numTWLParents)
  64350. {
  64351. best = tlw;
  64352. bestNumTWLParents = numTWLParents;
  64353. }
  64354. }
  64355. }
  64356. return best;
  64357. }
  64358. END_JUCE_NAMESPACE
  64359. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  64360. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  64361. BEGIN_JUCE_NAMESPACE
  64362. namespace RelativeCoordinateHelpers
  64363. {
  64364. static void skipComma (const juce_wchar* const s, int& i)
  64365. {
  64366. while (CharacterFunctions::isWhitespace (s[i]))
  64367. ++i;
  64368. if (s[i] == ',')
  64369. ++i;
  64370. }
  64371. }
  64372. const String RelativeCoordinate::Strings::parent ("parent");
  64373. const String RelativeCoordinate::Strings::left ("left");
  64374. const String RelativeCoordinate::Strings::right ("right");
  64375. const String RelativeCoordinate::Strings::top ("top");
  64376. const String RelativeCoordinate::Strings::bottom ("bottom");
  64377. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  64378. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  64379. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  64380. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  64381. RelativeCoordinate::RelativeCoordinate()
  64382. {
  64383. }
  64384. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  64385. : term (term_)
  64386. {
  64387. }
  64388. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  64389. : term (other.term)
  64390. {
  64391. }
  64392. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  64393. {
  64394. term = other.term;
  64395. return *this;
  64396. }
  64397. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  64398. : term (absoluteDistanceFromOrigin)
  64399. {
  64400. }
  64401. RelativeCoordinate::RelativeCoordinate (const String& s)
  64402. {
  64403. try
  64404. {
  64405. term = Expression (s);
  64406. }
  64407. catch (...)
  64408. {}
  64409. }
  64410. RelativeCoordinate::~RelativeCoordinate()
  64411. {
  64412. }
  64413. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64414. {
  64415. return term.toString() == other.term.toString();
  64416. }
  64417. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64418. {
  64419. return ! operator== (other);
  64420. }
  64421. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  64422. {
  64423. try
  64424. {
  64425. if (context != 0)
  64426. return term.evaluate (*context);
  64427. else
  64428. return term.evaluate();
  64429. }
  64430. catch (...)
  64431. {}
  64432. return 0.0;
  64433. }
  64434. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  64435. {
  64436. try
  64437. {
  64438. if (context != 0)
  64439. term.evaluate (*context);
  64440. else
  64441. term.evaluate();
  64442. }
  64443. catch (...)
  64444. {
  64445. return true;
  64446. }
  64447. return false;
  64448. }
  64449. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  64450. {
  64451. try
  64452. {
  64453. if (context != 0)
  64454. {
  64455. term = term.adjustedToGiveNewResult (newPos, *context);
  64456. }
  64457. else
  64458. {
  64459. Expression::EvaluationContext defaultContext;
  64460. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  64461. }
  64462. }
  64463. catch (...)
  64464. {}
  64465. }
  64466. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  64467. {
  64468. try
  64469. {
  64470. return term.referencesSymbol (coordName, context);
  64471. }
  64472. catch (...)
  64473. {}
  64474. return false;
  64475. }
  64476. bool RelativeCoordinate::isDynamic() const
  64477. {
  64478. return term.usesAnySymbols();
  64479. }
  64480. const String RelativeCoordinate::toString() const
  64481. {
  64482. return term.toString();
  64483. }
  64484. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName)
  64485. {
  64486. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  64487. if (term.referencesSymbol (oldName, 0))
  64488. term = term.withRenamedSymbol (oldName, newName);
  64489. }
  64490. RelativePoint::RelativePoint()
  64491. {
  64492. }
  64493. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64494. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64495. {
  64496. }
  64497. RelativePoint::RelativePoint (const float x_, const float y_)
  64498. : x (x_), y (y_)
  64499. {
  64500. }
  64501. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64502. : x (x_), y (y_)
  64503. {
  64504. }
  64505. RelativePoint::RelativePoint (const String& s)
  64506. {
  64507. int i = 0;
  64508. x = RelativeCoordinate (Expression::parse (s, i));
  64509. RelativeCoordinateHelpers::skipComma (s, i);
  64510. y = RelativeCoordinate (Expression::parse (s, i));
  64511. }
  64512. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64513. {
  64514. return x == other.x && y == other.y;
  64515. }
  64516. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64517. {
  64518. return ! operator== (other);
  64519. }
  64520. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64521. {
  64522. return Point<float> ((float) x.resolve (context),
  64523. (float) y.resolve (context));
  64524. }
  64525. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64526. {
  64527. x.moveToAbsolute (newPos.getX(), context);
  64528. y.moveToAbsolute (newPos.getY(), context);
  64529. }
  64530. const String RelativePoint::toString() const
  64531. {
  64532. return x.toString() + ", " + y.toString();
  64533. }
  64534. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName)
  64535. {
  64536. x.renameSymbolIfUsed (oldName, newName);
  64537. y.renameSymbolIfUsed (oldName, newName);
  64538. }
  64539. bool RelativePoint::isDynamic() const
  64540. {
  64541. return x.isDynamic() || y.isDynamic();
  64542. }
  64543. RelativeRectangle::RelativeRectangle()
  64544. {
  64545. }
  64546. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64547. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64548. : left (left_), right (right_), top (top_), bottom (bottom_)
  64549. {
  64550. }
  64551. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  64552. : left (rect.getX()),
  64553. right (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64554. top (rect.getY()),
  64555. bottom (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64556. {
  64557. }
  64558. RelativeRectangle::RelativeRectangle (const String& s)
  64559. {
  64560. int i = 0;
  64561. left = RelativeCoordinate (Expression::parse (s, i));
  64562. RelativeCoordinateHelpers::skipComma (s, i);
  64563. top = RelativeCoordinate (Expression::parse (s, i));
  64564. RelativeCoordinateHelpers::skipComma (s, i);
  64565. right = RelativeCoordinate (Expression::parse (s, i));
  64566. RelativeCoordinateHelpers::skipComma (s, i);
  64567. bottom = RelativeCoordinate (Expression::parse (s, i));
  64568. }
  64569. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64570. {
  64571. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64572. }
  64573. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64574. {
  64575. return ! operator== (other);
  64576. }
  64577. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64578. {
  64579. const double l = left.resolve (context);
  64580. const double r = right.resolve (context);
  64581. const double t = top.resolve (context);
  64582. const double b = bottom.resolve (context);
  64583. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  64584. }
  64585. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64586. {
  64587. left.moveToAbsolute (newPos.getX(), context);
  64588. right.moveToAbsolute (newPos.getRight(), context);
  64589. top.moveToAbsolute (newPos.getY(), context);
  64590. bottom.moveToAbsolute (newPos.getBottom(), context);
  64591. }
  64592. const String RelativeRectangle::toString() const
  64593. {
  64594. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64595. }
  64596. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName)
  64597. {
  64598. left.renameSymbolIfUsed (oldName, newName);
  64599. right.renameSymbolIfUsed (oldName, newName);
  64600. top.renameSymbolIfUsed (oldName, newName);
  64601. bottom.renameSymbolIfUsed (oldName, newName);
  64602. }
  64603. RelativePointPath::RelativePointPath()
  64604. : usesNonZeroWinding (true),
  64605. containsDynamicPoints (false)
  64606. {
  64607. }
  64608. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64609. : usesNonZeroWinding (true),
  64610. containsDynamicPoints (false)
  64611. {
  64612. ValueTree state (DrawablePath::valueTreeType);
  64613. other.writeTo (state, 0);
  64614. parse (state);
  64615. }
  64616. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64617. : usesNonZeroWinding (true),
  64618. containsDynamicPoints (false)
  64619. {
  64620. parse (drawable);
  64621. }
  64622. RelativePointPath::RelativePointPath (const Path& path)
  64623. {
  64624. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64625. Path::Iterator i (path);
  64626. while (i.next())
  64627. {
  64628. switch (i.elementType)
  64629. {
  64630. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64631. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64632. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64633. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64634. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64635. default: jassertfalse; break;
  64636. }
  64637. }
  64638. }
  64639. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64640. {
  64641. DrawablePath::ValueTreeWrapper wrapper (state);
  64642. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64643. ValueTree pathTree (wrapper.getPathState());
  64644. pathTree.removeAllChildren (undoManager);
  64645. for (int i = 0; i < elements.size(); ++i)
  64646. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64647. }
  64648. void RelativePointPath::parse (const ValueTree& state)
  64649. {
  64650. DrawablePath::ValueTreeWrapper wrapper (state);
  64651. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64652. RelativePoint points[3];
  64653. const ValueTree pathTree (wrapper.getPathState());
  64654. const int num = pathTree.getNumChildren();
  64655. for (int i = 0; i < num; ++i)
  64656. {
  64657. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64658. const int numCps = e.getNumControlPoints();
  64659. for (int j = 0; j < numCps; ++j)
  64660. {
  64661. points[j] = e.getControlPoint (j);
  64662. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64663. }
  64664. const Identifier type (e.getType());
  64665. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64666. elements.add (new StartSubPath (points[0]));
  64667. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64668. elements.add (new CloseSubPath());
  64669. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64670. elements.add (new LineTo (points[0]));
  64671. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64672. elements.add (new QuadraticTo (points[0], points[1]));
  64673. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64674. elements.add (new CubicTo (points[0], points[1], points[2]));
  64675. else
  64676. jassertfalse;
  64677. }
  64678. }
  64679. RelativePointPath::~RelativePointPath()
  64680. {
  64681. }
  64682. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64683. {
  64684. elements.swapWithArray (other.elements);
  64685. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64686. }
  64687. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder)
  64688. {
  64689. for (int i = 0; i < elements.size(); ++i)
  64690. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64691. }
  64692. bool RelativePointPath::containsAnyDynamicPoints() const
  64693. {
  64694. return containsDynamicPoints;
  64695. }
  64696. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64697. {
  64698. }
  64699. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64700. : ElementBase (startSubPathElement), startPos (pos)
  64701. {
  64702. }
  64703. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64704. {
  64705. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64706. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64707. return v;
  64708. }
  64709. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64710. {
  64711. path.startNewSubPath (startPos.resolve (coordFinder));
  64712. }
  64713. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64714. {
  64715. numPoints = 1;
  64716. return &startPos;
  64717. }
  64718. RelativePointPath::CloseSubPath::CloseSubPath()
  64719. : ElementBase (closeSubPathElement)
  64720. {
  64721. }
  64722. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64723. {
  64724. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64725. }
  64726. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64727. {
  64728. path.closeSubPath();
  64729. }
  64730. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64731. {
  64732. numPoints = 0;
  64733. return 0;
  64734. }
  64735. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64736. : ElementBase (lineToElement), endPoint (endPoint_)
  64737. {
  64738. }
  64739. const ValueTree RelativePointPath::LineTo::createTree() const
  64740. {
  64741. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64742. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64743. return v;
  64744. }
  64745. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64746. {
  64747. path.lineTo (endPoint.resolve (coordFinder));
  64748. }
  64749. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64750. {
  64751. numPoints = 1;
  64752. return &endPoint;
  64753. }
  64754. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64755. : ElementBase (quadraticToElement)
  64756. {
  64757. controlPoints[0] = controlPoint;
  64758. controlPoints[1] = endPoint;
  64759. }
  64760. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64761. {
  64762. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64763. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64764. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64765. return v;
  64766. }
  64767. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64768. {
  64769. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64770. controlPoints[1].resolve (coordFinder));
  64771. }
  64772. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64773. {
  64774. numPoints = 2;
  64775. return controlPoints;
  64776. }
  64777. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64778. : ElementBase (cubicToElement)
  64779. {
  64780. controlPoints[0] = controlPoint1;
  64781. controlPoints[1] = controlPoint2;
  64782. controlPoints[2] = endPoint;
  64783. }
  64784. const ValueTree RelativePointPath::CubicTo::createTree() const
  64785. {
  64786. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64787. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64788. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64789. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64790. return v;
  64791. }
  64792. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64793. {
  64794. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64795. controlPoints[1].resolve (coordFinder),
  64796. controlPoints[2].resolve (coordFinder));
  64797. }
  64798. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64799. {
  64800. numPoints = 3;
  64801. return controlPoints;
  64802. }
  64803. RelativeParallelogram::RelativeParallelogram()
  64804. {
  64805. }
  64806. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64807. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64808. {
  64809. }
  64810. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64811. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64812. {
  64813. }
  64814. RelativeParallelogram::~RelativeParallelogram()
  64815. {
  64816. }
  64817. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64818. {
  64819. points[0] = topLeft.resolve (coordFinder);
  64820. points[1] = topRight.resolve (coordFinder);
  64821. points[2] = bottomLeft.resolve (coordFinder);
  64822. }
  64823. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64824. {
  64825. resolveThreePoints (points, coordFinder);
  64826. points[3] = points[1] + (points[2] - points[0]);
  64827. }
  64828. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64829. {
  64830. Point<float> points[4];
  64831. resolveFourCorners (points, coordFinder);
  64832. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64833. }
  64834. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64835. {
  64836. Point<float> points[4];
  64837. resolveFourCorners (points, coordFinder);
  64838. path.startNewSubPath (points[0]);
  64839. path.lineTo (points[1]);
  64840. path.lineTo (points[3]);
  64841. path.lineTo (points[2]);
  64842. path.closeSubPath();
  64843. }
  64844. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64845. {
  64846. Point<float> corners[3];
  64847. resolveThreePoints (corners, coordFinder);
  64848. const Line<float> top (corners[0], corners[1]);
  64849. const Line<float> left (corners[0], corners[2]);
  64850. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64851. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64852. topRight.moveToAbsolute (newTopRight, coordFinder);
  64853. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64854. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64855. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64856. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64857. }
  64858. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64859. {
  64860. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64861. }
  64862. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64863. {
  64864. return ! operator== (other);
  64865. }
  64866. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64867. {
  64868. const Point<float> tr (corners[1] - corners[0]);
  64869. const Point<float> bl (corners[2] - corners[0]);
  64870. target -= corners[0];
  64871. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64872. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64873. }
  64874. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64875. {
  64876. return corners[0]
  64877. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64878. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64879. }
  64880. END_JUCE_NAMESPACE
  64881. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64882. #endif
  64883. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64884. /*** Start of inlined file: juce_Colour.cpp ***/
  64885. BEGIN_JUCE_NAMESPACE
  64886. namespace ColourHelpers
  64887. {
  64888. static uint8 floatAlphaToInt (const float alpha) throw()
  64889. {
  64890. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64891. }
  64892. static void convertHSBtoRGB (float h, float s, float v,
  64893. uint8& r, uint8& g, uint8& b) throw()
  64894. {
  64895. v = jlimit (0.0f, 1.0f, v);
  64896. v *= 255.0f;
  64897. const uint8 intV = (uint8) roundToInt (v);
  64898. if (s <= 0)
  64899. {
  64900. r = intV;
  64901. g = intV;
  64902. b = intV;
  64903. }
  64904. else
  64905. {
  64906. s = jmin (1.0f, s);
  64907. h = jlimit (0.0f, 1.0f, h);
  64908. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64909. const float f = h - std::floor (h);
  64910. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64911. const float y = v * (1.0f - s * f);
  64912. const float z = v * (1.0f - (s * (1.0f - f)));
  64913. if (h < 1.0f)
  64914. {
  64915. r = intV;
  64916. g = (uint8) roundToInt (z);
  64917. b = x;
  64918. }
  64919. else if (h < 2.0f)
  64920. {
  64921. r = (uint8) roundToInt (y);
  64922. g = intV;
  64923. b = x;
  64924. }
  64925. else if (h < 3.0f)
  64926. {
  64927. r = x;
  64928. g = intV;
  64929. b = (uint8) roundToInt (z);
  64930. }
  64931. else if (h < 4.0f)
  64932. {
  64933. r = x;
  64934. g = (uint8) roundToInt (y);
  64935. b = intV;
  64936. }
  64937. else if (h < 5.0f)
  64938. {
  64939. r = (uint8) roundToInt (z);
  64940. g = x;
  64941. b = intV;
  64942. }
  64943. else if (h < 6.0f)
  64944. {
  64945. r = intV;
  64946. g = x;
  64947. b = (uint8) roundToInt (y);
  64948. }
  64949. else
  64950. {
  64951. r = 0;
  64952. g = 0;
  64953. b = 0;
  64954. }
  64955. }
  64956. }
  64957. }
  64958. Colour::Colour() throw()
  64959. : argb (0)
  64960. {
  64961. }
  64962. Colour::Colour (const Colour& other) throw()
  64963. : argb (other.argb)
  64964. {
  64965. }
  64966. Colour& Colour::operator= (const Colour& other) throw()
  64967. {
  64968. argb = other.argb;
  64969. return *this;
  64970. }
  64971. bool Colour::operator== (const Colour& other) const throw()
  64972. {
  64973. return argb.getARGB() == other.argb.getARGB();
  64974. }
  64975. bool Colour::operator!= (const Colour& other) const throw()
  64976. {
  64977. return argb.getARGB() != other.argb.getARGB();
  64978. }
  64979. Colour::Colour (const uint32 argb_) throw()
  64980. : argb (argb_)
  64981. {
  64982. }
  64983. Colour::Colour (const uint8 red,
  64984. const uint8 green,
  64985. const uint8 blue) throw()
  64986. {
  64987. argb.setARGB (0xff, red, green, blue);
  64988. }
  64989. const Colour Colour::fromRGB (const uint8 red,
  64990. const uint8 green,
  64991. const uint8 blue) throw()
  64992. {
  64993. return Colour (red, green, blue);
  64994. }
  64995. Colour::Colour (const uint8 red,
  64996. const uint8 green,
  64997. const uint8 blue,
  64998. const uint8 alpha) throw()
  64999. {
  65000. argb.setARGB (alpha, red, green, blue);
  65001. }
  65002. const Colour Colour::fromRGBA (const uint8 red,
  65003. const uint8 green,
  65004. const uint8 blue,
  65005. const uint8 alpha) throw()
  65006. {
  65007. return Colour (red, green, blue, alpha);
  65008. }
  65009. Colour::Colour (const uint8 red,
  65010. const uint8 green,
  65011. const uint8 blue,
  65012. const float alpha) throw()
  65013. {
  65014. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  65015. }
  65016. const Colour Colour::fromRGBAFloat (const uint8 red,
  65017. const uint8 green,
  65018. const uint8 blue,
  65019. const float alpha) throw()
  65020. {
  65021. return Colour (red, green, blue, alpha);
  65022. }
  65023. Colour::Colour (const float hue,
  65024. const float saturation,
  65025. const float brightness,
  65026. const float alpha) throw()
  65027. {
  65028. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65029. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65030. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  65031. }
  65032. const Colour Colour::fromHSV (const float hue,
  65033. const float saturation,
  65034. const float brightness,
  65035. const float alpha) throw()
  65036. {
  65037. return Colour (hue, saturation, brightness, alpha);
  65038. }
  65039. Colour::Colour (const float hue,
  65040. const float saturation,
  65041. const float brightness,
  65042. const uint8 alpha) throw()
  65043. {
  65044. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65045. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65046. argb.setARGB (alpha, r, g, b);
  65047. }
  65048. Colour::~Colour() throw()
  65049. {
  65050. }
  65051. const PixelARGB Colour::getPixelARGB() const throw()
  65052. {
  65053. PixelARGB p (argb);
  65054. p.premultiply();
  65055. return p;
  65056. }
  65057. uint32 Colour::getARGB() const throw()
  65058. {
  65059. return argb.getARGB();
  65060. }
  65061. bool Colour::isTransparent() const throw()
  65062. {
  65063. return getAlpha() == 0;
  65064. }
  65065. bool Colour::isOpaque() const throw()
  65066. {
  65067. return getAlpha() == 0xff;
  65068. }
  65069. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  65070. {
  65071. PixelARGB newCol (argb);
  65072. newCol.setAlpha (newAlpha);
  65073. return Colour (newCol.getARGB());
  65074. }
  65075. const Colour Colour::withAlpha (const float newAlpha) const throw()
  65076. {
  65077. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  65078. PixelARGB newCol (argb);
  65079. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  65080. return Colour (newCol.getARGB());
  65081. }
  65082. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  65083. {
  65084. jassert (alphaMultiplier >= 0);
  65085. PixelARGB newCol (argb);
  65086. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  65087. return Colour (newCol.getARGB());
  65088. }
  65089. const Colour Colour::overlaidWith (const Colour& src) const throw()
  65090. {
  65091. const int destAlpha = getAlpha();
  65092. if (destAlpha > 0)
  65093. {
  65094. const int invA = 0xff - (int) src.getAlpha();
  65095. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  65096. if (resA > 0)
  65097. {
  65098. const int da = (invA * destAlpha) / resA;
  65099. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  65100. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  65101. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  65102. (uint8) resA);
  65103. }
  65104. return *this;
  65105. }
  65106. else
  65107. {
  65108. return src;
  65109. }
  65110. }
  65111. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  65112. {
  65113. if (proportionOfOther <= 0)
  65114. return *this;
  65115. if (proportionOfOther >= 1.0f)
  65116. return other;
  65117. PixelARGB c1 (getPixelARGB());
  65118. const PixelARGB c2 (other.getPixelARGB());
  65119. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  65120. c1.unpremultiply();
  65121. return Colour (c1.getARGB());
  65122. }
  65123. float Colour::getFloatRed() const throw()
  65124. {
  65125. return getRed() / 255.0f;
  65126. }
  65127. float Colour::getFloatGreen() const throw()
  65128. {
  65129. return getGreen() / 255.0f;
  65130. }
  65131. float Colour::getFloatBlue() const throw()
  65132. {
  65133. return getBlue() / 255.0f;
  65134. }
  65135. float Colour::getFloatAlpha() const throw()
  65136. {
  65137. return getAlpha() / 255.0f;
  65138. }
  65139. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65140. {
  65141. const int r = getRed();
  65142. const int g = getGreen();
  65143. const int b = getBlue();
  65144. const int hi = jmax (r, g, b);
  65145. const int lo = jmin (r, g, b);
  65146. if (hi != 0)
  65147. {
  65148. s = (hi - lo) / (float) hi;
  65149. if (s != 0)
  65150. {
  65151. const float invDiff = 1.0f / (hi - lo);
  65152. const float red = (hi - r) * invDiff;
  65153. const float green = (hi - g) * invDiff;
  65154. const float blue = (hi - b) * invDiff;
  65155. if (r == hi)
  65156. h = blue - green;
  65157. else if (g == hi)
  65158. h = 2.0f + red - blue;
  65159. else
  65160. h = 4.0f + green - red;
  65161. h *= 1.0f / 6.0f;
  65162. if (h < 0)
  65163. ++h;
  65164. }
  65165. else
  65166. {
  65167. h = 0;
  65168. }
  65169. }
  65170. else
  65171. {
  65172. s = 0;
  65173. h = 0;
  65174. }
  65175. v = hi / 255.0f;
  65176. }
  65177. float Colour::getHue() const throw()
  65178. {
  65179. float h, s, b;
  65180. getHSB (h, s, b);
  65181. return h;
  65182. }
  65183. const Colour Colour::withHue (const float hue) const throw()
  65184. {
  65185. float h, s, b;
  65186. getHSB (h, s, b);
  65187. return Colour (hue, s, b, getAlpha());
  65188. }
  65189. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65190. {
  65191. float h, s, b;
  65192. getHSB (h, s, b);
  65193. h += amountToRotate;
  65194. h -= std::floor (h);
  65195. return Colour (h, s, b, getAlpha());
  65196. }
  65197. float Colour::getSaturation() const throw()
  65198. {
  65199. float h, s, b;
  65200. getHSB (h, s, b);
  65201. return s;
  65202. }
  65203. const Colour Colour::withSaturation (const float saturation) const throw()
  65204. {
  65205. float h, s, b;
  65206. getHSB (h, s, b);
  65207. return Colour (h, saturation, b, getAlpha());
  65208. }
  65209. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65210. {
  65211. float h, s, b;
  65212. getHSB (h, s, b);
  65213. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65214. }
  65215. float Colour::getBrightness() const throw()
  65216. {
  65217. float h, s, b;
  65218. getHSB (h, s, b);
  65219. return b;
  65220. }
  65221. const Colour Colour::withBrightness (const float brightness) const throw()
  65222. {
  65223. float h, s, b;
  65224. getHSB (h, s, b);
  65225. return Colour (h, s, brightness, getAlpha());
  65226. }
  65227. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65228. {
  65229. float h, s, b;
  65230. getHSB (h, s, b);
  65231. b *= amount;
  65232. if (b > 1.0f)
  65233. b = 1.0f;
  65234. return Colour (h, s, b, getAlpha());
  65235. }
  65236. const Colour Colour::brighter (float amount) const throw()
  65237. {
  65238. amount = 1.0f / (1.0f + amount);
  65239. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65240. (uint8) (255 - (amount * (255 - getGreen()))),
  65241. (uint8) (255 - (amount * (255 - getBlue()))),
  65242. getAlpha());
  65243. }
  65244. const Colour Colour::darker (float amount) const throw()
  65245. {
  65246. amount = 1.0f / (1.0f + amount);
  65247. return Colour ((uint8) (amount * getRed()),
  65248. (uint8) (amount * getGreen()),
  65249. (uint8) (amount * getBlue()),
  65250. getAlpha());
  65251. }
  65252. const Colour Colour::greyLevel (const float brightness) throw()
  65253. {
  65254. const uint8 level
  65255. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65256. return Colour (level, level, level);
  65257. }
  65258. const Colour Colour::contrasting (const float amount) const throw()
  65259. {
  65260. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65261. ? Colours::black
  65262. : Colours::white).withAlpha (amount));
  65263. }
  65264. const Colour Colour::contrasting (const Colour& colour1,
  65265. const Colour& colour2) throw()
  65266. {
  65267. const float b1 = colour1.getBrightness();
  65268. const float b2 = colour2.getBrightness();
  65269. float best = 0.0f;
  65270. float bestDist = 0.0f;
  65271. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65272. {
  65273. const float d1 = std::abs (i - b1);
  65274. const float d2 = std::abs (i - b2);
  65275. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65276. if (dist > bestDist)
  65277. {
  65278. best = i;
  65279. bestDist = dist;
  65280. }
  65281. }
  65282. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65283. .withBrightness (best);
  65284. }
  65285. const String Colour::toString() const
  65286. {
  65287. return String::toHexString ((int) argb.getARGB());
  65288. }
  65289. const Colour Colour::fromString (const String& encodedColourString)
  65290. {
  65291. return Colour ((uint32) encodedColourString.getHexValue32());
  65292. }
  65293. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65294. {
  65295. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65296. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65297. .toUpperCase();
  65298. }
  65299. END_JUCE_NAMESPACE
  65300. /*** End of inlined file: juce_Colour.cpp ***/
  65301. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65302. BEGIN_JUCE_NAMESPACE
  65303. ColourGradient::ColourGradient() throw()
  65304. {
  65305. #if JUCE_DEBUG
  65306. point1.setX (987654.0f);
  65307. #endif
  65308. }
  65309. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65310. const Colour& colour2, const float x2_, const float y2_,
  65311. const bool isRadial_)
  65312. : point1 (x1_, y1_),
  65313. point2 (x2_, y2_),
  65314. isRadial (isRadial_)
  65315. {
  65316. colours.add (ColourPoint (0.0, colour1));
  65317. colours.add (ColourPoint (1.0, colour2));
  65318. }
  65319. ColourGradient::~ColourGradient()
  65320. {
  65321. }
  65322. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65323. {
  65324. return point1 == other.point1 && point2 == other.point2
  65325. && isRadial == other.isRadial
  65326. && colours == other.colours;
  65327. }
  65328. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65329. {
  65330. return ! operator== (other);
  65331. }
  65332. void ColourGradient::clearColours()
  65333. {
  65334. colours.clear();
  65335. }
  65336. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65337. {
  65338. // must be within the two end-points
  65339. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65340. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65341. int i;
  65342. for (i = 0; i < colours.size(); ++i)
  65343. if (colours.getReference(i).position > pos)
  65344. break;
  65345. colours.insert (i, ColourPoint (pos, colour));
  65346. return i;
  65347. }
  65348. void ColourGradient::removeColour (int index)
  65349. {
  65350. jassert (index > 0 && index < colours.size() - 1);
  65351. colours.remove (index);
  65352. }
  65353. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65354. {
  65355. for (int i = 0; i < colours.size(); ++i)
  65356. {
  65357. Colour& c = colours.getReference(i).colour;
  65358. c = c.withMultipliedAlpha (multiplier);
  65359. }
  65360. }
  65361. int ColourGradient::getNumColours() const throw()
  65362. {
  65363. return colours.size();
  65364. }
  65365. double ColourGradient::getColourPosition (const int index) const throw()
  65366. {
  65367. if (((unsigned int) index) < (unsigned int) colours.size())
  65368. return colours.getReference (index).position;
  65369. return 0;
  65370. }
  65371. const Colour ColourGradient::getColour (const int index) const throw()
  65372. {
  65373. if (((unsigned int) index) < (unsigned int) colours.size())
  65374. return colours.getReference (index).colour;
  65375. return Colour();
  65376. }
  65377. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65378. {
  65379. if (((unsigned int) index) < (unsigned int) colours.size())
  65380. colours.getReference (index).colour = newColour;
  65381. }
  65382. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65383. {
  65384. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65385. if (position <= 0 || colours.size() <= 1)
  65386. return colours.getReference(0).colour;
  65387. int i = colours.size() - 1;
  65388. while (position < colours.getReference(i).position)
  65389. --i;
  65390. const ColourPoint& p1 = colours.getReference (i);
  65391. if (i >= colours.size() - 1)
  65392. return p1.colour;
  65393. const ColourPoint& p2 = colours.getReference (i + 1);
  65394. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65395. }
  65396. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65397. {
  65398. #if JUCE_DEBUG
  65399. // trying to use the object without setting its co-ordinates? Have a careful read of
  65400. // the comments for the constructors.
  65401. jassert (point1.getX() != 987654.0f);
  65402. #endif
  65403. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65404. 3 * (int) point1.transformedBy (transform)
  65405. .getDistanceFrom (point2.transformedBy (transform)));
  65406. lookupTable.malloc (numEntries);
  65407. if (colours.size() >= 2)
  65408. {
  65409. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65410. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65411. int index = 0;
  65412. for (int j = 1; j < colours.size(); ++j)
  65413. {
  65414. const ColourPoint& p = colours.getReference (j);
  65415. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65416. const PixelARGB pix2 (p.colour.getPixelARGB());
  65417. for (int i = 0; i < numToDo; ++i)
  65418. {
  65419. jassert (index >= 0 && index < numEntries);
  65420. lookupTable[index] = pix1;
  65421. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65422. ++index;
  65423. }
  65424. pix1 = pix2;
  65425. }
  65426. while (index < numEntries)
  65427. lookupTable [index++] = pix1;
  65428. }
  65429. else
  65430. {
  65431. jassertfalse; // no colours specified!
  65432. }
  65433. return numEntries;
  65434. }
  65435. bool ColourGradient::isOpaque() const throw()
  65436. {
  65437. for (int i = 0; i < colours.size(); ++i)
  65438. if (! colours.getReference(i).colour.isOpaque())
  65439. return false;
  65440. return true;
  65441. }
  65442. bool ColourGradient::isInvisible() const throw()
  65443. {
  65444. for (int i = 0; i < colours.size(); ++i)
  65445. if (! colours.getReference(i).colour.isTransparent())
  65446. return false;
  65447. return true;
  65448. }
  65449. END_JUCE_NAMESPACE
  65450. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65451. /*** Start of inlined file: juce_Colours.cpp ***/
  65452. BEGIN_JUCE_NAMESPACE
  65453. const Colour Colours::transparentBlack (0);
  65454. const Colour Colours::transparentWhite (0x00ffffff);
  65455. const Colour Colours::aliceblue (0xfff0f8ff);
  65456. const Colour Colours::antiquewhite (0xfffaebd7);
  65457. const Colour Colours::aqua (0xff00ffff);
  65458. const Colour Colours::aquamarine (0xff7fffd4);
  65459. const Colour Colours::azure (0xfff0ffff);
  65460. const Colour Colours::beige (0xfff5f5dc);
  65461. const Colour Colours::bisque (0xffffe4c4);
  65462. const Colour Colours::black (0xff000000);
  65463. const Colour Colours::blanchedalmond (0xffffebcd);
  65464. const Colour Colours::blue (0xff0000ff);
  65465. const Colour Colours::blueviolet (0xff8a2be2);
  65466. const Colour Colours::brown (0xffa52a2a);
  65467. const Colour Colours::burlywood (0xffdeb887);
  65468. const Colour Colours::cadetblue (0xff5f9ea0);
  65469. const Colour Colours::chartreuse (0xff7fff00);
  65470. const Colour Colours::chocolate (0xffd2691e);
  65471. const Colour Colours::coral (0xffff7f50);
  65472. const Colour Colours::cornflowerblue (0xff6495ed);
  65473. const Colour Colours::cornsilk (0xfffff8dc);
  65474. const Colour Colours::crimson (0xffdc143c);
  65475. const Colour Colours::cyan (0xff00ffff);
  65476. const Colour Colours::darkblue (0xff00008b);
  65477. const Colour Colours::darkcyan (0xff008b8b);
  65478. const Colour Colours::darkgoldenrod (0xffb8860b);
  65479. const Colour Colours::darkgrey (0xff555555);
  65480. const Colour Colours::darkgreen (0xff006400);
  65481. const Colour Colours::darkkhaki (0xffbdb76b);
  65482. const Colour Colours::darkmagenta (0xff8b008b);
  65483. const Colour Colours::darkolivegreen (0xff556b2f);
  65484. const Colour Colours::darkorange (0xffff8c00);
  65485. const Colour Colours::darkorchid (0xff9932cc);
  65486. const Colour Colours::darkred (0xff8b0000);
  65487. const Colour Colours::darksalmon (0xffe9967a);
  65488. const Colour Colours::darkseagreen (0xff8fbc8f);
  65489. const Colour Colours::darkslateblue (0xff483d8b);
  65490. const Colour Colours::darkslategrey (0xff2f4f4f);
  65491. const Colour Colours::darkturquoise (0xff00ced1);
  65492. const Colour Colours::darkviolet (0xff9400d3);
  65493. const Colour Colours::deeppink (0xffff1493);
  65494. const Colour Colours::deepskyblue (0xff00bfff);
  65495. const Colour Colours::dimgrey (0xff696969);
  65496. const Colour Colours::dodgerblue (0xff1e90ff);
  65497. const Colour Colours::firebrick (0xffb22222);
  65498. const Colour Colours::floralwhite (0xfffffaf0);
  65499. const Colour Colours::forestgreen (0xff228b22);
  65500. const Colour Colours::fuchsia (0xffff00ff);
  65501. const Colour Colours::gainsboro (0xffdcdcdc);
  65502. const Colour Colours::gold (0xffffd700);
  65503. const Colour Colours::goldenrod (0xffdaa520);
  65504. const Colour Colours::grey (0xff808080);
  65505. const Colour Colours::green (0xff008000);
  65506. const Colour Colours::greenyellow (0xffadff2f);
  65507. const Colour Colours::honeydew (0xfff0fff0);
  65508. const Colour Colours::hotpink (0xffff69b4);
  65509. const Colour Colours::indianred (0xffcd5c5c);
  65510. const Colour Colours::indigo (0xff4b0082);
  65511. const Colour Colours::ivory (0xfffffff0);
  65512. const Colour Colours::khaki (0xfff0e68c);
  65513. const Colour Colours::lavender (0xffe6e6fa);
  65514. const Colour Colours::lavenderblush (0xfffff0f5);
  65515. const Colour Colours::lemonchiffon (0xfffffacd);
  65516. const Colour Colours::lightblue (0xffadd8e6);
  65517. const Colour Colours::lightcoral (0xfff08080);
  65518. const Colour Colours::lightcyan (0xffe0ffff);
  65519. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65520. const Colour Colours::lightgreen (0xff90ee90);
  65521. const Colour Colours::lightgrey (0xffd3d3d3);
  65522. const Colour Colours::lightpink (0xffffb6c1);
  65523. const Colour Colours::lightsalmon (0xffffa07a);
  65524. const Colour Colours::lightseagreen (0xff20b2aa);
  65525. const Colour Colours::lightskyblue (0xff87cefa);
  65526. const Colour Colours::lightslategrey (0xff778899);
  65527. const Colour Colours::lightsteelblue (0xffb0c4de);
  65528. const Colour Colours::lightyellow (0xffffffe0);
  65529. const Colour Colours::lime (0xff00ff00);
  65530. const Colour Colours::limegreen (0xff32cd32);
  65531. const Colour Colours::linen (0xfffaf0e6);
  65532. const Colour Colours::magenta (0xffff00ff);
  65533. const Colour Colours::maroon (0xff800000);
  65534. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65535. const Colour Colours::mediumblue (0xff0000cd);
  65536. const Colour Colours::mediumorchid (0xffba55d3);
  65537. const Colour Colours::mediumpurple (0xff9370db);
  65538. const Colour Colours::mediumseagreen (0xff3cb371);
  65539. const Colour Colours::mediumslateblue (0xff7b68ee);
  65540. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65541. const Colour Colours::mediumturquoise (0xff48d1cc);
  65542. const Colour Colours::mediumvioletred (0xffc71585);
  65543. const Colour Colours::midnightblue (0xff191970);
  65544. const Colour Colours::mintcream (0xfff5fffa);
  65545. const Colour Colours::mistyrose (0xffffe4e1);
  65546. const Colour Colours::navajowhite (0xffffdead);
  65547. const Colour Colours::navy (0xff000080);
  65548. const Colour Colours::oldlace (0xfffdf5e6);
  65549. const Colour Colours::olive (0xff808000);
  65550. const Colour Colours::olivedrab (0xff6b8e23);
  65551. const Colour Colours::orange (0xffffa500);
  65552. const Colour Colours::orangered (0xffff4500);
  65553. const Colour Colours::orchid (0xffda70d6);
  65554. const Colour Colours::palegoldenrod (0xffeee8aa);
  65555. const Colour Colours::palegreen (0xff98fb98);
  65556. const Colour Colours::paleturquoise (0xffafeeee);
  65557. const Colour Colours::palevioletred (0xffdb7093);
  65558. const Colour Colours::papayawhip (0xffffefd5);
  65559. const Colour Colours::peachpuff (0xffffdab9);
  65560. const Colour Colours::peru (0xffcd853f);
  65561. const Colour Colours::pink (0xffffc0cb);
  65562. const Colour Colours::plum (0xffdda0dd);
  65563. const Colour Colours::powderblue (0xffb0e0e6);
  65564. const Colour Colours::purple (0xff800080);
  65565. const Colour Colours::red (0xffff0000);
  65566. const Colour Colours::rosybrown (0xffbc8f8f);
  65567. const Colour Colours::royalblue (0xff4169e1);
  65568. const Colour Colours::saddlebrown (0xff8b4513);
  65569. const Colour Colours::salmon (0xfffa8072);
  65570. const Colour Colours::sandybrown (0xfff4a460);
  65571. const Colour Colours::seagreen (0xff2e8b57);
  65572. const Colour Colours::seashell (0xfffff5ee);
  65573. const Colour Colours::sienna (0xffa0522d);
  65574. const Colour Colours::silver (0xffc0c0c0);
  65575. const Colour Colours::skyblue (0xff87ceeb);
  65576. const Colour Colours::slateblue (0xff6a5acd);
  65577. const Colour Colours::slategrey (0xff708090);
  65578. const Colour Colours::snow (0xfffffafa);
  65579. const Colour Colours::springgreen (0xff00ff7f);
  65580. const Colour Colours::steelblue (0xff4682b4);
  65581. const Colour Colours::tan (0xffd2b48c);
  65582. const Colour Colours::teal (0xff008080);
  65583. const Colour Colours::thistle (0xffd8bfd8);
  65584. const Colour Colours::tomato (0xffff6347);
  65585. const Colour Colours::turquoise (0xff40e0d0);
  65586. const Colour Colours::violet (0xffee82ee);
  65587. const Colour Colours::wheat (0xfff5deb3);
  65588. const Colour Colours::white (0xffffffff);
  65589. const Colour Colours::whitesmoke (0xfff5f5f5);
  65590. const Colour Colours::yellow (0xffffff00);
  65591. const Colour Colours::yellowgreen (0xff9acd32);
  65592. const Colour Colours::findColourForName (const String& colourName,
  65593. const Colour& defaultColour)
  65594. {
  65595. static const int presets[] =
  65596. {
  65597. // (first value is the string's hashcode, second is ARGB)
  65598. 0x05978fff, 0xff000000, /* black */
  65599. 0x06bdcc29, 0xffffffff, /* white */
  65600. 0x002e305a, 0xff0000ff, /* blue */
  65601. 0x00308adf, 0xff808080, /* grey */
  65602. 0x05e0cf03, 0xff008000, /* green */
  65603. 0x0001b891, 0xffff0000, /* red */
  65604. 0xd43c6474, 0xffffff00, /* yellow */
  65605. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65606. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65607. 0x002dcebc, 0xff00ffff, /* aqua */
  65608. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65609. 0x0590228f, 0xfff0ffff, /* azure */
  65610. 0x05947fe4, 0xfff5f5dc, /* beige */
  65611. 0xad388e35, 0xffffe4c4, /* bisque */
  65612. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65613. 0x39129959, 0xff8a2be2, /* blueviolet */
  65614. 0x059a8136, 0xffa52a2a, /* brown */
  65615. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65616. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65617. 0x6b748956, 0xff7fff00, /* chartreuse */
  65618. 0x2903623c, 0xffd2691e, /* chocolate */
  65619. 0x05a74431, 0xffff7f50, /* coral */
  65620. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65621. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65622. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65623. 0x002ed323, 0xff00ffff, /* cyan */
  65624. 0x67cc74d0, 0xff00008b, /* darkblue */
  65625. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65626. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65627. 0x67cecf55, 0xff555555, /* darkgrey */
  65628. 0x920b194d, 0xff006400, /* darkgreen */
  65629. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65630. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65631. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65632. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65633. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65634. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65635. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65636. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65637. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65638. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65639. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65640. 0xc8769375, 0xff9400d3, /* darkviolet */
  65641. 0x25832862, 0xffff1493, /* deeppink */
  65642. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65643. 0x634c8b67, 0xff696969, /* dimgrey */
  65644. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65645. 0xef19e3cb, 0xffb22222, /* firebrick */
  65646. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65647. 0xd086fd06, 0xff228b22, /* forestgreen */
  65648. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65649. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65650. 0x00308060, 0xffffd700, /* gold */
  65651. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65652. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65653. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65654. 0x41892743, 0xffff69b4, /* hotpink */
  65655. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65656. 0xb969fed2, 0xff4b0082, /* indigo */
  65657. 0x05fef6a9, 0xfffffff0, /* ivory */
  65658. 0x06149302, 0xfff0e68c, /* khaki */
  65659. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65660. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65661. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65662. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65663. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65664. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65665. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65666. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65667. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65668. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65669. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65670. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65671. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65672. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65673. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65674. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65675. 0x0032afd5, 0xff00ff00, /* lime */
  65676. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65677. 0x06234efa, 0xfffaf0e6, /* linen */
  65678. 0x316858a9, 0xffff00ff, /* magenta */
  65679. 0xbf8ca470, 0xff800000, /* maroon */
  65680. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65681. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65682. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65683. 0x07556b71, 0xff9370db, /* mediumpurple */
  65684. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65685. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65686. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65687. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65688. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65689. 0x168eb32a, 0xff191970, /* midnightblue */
  65690. 0x4306b960, 0xfff5fffa, /* mintcream */
  65691. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65692. 0xe97218a6, 0xffffdead, /* navajowhite */
  65693. 0x00337bb6, 0xff000080, /* navy */
  65694. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65695. 0x064ee1db, 0xff808000, /* olive */
  65696. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65697. 0xc3de262e, 0xffffa500, /* orange */
  65698. 0x58bebba3, 0xffff4500, /* orangered */
  65699. 0xc3def8a3, 0xffda70d6, /* orchid */
  65700. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65701. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65702. 0x74022737, 0xffafeeee, /* paleturquoise */
  65703. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65704. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65705. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65706. 0x003472f8, 0xffcd853f, /* peru */
  65707. 0x00348176, 0xffffc0cb, /* pink */
  65708. 0x00348d94, 0xffdda0dd, /* plum */
  65709. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65710. 0xc5c507bc, 0xff800080, /* purple */
  65711. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65712. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65713. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65714. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65715. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65716. 0x34636c14, 0xff2e8b57, /* seagreen */
  65717. 0x3507fb41, 0xfffff5ee, /* seashell */
  65718. 0xca348772, 0xffa0522d, /* sienna */
  65719. 0xca37d30d, 0xffc0c0c0, /* silver */
  65720. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65721. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65722. 0x44ab37f8, 0xff708090, /* slategrey */
  65723. 0x0035f183, 0xfffffafa, /* snow */
  65724. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65725. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65726. 0x0001bfa1, 0xffd2b48c, /* tan */
  65727. 0x0036425c, 0xff008080, /* teal */
  65728. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65729. 0xcc41600a, 0xffff6347, /* tomato */
  65730. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65731. 0xcf57947f, 0xffee82ee, /* violet */
  65732. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65733. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65734. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65735. };
  65736. const int hash = colourName.trim().toLowerCase().hashCode();
  65737. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65738. if (presets [i] == hash)
  65739. return Colour (presets [i + 1]);
  65740. return defaultColour;
  65741. }
  65742. END_JUCE_NAMESPACE
  65743. /*** End of inlined file: juce_Colours.cpp ***/
  65744. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65745. BEGIN_JUCE_NAMESPACE
  65746. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65747. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65748. const Path& path, const AffineTransform& transform)
  65749. : bounds (bounds_),
  65750. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65751. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65752. needToCheckEmptinesss (true)
  65753. {
  65754. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65755. int* t = table;
  65756. for (int i = bounds.getHeight(); --i >= 0;)
  65757. {
  65758. *t = 0;
  65759. t += lineStrideElements;
  65760. }
  65761. const int topLimit = bounds.getY() << 8;
  65762. const int heightLimit = bounds.getHeight() << 8;
  65763. const int leftLimit = bounds.getX() << 8;
  65764. const int rightLimit = bounds.getRight() << 8;
  65765. PathFlatteningIterator iter (path, transform);
  65766. while (iter.next())
  65767. {
  65768. int y1 = roundToInt (iter.y1 * 256.0f);
  65769. int y2 = roundToInt (iter.y2 * 256.0f);
  65770. if (y1 != y2)
  65771. {
  65772. y1 -= topLimit;
  65773. y2 -= topLimit;
  65774. const int startY = y1;
  65775. int direction = -1;
  65776. if (y1 > y2)
  65777. {
  65778. swapVariables (y1, y2);
  65779. direction = 1;
  65780. }
  65781. if (y1 < 0)
  65782. y1 = 0;
  65783. if (y2 > heightLimit)
  65784. y2 = heightLimit;
  65785. if (y1 < y2)
  65786. {
  65787. const double startX = 256.0f * iter.x1;
  65788. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65789. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65790. do
  65791. {
  65792. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65793. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65794. if (x < leftLimit)
  65795. x = leftLimit;
  65796. else if (x >= rightLimit)
  65797. x = rightLimit - 1;
  65798. addEdgePoint (x, y1 >> 8, direction * step);
  65799. y1 += step;
  65800. }
  65801. while (y1 < y2);
  65802. }
  65803. }
  65804. }
  65805. sanitiseLevels (path.isUsingNonZeroWinding());
  65806. }
  65807. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65808. : bounds (rectangleToAdd),
  65809. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65810. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65811. needToCheckEmptinesss (true)
  65812. {
  65813. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65814. table[0] = 0;
  65815. const int x1 = rectangleToAdd.getX() << 8;
  65816. const int x2 = rectangleToAdd.getRight() << 8;
  65817. int* t = table;
  65818. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65819. {
  65820. t[0] = 2;
  65821. t[1] = x1;
  65822. t[2] = 255;
  65823. t[3] = x2;
  65824. t[4] = 0;
  65825. t += lineStrideElements;
  65826. }
  65827. }
  65828. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65829. : bounds (rectanglesToAdd.getBounds()),
  65830. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65831. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65832. needToCheckEmptinesss (true)
  65833. {
  65834. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65835. int* t = table;
  65836. for (int i = bounds.getHeight(); --i >= 0;)
  65837. {
  65838. *t = 0;
  65839. t += lineStrideElements;
  65840. }
  65841. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65842. {
  65843. const Rectangle<int>* const r = iter.getRectangle();
  65844. const int x1 = r->getX() << 8;
  65845. const int x2 = r->getRight() << 8;
  65846. int y = r->getY() - bounds.getY();
  65847. for (int j = r->getHeight(); --j >= 0;)
  65848. {
  65849. addEdgePoint (x1, y, 255);
  65850. addEdgePoint (x2, y, -255);
  65851. ++y;
  65852. }
  65853. }
  65854. sanitiseLevels (true);
  65855. }
  65856. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65857. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65858. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65859. 2 + (int) rectangleToAdd.getWidth(),
  65860. 2 + (int) rectangleToAdd.getHeight())),
  65861. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65862. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65863. needToCheckEmptinesss (true)
  65864. {
  65865. jassert (! rectangleToAdd.isEmpty());
  65866. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65867. table[0] = 0;
  65868. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65869. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65870. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65871. jassert (y1 < 256);
  65872. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65873. if (x2 <= x1 || y2 <= y1)
  65874. {
  65875. bounds.setHeight (0);
  65876. return;
  65877. }
  65878. int lineY = 0;
  65879. int* t = table;
  65880. if ((y1 >> 8) == (y2 >> 8))
  65881. {
  65882. t[0] = 2;
  65883. t[1] = x1;
  65884. t[2] = y2 - y1;
  65885. t[3] = x2;
  65886. t[4] = 0;
  65887. ++lineY;
  65888. t += lineStrideElements;
  65889. }
  65890. else
  65891. {
  65892. t[0] = 2;
  65893. t[1] = x1;
  65894. t[2] = 255 - (y1 & 255);
  65895. t[3] = x2;
  65896. t[4] = 0;
  65897. ++lineY;
  65898. t += lineStrideElements;
  65899. while (lineY < (y2 >> 8))
  65900. {
  65901. t[0] = 2;
  65902. t[1] = x1;
  65903. t[2] = 255;
  65904. t[3] = x2;
  65905. t[4] = 0;
  65906. ++lineY;
  65907. t += lineStrideElements;
  65908. }
  65909. jassert (lineY < bounds.getHeight());
  65910. t[0] = 2;
  65911. t[1] = x1;
  65912. t[2] = y2 & 255;
  65913. t[3] = x2;
  65914. t[4] = 0;
  65915. ++lineY;
  65916. t += lineStrideElements;
  65917. }
  65918. while (lineY < bounds.getHeight())
  65919. {
  65920. t[0] = 0;
  65921. t += lineStrideElements;
  65922. ++lineY;
  65923. }
  65924. }
  65925. EdgeTable::EdgeTable (const EdgeTable& other)
  65926. {
  65927. operator= (other);
  65928. }
  65929. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65930. {
  65931. bounds = other.bounds;
  65932. maxEdgesPerLine = other.maxEdgesPerLine;
  65933. lineStrideElements = other.lineStrideElements;
  65934. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65935. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65936. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65937. return *this;
  65938. }
  65939. EdgeTable::~EdgeTable()
  65940. {
  65941. }
  65942. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65943. {
  65944. while (--numLines >= 0)
  65945. {
  65946. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65947. src += srcLineStride;
  65948. dest += destLineStride;
  65949. }
  65950. }
  65951. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65952. {
  65953. // Convert the table from relative windings to absolute levels..
  65954. int* lineStart = table;
  65955. for (int i = bounds.getHeight(); --i >= 0;)
  65956. {
  65957. int* line = lineStart;
  65958. lineStart += lineStrideElements;
  65959. int num = *line;
  65960. if (num == 0)
  65961. continue;
  65962. int level = 0;
  65963. if (useNonZeroWinding)
  65964. {
  65965. while (--num > 0)
  65966. {
  65967. line += 2;
  65968. level += *line;
  65969. int corrected = abs (level);
  65970. if (corrected >> 8)
  65971. corrected = 255;
  65972. *line = corrected;
  65973. }
  65974. }
  65975. else
  65976. {
  65977. while (--num > 0)
  65978. {
  65979. line += 2;
  65980. level += *line;
  65981. int corrected = abs (level);
  65982. if (corrected >> 8)
  65983. {
  65984. corrected &= 511;
  65985. if (corrected >> 8)
  65986. corrected = 511 - corrected;
  65987. }
  65988. *line = corrected;
  65989. }
  65990. }
  65991. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65992. }
  65993. }
  65994. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  65995. {
  65996. if (newNumEdgesPerLine != maxEdgesPerLine)
  65997. {
  65998. maxEdgesPerLine = newNumEdgesPerLine;
  65999. jassert (bounds.getHeight() > 0);
  66000. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  66001. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  66002. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  66003. table.swapWith (newTable);
  66004. lineStrideElements = newLineStrideElements;
  66005. }
  66006. }
  66007. void EdgeTable::optimiseTable() throw()
  66008. {
  66009. int maxLineElements = 0;
  66010. for (int i = bounds.getHeight(); --i >= 0;)
  66011. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  66012. remapTableForNumEdges (maxLineElements);
  66013. }
  66014. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  66015. {
  66016. jassert (y >= 0 && y < bounds.getHeight());
  66017. int* line = table + lineStrideElements * y;
  66018. const int numPoints = line[0];
  66019. int n = numPoints << 1;
  66020. if (n > 0)
  66021. {
  66022. while (n > 0)
  66023. {
  66024. const int cx = line [n - 1];
  66025. if (cx <= x)
  66026. {
  66027. if (cx == x)
  66028. {
  66029. line [n] += winding;
  66030. return;
  66031. }
  66032. break;
  66033. }
  66034. n -= 2;
  66035. }
  66036. if (numPoints >= maxEdgesPerLine)
  66037. {
  66038. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66039. jassert (numPoints < maxEdgesPerLine);
  66040. line = table + lineStrideElements * y;
  66041. }
  66042. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  66043. }
  66044. line [n + 1] = x;
  66045. line [n + 2] = winding;
  66046. line[0]++;
  66047. }
  66048. void EdgeTable::translate (float dx, const int dy) throw()
  66049. {
  66050. bounds.translate ((int) std::floor (dx), dy);
  66051. int* lineStart = table;
  66052. const int intDx = (int) (dx * 256.0f);
  66053. for (int i = bounds.getHeight(); --i >= 0;)
  66054. {
  66055. int* line = lineStart;
  66056. lineStart += lineStrideElements;
  66057. int num = *line++;
  66058. while (--num >= 0)
  66059. {
  66060. *line += intDx;
  66061. line += 2;
  66062. }
  66063. }
  66064. }
  66065. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  66066. {
  66067. jassert (y >= 0 && y < bounds.getHeight());
  66068. int* dest = table + lineStrideElements * y;
  66069. if (dest[0] == 0)
  66070. return;
  66071. int otherNumPoints = *otherLine;
  66072. if (otherNumPoints == 0)
  66073. {
  66074. *dest = 0;
  66075. return;
  66076. }
  66077. const int right = bounds.getRight() << 8;
  66078. // optimise for the common case where our line lies entirely within a
  66079. // single pair of points, as happens when clipping to a simple rect.
  66080. if (otherNumPoints == 2 && otherLine[2] >= 255)
  66081. {
  66082. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  66083. return;
  66084. }
  66085. ++otherLine;
  66086. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  66087. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  66088. memcpy (temp, dest, lineSizeBytes);
  66089. const int* src1 = temp;
  66090. int srcNum1 = *src1++;
  66091. int x1 = *src1++;
  66092. const int* src2 = otherLine;
  66093. int srcNum2 = otherNumPoints;
  66094. int x2 = *src2++;
  66095. int destIndex = 0, destTotal = 0;
  66096. int level1 = 0, level2 = 0;
  66097. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  66098. while (srcNum1 > 0 && srcNum2 > 0)
  66099. {
  66100. int nextX;
  66101. if (x1 < x2)
  66102. {
  66103. nextX = x1;
  66104. level1 = *src1++;
  66105. x1 = *src1++;
  66106. --srcNum1;
  66107. }
  66108. else if (x1 == x2)
  66109. {
  66110. nextX = x1;
  66111. level1 = *src1++;
  66112. level2 = *src2++;
  66113. x1 = *src1++;
  66114. x2 = *src2++;
  66115. --srcNum1;
  66116. --srcNum2;
  66117. }
  66118. else
  66119. {
  66120. nextX = x2;
  66121. level2 = *src2++;
  66122. x2 = *src2++;
  66123. --srcNum2;
  66124. }
  66125. if (nextX > lastX)
  66126. {
  66127. if (nextX >= right)
  66128. break;
  66129. lastX = nextX;
  66130. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66131. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  66132. if (nextLevel != lastLevel)
  66133. {
  66134. if (destTotal >= maxEdgesPerLine)
  66135. {
  66136. dest[0] = destTotal;
  66137. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66138. dest = table + lineStrideElements * y;
  66139. }
  66140. ++destTotal;
  66141. lastLevel = nextLevel;
  66142. dest[++destIndex] = nextX;
  66143. dest[++destIndex] = nextLevel;
  66144. }
  66145. }
  66146. }
  66147. if (lastLevel > 0)
  66148. {
  66149. if (destTotal >= maxEdgesPerLine)
  66150. {
  66151. dest[0] = destTotal;
  66152. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66153. dest = table + lineStrideElements * y;
  66154. }
  66155. ++destTotal;
  66156. dest[++destIndex] = right;
  66157. dest[++destIndex] = 0;
  66158. }
  66159. dest[0] = destTotal;
  66160. #if JUCE_DEBUG
  66161. int last = std::numeric_limits<int>::min();
  66162. for (int i = 0; i < dest[0]; ++i)
  66163. {
  66164. jassert (dest[i * 2 + 1] > last);
  66165. last = dest[i * 2 + 1];
  66166. }
  66167. jassert (dest [dest[0] * 2] == 0);
  66168. #endif
  66169. }
  66170. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66171. {
  66172. int* lastItem = dest + (dest[0] * 2 - 1);
  66173. if (x2 < lastItem[0])
  66174. {
  66175. if (x2 <= dest[1])
  66176. {
  66177. dest[0] = 0;
  66178. return;
  66179. }
  66180. while (x2 < lastItem[-2])
  66181. {
  66182. --(dest[0]);
  66183. lastItem -= 2;
  66184. }
  66185. lastItem[0] = x2;
  66186. lastItem[1] = 0;
  66187. }
  66188. if (x1 > dest[1])
  66189. {
  66190. while (lastItem[0] > x1)
  66191. lastItem -= 2;
  66192. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66193. if (itemsRemoved > 0)
  66194. {
  66195. dest[0] -= itemsRemoved;
  66196. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66197. }
  66198. dest[1] = x1;
  66199. }
  66200. }
  66201. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  66202. {
  66203. const Rectangle<int> clipped (r.getIntersection (bounds));
  66204. if (clipped.isEmpty())
  66205. {
  66206. needToCheckEmptinesss = false;
  66207. bounds.setHeight (0);
  66208. }
  66209. else
  66210. {
  66211. const int top = clipped.getY() - bounds.getY();
  66212. const int bottom = clipped.getBottom() - bounds.getY();
  66213. if (bottom < bounds.getHeight())
  66214. bounds.setHeight (bottom);
  66215. if (clipped.getRight() < bounds.getRight())
  66216. bounds.setRight (clipped.getRight());
  66217. for (int i = top; --i >= 0;)
  66218. table [lineStrideElements * i] = 0;
  66219. if (clipped.getX() > bounds.getX())
  66220. {
  66221. const int x1 = clipped.getX() << 8;
  66222. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66223. int* line = table + lineStrideElements * top;
  66224. for (int i = bottom - top; --i >= 0;)
  66225. {
  66226. if (line[0] != 0)
  66227. clipEdgeTableLineToRange (line, x1, x2);
  66228. line += lineStrideElements;
  66229. }
  66230. }
  66231. needToCheckEmptinesss = true;
  66232. }
  66233. }
  66234. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  66235. {
  66236. const Rectangle<int> clipped (r.getIntersection (bounds));
  66237. if (! clipped.isEmpty())
  66238. {
  66239. const int top = clipped.getY() - bounds.getY();
  66240. const int bottom = clipped.getBottom() - bounds.getY();
  66241. //XXX optimise here by shortening the table if it fills top or bottom
  66242. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66243. clipped.getX() << 8, 0,
  66244. clipped.getRight() << 8, 255,
  66245. std::numeric_limits<int>::max(), 0 };
  66246. for (int i = top; i < bottom; ++i)
  66247. intersectWithEdgeTableLine (i, rectLine);
  66248. needToCheckEmptinesss = true;
  66249. }
  66250. }
  66251. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66252. {
  66253. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66254. if (clipped.isEmpty())
  66255. {
  66256. needToCheckEmptinesss = false;
  66257. bounds.setHeight (0);
  66258. }
  66259. else
  66260. {
  66261. const int top = clipped.getY() - bounds.getY();
  66262. const int bottom = clipped.getBottom() - bounds.getY();
  66263. if (bottom < bounds.getHeight())
  66264. bounds.setHeight (bottom);
  66265. if (clipped.getRight() < bounds.getRight())
  66266. bounds.setRight (clipped.getRight());
  66267. int i = 0;
  66268. for (i = top; --i >= 0;)
  66269. table [lineStrideElements * i] = 0;
  66270. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66271. for (i = top; i < bottom; ++i)
  66272. {
  66273. intersectWithEdgeTableLine (i, otherLine);
  66274. otherLine += other.lineStrideElements;
  66275. }
  66276. needToCheckEmptinesss = true;
  66277. }
  66278. }
  66279. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  66280. {
  66281. y -= bounds.getY();
  66282. if (y < 0 || y >= bounds.getHeight())
  66283. return;
  66284. needToCheckEmptinesss = true;
  66285. if (numPixels <= 0)
  66286. {
  66287. table [lineStrideElements * y] = 0;
  66288. return;
  66289. }
  66290. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66291. int destIndex = 0, lastLevel = 0;
  66292. while (--numPixels >= 0)
  66293. {
  66294. const int alpha = *mask;
  66295. mask += maskStride;
  66296. if (alpha != lastLevel)
  66297. {
  66298. tempLine[++destIndex] = (x << 8);
  66299. tempLine[++destIndex] = alpha;
  66300. lastLevel = alpha;
  66301. }
  66302. ++x;
  66303. }
  66304. if (lastLevel > 0)
  66305. {
  66306. tempLine[++destIndex] = (x << 8);
  66307. tempLine[++destIndex] = 0;
  66308. }
  66309. tempLine[0] = destIndex >> 1;
  66310. intersectWithEdgeTableLine (y, tempLine);
  66311. }
  66312. bool EdgeTable::isEmpty() throw()
  66313. {
  66314. if (needToCheckEmptinesss)
  66315. {
  66316. needToCheckEmptinesss = false;
  66317. int* t = table;
  66318. for (int i = bounds.getHeight(); --i >= 0;)
  66319. {
  66320. if (t[0] > 1)
  66321. return false;
  66322. t += lineStrideElements;
  66323. }
  66324. bounds.setHeight (0);
  66325. }
  66326. return bounds.getHeight() == 0;
  66327. }
  66328. END_JUCE_NAMESPACE
  66329. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66330. /*** Start of inlined file: juce_FillType.cpp ***/
  66331. BEGIN_JUCE_NAMESPACE
  66332. FillType::FillType() throw()
  66333. : colour (0xff000000), image (0)
  66334. {
  66335. }
  66336. FillType::FillType (const Colour& colour_) throw()
  66337. : colour (colour_), image (0)
  66338. {
  66339. }
  66340. FillType::FillType (const ColourGradient& gradient_)
  66341. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66342. {
  66343. }
  66344. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66345. : colour (0xff000000), image (image_), transform (transform_)
  66346. {
  66347. }
  66348. FillType::FillType (const FillType& other)
  66349. : colour (other.colour),
  66350. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66351. image (other.image), transform (other.transform)
  66352. {
  66353. }
  66354. FillType& FillType::operator= (const FillType& other)
  66355. {
  66356. if (this != &other)
  66357. {
  66358. colour = other.colour;
  66359. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66360. image = other.image;
  66361. transform = other.transform;
  66362. }
  66363. return *this;
  66364. }
  66365. FillType::~FillType() throw()
  66366. {
  66367. }
  66368. bool FillType::operator== (const FillType& other) const
  66369. {
  66370. return colour == other.colour && image == other.image
  66371. && transform == other.transform
  66372. && (gradient == other.gradient
  66373. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66374. }
  66375. bool FillType::operator!= (const FillType& other) const
  66376. {
  66377. return ! operator== (other);
  66378. }
  66379. void FillType::setColour (const Colour& newColour) throw()
  66380. {
  66381. gradient = 0;
  66382. image = Image::null;
  66383. colour = newColour;
  66384. }
  66385. void FillType::setGradient (const ColourGradient& newGradient)
  66386. {
  66387. if (gradient != 0)
  66388. {
  66389. *gradient = newGradient;
  66390. }
  66391. else
  66392. {
  66393. image = Image::null;
  66394. gradient = new ColourGradient (newGradient);
  66395. colour = Colours::black;
  66396. }
  66397. }
  66398. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66399. {
  66400. gradient = 0;
  66401. image = image_;
  66402. transform = transform_;
  66403. colour = Colours::black;
  66404. }
  66405. void FillType::setOpacity (const float newOpacity) throw()
  66406. {
  66407. colour = colour.withAlpha (newOpacity);
  66408. }
  66409. bool FillType::isInvisible() const throw()
  66410. {
  66411. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66412. }
  66413. END_JUCE_NAMESPACE
  66414. /*** End of inlined file: juce_FillType.cpp ***/
  66415. /*** Start of inlined file: juce_Graphics.cpp ***/
  66416. BEGIN_JUCE_NAMESPACE
  66417. template <typename Type>
  66418. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66419. {
  66420. const int maxVal = 0x3fffffff;
  66421. return (int) x >= -maxVal && (int) x <= maxVal
  66422. && (int) y >= -maxVal && (int) y <= maxVal
  66423. && (int) w >= -maxVal && (int) w <= maxVal
  66424. && (int) h >= -maxVal && (int) h <= maxVal;
  66425. }
  66426. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66427. {
  66428. }
  66429. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66430. {
  66431. }
  66432. Graphics::Graphics (const Image& imageToDrawOnto)
  66433. : context (imageToDrawOnto.createLowLevelContext()),
  66434. contextToDelete (context),
  66435. saveStatePending (false)
  66436. {
  66437. }
  66438. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66439. : context (internalContext),
  66440. saveStatePending (false)
  66441. {
  66442. }
  66443. Graphics::~Graphics()
  66444. {
  66445. }
  66446. void Graphics::resetToDefaultState()
  66447. {
  66448. saveStateIfPending();
  66449. context->setFill (FillType());
  66450. context->setFont (Font());
  66451. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66452. }
  66453. bool Graphics::isVectorDevice() const
  66454. {
  66455. return context->isVectorDevice();
  66456. }
  66457. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66458. {
  66459. saveStateIfPending();
  66460. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  66461. }
  66462. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66463. {
  66464. saveStateIfPending();
  66465. return context->clipToRectangleList (clipRegion);
  66466. }
  66467. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66468. {
  66469. saveStateIfPending();
  66470. context->clipToPath (path, transform);
  66471. return ! context->isClipEmpty();
  66472. }
  66473. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66474. {
  66475. saveStateIfPending();
  66476. context->clipToImageAlpha (image, transform);
  66477. return ! context->isClipEmpty();
  66478. }
  66479. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66480. {
  66481. saveStateIfPending();
  66482. context->excludeClipRectangle (rectangleToExclude);
  66483. }
  66484. bool Graphics::isClipEmpty() const
  66485. {
  66486. return context->isClipEmpty();
  66487. }
  66488. const Rectangle<int> Graphics::getClipBounds() const
  66489. {
  66490. return context->getClipBounds();
  66491. }
  66492. void Graphics::saveState()
  66493. {
  66494. saveStateIfPending();
  66495. saveStatePending = true;
  66496. }
  66497. void Graphics::restoreState()
  66498. {
  66499. if (saveStatePending)
  66500. saveStatePending = false;
  66501. else
  66502. context->restoreState();
  66503. }
  66504. void Graphics::saveStateIfPending()
  66505. {
  66506. if (saveStatePending)
  66507. {
  66508. saveStatePending = false;
  66509. context->saveState();
  66510. }
  66511. }
  66512. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66513. {
  66514. saveStateIfPending();
  66515. context->setOrigin (newOriginX, newOriginY);
  66516. }
  66517. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66518. {
  66519. return context->clipRegionIntersects (area);
  66520. }
  66521. void Graphics::setColour (const Colour& newColour)
  66522. {
  66523. saveStateIfPending();
  66524. context->setFill (newColour);
  66525. }
  66526. void Graphics::setOpacity (const float newOpacity)
  66527. {
  66528. saveStateIfPending();
  66529. context->setOpacity (newOpacity);
  66530. }
  66531. void Graphics::setGradientFill (const ColourGradient& gradient)
  66532. {
  66533. setFillType (gradient);
  66534. }
  66535. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66536. {
  66537. saveStateIfPending();
  66538. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66539. context->setOpacity (opacity);
  66540. }
  66541. void Graphics::setFillType (const FillType& newFill)
  66542. {
  66543. saveStateIfPending();
  66544. context->setFill (newFill);
  66545. }
  66546. void Graphics::setFont (const Font& newFont)
  66547. {
  66548. saveStateIfPending();
  66549. context->setFont (newFont);
  66550. }
  66551. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66552. {
  66553. saveStateIfPending();
  66554. Font f (context->getFont());
  66555. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66556. context->setFont (f);
  66557. }
  66558. const Font Graphics::getCurrentFont() const
  66559. {
  66560. return context->getFont();
  66561. }
  66562. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66563. {
  66564. if (text.isNotEmpty()
  66565. && startX < context->getClipBounds().getRight())
  66566. {
  66567. GlyphArrangement arr;
  66568. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66569. arr.draw (*this);
  66570. }
  66571. }
  66572. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66573. {
  66574. if (text.isNotEmpty())
  66575. {
  66576. GlyphArrangement arr;
  66577. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66578. arr.draw (*this, transform);
  66579. }
  66580. }
  66581. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66582. {
  66583. if (text.isNotEmpty()
  66584. && startX < context->getClipBounds().getRight())
  66585. {
  66586. GlyphArrangement arr;
  66587. arr.addJustifiedText (context->getFont(), text,
  66588. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66589. Justification::left);
  66590. arr.draw (*this);
  66591. }
  66592. }
  66593. void Graphics::drawText (const String& text,
  66594. const int x, const int y, const int width, const int height,
  66595. const Justification& justificationType,
  66596. const bool useEllipsesIfTooBig) const
  66597. {
  66598. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66599. {
  66600. GlyphArrangement arr;
  66601. arr.addCurtailedLineOfText (context->getFont(), text,
  66602. 0.0f, 0.0f, (float) width,
  66603. useEllipsesIfTooBig);
  66604. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66605. (float) x, (float) y, (float) width, (float) height,
  66606. justificationType);
  66607. arr.draw (*this);
  66608. }
  66609. }
  66610. void Graphics::drawFittedText (const String& text,
  66611. const int x, const int y, const int width, const int height,
  66612. const Justification& justification,
  66613. const int maximumNumberOfLines,
  66614. const float minimumHorizontalScale) const
  66615. {
  66616. if (text.isNotEmpty()
  66617. && width > 0 && height > 0
  66618. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66619. {
  66620. GlyphArrangement arr;
  66621. arr.addFittedText (context->getFont(), text,
  66622. (float) x, (float) y, (float) width, (float) height,
  66623. justification,
  66624. maximumNumberOfLines,
  66625. minimumHorizontalScale);
  66626. arr.draw (*this);
  66627. }
  66628. }
  66629. void Graphics::fillRect (int x, int y, int width, int height) const
  66630. {
  66631. // passing in a silly number can cause maths problems in rendering!
  66632. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66633. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66634. }
  66635. void Graphics::fillRect (const Rectangle<int>& r) const
  66636. {
  66637. context->fillRect (r, false);
  66638. }
  66639. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66640. {
  66641. // passing in a silly number can cause maths problems in rendering!
  66642. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66643. Path p;
  66644. p.addRectangle (x, y, width, height);
  66645. fillPath (p);
  66646. }
  66647. void Graphics::setPixel (int x, int y) const
  66648. {
  66649. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66650. }
  66651. void Graphics::fillAll() const
  66652. {
  66653. fillRect (context->getClipBounds());
  66654. }
  66655. void Graphics::fillAll (const Colour& colourToUse) const
  66656. {
  66657. if (! colourToUse.isTransparent())
  66658. {
  66659. const Rectangle<int> clip (context->getClipBounds());
  66660. context->saveState();
  66661. context->setFill (colourToUse);
  66662. context->fillRect (clip, false);
  66663. context->restoreState();
  66664. }
  66665. }
  66666. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66667. {
  66668. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66669. context->fillPath (path, transform);
  66670. }
  66671. void Graphics::strokePath (const Path& path,
  66672. const PathStrokeType& strokeType,
  66673. const AffineTransform& transform) const
  66674. {
  66675. Path stroke;
  66676. strokeType.createStrokedPath (stroke, path, transform);
  66677. fillPath (stroke);
  66678. }
  66679. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66680. const int lineThickness) const
  66681. {
  66682. // passing in a silly number can cause maths problems in rendering!
  66683. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66684. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66685. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66686. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66687. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66688. }
  66689. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66690. {
  66691. // passing in a silly number can cause maths problems in rendering!
  66692. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66693. Path p;
  66694. p.addRectangle (x, y, width, lineThickness);
  66695. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66696. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66697. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66698. fillPath (p);
  66699. }
  66700. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66701. {
  66702. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66703. }
  66704. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66705. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66706. const bool useGradient, const bool sharpEdgeOnOutside) const
  66707. {
  66708. // passing in a silly number can cause maths problems in rendering!
  66709. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66710. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66711. {
  66712. context->saveState();
  66713. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66714. const float ramp = oldOpacity / bevelThickness;
  66715. for (int i = bevelThickness; --i >= 0;)
  66716. {
  66717. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66718. : oldOpacity;
  66719. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66720. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66721. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66722. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66723. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66724. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66725. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66726. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66727. }
  66728. context->restoreState();
  66729. }
  66730. }
  66731. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66732. {
  66733. // passing in a silly number can cause maths problems in rendering!
  66734. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66735. Path p;
  66736. p.addEllipse (x, y, width, height);
  66737. fillPath (p);
  66738. }
  66739. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66740. const float lineThickness) const
  66741. {
  66742. // passing in a silly number can cause maths problems in rendering!
  66743. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66744. Path p;
  66745. p.addEllipse (x, y, width, height);
  66746. strokePath (p, PathStrokeType (lineThickness));
  66747. }
  66748. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66749. {
  66750. // passing in a silly number can cause maths problems in rendering!
  66751. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66752. Path p;
  66753. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66754. fillPath (p);
  66755. }
  66756. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66757. {
  66758. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66759. }
  66760. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66761. const float cornerSize, const float lineThickness) const
  66762. {
  66763. // passing in a silly number can cause maths problems in rendering!
  66764. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66765. Path p;
  66766. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66767. strokePath (p, PathStrokeType (lineThickness));
  66768. }
  66769. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66770. {
  66771. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66772. }
  66773. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66774. {
  66775. Path p;
  66776. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66777. fillPath (p);
  66778. }
  66779. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66780. const int checkWidth, const int checkHeight,
  66781. const Colour& colour1, const Colour& colour2) const
  66782. {
  66783. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66784. if (checkWidth > 0 && checkHeight > 0)
  66785. {
  66786. context->saveState();
  66787. if (colour1 == colour2)
  66788. {
  66789. context->setFill (colour1);
  66790. context->fillRect (area, false);
  66791. }
  66792. else
  66793. {
  66794. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66795. if (! clipped.isEmpty())
  66796. {
  66797. context->clipToRectangle (clipped);
  66798. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66799. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66800. const int startX = area.getX() + checkNumX * checkWidth;
  66801. const int startY = area.getY() + checkNumY * checkHeight;
  66802. const int right = clipped.getRight();
  66803. const int bottom = clipped.getBottom();
  66804. for (int i = 0; i < 2; ++i)
  66805. {
  66806. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66807. int cy = i;
  66808. for (int y = startY; y < bottom; y += checkHeight)
  66809. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66810. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66811. }
  66812. }
  66813. }
  66814. context->restoreState();
  66815. }
  66816. }
  66817. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66818. {
  66819. context->drawVerticalLine (x, top, bottom);
  66820. }
  66821. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66822. {
  66823. context->drawHorizontalLine (y, left, right);
  66824. }
  66825. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66826. {
  66827. context->drawLine (Line<float> (x1, y1, x2, y2));
  66828. }
  66829. void Graphics::drawLine (const float startX, const float startY,
  66830. const float endX, const float endY,
  66831. const float lineThickness) const
  66832. {
  66833. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66834. }
  66835. void Graphics::drawLine (const Line<float>& line) const
  66836. {
  66837. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66838. }
  66839. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66840. {
  66841. Path p;
  66842. p.addLineSegment (line, lineThickness);
  66843. fillPath (p);
  66844. }
  66845. void Graphics::drawDashedLine (const float startX, const float startY,
  66846. const float endX, const float endY,
  66847. const float* const dashLengths,
  66848. const int numDashLengths,
  66849. const float lineThickness) const
  66850. {
  66851. const double dx = endX - startX;
  66852. const double dy = endY - startY;
  66853. const double totalLen = juce_hypot (dx, dy);
  66854. if (totalLen >= 0.5)
  66855. {
  66856. const double onePixAlpha = 1.0 / totalLen;
  66857. double alpha = 0.0;
  66858. float x = startX;
  66859. float y = startY;
  66860. int n = 0;
  66861. while (alpha < 1.0f)
  66862. {
  66863. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66864. n = n % numDashLengths;
  66865. const float oldX = x;
  66866. const float oldY = y;
  66867. x = (float) (startX + dx * alpha);
  66868. y = (float) (startY + dy * alpha);
  66869. if ((n & 1) != 0)
  66870. {
  66871. if (lineThickness != 1.0f)
  66872. drawLine (oldX, oldY, x, y, lineThickness);
  66873. else
  66874. drawLine (oldX, oldY, x, y);
  66875. }
  66876. }
  66877. }
  66878. }
  66879. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66880. {
  66881. saveStateIfPending();
  66882. context->setInterpolationQuality (newQuality);
  66883. }
  66884. void Graphics::drawImageAt (const Image& imageToDraw,
  66885. const int topLeftX, const int topLeftY,
  66886. const bool fillAlphaChannelWithCurrentBrush) const
  66887. {
  66888. const int imageW = imageToDraw.getWidth();
  66889. const int imageH = imageToDraw.getHeight();
  66890. drawImage (imageToDraw,
  66891. topLeftX, topLeftY, imageW, imageH,
  66892. 0, 0, imageW, imageH,
  66893. fillAlphaChannelWithCurrentBrush);
  66894. }
  66895. void Graphics::drawImageWithin (const Image& imageToDraw,
  66896. const int destX, const int destY,
  66897. const int destW, const int destH,
  66898. const RectanglePlacement& placementWithinTarget,
  66899. const bool fillAlphaChannelWithCurrentBrush) const
  66900. {
  66901. // passing in a silly number can cause maths problems in rendering!
  66902. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66903. if (imageToDraw.isValid())
  66904. {
  66905. const int imageW = imageToDraw.getWidth();
  66906. const int imageH = imageToDraw.getHeight();
  66907. if (imageW > 0 && imageH > 0)
  66908. {
  66909. double newX = 0.0, newY = 0.0;
  66910. double newW = imageW;
  66911. double newH = imageH;
  66912. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66913. destX, destY, destW, destH);
  66914. if (newW > 0 && newH > 0)
  66915. {
  66916. drawImage (imageToDraw,
  66917. roundToInt (newX), roundToInt (newY),
  66918. roundToInt (newW), roundToInt (newH),
  66919. 0, 0, imageW, imageH,
  66920. fillAlphaChannelWithCurrentBrush);
  66921. }
  66922. }
  66923. }
  66924. }
  66925. void Graphics::drawImage (const Image& imageToDraw,
  66926. int dx, int dy, int dw, int dh,
  66927. int sx, int sy, int sw, int sh,
  66928. const bool fillAlphaChannelWithCurrentBrush) const
  66929. {
  66930. // passing in a silly number can cause maths problems in rendering!
  66931. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66932. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66933. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66934. {
  66935. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66936. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66937. .translated ((float) dx, (float) dy),
  66938. fillAlphaChannelWithCurrentBrush);
  66939. }
  66940. }
  66941. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66942. const AffineTransform& transform,
  66943. const bool fillAlphaChannelWithCurrentBrush) const
  66944. {
  66945. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66946. {
  66947. if (fillAlphaChannelWithCurrentBrush)
  66948. {
  66949. context->saveState();
  66950. context->clipToImageAlpha (imageToDraw, transform);
  66951. fillAll();
  66952. context->restoreState();
  66953. }
  66954. else
  66955. {
  66956. context->drawImage (imageToDraw, transform, false);
  66957. }
  66958. }
  66959. }
  66960. END_JUCE_NAMESPACE
  66961. /*** End of inlined file: juce_Graphics.cpp ***/
  66962. /*** Start of inlined file: juce_Justification.cpp ***/
  66963. BEGIN_JUCE_NAMESPACE
  66964. Justification::Justification (const Justification& other) throw()
  66965. : flags (other.flags)
  66966. {
  66967. }
  66968. Justification& Justification::operator= (const Justification& other) throw()
  66969. {
  66970. flags = other.flags;
  66971. return *this;
  66972. }
  66973. int Justification::getOnlyVerticalFlags() const throw()
  66974. {
  66975. return flags & (top | bottom | verticallyCentred);
  66976. }
  66977. int Justification::getOnlyHorizontalFlags() const throw()
  66978. {
  66979. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66980. }
  66981. void Justification::applyToRectangle (int& x, int& y,
  66982. const int w, const int h,
  66983. const int spaceX, const int spaceY,
  66984. const int spaceW, const int spaceH) const throw()
  66985. {
  66986. if ((flags & horizontallyCentred) != 0)
  66987. x = spaceX + ((spaceW - w) >> 1);
  66988. else if ((flags & right) != 0)
  66989. x = spaceX + spaceW - w;
  66990. else
  66991. x = spaceX;
  66992. if ((flags & verticallyCentred) != 0)
  66993. y = spaceY + ((spaceH - h) >> 1);
  66994. else if ((flags & bottom) != 0)
  66995. y = spaceY + spaceH - h;
  66996. else
  66997. y = spaceY;
  66998. }
  66999. END_JUCE_NAMESPACE
  67000. /*** End of inlined file: juce_Justification.cpp ***/
  67001. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67002. BEGIN_JUCE_NAMESPACE
  67003. // this will throw an assertion if you try to draw something that's not
  67004. // possible in postscript
  67005. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  67006. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  67007. #define notPossibleInPostscriptAssert jassertfalse
  67008. #else
  67009. #define notPossibleInPostscriptAssert
  67010. #endif
  67011. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  67012. const String& documentTitle,
  67013. const int totalWidth_,
  67014. const int totalHeight_)
  67015. : out (resultingPostScript),
  67016. totalWidth (totalWidth_),
  67017. totalHeight (totalHeight_),
  67018. needToClip (true)
  67019. {
  67020. stateStack.add (new SavedState());
  67021. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  67022. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  67023. out << "%!PS-Adobe-3.0 EPSF-3.0"
  67024. "\n%%BoundingBox: 0 0 600 824"
  67025. "\n%%Pages: 0"
  67026. "\n%%Creator: Raw Material Software JUCE"
  67027. "\n%%Title: " << documentTitle <<
  67028. "\n%%CreationDate: none"
  67029. "\n%%LanguageLevel: 2"
  67030. "\n%%EndComments"
  67031. "\n%%BeginProlog"
  67032. "\n%%BeginResource: JRes"
  67033. "\n/bd {bind def} bind def"
  67034. "\n/c {setrgbcolor} bd"
  67035. "\n/m {moveto} bd"
  67036. "\n/l {lineto} bd"
  67037. "\n/rl {rlineto} bd"
  67038. "\n/ct {curveto} bd"
  67039. "\n/cp {closepath} bd"
  67040. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  67041. "\n/doclip {initclip newpath} bd"
  67042. "\n/endclip {clip newpath} bd"
  67043. "\n%%EndResource"
  67044. "\n%%EndProlog"
  67045. "\n%%BeginSetup"
  67046. "\n%%EndSetup"
  67047. "\n%%Page: 1 1"
  67048. "\n%%BeginPageSetup"
  67049. "\n%%EndPageSetup\n\n"
  67050. << "40 800 translate\n"
  67051. << scale << ' ' << scale << " scale\n\n";
  67052. }
  67053. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  67054. {
  67055. }
  67056. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  67057. {
  67058. return true;
  67059. }
  67060. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  67061. {
  67062. if (x != 0 || y != 0)
  67063. {
  67064. stateStack.getLast()->xOffset += x;
  67065. stateStack.getLast()->yOffset += y;
  67066. needToClip = true;
  67067. }
  67068. }
  67069. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  67070. {
  67071. needToClip = true;
  67072. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67073. }
  67074. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67075. {
  67076. needToClip = true;
  67077. return stateStack.getLast()->clip.clipTo (clipRegion);
  67078. }
  67079. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67080. {
  67081. needToClip = true;
  67082. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67083. }
  67084. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67085. {
  67086. writeClip();
  67087. Path p (path);
  67088. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67089. writePath (p);
  67090. out << "clip\n";
  67091. }
  67092. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  67093. {
  67094. needToClip = true;
  67095. jassertfalse; // xxx
  67096. }
  67097. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67098. {
  67099. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67100. }
  67101. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  67102. {
  67103. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  67104. -stateStack.getLast()->yOffset);
  67105. }
  67106. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  67107. {
  67108. return stateStack.getLast()->clip.isEmpty();
  67109. }
  67110. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  67111. : xOffset (0),
  67112. yOffset (0)
  67113. {
  67114. }
  67115. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67116. {
  67117. }
  67118. void LowLevelGraphicsPostScriptRenderer::saveState()
  67119. {
  67120. stateStack.add (new SavedState (*stateStack.getLast()));
  67121. }
  67122. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67123. {
  67124. jassert (stateStack.size() > 0);
  67125. if (stateStack.size() > 0)
  67126. stateStack.removeLast();
  67127. }
  67128. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67129. {
  67130. if (needToClip)
  67131. {
  67132. needToClip = false;
  67133. out << "doclip ";
  67134. int itemsOnLine = 0;
  67135. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67136. {
  67137. if (++itemsOnLine == 6)
  67138. {
  67139. itemsOnLine = 0;
  67140. out << '\n';
  67141. }
  67142. const Rectangle<int>& r = *i.getRectangle();
  67143. out << r.getX() << ' ' << -r.getY() << ' '
  67144. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67145. }
  67146. out << "endclip\n";
  67147. }
  67148. }
  67149. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67150. {
  67151. Colour c (Colours::white.overlaidWith (colour));
  67152. if (lastColour != c)
  67153. {
  67154. lastColour = c;
  67155. out << String (c.getFloatRed(), 3) << ' '
  67156. << String (c.getFloatGreen(), 3) << ' '
  67157. << String (c.getFloatBlue(), 3) << " c\n";
  67158. }
  67159. }
  67160. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67161. {
  67162. out << String (x, 2) << ' '
  67163. << String (-y, 2) << ' ';
  67164. }
  67165. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67166. {
  67167. out << "newpath ";
  67168. float lastX = 0.0f;
  67169. float lastY = 0.0f;
  67170. int itemsOnLine = 0;
  67171. Path::Iterator i (path);
  67172. while (i.next())
  67173. {
  67174. if (++itemsOnLine == 4)
  67175. {
  67176. itemsOnLine = 0;
  67177. out << '\n';
  67178. }
  67179. switch (i.elementType)
  67180. {
  67181. case Path::Iterator::startNewSubPath:
  67182. writeXY (i.x1, i.y1);
  67183. lastX = i.x1;
  67184. lastY = i.y1;
  67185. out << "m ";
  67186. break;
  67187. case Path::Iterator::lineTo:
  67188. writeXY (i.x1, i.y1);
  67189. lastX = i.x1;
  67190. lastY = i.y1;
  67191. out << "l ";
  67192. break;
  67193. case Path::Iterator::quadraticTo:
  67194. {
  67195. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67196. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67197. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67198. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67199. writeXY (cp1x, cp1y);
  67200. writeXY (cp2x, cp2y);
  67201. writeXY (i.x2, i.y2);
  67202. out << "ct ";
  67203. lastX = i.x2;
  67204. lastY = i.y2;
  67205. }
  67206. break;
  67207. case Path::Iterator::cubicTo:
  67208. writeXY (i.x1, i.y1);
  67209. writeXY (i.x2, i.y2);
  67210. writeXY (i.x3, i.y3);
  67211. out << "ct ";
  67212. lastX = i.x3;
  67213. lastY = i.y3;
  67214. break;
  67215. case Path::Iterator::closePath:
  67216. out << "cp ";
  67217. break;
  67218. default:
  67219. jassertfalse;
  67220. break;
  67221. }
  67222. }
  67223. out << '\n';
  67224. }
  67225. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67226. {
  67227. out << "[ "
  67228. << trans.mat00 << ' '
  67229. << trans.mat10 << ' '
  67230. << trans.mat01 << ' '
  67231. << trans.mat11 << ' '
  67232. << trans.mat02 << ' '
  67233. << trans.mat12 << " ] concat ";
  67234. }
  67235. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67236. {
  67237. stateStack.getLast()->fillType = fillType;
  67238. }
  67239. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67240. {
  67241. }
  67242. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67243. {
  67244. }
  67245. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67246. {
  67247. if (stateStack.getLast()->fillType.isColour())
  67248. {
  67249. writeClip();
  67250. writeColour (stateStack.getLast()->fillType.colour);
  67251. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67252. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67253. }
  67254. else
  67255. {
  67256. Path p;
  67257. p.addRectangle (r);
  67258. fillPath (p, AffineTransform::identity);
  67259. }
  67260. }
  67261. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67262. {
  67263. if (stateStack.getLast()->fillType.isColour())
  67264. {
  67265. writeClip();
  67266. Path p (path);
  67267. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67268. (float) stateStack.getLast()->yOffset));
  67269. writePath (p);
  67270. writeColour (stateStack.getLast()->fillType.colour);
  67271. out << "fill\n";
  67272. }
  67273. else if (stateStack.getLast()->fillType.isGradient())
  67274. {
  67275. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67276. // postscript can't do semi-transparent ones.
  67277. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67278. writeClip();
  67279. out << "gsave ";
  67280. {
  67281. Path p (path);
  67282. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67283. writePath (p);
  67284. out << "clip\n";
  67285. }
  67286. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67287. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67288. // time-being, this just fills it with the average colour..
  67289. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67290. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67291. out << "grestore\n";
  67292. }
  67293. }
  67294. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67295. const int sx, const int sy,
  67296. const int maxW, const int maxH) const
  67297. {
  67298. out << "{<\n";
  67299. const int w = jmin (maxW, im.getWidth());
  67300. const int h = jmin (maxH, im.getHeight());
  67301. int charsOnLine = 0;
  67302. const Image::BitmapData srcData (im, 0, 0, w, h);
  67303. Colour pixel;
  67304. for (int y = h; --y >= 0;)
  67305. {
  67306. for (int x = 0; x < w; ++x)
  67307. {
  67308. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67309. if (x >= sx && y >= sy)
  67310. {
  67311. if (im.isARGB())
  67312. {
  67313. PixelARGB p (*(const PixelARGB*) pixelData);
  67314. p.unpremultiply();
  67315. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67316. }
  67317. else if (im.isRGB())
  67318. {
  67319. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67320. }
  67321. else
  67322. {
  67323. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67324. }
  67325. }
  67326. else
  67327. {
  67328. pixel = Colours::transparentWhite;
  67329. }
  67330. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67331. out << String::toHexString (pixelValues, 3, 0);
  67332. charsOnLine += 3;
  67333. if (charsOnLine > 100)
  67334. {
  67335. out << '\n';
  67336. charsOnLine = 0;
  67337. }
  67338. }
  67339. }
  67340. out << "\n>}\n";
  67341. }
  67342. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67343. {
  67344. const int w = sourceImage.getWidth();
  67345. const int h = sourceImage.getHeight();
  67346. writeClip();
  67347. out << "gsave ";
  67348. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67349. .scaled (1.0f, -1.0f));
  67350. RectangleList imageClip;
  67351. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67352. out << "newpath ";
  67353. int itemsOnLine = 0;
  67354. for (RectangleList::Iterator i (imageClip); i.next();)
  67355. {
  67356. if (++itemsOnLine == 6)
  67357. {
  67358. out << '\n';
  67359. itemsOnLine = 0;
  67360. }
  67361. const Rectangle<int>& r = *i.getRectangle();
  67362. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67363. }
  67364. out << " clip newpath\n";
  67365. out << w << ' ' << h << " scale\n";
  67366. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67367. writeImage (sourceImage, 0, 0, w, h);
  67368. out << "false 3 colorimage grestore\n";
  67369. needToClip = true;
  67370. }
  67371. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67372. {
  67373. Path p;
  67374. p.addLineSegment (line, 1.0f);
  67375. fillPath (p, AffineTransform::identity);
  67376. }
  67377. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67378. {
  67379. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67380. }
  67381. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67382. {
  67383. drawLine (Line<float> (left, (float) y, right, (float) y));
  67384. }
  67385. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67386. {
  67387. stateStack.getLast()->font = newFont;
  67388. }
  67389. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67390. {
  67391. return stateStack.getLast()->font;
  67392. }
  67393. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67394. {
  67395. Path p;
  67396. Font& font = stateStack.getLast()->font;
  67397. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67398. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67399. }
  67400. END_JUCE_NAMESPACE
  67401. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67402. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67403. BEGIN_JUCE_NAMESPACE
  67404. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67405. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67406. #endif
  67407. #if JUCE_MSVC
  67408. #pragma warning (push)
  67409. #pragma warning (disable: 4127) // "expression is constant" warning
  67410. #if JUCE_DEBUG
  67411. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67412. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67413. #endif
  67414. #endif
  67415. namespace SoftwareRendererClasses
  67416. {
  67417. template <class PixelType, bool replaceExisting = false>
  67418. class SolidColourEdgeTableRenderer
  67419. {
  67420. public:
  67421. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67422. : data (data_),
  67423. sourceColour (colour)
  67424. {
  67425. if (sizeof (PixelType) == 3)
  67426. {
  67427. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67428. && sourceColour.getGreen() == sourceColour.getBlue();
  67429. filler[0].set (sourceColour);
  67430. filler[1].set (sourceColour);
  67431. filler[2].set (sourceColour);
  67432. filler[3].set (sourceColour);
  67433. }
  67434. }
  67435. forcedinline void setEdgeTableYPos (const int y) throw()
  67436. {
  67437. linePixels = (PixelType*) data.getLinePointer (y);
  67438. }
  67439. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67440. {
  67441. if (replaceExisting)
  67442. linePixels[x].set (sourceColour);
  67443. else
  67444. linePixels[x].blend (sourceColour, alphaLevel);
  67445. }
  67446. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67447. {
  67448. if (replaceExisting)
  67449. linePixels[x].set (sourceColour);
  67450. else
  67451. linePixels[x].blend (sourceColour);
  67452. }
  67453. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67454. {
  67455. PixelARGB p (sourceColour);
  67456. p.multiplyAlpha (alphaLevel);
  67457. PixelType* dest = linePixels + x;
  67458. if (replaceExisting || p.getAlpha() >= 0xff)
  67459. replaceLine (dest, p, width);
  67460. else
  67461. blendLine (dest, p, width);
  67462. }
  67463. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67464. {
  67465. PixelType* dest = linePixels + x;
  67466. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67467. replaceLine (dest, sourceColour, width);
  67468. else
  67469. blendLine (dest, sourceColour, width);
  67470. }
  67471. private:
  67472. const Image::BitmapData& data;
  67473. PixelType* linePixels;
  67474. PixelARGB sourceColour;
  67475. PixelRGB filler [4];
  67476. bool areRGBComponentsEqual;
  67477. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67478. {
  67479. do
  67480. {
  67481. dest->blend (colour);
  67482. ++dest;
  67483. } while (--width > 0);
  67484. }
  67485. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67486. {
  67487. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67488. {
  67489. memset (dest, colour.getRed(), width * 3);
  67490. }
  67491. else
  67492. {
  67493. if (width >> 5)
  67494. {
  67495. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67496. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67497. {
  67498. dest->set (colour);
  67499. ++dest;
  67500. --width;
  67501. }
  67502. while (width > 4)
  67503. {
  67504. int* d = reinterpret_cast<int*> (dest);
  67505. *d++ = intFiller[0];
  67506. *d++ = intFiller[1];
  67507. *d++ = intFiller[2];
  67508. dest = reinterpret_cast<PixelRGB*> (d);
  67509. width -= 4;
  67510. }
  67511. }
  67512. while (--width >= 0)
  67513. {
  67514. dest->set (colour);
  67515. ++dest;
  67516. }
  67517. }
  67518. }
  67519. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67520. {
  67521. memset (dest, colour.getAlpha(), width);
  67522. }
  67523. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67524. {
  67525. do
  67526. {
  67527. dest->set (colour);
  67528. ++dest;
  67529. } while (--width > 0);
  67530. }
  67531. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  67532. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  67533. };
  67534. class LinearGradientPixelGenerator
  67535. {
  67536. public:
  67537. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67538. : lookupTable (lookupTable_), numEntries (numEntries_)
  67539. {
  67540. jassert (numEntries_ >= 0);
  67541. Point<float> p1 (gradient.point1);
  67542. Point<float> p2 (gradient.point2);
  67543. if (! transform.isIdentity())
  67544. {
  67545. const Line<float> l (p2, p1);
  67546. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67547. p1.applyTransform (transform);
  67548. p2.applyTransform (transform);
  67549. p3.applyTransform (transform);
  67550. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67551. }
  67552. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67553. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67554. if (vertical)
  67555. {
  67556. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67557. start = roundToInt (p1.getY() * scale);
  67558. }
  67559. else if (horizontal)
  67560. {
  67561. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67562. start = roundToInt (p1.getX() * scale);
  67563. }
  67564. else
  67565. {
  67566. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67567. yTerm = p1.getY() - p1.getX() / grad;
  67568. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67569. grad *= scale;
  67570. }
  67571. }
  67572. forcedinline void setY (const int y) throw()
  67573. {
  67574. if (vertical)
  67575. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67576. else if (! horizontal)
  67577. start = roundToInt ((y - yTerm) * grad);
  67578. }
  67579. inline const PixelARGB getPixel (const int x) const throw()
  67580. {
  67581. return vertical ? linePix
  67582. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67583. }
  67584. private:
  67585. const PixelARGB* const lookupTable;
  67586. const int numEntries;
  67587. PixelARGB linePix;
  67588. int start, scale;
  67589. double grad, yTerm;
  67590. bool vertical, horizontal;
  67591. enum { numScaleBits = 12 };
  67592. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  67593. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  67594. };
  67595. class RadialGradientPixelGenerator
  67596. {
  67597. public:
  67598. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67599. const PixelARGB* const lookupTable_, const int numEntries_)
  67600. : lookupTable (lookupTable_),
  67601. numEntries (numEntries_),
  67602. gx1 (gradient.point1.getX()),
  67603. gy1 (gradient.point1.getY())
  67604. {
  67605. jassert (numEntries_ >= 0);
  67606. const Point<float> diff (gradient.point1 - gradient.point2);
  67607. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67608. invScale = numEntries / std::sqrt (maxDist);
  67609. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67610. }
  67611. forcedinline void setY (const int y) throw()
  67612. {
  67613. dy = y - gy1;
  67614. dy *= dy;
  67615. }
  67616. inline const PixelARGB getPixel (const int px) const throw()
  67617. {
  67618. double x = px - gx1;
  67619. x *= x;
  67620. x += dy;
  67621. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67622. }
  67623. protected:
  67624. const PixelARGB* const lookupTable;
  67625. const int numEntries;
  67626. const double gx1, gy1;
  67627. double maxDist, invScale, dy;
  67628. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  67629. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  67630. };
  67631. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67632. {
  67633. public:
  67634. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67635. const PixelARGB* const lookupTable_, const int numEntries_)
  67636. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67637. inverseTransform (transform.inverted())
  67638. {
  67639. tM10 = inverseTransform.mat10;
  67640. tM00 = inverseTransform.mat00;
  67641. }
  67642. forcedinline void setY (const int y) throw()
  67643. {
  67644. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67645. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67646. }
  67647. inline const PixelARGB getPixel (const int px) const throw()
  67648. {
  67649. double x = px;
  67650. const double y = tM10 * x + lineYM11;
  67651. x = tM00 * x + lineYM01;
  67652. x *= x;
  67653. x += y * y;
  67654. if (x >= maxDist)
  67655. return lookupTable [numEntries];
  67656. else
  67657. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67658. }
  67659. private:
  67660. double tM10, tM00, lineYM01, lineYM11;
  67661. const AffineTransform inverseTransform;
  67662. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  67663. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  67664. };
  67665. template <class PixelType, class GradientType>
  67666. class GradientEdgeTableRenderer : public GradientType
  67667. {
  67668. public:
  67669. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67670. const PixelARGB* const lookupTable_, const int numEntries_)
  67671. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67672. destData (destData_)
  67673. {
  67674. }
  67675. forcedinline void setEdgeTableYPos (const int y) throw()
  67676. {
  67677. linePixels = (PixelType*) destData.getLinePointer (y);
  67678. GradientType::setY (y);
  67679. }
  67680. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67681. {
  67682. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67683. }
  67684. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67685. {
  67686. linePixels[x].blend (GradientType::getPixel (x));
  67687. }
  67688. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67689. {
  67690. PixelType* dest = linePixels + x;
  67691. if (alphaLevel < 0xff)
  67692. {
  67693. do
  67694. {
  67695. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67696. } while (--width > 0);
  67697. }
  67698. else
  67699. {
  67700. do
  67701. {
  67702. (dest++)->blend (GradientType::getPixel (x++));
  67703. } while (--width > 0);
  67704. }
  67705. }
  67706. void handleEdgeTableLineFull (int x, int width) const throw()
  67707. {
  67708. PixelType* dest = linePixels + x;
  67709. do
  67710. {
  67711. (dest++)->blend (GradientType::getPixel (x++));
  67712. } while (--width > 0);
  67713. }
  67714. private:
  67715. const Image::BitmapData& destData;
  67716. PixelType* linePixels;
  67717. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  67718. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  67719. };
  67720. static forcedinline int safeModulo (int n, const int divisor) throw()
  67721. {
  67722. jassert (divisor > 0);
  67723. n %= divisor;
  67724. return (n < 0) ? (n + divisor) : n;
  67725. }
  67726. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67727. class ImageFillEdgeTableRenderer
  67728. {
  67729. public:
  67730. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67731. const Image::BitmapData& srcData_,
  67732. const int extraAlpha_,
  67733. const int x, const int y)
  67734. : destData (destData_),
  67735. srcData (srcData_),
  67736. extraAlpha (extraAlpha_ + 1),
  67737. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  67738. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  67739. {
  67740. }
  67741. forcedinline void setEdgeTableYPos (int y) throw()
  67742. {
  67743. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67744. y -= yOffset;
  67745. if (repeatPattern)
  67746. {
  67747. jassert (y >= 0);
  67748. y %= srcData.height;
  67749. }
  67750. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67751. }
  67752. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67753. {
  67754. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67755. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67756. }
  67757. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67758. {
  67759. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67760. }
  67761. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67762. {
  67763. DestPixelType* dest = linePixels + x;
  67764. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67765. x -= xOffset;
  67766. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67767. if (alphaLevel < 0xfe)
  67768. {
  67769. do
  67770. {
  67771. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67772. } while (--width > 0);
  67773. }
  67774. else
  67775. {
  67776. if (repeatPattern)
  67777. {
  67778. do
  67779. {
  67780. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67781. } while (--width > 0);
  67782. }
  67783. else
  67784. {
  67785. copyRow (dest, sourceLineStart + x, width);
  67786. }
  67787. }
  67788. }
  67789. void handleEdgeTableLineFull (int x, int width) const throw()
  67790. {
  67791. DestPixelType* dest = linePixels + x;
  67792. x -= xOffset;
  67793. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67794. if (extraAlpha < 0xfe)
  67795. {
  67796. do
  67797. {
  67798. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67799. } while (--width > 0);
  67800. }
  67801. else
  67802. {
  67803. if (repeatPattern)
  67804. {
  67805. do
  67806. {
  67807. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67808. } while (--width > 0);
  67809. }
  67810. else
  67811. {
  67812. copyRow (dest, sourceLineStart + x, width);
  67813. }
  67814. }
  67815. }
  67816. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67817. {
  67818. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67819. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67820. uint8* mask = (uint8*) (s + x - xOffset);
  67821. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67822. mask += PixelARGB::indexA;
  67823. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67824. }
  67825. private:
  67826. const Image::BitmapData& destData;
  67827. const Image::BitmapData& srcData;
  67828. const int extraAlpha, xOffset, yOffset;
  67829. DestPixelType* linePixels;
  67830. SrcPixelType* sourceLineStart;
  67831. template <class PixelType1, class PixelType2>
  67832. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67833. {
  67834. do
  67835. {
  67836. dest++ ->blend (*src++);
  67837. } while (--width > 0);
  67838. }
  67839. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67840. {
  67841. memcpy (dest, src, width * sizeof (PixelRGB));
  67842. }
  67843. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  67844. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  67845. };
  67846. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67847. class TransformedImageFillEdgeTableRenderer
  67848. {
  67849. public:
  67850. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67851. const Image::BitmapData& srcData_,
  67852. const AffineTransform& transform,
  67853. const int extraAlpha_,
  67854. const bool betterQuality_)
  67855. : interpolator (transform),
  67856. destData (destData_),
  67857. srcData (srcData_),
  67858. extraAlpha (extraAlpha_ + 1),
  67859. betterQuality (betterQuality_),
  67860. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  67861. pixelOffsetInt (betterQuality_ ? -128 : 0),
  67862. maxX (srcData_.width - 1),
  67863. maxY (srcData_.height - 1),
  67864. scratchSize (2048)
  67865. {
  67866. scratchBuffer.malloc (scratchSize);
  67867. }
  67868. ~TransformedImageFillEdgeTableRenderer()
  67869. {
  67870. }
  67871. forcedinline void setEdgeTableYPos (const int newY) throw()
  67872. {
  67873. y = newY;
  67874. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67875. }
  67876. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  67877. {
  67878. alphaLevel *= extraAlpha;
  67879. alphaLevel >>= 8;
  67880. SrcPixelType p;
  67881. generate (&p, x, 1);
  67882. linePixels[x].blend (p, alphaLevel);
  67883. }
  67884. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67885. {
  67886. SrcPixelType p;
  67887. generate (&p, x, 1);
  67888. linePixels[x].blend (p, extraAlpha);
  67889. }
  67890. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67891. {
  67892. if (width > scratchSize)
  67893. {
  67894. scratchSize = width;
  67895. scratchBuffer.malloc (scratchSize);
  67896. }
  67897. SrcPixelType* span = scratchBuffer;
  67898. generate (span, x, width);
  67899. DestPixelType* dest = linePixels + x;
  67900. alphaLevel *= extraAlpha;
  67901. alphaLevel >>= 8;
  67902. if (alphaLevel < 0xfe)
  67903. {
  67904. do
  67905. {
  67906. dest++ ->blend (*span++, alphaLevel);
  67907. } while (--width > 0);
  67908. }
  67909. else
  67910. {
  67911. do
  67912. {
  67913. dest++ ->blend (*span++);
  67914. } while (--width > 0);
  67915. }
  67916. }
  67917. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67918. {
  67919. handleEdgeTableLine (x, width, 255);
  67920. }
  67921. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67922. {
  67923. if (width > scratchSize)
  67924. {
  67925. scratchSize = width;
  67926. scratchBuffer.malloc (scratchSize);
  67927. }
  67928. y = y_;
  67929. generate (scratchBuffer, x, width);
  67930. et.clipLineToMask (x, y_,
  67931. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67932. sizeof (SrcPixelType), width);
  67933. }
  67934. private:
  67935. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  67936. {
  67937. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67938. do
  67939. {
  67940. int hiResX, hiResY;
  67941. this->interpolator.next (hiResX, hiResY);
  67942. hiResX += pixelOffsetInt;
  67943. hiResY += pixelOffsetInt;
  67944. int loResX = hiResX >> 8;
  67945. int loResY = hiResY >> 8;
  67946. if (repeatPattern)
  67947. {
  67948. loResX = safeModulo (loResX, srcData.width);
  67949. loResY = safeModulo (loResY, srcData.height);
  67950. }
  67951. if (betterQuality
  67952. && ((unsigned int) loResX) < (unsigned int) maxX
  67953. && ((unsigned int) loResY) < (unsigned int) maxY)
  67954. {
  67955. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67956. hiResX &= 255;
  67957. hiResY &= 255;
  67958. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67959. uint32 weight = (256 - hiResX) * (256 - hiResY);
  67960. c[0] += weight * src[0];
  67961. c[1] += weight * src[1];
  67962. c[2] += weight * src[2];
  67963. c[3] += weight * src[3];
  67964. weight = hiResX * (256 - hiResY);
  67965. c[0] += weight * src[4];
  67966. c[1] += weight * src[5];
  67967. c[2] += weight * src[6];
  67968. c[3] += weight * src[7];
  67969. src += this->srcData.lineStride;
  67970. weight = (256 - hiResX) * hiResY;
  67971. c[0] += weight * src[0];
  67972. c[1] += weight * src[1];
  67973. c[2] += weight * src[2];
  67974. c[3] += weight * src[3];
  67975. weight = hiResX * hiResY;
  67976. c[0] += weight * src[4];
  67977. c[1] += weight * src[5];
  67978. c[2] += weight * src[6];
  67979. c[3] += weight * src[7];
  67980. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67981. (uint8) (c[PixelARGB::indexR] >> 16),
  67982. (uint8) (c[PixelARGB::indexG] >> 16),
  67983. (uint8) (c[PixelARGB::indexB] >> 16));
  67984. }
  67985. else
  67986. {
  67987. if (! repeatPattern)
  67988. {
  67989. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67990. if (loResX < 0) loResX = 0;
  67991. if (loResY < 0) loResY = 0;
  67992. if (loResX > maxX) loResX = maxX;
  67993. if (loResY > maxY) loResY = maxY;
  67994. }
  67995. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  67996. }
  67997. ++dest;
  67998. } while (--numPixels > 0);
  67999. }
  68000. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  68001. {
  68002. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68003. do
  68004. {
  68005. int hiResX, hiResY;
  68006. this->interpolator.next (hiResX, hiResY);
  68007. hiResX += pixelOffsetInt;
  68008. hiResY += pixelOffsetInt;
  68009. int loResX = hiResX >> 8;
  68010. int loResY = hiResY >> 8;
  68011. if (repeatPattern)
  68012. {
  68013. loResX = safeModulo (loResX, srcData.width);
  68014. loResY = safeModulo (loResY, srcData.height);
  68015. }
  68016. if (betterQuality
  68017. && ((unsigned int) loResX) < (unsigned int) maxX
  68018. && ((unsigned int) loResY) < (unsigned int) maxY)
  68019. {
  68020. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  68021. hiResX &= 255;
  68022. hiResY &= 255;
  68023. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68024. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  68025. c[0] += weight * src[0];
  68026. c[1] += weight * src[1];
  68027. c[2] += weight * src[2];
  68028. weight = hiResX * (256 - hiResY);
  68029. c[0] += weight * src[3];
  68030. c[1] += weight * src[4];
  68031. c[2] += weight * src[5];
  68032. src += this->srcData.lineStride;
  68033. weight = (256 - hiResX) * hiResY;
  68034. c[0] += weight * src[0];
  68035. c[1] += weight * src[1];
  68036. c[2] += weight * src[2];
  68037. weight = hiResX * hiResY;
  68038. c[0] += weight * src[3];
  68039. c[1] += weight * src[4];
  68040. c[2] += weight * src[5];
  68041. dest->setARGB ((uint8) 255,
  68042. (uint8) (c[PixelRGB::indexR] >> 16),
  68043. (uint8) (c[PixelRGB::indexG] >> 16),
  68044. (uint8) (c[PixelRGB::indexB] >> 16));
  68045. }
  68046. else
  68047. {
  68048. if (! repeatPattern)
  68049. {
  68050. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68051. if (loResX < 0) loResX = 0;
  68052. if (loResY < 0) loResY = 0;
  68053. if (loResX > maxX) loResX = maxX;
  68054. if (loResY > maxY) loResY = maxY;
  68055. }
  68056. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  68057. }
  68058. ++dest;
  68059. } while (--numPixels > 0);
  68060. }
  68061. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  68062. {
  68063. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68064. do
  68065. {
  68066. int hiResX, hiResY;
  68067. this->interpolator.next (hiResX, hiResY);
  68068. hiResX += pixelOffsetInt;
  68069. hiResY += pixelOffsetInt;
  68070. int loResX = hiResX >> 8;
  68071. int loResY = hiResY >> 8;
  68072. if (repeatPattern)
  68073. {
  68074. loResX = safeModulo (loResX, srcData.width);
  68075. loResY = safeModulo (loResY, srcData.height);
  68076. }
  68077. if (betterQuality
  68078. && ((unsigned int) loResX) < (unsigned int) maxX
  68079. && ((unsigned int) loResY) < (unsigned int) maxY)
  68080. {
  68081. hiResX &= 255;
  68082. hiResY &= 255;
  68083. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68084. uint32 c = 256 * 128;
  68085. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  68086. c += src[1] * (hiResX * (256 - hiResY));
  68087. src += this->srcData.lineStride;
  68088. c += src[0] * ((256 - hiResX) * hiResY);
  68089. c += src[1] * (hiResX * hiResY);
  68090. *((uint8*) dest) = (uint8) c;
  68091. }
  68092. else
  68093. {
  68094. if (! repeatPattern)
  68095. {
  68096. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68097. if (loResX < 0) loResX = 0;
  68098. if (loResY < 0) loResY = 0;
  68099. if (loResX > maxX) loResX = maxX;
  68100. if (loResY > maxY) loResY = maxY;
  68101. }
  68102. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  68103. }
  68104. ++dest;
  68105. } while (--numPixels > 0);
  68106. }
  68107. class TransformedImageSpanInterpolator
  68108. {
  68109. public:
  68110. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  68111. : inverseTransform (transform.inverted())
  68112. {}
  68113. void setStartOfLine (float x, float y, const int numPixels) throw()
  68114. {
  68115. float x1 = x, y1 = y;
  68116. x += numPixels;
  68117. inverseTransform.transformPoints (x1, y1, x, y);
  68118. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  68119. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  68120. }
  68121. void next (int& x, int& y) throw()
  68122. {
  68123. x = xBresenham.n;
  68124. xBresenham.stepToNext();
  68125. y = yBresenham.n;
  68126. yBresenham.stepToNext();
  68127. }
  68128. private:
  68129. class BresenhamInterpolator
  68130. {
  68131. public:
  68132. BresenhamInterpolator() throw() {}
  68133. void set (const int n1, const int n2, const int numSteps_) throw()
  68134. {
  68135. numSteps = jmax (1, numSteps_);
  68136. step = (n2 - n1) / numSteps;
  68137. remainder = modulo = (n2 - n1) % numSteps;
  68138. n = n1;
  68139. if (modulo <= 0)
  68140. {
  68141. modulo += numSteps;
  68142. remainder += numSteps;
  68143. --step;
  68144. }
  68145. modulo -= numSteps;
  68146. }
  68147. forcedinline void stepToNext() throw()
  68148. {
  68149. modulo += remainder;
  68150. n += step;
  68151. if (modulo > 0)
  68152. {
  68153. modulo -= numSteps;
  68154. ++n;
  68155. }
  68156. }
  68157. int n;
  68158. private:
  68159. int numSteps, step, modulo, remainder;
  68160. };
  68161. const AffineTransform inverseTransform;
  68162. BresenhamInterpolator xBresenham, yBresenham;
  68163. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  68164. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  68165. };
  68166. TransformedImageSpanInterpolator interpolator;
  68167. const Image::BitmapData& destData;
  68168. const Image::BitmapData& srcData;
  68169. const int extraAlpha;
  68170. const bool betterQuality;
  68171. const float pixelOffset;
  68172. const int pixelOffsetInt, maxX, maxY;
  68173. int y;
  68174. DestPixelType* linePixels;
  68175. HeapBlock <SrcPixelType> scratchBuffer;
  68176. int scratchSize;
  68177. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  68178. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  68179. };
  68180. class ClipRegionBase : public ReferenceCountedObject
  68181. {
  68182. public:
  68183. ClipRegionBase() {}
  68184. virtual ~ClipRegionBase() {}
  68185. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68186. virtual const Ptr clone() const = 0;
  68187. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68188. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68189. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68190. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68191. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68192. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68193. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68194. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68195. virtual const Rectangle<int> getClipBounds() const = 0;
  68196. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68197. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68198. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68199. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68200. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68201. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68202. protected:
  68203. template <class Iterator>
  68204. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68205. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68206. {
  68207. switch (destData.pixelFormat)
  68208. {
  68209. case Image::ARGB:
  68210. switch (srcData.pixelFormat)
  68211. {
  68212. case Image::ARGB:
  68213. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68214. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68215. break;
  68216. case Image::RGB:
  68217. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68218. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68219. break;
  68220. default:
  68221. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68222. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68223. break;
  68224. }
  68225. break;
  68226. case Image::RGB:
  68227. switch (srcData.pixelFormat)
  68228. {
  68229. case Image::ARGB:
  68230. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68231. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68232. break;
  68233. case Image::RGB:
  68234. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68235. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68236. break;
  68237. default:
  68238. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68239. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68240. break;
  68241. }
  68242. break;
  68243. default:
  68244. switch (srcData.pixelFormat)
  68245. {
  68246. case Image::ARGB:
  68247. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68248. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68249. break;
  68250. case Image::RGB:
  68251. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68252. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68253. break;
  68254. default:
  68255. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68256. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68257. break;
  68258. }
  68259. break;
  68260. }
  68261. }
  68262. template <class Iterator>
  68263. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68264. {
  68265. switch (destData.pixelFormat)
  68266. {
  68267. case Image::ARGB:
  68268. switch (srcData.pixelFormat)
  68269. {
  68270. case Image::ARGB:
  68271. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68272. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68273. break;
  68274. case Image::RGB:
  68275. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68276. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68277. break;
  68278. default:
  68279. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68280. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68281. break;
  68282. }
  68283. break;
  68284. case Image::RGB:
  68285. switch (srcData.pixelFormat)
  68286. {
  68287. case Image::ARGB:
  68288. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68289. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68290. break;
  68291. case Image::RGB:
  68292. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68293. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68294. break;
  68295. default:
  68296. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68297. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68298. break;
  68299. }
  68300. break;
  68301. default:
  68302. switch (srcData.pixelFormat)
  68303. {
  68304. case Image::ARGB:
  68305. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68306. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68307. break;
  68308. case Image::RGB:
  68309. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68310. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68311. break;
  68312. default:
  68313. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68314. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68315. break;
  68316. }
  68317. break;
  68318. }
  68319. }
  68320. template <class Iterator, class DestPixelType>
  68321. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68322. {
  68323. jassert (destData.pixelStride == sizeof (DestPixelType));
  68324. if (replaceContents)
  68325. {
  68326. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68327. iter.iterate (r);
  68328. }
  68329. else
  68330. {
  68331. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68332. iter.iterate (r);
  68333. }
  68334. }
  68335. template <class Iterator, class DestPixelType>
  68336. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68337. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68338. {
  68339. jassert (destData.pixelStride == sizeof (DestPixelType));
  68340. if (g.isRadial)
  68341. {
  68342. if (isIdentity)
  68343. {
  68344. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68345. iter.iterate (renderer);
  68346. }
  68347. else
  68348. {
  68349. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68350. iter.iterate (renderer);
  68351. }
  68352. }
  68353. else
  68354. {
  68355. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68356. iter.iterate (renderer);
  68357. }
  68358. }
  68359. };
  68360. class ClipRegion_EdgeTable : public ClipRegionBase
  68361. {
  68362. public:
  68363. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68364. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68365. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68366. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68367. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68368. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68369. ~ClipRegion_EdgeTable() {}
  68370. const Ptr clone() const
  68371. {
  68372. return new ClipRegion_EdgeTable (*this);
  68373. }
  68374. const Ptr applyClipTo (const Ptr& target) const
  68375. {
  68376. return target->clipToEdgeTable (edgeTable);
  68377. }
  68378. const Ptr clipToRectangle (const Rectangle<int>& r)
  68379. {
  68380. edgeTable.clipToRectangle (r);
  68381. return edgeTable.isEmpty() ? 0 : this;
  68382. }
  68383. const Ptr clipToRectangleList (const RectangleList& r)
  68384. {
  68385. RectangleList inverse (edgeTable.getMaximumBounds());
  68386. if (inverse.subtract (r))
  68387. for (RectangleList::Iterator iter (inverse); iter.next();)
  68388. edgeTable.excludeRectangle (*iter.getRectangle());
  68389. return edgeTable.isEmpty() ? 0 : this;
  68390. }
  68391. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68392. {
  68393. edgeTable.excludeRectangle (r);
  68394. return edgeTable.isEmpty() ? 0 : this;
  68395. }
  68396. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68397. {
  68398. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68399. edgeTable.clipToEdgeTable (et);
  68400. return edgeTable.isEmpty() ? 0 : this;
  68401. }
  68402. const Ptr clipToEdgeTable (const EdgeTable& et)
  68403. {
  68404. edgeTable.clipToEdgeTable (et);
  68405. return edgeTable.isEmpty() ? 0 : this;
  68406. }
  68407. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68408. {
  68409. const Image::BitmapData srcData (image, false);
  68410. if (transform.isOnlyTranslation())
  68411. {
  68412. // If our translation doesn't involve any distortion, just use a simple blit..
  68413. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68414. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68415. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68416. {
  68417. const int imageX = ((tx + 128) >> 8);
  68418. const int imageY = ((ty + 128) >> 8);
  68419. if (image.getFormat() == Image::ARGB)
  68420. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68421. else
  68422. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68423. return edgeTable.isEmpty() ? 0 : this;
  68424. }
  68425. }
  68426. if (transform.isSingularity())
  68427. return 0;
  68428. {
  68429. Path p;
  68430. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68431. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68432. edgeTable.clipToEdgeTable (et2);
  68433. }
  68434. if (! edgeTable.isEmpty())
  68435. {
  68436. if (image.getFormat() == Image::ARGB)
  68437. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68438. else
  68439. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68440. }
  68441. return edgeTable.isEmpty() ? 0 : this;
  68442. }
  68443. bool clipRegionIntersects (const Rectangle<int>& r) const
  68444. {
  68445. return edgeTable.getMaximumBounds().intersects (r);
  68446. }
  68447. const Rectangle<int> getClipBounds() const
  68448. {
  68449. return edgeTable.getMaximumBounds();
  68450. }
  68451. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68452. {
  68453. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68454. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68455. if (! clipped.isEmpty())
  68456. {
  68457. ClipRegion_EdgeTable et (clipped);
  68458. et.edgeTable.clipToEdgeTable (edgeTable);
  68459. et.fillAllWithColour (destData, colour, replaceContents);
  68460. }
  68461. }
  68462. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68463. {
  68464. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68465. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68466. if (! clipped.isEmpty())
  68467. {
  68468. ClipRegion_EdgeTable et (clipped);
  68469. et.edgeTable.clipToEdgeTable (edgeTable);
  68470. et.fillAllWithColour (destData, colour, false);
  68471. }
  68472. }
  68473. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68474. {
  68475. switch (destData.pixelFormat)
  68476. {
  68477. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68478. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68479. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68480. }
  68481. }
  68482. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68483. {
  68484. HeapBlock <PixelARGB> lookupTable;
  68485. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68486. jassert (numLookupEntries > 0);
  68487. switch (destData.pixelFormat)
  68488. {
  68489. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68490. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68491. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68492. }
  68493. }
  68494. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68495. {
  68496. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68497. }
  68498. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68499. {
  68500. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68501. }
  68502. EdgeTable edgeTable;
  68503. private:
  68504. template <class SrcPixelType>
  68505. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68506. {
  68507. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68508. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68509. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68510. edgeTable.getMaximumBounds().getWidth());
  68511. }
  68512. template <class SrcPixelType>
  68513. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68514. {
  68515. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68516. edgeTable.clipToRectangle (r);
  68517. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68518. for (int y = 0; y < r.getHeight(); ++y)
  68519. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68520. }
  68521. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68522. };
  68523. class ClipRegion_RectangleList : public ClipRegionBase
  68524. {
  68525. public:
  68526. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68527. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68528. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68529. ~ClipRegion_RectangleList() {}
  68530. const Ptr clone() const
  68531. {
  68532. return new ClipRegion_RectangleList (*this);
  68533. }
  68534. const Ptr applyClipTo (const Ptr& target) const
  68535. {
  68536. return target->clipToRectangleList (clip);
  68537. }
  68538. const Ptr clipToRectangle (const Rectangle<int>& r)
  68539. {
  68540. clip.clipTo (r);
  68541. return clip.isEmpty() ? 0 : this;
  68542. }
  68543. const Ptr clipToRectangleList (const RectangleList& r)
  68544. {
  68545. clip.clipTo (r);
  68546. return clip.isEmpty() ? 0 : this;
  68547. }
  68548. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68549. {
  68550. clip.subtract (r);
  68551. return clip.isEmpty() ? 0 : this;
  68552. }
  68553. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68554. {
  68555. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68556. }
  68557. const Ptr clipToEdgeTable (const EdgeTable& et)
  68558. {
  68559. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68560. }
  68561. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68562. {
  68563. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68564. }
  68565. bool clipRegionIntersects (const Rectangle<int>& r) const
  68566. {
  68567. return clip.intersects (r);
  68568. }
  68569. const Rectangle<int> getClipBounds() const
  68570. {
  68571. return clip.getBounds();
  68572. }
  68573. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68574. {
  68575. SubRectangleIterator iter (clip, area);
  68576. switch (destData.pixelFormat)
  68577. {
  68578. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68579. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68580. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68581. }
  68582. }
  68583. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68584. {
  68585. SubRectangleIteratorFloat iter (clip, area);
  68586. switch (destData.pixelFormat)
  68587. {
  68588. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68589. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68590. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68591. }
  68592. }
  68593. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68594. {
  68595. switch (destData.pixelFormat)
  68596. {
  68597. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68598. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68599. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68600. }
  68601. }
  68602. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68603. {
  68604. HeapBlock <PixelARGB> lookupTable;
  68605. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68606. jassert (numLookupEntries > 0);
  68607. switch (destData.pixelFormat)
  68608. {
  68609. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68610. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68611. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68612. }
  68613. }
  68614. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68615. {
  68616. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68617. }
  68618. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68619. {
  68620. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68621. }
  68622. RectangleList clip;
  68623. template <class Renderer>
  68624. void iterate (Renderer& r) const throw()
  68625. {
  68626. RectangleList::Iterator iter (clip);
  68627. while (iter.next())
  68628. {
  68629. const Rectangle<int> rect (*iter.getRectangle());
  68630. const int x = rect.getX();
  68631. const int w = rect.getWidth();
  68632. jassert (w > 0);
  68633. const int bottom = rect.getBottom();
  68634. for (int y = rect.getY(); y < bottom; ++y)
  68635. {
  68636. r.setEdgeTableYPos (y);
  68637. r.handleEdgeTableLineFull (x, w);
  68638. }
  68639. }
  68640. }
  68641. private:
  68642. class SubRectangleIterator
  68643. {
  68644. public:
  68645. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68646. : clip (clip_), area (area_)
  68647. {
  68648. }
  68649. template <class Renderer>
  68650. void iterate (Renderer& r) const throw()
  68651. {
  68652. RectangleList::Iterator iter (clip);
  68653. while (iter.next())
  68654. {
  68655. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68656. if (! rect.isEmpty())
  68657. {
  68658. const int x = rect.getX();
  68659. const int w = rect.getWidth();
  68660. const int bottom = rect.getBottom();
  68661. for (int y = rect.getY(); y < bottom; ++y)
  68662. {
  68663. r.setEdgeTableYPos (y);
  68664. r.handleEdgeTableLineFull (x, w);
  68665. }
  68666. }
  68667. }
  68668. }
  68669. private:
  68670. const RectangleList& clip;
  68671. const Rectangle<int> area;
  68672. SubRectangleIterator (const SubRectangleIterator&);
  68673. SubRectangleIterator& operator= (const SubRectangleIterator&);
  68674. };
  68675. class SubRectangleIteratorFloat
  68676. {
  68677. public:
  68678. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68679. : clip (clip_), area (area_)
  68680. {
  68681. }
  68682. template <class Renderer>
  68683. void iterate (Renderer& r) const throw()
  68684. {
  68685. int left = roundToInt (area.getX() * 256.0f);
  68686. int top = roundToInt (area.getY() * 256.0f);
  68687. int right = roundToInt (area.getRight() * 256.0f);
  68688. int bottom = roundToInt (area.getBottom() * 256.0f);
  68689. int totalTop, totalLeft, totalBottom, totalRight;
  68690. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68691. if ((top >> 8) == (bottom >> 8))
  68692. {
  68693. topAlpha = bottom - top;
  68694. bottomAlpha = 0;
  68695. totalTop = top >> 8;
  68696. totalBottom = bottom = top = totalTop + 1;
  68697. }
  68698. else
  68699. {
  68700. if ((top & 255) == 0)
  68701. {
  68702. topAlpha = 0;
  68703. top = totalTop = (top >> 8);
  68704. }
  68705. else
  68706. {
  68707. topAlpha = 255 - (top & 255);
  68708. totalTop = (top >> 8);
  68709. top = totalTop + 1;
  68710. }
  68711. bottomAlpha = bottom & 255;
  68712. bottom >>= 8;
  68713. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68714. }
  68715. if ((left >> 8) == (right >> 8))
  68716. {
  68717. leftAlpha = right - left;
  68718. rightAlpha = 0;
  68719. totalLeft = (left >> 8);
  68720. totalRight = right = left = totalLeft + 1;
  68721. }
  68722. else
  68723. {
  68724. if ((left & 255) == 0)
  68725. {
  68726. leftAlpha = 0;
  68727. left = totalLeft = (left >> 8);
  68728. }
  68729. else
  68730. {
  68731. leftAlpha = 255 - (left & 255);
  68732. totalLeft = (left >> 8);
  68733. left = totalLeft + 1;
  68734. }
  68735. rightAlpha = right & 255;
  68736. right >>= 8;
  68737. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68738. }
  68739. RectangleList::Iterator iter (clip);
  68740. while (iter.next())
  68741. {
  68742. const int clipLeft = iter.getRectangle()->getX();
  68743. const int clipRight = iter.getRectangle()->getRight();
  68744. const int clipTop = iter.getRectangle()->getY();
  68745. const int clipBottom = iter.getRectangle()->getBottom();
  68746. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68747. {
  68748. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68749. {
  68750. if (topAlpha != 0 && totalTop >= clipTop)
  68751. {
  68752. r.setEdgeTableYPos (totalTop);
  68753. r.handleEdgeTablePixel (left, topAlpha);
  68754. }
  68755. const int endY = jmin (bottom, clipBottom);
  68756. for (int y = jmax (clipTop, top); y < endY; ++y)
  68757. {
  68758. r.setEdgeTableYPos (y);
  68759. r.handleEdgeTablePixelFull (left);
  68760. }
  68761. if (bottomAlpha != 0 && bottom < clipBottom)
  68762. {
  68763. r.setEdgeTableYPos (bottom);
  68764. r.handleEdgeTablePixel (left, bottomAlpha);
  68765. }
  68766. }
  68767. else
  68768. {
  68769. const int clippedLeft = jmax (left, clipLeft);
  68770. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68771. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68772. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68773. if (topAlpha != 0 && totalTop >= clipTop)
  68774. {
  68775. r.setEdgeTableYPos (totalTop);
  68776. if (doLeftAlpha)
  68777. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68778. if (clippedWidth > 0)
  68779. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68780. if (doRightAlpha)
  68781. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68782. }
  68783. const int endY = jmin (bottom, clipBottom);
  68784. for (int y = jmax (clipTop, top); y < endY; ++y)
  68785. {
  68786. r.setEdgeTableYPos (y);
  68787. if (doLeftAlpha)
  68788. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68789. if (clippedWidth > 0)
  68790. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68791. if (doRightAlpha)
  68792. r.handleEdgeTablePixel (right, rightAlpha);
  68793. }
  68794. if (bottomAlpha != 0 && bottom < clipBottom)
  68795. {
  68796. r.setEdgeTableYPos (bottom);
  68797. if (doLeftAlpha)
  68798. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68799. if (clippedWidth > 0)
  68800. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68801. if (doRightAlpha)
  68802. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68803. }
  68804. }
  68805. }
  68806. }
  68807. }
  68808. private:
  68809. const RectangleList& clip;
  68810. const Rectangle<float>& area;
  68811. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  68812. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  68813. };
  68814. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68815. };
  68816. }
  68817. class LowLevelGraphicsSoftwareRenderer::SavedState
  68818. {
  68819. public:
  68820. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68821. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68822. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68823. {
  68824. }
  68825. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68826. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68827. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68828. {
  68829. }
  68830. SavedState (const SavedState& other)
  68831. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  68832. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  68833. {
  68834. }
  68835. ~SavedState()
  68836. {
  68837. }
  68838. void setOrigin (const int x, const int y) throw()
  68839. {
  68840. xOffset += x;
  68841. yOffset += y;
  68842. }
  68843. bool clipToRectangle (const Rectangle<int>& r)
  68844. {
  68845. if (clip != 0)
  68846. {
  68847. cloneClipIfMultiplyReferenced();
  68848. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68849. }
  68850. return clip != 0;
  68851. }
  68852. bool clipToRectangleList (const RectangleList& r)
  68853. {
  68854. if (clip != 0)
  68855. {
  68856. cloneClipIfMultiplyReferenced();
  68857. RectangleList offsetList (r);
  68858. offsetList.offsetAll (xOffset, yOffset);
  68859. clip = clip->clipToRectangleList (offsetList);
  68860. }
  68861. return clip != 0;
  68862. }
  68863. bool excludeClipRectangle (const Rectangle<int>& r)
  68864. {
  68865. if (clip != 0)
  68866. {
  68867. cloneClipIfMultiplyReferenced();
  68868. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68869. }
  68870. return clip != 0;
  68871. }
  68872. void clipToPath (const Path& p, const AffineTransform& transform)
  68873. {
  68874. if (clip != 0)
  68875. {
  68876. cloneClipIfMultiplyReferenced();
  68877. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  68878. }
  68879. }
  68880. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68881. {
  68882. if (clip != 0)
  68883. {
  68884. if (image.hasAlphaChannel())
  68885. {
  68886. cloneClipIfMultiplyReferenced();
  68887. clip = clip->clipToImageAlpha (image, t.translated ((float) xOffset, (float) yOffset),
  68888. interpolationQuality != Graphics::lowResamplingQuality);
  68889. }
  68890. else
  68891. {
  68892. Path p;
  68893. p.addRectangle (image.getBounds());
  68894. clipToPath (p, t);
  68895. }
  68896. }
  68897. }
  68898. bool clipRegionIntersects (const Rectangle<int>& r) const
  68899. {
  68900. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68901. }
  68902. const Rectangle<int> getClipBounds() const
  68903. {
  68904. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  68905. }
  68906. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  68907. {
  68908. if (clip != 0)
  68909. {
  68910. if (fillType.isColour())
  68911. {
  68912. Image::BitmapData destData (image, true);
  68913. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68914. }
  68915. else
  68916. {
  68917. const Rectangle<int> totalClip (clip->getClipBounds());
  68918. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68919. if (! clipped.isEmpty())
  68920. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68921. }
  68922. }
  68923. }
  68924. void fillRect (Image& image, const Rectangle<float>& r)
  68925. {
  68926. if (clip != 0)
  68927. {
  68928. if (fillType.isColour())
  68929. {
  68930. Image::BitmapData destData (image, true);
  68931. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68932. }
  68933. else
  68934. {
  68935. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68936. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68937. if (! clipped.isEmpty())
  68938. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68939. }
  68940. }
  68941. }
  68942. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  68943. {
  68944. if (clip != 0)
  68945. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  68946. }
  68947. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  68948. {
  68949. if (clip != 0)
  68950. {
  68951. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68952. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68953. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68954. fillShape (image, shapeToFill, false);
  68955. }
  68956. }
  68957. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68958. {
  68959. jassert (clip != 0);
  68960. shapeToFill = clip->applyClipTo (shapeToFill);
  68961. if (shapeToFill != 0)
  68962. {
  68963. Image::BitmapData destData (image, true);
  68964. if (fillType.isGradient())
  68965. {
  68966. jassert (! replaceContents); // that option is just for solid colours
  68967. ColourGradient g2 (*(fillType.gradient));
  68968. g2.multiplyOpacity (fillType.getOpacity());
  68969. g2.point1.addXY (-0.5f, -0.5f);
  68970. g2.point2.addXY (-0.5f, -0.5f);
  68971. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  68972. const bool isIdentity = transform.isOnlyTranslation();
  68973. if (isIdentity)
  68974. {
  68975. // If our translation doesn't involve any distortion, we can speed it up..
  68976. g2.point1.applyTransform (transform);
  68977. g2.point2.applyTransform (transform);
  68978. transform = AffineTransform::identity;
  68979. }
  68980. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68981. }
  68982. else if (fillType.isTiledImage())
  68983. {
  68984. renderImage (image, fillType.image, fillType.transform, shapeToFill);
  68985. }
  68986. else
  68987. {
  68988. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68989. }
  68990. }
  68991. }
  68992. void renderImage (Image& destImage, const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68993. {
  68994. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  68995. const Image::BitmapData destData (destImage, true);
  68996. const Image::BitmapData srcData (sourceImage, false);
  68997. const int alpha = fillType.colour.getAlpha();
  68998. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68999. if (transform.isOnlyTranslation())
  69000. {
  69001. // If our translation doesn't involve any distortion, just use a simple blit..
  69002. int tx = (int) (transform.getTranslationX() * 256.0f);
  69003. int ty = (int) (transform.getTranslationY() * 256.0f);
  69004. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  69005. {
  69006. tx = ((tx + 128) >> 8);
  69007. ty = ((ty + 128) >> 8);
  69008. if (tiledFillClipRegion != 0)
  69009. {
  69010. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  69011. }
  69012. else
  69013. {
  69014. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (destImage.getBounds())));
  69015. c = clip->applyClipTo (c);
  69016. if (c != 0)
  69017. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  69018. }
  69019. return;
  69020. }
  69021. }
  69022. if (transform.isSingularity())
  69023. return;
  69024. if (tiledFillClipRegion != 0)
  69025. {
  69026. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  69027. }
  69028. else
  69029. {
  69030. Path p;
  69031. p.addRectangle (sourceImage.getBounds());
  69032. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  69033. c = c->clipToPath (p, transform);
  69034. if (c != 0)
  69035. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  69036. }
  69037. }
  69038. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  69039. int xOffset, yOffset;
  69040. Font font;
  69041. FillType fillType;
  69042. Graphics::ResamplingQuality interpolationQuality;
  69043. private:
  69044. void cloneClipIfMultiplyReferenced()
  69045. {
  69046. if (clip->getReferenceCount() > 1)
  69047. clip = clip->clone();
  69048. }
  69049. SavedState& operator= (const SavedState&);
  69050. };
  69051. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69052. : image (image_)
  69053. {
  69054. currentState = new SavedState (image_.getBounds(), 0, 0);
  69055. }
  69056. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69057. const RectangleList& initialClip)
  69058. : image (image_)
  69059. {
  69060. currentState = new SavedState (initialClip, xOffset, yOffset);
  69061. }
  69062. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69063. {
  69064. }
  69065. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69066. {
  69067. return false;
  69068. }
  69069. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69070. {
  69071. currentState->setOrigin (x, y);
  69072. }
  69073. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69074. {
  69075. return currentState->clipToRectangle (r);
  69076. }
  69077. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69078. {
  69079. return currentState->clipToRectangleList (clipRegion);
  69080. }
  69081. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69082. {
  69083. currentState->excludeClipRectangle (r);
  69084. }
  69085. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69086. {
  69087. currentState->clipToPath (path, transform);
  69088. }
  69089. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69090. {
  69091. currentState->clipToImageAlpha (sourceImage, transform);
  69092. }
  69093. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69094. {
  69095. return currentState->clipRegionIntersects (r);
  69096. }
  69097. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69098. {
  69099. return currentState->getClipBounds();
  69100. }
  69101. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69102. {
  69103. return currentState->clip == 0;
  69104. }
  69105. void LowLevelGraphicsSoftwareRenderer::saveState()
  69106. {
  69107. stateStack.add (new SavedState (*currentState));
  69108. }
  69109. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69110. {
  69111. SavedState* const top = stateStack.getLast();
  69112. if (top != 0)
  69113. {
  69114. currentState = top;
  69115. stateStack.removeLast (1, false);
  69116. }
  69117. else
  69118. {
  69119. jassertfalse; // trying to pop with an empty stack!
  69120. }
  69121. }
  69122. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69123. {
  69124. currentState->fillType = fillType;
  69125. }
  69126. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69127. {
  69128. currentState->fillType.setOpacity (newOpacity);
  69129. }
  69130. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69131. {
  69132. currentState->interpolationQuality = quality;
  69133. }
  69134. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69135. {
  69136. currentState->fillRect (image, r, replaceExistingContents);
  69137. }
  69138. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69139. {
  69140. currentState->fillPath (image, path, transform);
  69141. }
  69142. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69143. {
  69144. currentState->renderImage (image, sourceImage, transform,
  69145. fillEntireClipAsTiles ? currentState->clip : 0);
  69146. }
  69147. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69148. {
  69149. Path p;
  69150. p.addLineSegment (line, 1.0f);
  69151. fillPath (p, AffineTransform::identity);
  69152. }
  69153. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69154. {
  69155. if (bottom > top)
  69156. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69157. }
  69158. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69159. {
  69160. if (right > left)
  69161. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  69162. }
  69163. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69164. {
  69165. public:
  69166. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69167. ~CachedGlyph() {}
  69168. void draw (SavedState& state, Image& image, const float x, const float y) const
  69169. {
  69170. if (edgeTable != 0)
  69171. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  69172. }
  69173. void generate (const Font& newFont, const int glyphNumber)
  69174. {
  69175. font = newFont;
  69176. glyph = glyphNumber;
  69177. edgeTable = 0;
  69178. Path glyphPath;
  69179. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69180. if (! glyphPath.isEmpty())
  69181. {
  69182. const float fontHeight = font.getHeight();
  69183. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69184. #if JUCE_MAC || JUCE_IOS
  69185. .translated (0.0f, -0.5f)
  69186. #endif
  69187. );
  69188. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69189. glyphPath, transform);
  69190. }
  69191. }
  69192. int glyph, lastAccessCount;
  69193. Font font;
  69194. juce_UseDebuggingNewOperator
  69195. private:
  69196. ScopedPointer <EdgeTable> edgeTable;
  69197. CachedGlyph (const CachedGlyph&);
  69198. CachedGlyph& operator= (const CachedGlyph&);
  69199. };
  69200. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69201. {
  69202. public:
  69203. GlyphCache()
  69204. : accessCounter (0), hits (0), misses (0)
  69205. {
  69206. for (int i = 120; --i >= 0;)
  69207. glyphs.add (new CachedGlyph());
  69208. }
  69209. ~GlyphCache()
  69210. {
  69211. clearSingletonInstance();
  69212. }
  69213. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69214. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  69215. {
  69216. ++accessCounter;
  69217. int oldestCounter = std::numeric_limits<int>::max();
  69218. CachedGlyph* oldest = 0;
  69219. for (int i = glyphs.size(); --i >= 0;)
  69220. {
  69221. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69222. if (glyph->glyph == glyphNumber && glyph->font == font)
  69223. {
  69224. ++hits;
  69225. glyph->lastAccessCount = accessCounter;
  69226. glyph->draw (state, image, x, y);
  69227. return;
  69228. }
  69229. if (glyph->lastAccessCount <= oldestCounter)
  69230. {
  69231. oldestCounter = glyph->lastAccessCount;
  69232. oldest = glyph;
  69233. }
  69234. }
  69235. if (hits + ++misses > (glyphs.size() << 4))
  69236. {
  69237. if (misses * 2 > hits)
  69238. {
  69239. for (int i = 32; --i >= 0;)
  69240. glyphs.add (new CachedGlyph());
  69241. }
  69242. hits = misses = 0;
  69243. oldest = glyphs.getLast();
  69244. }
  69245. jassert (oldest != 0);
  69246. oldest->lastAccessCount = accessCounter;
  69247. oldest->generate (font, glyphNumber);
  69248. oldest->draw (state, image, x, y);
  69249. }
  69250. juce_UseDebuggingNewOperator
  69251. private:
  69252. friend class OwnedArray <CachedGlyph>;
  69253. OwnedArray <CachedGlyph> glyphs;
  69254. int accessCounter, hits, misses;
  69255. GlyphCache (const GlyphCache&);
  69256. GlyphCache& operator= (const GlyphCache&);
  69257. };
  69258. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69259. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69260. {
  69261. currentState->font = newFont;
  69262. }
  69263. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69264. {
  69265. return currentState->font;
  69266. }
  69267. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69268. {
  69269. Font& f = currentState->font;
  69270. if (transform.isOnlyTranslation())
  69271. {
  69272. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  69273. transform.getTranslationX(),
  69274. transform.getTranslationY());
  69275. }
  69276. else
  69277. {
  69278. Path p;
  69279. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69280. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69281. }
  69282. }
  69283. #if JUCE_MSVC
  69284. #pragma warning (pop)
  69285. #if JUCE_DEBUG
  69286. #pragma optimize ("", on) // resets optimisations to the project defaults
  69287. #endif
  69288. #endif
  69289. END_JUCE_NAMESPACE
  69290. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69291. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69292. BEGIN_JUCE_NAMESPACE
  69293. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69294. : flags (other.flags)
  69295. {
  69296. }
  69297. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69298. {
  69299. flags = other.flags;
  69300. return *this;
  69301. }
  69302. void RectanglePlacement::applyTo (double& x, double& y,
  69303. double& w, double& h,
  69304. const double dx, const double dy,
  69305. const double dw, const double dh) const throw()
  69306. {
  69307. if (w == 0 || h == 0)
  69308. return;
  69309. if ((flags & stretchToFit) != 0)
  69310. {
  69311. x = dx;
  69312. y = dy;
  69313. w = dw;
  69314. h = dh;
  69315. }
  69316. else
  69317. {
  69318. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69319. : jmin (dw / w, dh / h);
  69320. if ((flags & onlyReduceInSize) != 0)
  69321. scale = jmin (scale, 1.0);
  69322. if ((flags & onlyIncreaseInSize) != 0)
  69323. scale = jmax (scale, 1.0);
  69324. w *= scale;
  69325. h *= scale;
  69326. if ((flags & xLeft) != 0)
  69327. x = dx;
  69328. else if ((flags & xRight) != 0)
  69329. x = dx + dw - w;
  69330. else
  69331. x = dx + (dw - w) * 0.5;
  69332. if ((flags & yTop) != 0)
  69333. y = dy;
  69334. else if ((flags & yBottom) != 0)
  69335. y = dy + dh - h;
  69336. else
  69337. y = dy + (dh - h) * 0.5;
  69338. }
  69339. }
  69340. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  69341. float w, float h,
  69342. const float dx, const float dy,
  69343. const float dw, const float dh) const throw()
  69344. {
  69345. if (w == 0 || h == 0)
  69346. return AffineTransform::identity;
  69347. const float scaleX = dw / w;
  69348. const float scaleY = dh / h;
  69349. if ((flags & stretchToFit) != 0)
  69350. return AffineTransform::translation (-x, -y)
  69351. .scaled (scaleX, scaleY)
  69352. .translated (dx, dy);
  69353. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69354. : jmin (scaleX, scaleY);
  69355. if ((flags & onlyReduceInSize) != 0)
  69356. scale = jmin (scale, 1.0f);
  69357. if ((flags & onlyIncreaseInSize) != 0)
  69358. scale = jmax (scale, 1.0f);
  69359. w *= scale;
  69360. h *= scale;
  69361. float newX = dx;
  69362. if ((flags & xRight) != 0)
  69363. newX += dw - w; // right
  69364. else if ((flags & xLeft) == 0)
  69365. newX += (dw - w) / 2.0f; // centre
  69366. float newY = dy;
  69367. if ((flags & yBottom) != 0)
  69368. newY += dh - h; // bottom
  69369. else if ((flags & yTop) == 0)
  69370. newY += (dh - h) / 2.0f; // centre
  69371. return AffineTransform::translation (-x, -y)
  69372. .scaled (scale, scale)
  69373. .translated (newX, newY);
  69374. }
  69375. END_JUCE_NAMESPACE
  69376. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69377. /*** Start of inlined file: juce_Drawable.cpp ***/
  69378. BEGIN_JUCE_NAMESPACE
  69379. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  69380. const AffineTransform& transform_,
  69381. const float opacity_) throw()
  69382. : g (g_),
  69383. transform (transform_),
  69384. opacity (opacity_)
  69385. {
  69386. }
  69387. Drawable::Drawable()
  69388. : parent (0)
  69389. {
  69390. }
  69391. Drawable::~Drawable()
  69392. {
  69393. }
  69394. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  69395. {
  69396. render (RenderingContext (g, transform, opacity));
  69397. }
  69398. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  69399. {
  69400. draw (g, opacity, AffineTransform::translation (x, y));
  69401. }
  69402. void Drawable::drawWithin (Graphics& g,
  69403. const int destX,
  69404. const int destY,
  69405. const int destW,
  69406. const int destH,
  69407. const RectanglePlacement& placement,
  69408. const float opacity) const
  69409. {
  69410. if (destW > 0 && destH > 0)
  69411. {
  69412. Rectangle<float> bounds (getBounds());
  69413. draw (g, opacity,
  69414. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  69415. (float) destX, (float) destY,
  69416. (float) destW, (float) destH));
  69417. }
  69418. }
  69419. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69420. {
  69421. Drawable* result = 0;
  69422. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69423. if (image.isValid())
  69424. {
  69425. DrawableImage* const di = new DrawableImage();
  69426. di->setImage (image);
  69427. result = di;
  69428. }
  69429. else
  69430. {
  69431. const String asString (String::createStringFromData (data, (int) numBytes));
  69432. XmlDocument doc (asString);
  69433. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69434. if (outer != 0 && outer->hasTagName ("svg"))
  69435. {
  69436. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69437. if (svg != 0)
  69438. result = Drawable::createFromSVG (*svg);
  69439. }
  69440. }
  69441. return result;
  69442. }
  69443. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69444. {
  69445. MemoryOutputStream mo;
  69446. mo.writeFromInputStream (dataSource, -1);
  69447. return createFromImageData (mo.getData(), mo.getDataSize());
  69448. }
  69449. Drawable* Drawable::createFromImageFile (const File& file)
  69450. {
  69451. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69452. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69453. }
  69454. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69455. {
  69456. return createChildFromValueTree (0, tree, imageProvider);
  69457. }
  69458. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  69459. {
  69460. const Identifier type (tree.getType());
  69461. Drawable* d = 0;
  69462. if (type == DrawablePath::valueTreeType)
  69463. d = new DrawablePath();
  69464. else if (type == DrawableComposite::valueTreeType)
  69465. d = new DrawableComposite();
  69466. else if (type == DrawableImage::valueTreeType)
  69467. d = new DrawableImage();
  69468. else if (type == DrawableText::valueTreeType)
  69469. d = new DrawableText();
  69470. if (d != 0)
  69471. {
  69472. d->parent = parent;
  69473. d->refreshFromValueTree (tree, imageProvider);
  69474. }
  69475. return d;
  69476. }
  69477. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  69478. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  69479. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  69480. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  69481. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint3 ("point3");
  69482. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  69483. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  69484. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  69485. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  69486. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  69487. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69488. : state (state_)
  69489. {
  69490. }
  69491. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  69492. {
  69493. }
  69494. const String Drawable::ValueTreeWrapperBase::getID() const
  69495. {
  69496. return state [idProperty];
  69497. }
  69498. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  69499. {
  69500. if (newID.isEmpty())
  69501. state.removeProperty (idProperty, undoManager);
  69502. else
  69503. state.setProperty (idProperty, newID, undoManager);
  69504. }
  69505. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  69506. Expression::EvaluationContext* const nameFinder, ImageProvider* imageProvider)
  69507. {
  69508. const String newType (v[type].toString());
  69509. if (newType == "solid")
  69510. {
  69511. const String colourString (v [colour].toString());
  69512. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69513. : (uint32) colourString.getHexValue32()));
  69514. }
  69515. else if (newType == "gradient")
  69516. {
  69517. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  69518. ColourGradient g;
  69519. if (gp1 != 0) *gp1 = p1;
  69520. if (gp2 != 0) *gp2 = p2;
  69521. if (gp3 != 0) *gp3 = p3;
  69522. g.point1 = p1.resolve (nameFinder);
  69523. g.point2 = p2.resolve (nameFinder);
  69524. g.isRadial = v[radial];
  69525. StringArray colourSteps;
  69526. colourSteps.addTokens (v[colours].toString(), false);
  69527. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69528. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69529. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69530. FillType fillType (g);
  69531. if (g.isRadial)
  69532. {
  69533. const Point<float> point3 (p3.resolve (nameFinder));
  69534. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69535. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69536. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  69537. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  69538. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  69539. }
  69540. return fillType;
  69541. }
  69542. else if (newType == "image")
  69543. {
  69544. Image im;
  69545. if (imageProvider != 0)
  69546. im = imageProvider->getImageForIdentifier (v[imageId]);
  69547. FillType f (im, AffineTransform::identity);
  69548. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  69549. return f;
  69550. }
  69551. jassertfalse;
  69552. return FillType();
  69553. }
  69554. static const Point<float> calcThirdGradientPoint (const FillType& fillType)
  69555. {
  69556. const ColourGradient& g = *fillType.gradient;
  69557. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69558. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69559. return point3Source.transformedBy (fillType.transform);
  69560. }
  69561. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  69562. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  69563. ImageProvider* imageProvider, UndoManager* const undoManager)
  69564. {
  69565. if (fillType.isColour())
  69566. {
  69567. v.setProperty (type, "solid", undoManager);
  69568. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  69569. }
  69570. else if (fillType.isGradient())
  69571. {
  69572. v.setProperty (type, "gradient", undoManager);
  69573. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  69574. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  69575. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : calcThirdGradientPoint (fillType).toString(), undoManager);
  69576. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  69577. String s;
  69578. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  69579. s << ' ' << fillType.gradient->getColourPosition (i)
  69580. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  69581. v.setProperty (colours, s.trimStart(), undoManager);
  69582. }
  69583. else if (fillType.isTiledImage())
  69584. {
  69585. v.setProperty (type, "image", undoManager);
  69586. if (imageProvider != 0)
  69587. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  69588. if (fillType.getOpacity() < 1.0f)
  69589. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  69590. else
  69591. v.removeProperty (imageOpacity, undoManager);
  69592. }
  69593. else
  69594. {
  69595. jassertfalse;
  69596. }
  69597. }
  69598. END_JUCE_NAMESPACE
  69599. /*** End of inlined file: juce_Drawable.cpp ***/
  69600. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69601. BEGIN_JUCE_NAMESPACE
  69602. DrawableComposite::DrawableComposite()
  69603. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  69604. {
  69605. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69606. RelativeCoordinate (100.0),
  69607. RelativeCoordinate (0.0),
  69608. RelativeCoordinate (100.0)));
  69609. }
  69610. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69611. {
  69612. bounds = other.bounds;
  69613. for (int i = 0; i < other.drawables.size(); ++i)
  69614. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  69615. markersX.addCopiesOf (other.markersX);
  69616. markersY.addCopiesOf (other.markersY);
  69617. }
  69618. DrawableComposite::~DrawableComposite()
  69619. {
  69620. }
  69621. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69622. {
  69623. if (drawable != 0)
  69624. {
  69625. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  69626. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  69627. drawables.insert (index, drawable);
  69628. drawable->parent = this;
  69629. }
  69630. }
  69631. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69632. {
  69633. insertDrawable (drawable.createCopy(), index);
  69634. }
  69635. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69636. {
  69637. drawables.remove (index, deleteDrawable);
  69638. }
  69639. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69640. {
  69641. for (int i = drawables.size(); --i >= 0;)
  69642. if (drawables.getUnchecked(i)->getName() == name)
  69643. return drawables.getUnchecked(i);
  69644. return 0;
  69645. }
  69646. void DrawableComposite::bringToFront (const int index)
  69647. {
  69648. if (index >= 0 && index < drawables.size() - 1)
  69649. drawables.move (index, -1);
  69650. }
  69651. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69652. {
  69653. bounds = newBoundingBox;
  69654. }
  69655. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69656. : name (other.name), position (other.position)
  69657. {
  69658. }
  69659. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69660. : name (name_), position (position_)
  69661. {
  69662. }
  69663. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69664. {
  69665. return name != other.name || position != other.position;
  69666. }
  69667. const char* const DrawableComposite::contentLeftMarkerName ("left");
  69668. const char* const DrawableComposite::contentRightMarkerName ("right");
  69669. const char* const DrawableComposite::contentTopMarkerName ("top");
  69670. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  69671. const RelativeRectangle DrawableComposite::getContentArea() const
  69672. {
  69673. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69674. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69675. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69676. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69677. }
  69678. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69679. {
  69680. setMarker (contentLeftMarkerName, true, newArea.left);
  69681. setMarker (contentRightMarkerName, true, newArea.right);
  69682. setMarker (contentTopMarkerName, false, newArea.top);
  69683. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69684. }
  69685. void DrawableComposite::resetBoundingBoxToContentArea()
  69686. {
  69687. const RelativeRectangle content (getContentArea());
  69688. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69689. RelativePoint (content.right, content.top),
  69690. RelativePoint (content.left, content.bottom)));
  69691. }
  69692. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69693. {
  69694. const Rectangle<float> bounds (getUntransformedBounds (false));
  69695. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  69696. RelativeCoordinate (bounds.getRight()),
  69697. RelativeCoordinate (bounds.getY()),
  69698. RelativeCoordinate (bounds.getBottom())));
  69699. resetBoundingBoxToContentArea();
  69700. }
  69701. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69702. {
  69703. return (xAxis ? markersX : markersY).size();
  69704. }
  69705. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69706. {
  69707. return (xAxis ? markersX : markersY) [index];
  69708. }
  69709. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69710. {
  69711. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69712. for (int i = 0; i < markers.size(); ++i)
  69713. {
  69714. Marker* const m = markers.getUnchecked(i);
  69715. if (m->name == name)
  69716. {
  69717. if (m->position != position)
  69718. {
  69719. m->position = position;
  69720. invalidatePoints();
  69721. }
  69722. return;
  69723. }
  69724. }
  69725. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69726. invalidatePoints();
  69727. }
  69728. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69729. {
  69730. jassert (index >= 2);
  69731. if (index >= 2)
  69732. (xAxis ? markersX : markersY).remove (index);
  69733. }
  69734. const AffineTransform DrawableComposite::calculateTransform() const
  69735. {
  69736. Point<float> resolved[3];
  69737. bounds.resolveThreePoints (resolved, parent);
  69738. const Rectangle<float> content (getContentArea().resolve (parent));
  69739. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69740. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69741. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  69742. }
  69743. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  69744. {
  69745. if (drawables.size() > 0 && context.opacity > 0)
  69746. {
  69747. if (context.opacity >= 1.0f || drawables.size() == 1)
  69748. {
  69749. Drawable::RenderingContext contextCopy (context);
  69750. contextCopy.transform = calculateTransform().followedBy (context.transform);
  69751. for (int i = 0; i < drawables.size(); ++i)
  69752. drawables.getUnchecked(i)->render (contextCopy);
  69753. }
  69754. else
  69755. {
  69756. // To correctly render a whole composite layer with an overall transparency,
  69757. // we need to render everything opaquely into a temp buffer, then blend that
  69758. // with the target opacity...
  69759. const Rectangle<int> clipBounds (context.g.getClipBounds());
  69760. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  69761. {
  69762. Graphics tempG (tempImage);
  69763. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  69764. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  69765. render (tempContext);
  69766. }
  69767. context.g.setOpacity (context.opacity);
  69768. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  69769. }
  69770. }
  69771. }
  69772. const Expression DrawableComposite::getSymbolValue (const String& symbol, const String& member) const
  69773. {
  69774. jassert (member.isEmpty()) // the only symbols available in a Drawable are markers.
  69775. int i;
  69776. for (i = 0; i < markersX.size(); ++i)
  69777. {
  69778. Marker* const m = markersX.getUnchecked(i);
  69779. if (m->name == symbol)
  69780. return m->position.getExpression();
  69781. }
  69782. for (i = 0; i < markersY.size(); ++i)
  69783. {
  69784. Marker* const m = markersY.getUnchecked(i);
  69785. if (m->name == symbol)
  69786. return m->position.getExpression();
  69787. }
  69788. throw Expression::EvaluationError (symbol, member);
  69789. }
  69790. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  69791. {
  69792. Rectangle<float> bounds;
  69793. int i;
  69794. for (i = 0; i < drawables.size(); ++i)
  69795. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  69796. if (includeMarkers)
  69797. {
  69798. if (markersX.size() > 0)
  69799. {
  69800. float minX = std::numeric_limits<float>::max();
  69801. float maxX = std::numeric_limits<float>::min();
  69802. for (i = markersX.size(); --i >= 0;)
  69803. {
  69804. const Marker* m = markersX.getUnchecked(i);
  69805. const float pos = (float) m->position.resolve (this);
  69806. minX = jmin (minX, pos);
  69807. maxX = jmax (maxX, pos);
  69808. }
  69809. if (minX <= maxX)
  69810. {
  69811. if (bounds.getHeight() > 0)
  69812. {
  69813. minX = jmin (minX, bounds.getX());
  69814. maxX = jmax (maxX, bounds.getRight());
  69815. }
  69816. bounds.setLeft (minX);
  69817. bounds.setWidth (maxX - minX);
  69818. }
  69819. }
  69820. if (markersY.size() > 0)
  69821. {
  69822. float minY = std::numeric_limits<float>::max();
  69823. float maxY = std::numeric_limits<float>::min();
  69824. for (i = markersY.size(); --i >= 0;)
  69825. {
  69826. const Marker* m = markersY.getUnchecked(i);
  69827. const float pos = (float) m->position.resolve (this);
  69828. minY = jmin (minY, pos);
  69829. maxY = jmax (maxY, pos);
  69830. }
  69831. if (minY <= maxY)
  69832. {
  69833. if (bounds.getHeight() > 0)
  69834. {
  69835. minY = jmin (minY, bounds.getY());
  69836. maxY = jmax (maxY, bounds.getBottom());
  69837. }
  69838. bounds.setTop (minY);
  69839. bounds.setHeight (maxY - minY);
  69840. }
  69841. }
  69842. }
  69843. return bounds;
  69844. }
  69845. const Rectangle<float> DrawableComposite::getBounds() const
  69846. {
  69847. return getUntransformedBounds (true).transformed (calculateTransform());
  69848. }
  69849. bool DrawableComposite::hitTest (float x, float y) const
  69850. {
  69851. calculateTransform().inverted().transformPoint (x, y);
  69852. for (int i = 0; i < drawables.size(); ++i)
  69853. if (drawables.getUnchecked(i)->hitTest (x, y))
  69854. return true;
  69855. return false;
  69856. }
  69857. Drawable* DrawableComposite::createCopy() const
  69858. {
  69859. return new DrawableComposite (*this);
  69860. }
  69861. void DrawableComposite::invalidatePoints()
  69862. {
  69863. for (int i = 0; i < drawables.size(); ++i)
  69864. drawables.getUnchecked(i)->invalidatePoints();
  69865. }
  69866. const Identifier DrawableComposite::valueTreeType ("Group");
  69867. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  69868. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  69869. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69870. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  69871. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  69872. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  69873. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  69874. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  69875. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  69876. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69877. : ValueTreeWrapperBase (state_)
  69878. {
  69879. jassert (state.hasType (valueTreeType));
  69880. }
  69881. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  69882. {
  69883. return state.getChildWithName (childGroupTag);
  69884. }
  69885. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  69886. {
  69887. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  69888. }
  69889. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  69890. {
  69891. return getChildList().getNumChildren();
  69892. }
  69893. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  69894. {
  69895. return getChildList().getChild (index);
  69896. }
  69897. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  69898. {
  69899. if (getID() == objectId)
  69900. return state;
  69901. if (! recursive)
  69902. {
  69903. return getChildList().getChildWithProperty (idProperty, objectId);
  69904. }
  69905. else
  69906. {
  69907. const ValueTree childList (getChildList());
  69908. for (int i = getNumDrawables(); --i >= 0;)
  69909. {
  69910. const ValueTree& child = childList.getChild (i);
  69911. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  69912. return child;
  69913. if (child.hasType (DrawableComposite::valueTreeType))
  69914. {
  69915. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  69916. if (v.isValid())
  69917. return v;
  69918. }
  69919. }
  69920. return ValueTree::invalid;
  69921. }
  69922. }
  69923. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  69924. {
  69925. return getChildList().indexOf (item);
  69926. }
  69927. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  69928. {
  69929. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  69930. }
  69931. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  69932. {
  69933. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  69934. }
  69935. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  69936. {
  69937. getChildList().removeChild (child, undoManager);
  69938. }
  69939. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  69940. {
  69941. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69942. state.getProperty (topRight, "100, 0"),
  69943. state.getProperty (bottomLeft, "0, 100"));
  69944. }
  69945. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69946. {
  69947. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69948. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69949. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69950. }
  69951. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  69952. {
  69953. const RelativeRectangle content (getContentArea());
  69954. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69955. RelativePoint (content.right, content.top),
  69956. RelativePoint (content.left, content.bottom)), undoManager);
  69957. }
  69958. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  69959. {
  69960. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  69961. getMarker (true, getMarkerState (true, 1)).position,
  69962. getMarker (false, getMarkerState (false, 0)).position,
  69963. getMarker (false, getMarkerState (false, 1)).position);
  69964. }
  69965. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  69966. {
  69967. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  69968. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  69969. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  69970. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  69971. }
  69972. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  69973. {
  69974. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  69975. }
  69976. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  69977. {
  69978. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  69979. }
  69980. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  69981. {
  69982. return getMarkerList (xAxis).getNumChildren();
  69983. }
  69984. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  69985. {
  69986. return getMarkerList (xAxis).getChild (index);
  69987. }
  69988. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  69989. {
  69990. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  69991. }
  69992. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  69993. {
  69994. return state.isAChildOf (getMarkerList (xAxis));
  69995. }
  69996. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  69997. {
  69998. (void) xAxis;
  69999. jassert (containsMarker (xAxis, state));
  70000. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString()));
  70001. }
  70002. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  70003. {
  70004. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  70005. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  70006. if (marker.isValid())
  70007. {
  70008. marker.setProperty (posProperty, m.position.toString(), undoManager);
  70009. }
  70010. else
  70011. {
  70012. marker = ValueTree (markerTag);
  70013. marker.setProperty (nameProperty, m.name, 0);
  70014. marker.setProperty (posProperty, m.position.toString(), 0);
  70015. markerList.addChild (marker, -1, undoManager);
  70016. }
  70017. }
  70018. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  70019. {
  70020. if (state [nameProperty].toString() != contentLeftMarkerName
  70021. && state [nameProperty].toString() != contentRightMarkerName
  70022. && state [nameProperty].toString() != contentTopMarkerName
  70023. && state [nameProperty].toString() != contentBottomMarkerName)
  70024. return getMarkerList (xAxis).removeChild (state, undoManager);
  70025. }
  70026. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70027. {
  70028. const ValueTreeWrapper wrapper (tree);
  70029. setName (wrapper.getID());
  70030. Rectangle<float> damage;
  70031. bool redrawAll = false;
  70032. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  70033. if (bounds != newBounds)
  70034. {
  70035. redrawAll = true;
  70036. damage = getBounds();
  70037. bounds = newBounds;
  70038. }
  70039. const int numMarkersX = wrapper.getNumMarkers (true);
  70040. const int numMarkersY = wrapper.getNumMarkers (false);
  70041. // Remove deleted markers...
  70042. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  70043. {
  70044. if (! redrawAll)
  70045. {
  70046. redrawAll = true;
  70047. damage = getBounds();
  70048. }
  70049. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  70050. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  70051. }
  70052. // Update markers and add new ones..
  70053. int i;
  70054. for (i = 0; i < numMarkersX; ++i)
  70055. {
  70056. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  70057. Marker* m = markersX[i];
  70058. if (m == 0 || newMarker != *m)
  70059. {
  70060. if (! redrawAll)
  70061. {
  70062. redrawAll = true;
  70063. damage = getBounds();
  70064. }
  70065. if (m == 0)
  70066. markersX.add (new Marker (newMarker));
  70067. else
  70068. *m = newMarker;
  70069. }
  70070. }
  70071. for (i = 0; i < numMarkersY; ++i)
  70072. {
  70073. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  70074. Marker* m = markersY[i];
  70075. if (m == 0 || newMarker != *m)
  70076. {
  70077. if (! redrawAll)
  70078. {
  70079. redrawAll = true;
  70080. damage = getBounds();
  70081. }
  70082. if (m == 0)
  70083. markersY.add (new Marker (newMarker));
  70084. else
  70085. *m = newMarker;
  70086. }
  70087. }
  70088. // Remove deleted drawables..
  70089. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  70090. {
  70091. Drawable* const d = drawables.getUnchecked(i);
  70092. if (! redrawAll)
  70093. damage = damage.getUnion (d->getBounds());
  70094. d->parent = 0;
  70095. drawables.remove (i);
  70096. }
  70097. // Update drawables and add new ones..
  70098. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  70099. {
  70100. const ValueTree newDrawable (wrapper.getDrawableState (i));
  70101. Drawable* d = drawables[i];
  70102. if (d != 0)
  70103. {
  70104. if (newDrawable.hasType (d->getValueTreeType()))
  70105. {
  70106. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  70107. if (! redrawAll)
  70108. damage = damage.getUnion (area);
  70109. }
  70110. else
  70111. {
  70112. if (! redrawAll)
  70113. damage = damage.getUnion (d->getBounds());
  70114. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70115. drawables.set (i, d);
  70116. if (! redrawAll)
  70117. damage = damage.getUnion (d->getBounds());
  70118. }
  70119. }
  70120. else
  70121. {
  70122. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70123. drawables.set (i, d);
  70124. if (! redrawAll)
  70125. damage = damage.getUnion (d->getBounds());
  70126. }
  70127. }
  70128. if (redrawAll)
  70129. damage = damage.getUnion (getBounds());
  70130. else if (! damage.isEmpty())
  70131. damage = damage.transformed (calculateTransform());
  70132. return damage;
  70133. }
  70134. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  70135. {
  70136. ValueTree tree (valueTreeType);
  70137. ValueTreeWrapper v (tree);
  70138. v.setID (getName(), 0);
  70139. v.setBoundingBox (bounds, 0);
  70140. int i;
  70141. for (i = 0; i < drawables.size(); ++i)
  70142. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  70143. for (i = 0; i < markersX.size(); ++i)
  70144. v.setMarker (true, *markersX.getUnchecked(i), 0);
  70145. for (i = 0; i < markersY.size(); ++i)
  70146. v.setMarker (false, *markersY.getUnchecked(i), 0);
  70147. return tree;
  70148. }
  70149. END_JUCE_NAMESPACE
  70150. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70151. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70152. BEGIN_JUCE_NAMESPACE
  70153. DrawableImage::DrawableImage()
  70154. : image (0),
  70155. opacity (1.0f),
  70156. overlayColour (0x00000000)
  70157. {
  70158. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70159. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70160. }
  70161. DrawableImage::DrawableImage (const DrawableImage& other)
  70162. : image (other.image),
  70163. opacity (other.opacity),
  70164. overlayColour (other.overlayColour),
  70165. bounds (other.bounds)
  70166. {
  70167. }
  70168. DrawableImage::~DrawableImage()
  70169. {
  70170. }
  70171. void DrawableImage::setImage (const Image& imageToUse)
  70172. {
  70173. image = imageToUse;
  70174. if (image.isValid())
  70175. {
  70176. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70177. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70178. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70179. }
  70180. }
  70181. void DrawableImage::setOpacity (const float newOpacity)
  70182. {
  70183. opacity = newOpacity;
  70184. }
  70185. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70186. {
  70187. overlayColour = newOverlayColour;
  70188. }
  70189. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70190. {
  70191. bounds = newBounds;
  70192. }
  70193. const AffineTransform DrawableImage::calculateTransform() const
  70194. {
  70195. if (image.isNull())
  70196. return AffineTransform::identity;
  70197. Point<float> resolved[3];
  70198. bounds.resolveThreePoints (resolved, parent);
  70199. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70200. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70201. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70202. tr.getX(), tr.getY(),
  70203. bl.getX(), bl.getY());
  70204. }
  70205. void DrawableImage::render (const Drawable::RenderingContext& context) const
  70206. {
  70207. if (image.isValid())
  70208. {
  70209. const AffineTransform t (calculateTransform().followedBy (context.transform));
  70210. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70211. {
  70212. context.g.setOpacity (context.opacity * opacity);
  70213. context.g.drawImageTransformed (image, t, false);
  70214. }
  70215. if (! overlayColour.isTransparent())
  70216. {
  70217. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  70218. context.g.drawImageTransformed (image, t, true);
  70219. }
  70220. }
  70221. }
  70222. const Rectangle<float> DrawableImage::getBounds() const
  70223. {
  70224. if (image.isNull())
  70225. return Rectangle<float>();
  70226. return bounds.getBounds (parent);
  70227. }
  70228. bool DrawableImage::hitTest (float x, float y) const
  70229. {
  70230. if (image.isNull())
  70231. return false;
  70232. calculateTransform().inverted().transformPoint (x, y);
  70233. const int ix = roundToInt (x);
  70234. const int iy = roundToInt (y);
  70235. return ix >= 0
  70236. && iy >= 0
  70237. && ix < image.getWidth()
  70238. && iy < image.getHeight()
  70239. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  70240. }
  70241. Drawable* DrawableImage::createCopy() const
  70242. {
  70243. return new DrawableImage (*this);
  70244. }
  70245. void DrawableImage::invalidatePoints()
  70246. {
  70247. }
  70248. const Identifier DrawableImage::valueTreeType ("Image");
  70249. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70250. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70251. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70252. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70253. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70254. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70255. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70256. : ValueTreeWrapperBase (state_)
  70257. {
  70258. jassert (state.hasType (valueTreeType));
  70259. }
  70260. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70261. {
  70262. return state [image];
  70263. }
  70264. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70265. {
  70266. return state.getPropertyAsValue (image, undoManager);
  70267. }
  70268. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70269. {
  70270. state.setProperty (image, newIdentifier, undoManager);
  70271. }
  70272. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70273. {
  70274. return (float) state.getProperty (opacity, 1.0);
  70275. }
  70276. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70277. {
  70278. if (! state.hasProperty (opacity))
  70279. state.setProperty (opacity, 1.0, undoManager);
  70280. return state.getPropertyAsValue (opacity, undoManager);
  70281. }
  70282. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70283. {
  70284. state.setProperty (opacity, newOpacity, undoManager);
  70285. }
  70286. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70287. {
  70288. return Colour (state [overlay].toString().getHexValue32());
  70289. }
  70290. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70291. {
  70292. if (newColour.isTransparent())
  70293. state.removeProperty (overlay, undoManager);
  70294. else
  70295. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70296. }
  70297. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70298. {
  70299. return state.getPropertyAsValue (overlay, undoManager);
  70300. }
  70301. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70302. {
  70303. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70304. state.getProperty (topRight, "100, 0"),
  70305. state.getProperty (bottomLeft, "0, 100"));
  70306. }
  70307. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70308. {
  70309. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70310. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70311. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70312. }
  70313. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70314. {
  70315. const ValueTreeWrapper controller (tree);
  70316. setName (controller.getID());
  70317. const float newOpacity = controller.getOpacity();
  70318. const Colour newOverlayColour (controller.getOverlayColour());
  70319. Image newImage;
  70320. const var imageIdentifier (controller.getImageIdentifier());
  70321. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70322. if (imageProvider != 0)
  70323. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  70324. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70325. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  70326. {
  70327. const Rectangle<float> damage (getBounds());
  70328. opacity = newOpacity;
  70329. overlayColour = newOverlayColour;
  70330. bounds = newBounds;
  70331. image = newImage;
  70332. return damage.getUnion (getBounds());
  70333. }
  70334. return Rectangle<float>();
  70335. }
  70336. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  70337. {
  70338. ValueTree tree (valueTreeType);
  70339. ValueTreeWrapper v (tree);
  70340. v.setID (getName(), 0);
  70341. v.setOpacity (opacity, 0);
  70342. v.setOverlayColour (overlayColour, 0);
  70343. v.setBoundingBox (bounds, 0);
  70344. if (image.isValid())
  70345. {
  70346. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70347. if (imageProvider != 0)
  70348. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70349. }
  70350. return tree;
  70351. }
  70352. END_JUCE_NAMESPACE
  70353. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70354. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70355. BEGIN_JUCE_NAMESPACE
  70356. DrawablePath::DrawablePath()
  70357. : mainFill (Colours::black),
  70358. strokeFill (Colours::black),
  70359. strokeType (0.0f),
  70360. pathNeedsUpdating (true),
  70361. strokeNeedsUpdating (true)
  70362. {
  70363. }
  70364. DrawablePath::DrawablePath (const DrawablePath& other)
  70365. : mainFill (other.mainFill),
  70366. strokeFill (other.strokeFill),
  70367. strokeType (other.strokeType),
  70368. pathNeedsUpdating (true),
  70369. strokeNeedsUpdating (true)
  70370. {
  70371. if (other.relativePath != 0)
  70372. relativePath = new RelativePointPath (*other.relativePath);
  70373. else
  70374. path = other.path;
  70375. }
  70376. DrawablePath::~DrawablePath()
  70377. {
  70378. }
  70379. void DrawablePath::setPath (const Path& newPath)
  70380. {
  70381. path = newPath;
  70382. strokeNeedsUpdating = true;
  70383. }
  70384. void DrawablePath::setFill (const FillType& newFill)
  70385. {
  70386. mainFill = newFill;
  70387. }
  70388. void DrawablePath::setStrokeFill (const FillType& newFill)
  70389. {
  70390. strokeFill = newFill;
  70391. }
  70392. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  70393. {
  70394. strokeType = newStrokeType;
  70395. strokeNeedsUpdating = true;
  70396. }
  70397. void DrawablePath::setStrokeThickness (const float newThickness)
  70398. {
  70399. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  70400. }
  70401. void DrawablePath::updatePath() const
  70402. {
  70403. if (pathNeedsUpdating)
  70404. {
  70405. pathNeedsUpdating = false;
  70406. if (relativePath != 0)
  70407. {
  70408. path.clear();
  70409. relativePath->createPath (path, parent);
  70410. strokeNeedsUpdating = true;
  70411. }
  70412. }
  70413. }
  70414. void DrawablePath::updateStroke() const
  70415. {
  70416. if (strokeNeedsUpdating)
  70417. {
  70418. strokeNeedsUpdating = false;
  70419. updatePath();
  70420. stroke.clear();
  70421. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  70422. }
  70423. }
  70424. const Path& DrawablePath::getPath() const
  70425. {
  70426. updatePath();
  70427. return path;
  70428. }
  70429. const Path& DrawablePath::getStrokePath() const
  70430. {
  70431. updateStroke();
  70432. return stroke;
  70433. }
  70434. bool DrawablePath::isStrokeVisible() const throw()
  70435. {
  70436. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  70437. }
  70438. void DrawablePath::invalidatePoints()
  70439. {
  70440. pathNeedsUpdating = true;
  70441. strokeNeedsUpdating = true;
  70442. }
  70443. void DrawablePath::render (const Drawable::RenderingContext& context) const
  70444. {
  70445. {
  70446. FillType f (mainFill);
  70447. if (f.isGradient())
  70448. f.gradient->multiplyOpacity (context.opacity);
  70449. else
  70450. f.setOpacity (f.getOpacity() * context.opacity);
  70451. f.transform = f.transform.followedBy (context.transform);
  70452. context.g.setFillType (f);
  70453. context.g.fillPath (getPath(), context.transform);
  70454. }
  70455. if (isStrokeVisible())
  70456. {
  70457. FillType f (strokeFill);
  70458. if (f.isGradient())
  70459. f.gradient->multiplyOpacity (context.opacity);
  70460. else
  70461. f.setOpacity (f.getOpacity() * context.opacity);
  70462. f.transform = f.transform.followedBy (context.transform);
  70463. context.g.setFillType (f);
  70464. context.g.fillPath (getStrokePath(), context.transform);
  70465. }
  70466. }
  70467. const Rectangle<float> DrawablePath::getBounds() const
  70468. {
  70469. if (isStrokeVisible())
  70470. return getStrokePath().getBounds();
  70471. else
  70472. return getPath().getBounds();
  70473. }
  70474. bool DrawablePath::hitTest (float x, float y) const
  70475. {
  70476. return getPath().contains (x, y)
  70477. || (isStrokeVisible() && getStrokePath().contains (x, y));
  70478. }
  70479. Drawable* DrawablePath::createCopy() const
  70480. {
  70481. return new DrawablePath (*this);
  70482. }
  70483. const Identifier DrawablePath::valueTreeType ("Path");
  70484. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  70485. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  70486. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  70487. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  70488. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  70489. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  70490. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70491. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70492. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70493. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70494. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70495. : ValueTreeWrapperBase (state_)
  70496. {
  70497. jassert (state.hasType (valueTreeType));
  70498. }
  70499. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70500. {
  70501. return state.getOrCreateChildWithName (path, 0);
  70502. }
  70503. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  70504. {
  70505. ValueTree v (state.getChildWithName (fill));
  70506. if (v.isValid())
  70507. return v;
  70508. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  70509. return getMainFillState();
  70510. }
  70511. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  70512. {
  70513. ValueTree v (state.getChildWithName (stroke));
  70514. if (v.isValid())
  70515. return v;
  70516. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  70517. return getStrokeFillState();
  70518. }
  70519. const FillType DrawablePath::ValueTreeWrapper::getMainFill (Expression::EvaluationContext* nameFinder,
  70520. ImageProvider* imageProvider) const
  70521. {
  70522. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  70523. }
  70524. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  70525. const RelativePoint* gp2, const RelativePoint* gp3,
  70526. ImageProvider* imageProvider, UndoManager* undoManager)
  70527. {
  70528. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  70529. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70530. }
  70531. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (Expression::EvaluationContext* nameFinder,
  70532. ImageProvider* imageProvider) const
  70533. {
  70534. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  70535. }
  70536. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  70537. const RelativePoint* gp2, const RelativePoint* gp3,
  70538. ImageProvider* imageProvider, UndoManager* undoManager)
  70539. {
  70540. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  70541. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70542. }
  70543. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  70544. {
  70545. const String jointStyleString (state [jointStyle].toString());
  70546. const String capStyleString (state [capStyle].toString());
  70547. return PathStrokeType (state [strokeWidth],
  70548. jointStyleString == "curved" ? PathStrokeType::curved
  70549. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  70550. : PathStrokeType::mitered),
  70551. capStyleString == "square" ? PathStrokeType::square
  70552. : (capStyleString == "round" ? PathStrokeType::rounded
  70553. : PathStrokeType::butt));
  70554. }
  70555. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  70556. {
  70557. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  70558. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  70559. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  70560. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  70561. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  70562. }
  70563. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70564. {
  70565. return state [nonZeroWinding];
  70566. }
  70567. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70568. {
  70569. state.setProperty (nonZeroWinding, b, undoManager);
  70570. }
  70571. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70572. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70573. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70574. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70575. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70576. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70577. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70578. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70579. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70580. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70581. : state (state_)
  70582. {
  70583. }
  70584. DrawablePath::ValueTreeWrapper::Element::~Element()
  70585. {
  70586. }
  70587. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70588. {
  70589. return ValueTreeWrapper (state.getParent().getParent());
  70590. }
  70591. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70592. {
  70593. return Element (state.getSibling (-1));
  70594. }
  70595. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70596. {
  70597. const Identifier i (state.getType());
  70598. if (i == startSubPathElement || i == lineToElement) return 1;
  70599. if (i == quadraticToElement) return 2;
  70600. if (i == cubicToElement) return 3;
  70601. return 0;
  70602. }
  70603. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70604. {
  70605. jassert (index >= 0 && index < getNumControlPoints());
  70606. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70607. }
  70608. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70609. {
  70610. jassert (index >= 0 && index < getNumControlPoints());
  70611. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70612. }
  70613. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70614. {
  70615. jassert (index >= 0 && index < getNumControlPoints());
  70616. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70617. }
  70618. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70619. {
  70620. const Identifier i (state.getType());
  70621. if (i == startSubPathElement)
  70622. return getControlPoint (0);
  70623. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70624. return getPreviousElement().getEndPoint();
  70625. }
  70626. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70627. {
  70628. const Identifier i (state.getType());
  70629. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70630. if (i == quadraticToElement) return getControlPoint (1);
  70631. if (i == cubicToElement) return getControlPoint (2);
  70632. jassert (i == closeSubPathElement);
  70633. return RelativePoint();
  70634. }
  70635. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* nameFinder) const
  70636. {
  70637. const Identifier i (state.getType());
  70638. if (i == lineToElement || i == closeSubPathElement)
  70639. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70640. if (i == cubicToElement)
  70641. {
  70642. Path p;
  70643. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70644. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70645. return p.getLength();
  70646. }
  70647. if (i == quadraticToElement)
  70648. {
  70649. Path p;
  70650. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70651. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70652. return p.getLength();
  70653. }
  70654. jassert (i == startSubPathElement);
  70655. return 0;
  70656. }
  70657. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70658. {
  70659. return state [mode].toString();
  70660. }
  70661. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70662. {
  70663. if (state.hasType (cubicToElement))
  70664. state.setProperty (mode, newMode, undoManager);
  70665. }
  70666. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70667. {
  70668. const Identifier i (state.getType());
  70669. if (i == quadraticToElement || i == cubicToElement)
  70670. {
  70671. ValueTree newState (lineToElement);
  70672. Element e (newState);
  70673. e.setControlPoint (0, getEndPoint(), undoManager);
  70674. state = newState;
  70675. }
  70676. }
  70677. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70678. {
  70679. const Identifier i (state.getType());
  70680. if (i == lineToElement || i == quadraticToElement)
  70681. {
  70682. ValueTree newState (cubicToElement);
  70683. Element e (newState);
  70684. const RelativePoint start (getStartPoint());
  70685. const RelativePoint end (getEndPoint());
  70686. const Point<float> startResolved (start.resolve (nameFinder));
  70687. const Point<float> endResolved (end.resolve (nameFinder));
  70688. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70689. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70690. e.setControlPoint (2, end, undoManager);
  70691. state = newState;
  70692. }
  70693. }
  70694. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70695. {
  70696. const Identifier i (state.getType());
  70697. if (i != startSubPathElement)
  70698. {
  70699. ValueTree newState (startSubPathElement);
  70700. Element e (newState);
  70701. e.setControlPoint (0, getEndPoint(), undoManager);
  70702. state = newState;
  70703. }
  70704. }
  70705. static const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70706. {
  70707. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70708. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70709. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70710. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70711. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70712. return newCp1 + (newCp2 - newCp1) * proportion;
  70713. }
  70714. static const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70715. {
  70716. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70717. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70718. return mid1 + (mid2 - mid1) * proportion;
  70719. }
  70720. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder) const
  70721. {
  70722. const Identifier i (state.getType());
  70723. float bestProp = 0;
  70724. if (i == cubicToElement)
  70725. {
  70726. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70727. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70728. float bestDistance = std::numeric_limits<float>::max();
  70729. for (int i = 110; --i >= 0;)
  70730. {
  70731. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70732. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70733. const float distance = centre.getDistanceFrom (targetPoint);
  70734. if (distance < bestDistance)
  70735. {
  70736. bestProp = prop;
  70737. bestDistance = distance;
  70738. }
  70739. }
  70740. }
  70741. else if (i == quadraticToElement)
  70742. {
  70743. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70744. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70745. float bestDistance = std::numeric_limits<float>::max();
  70746. for (int i = 110; --i >= 0;)
  70747. {
  70748. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70749. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70750. const float distance = centre.getDistanceFrom (targetPoint);
  70751. if (distance < bestDistance)
  70752. {
  70753. bestProp = prop;
  70754. bestDistance = distance;
  70755. }
  70756. }
  70757. }
  70758. else if (i == lineToElement)
  70759. {
  70760. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70761. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70762. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70763. }
  70764. return bestProp;
  70765. }
  70766. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70767. {
  70768. ValueTree newTree;
  70769. const Identifier i (state.getType());
  70770. if (i == cubicToElement)
  70771. {
  70772. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70773. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70774. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70775. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70776. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70777. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70778. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70779. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70780. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70781. setControlPoint (0, mid1, undoManager);
  70782. setControlPoint (1, newCp1, undoManager);
  70783. setControlPoint (2, newCentre, undoManager);
  70784. setModeOfEndPoint (roundedMode, undoManager);
  70785. Element newElement (newTree = ValueTree (cubicToElement));
  70786. newElement.setControlPoint (0, newCp2, 0);
  70787. newElement.setControlPoint (1, mid3, 0);
  70788. newElement.setControlPoint (2, rp4, 0);
  70789. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70790. }
  70791. else if (i == quadraticToElement)
  70792. {
  70793. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70794. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70795. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70796. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70797. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70798. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70799. setControlPoint (0, mid1, undoManager);
  70800. setControlPoint (1, newCentre, undoManager);
  70801. setModeOfEndPoint (roundedMode, undoManager);
  70802. Element newElement (newTree = ValueTree (quadraticToElement));
  70803. newElement.setControlPoint (0, mid2, 0);
  70804. newElement.setControlPoint (1, rp3, 0);
  70805. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70806. }
  70807. else if (i == lineToElement)
  70808. {
  70809. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70810. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70811. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70812. setControlPoint (0, newPoint, undoManager);
  70813. Element newElement (newTree = ValueTree (lineToElement));
  70814. newElement.setControlPoint (0, rp2, 0);
  70815. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70816. }
  70817. else if (i == closeSubPathElement)
  70818. {
  70819. }
  70820. return newTree;
  70821. }
  70822. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70823. {
  70824. state.getParent().removeChild (state, undoManager);
  70825. }
  70826. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70827. {
  70828. Rectangle<float> damageRect;
  70829. ValueTreeWrapper v (tree);
  70830. setName (v.getID());
  70831. bool needsRedraw = false;
  70832. const FillType newFill (v.getMainFill (parent, imageProvider));
  70833. if (mainFill != newFill)
  70834. {
  70835. needsRedraw = true;
  70836. mainFill = newFill;
  70837. }
  70838. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  70839. if (strokeFill != newStrokeFill)
  70840. {
  70841. needsRedraw = true;
  70842. strokeFill = newStrokeFill;
  70843. }
  70844. const PathStrokeType newStroke (v.getStrokeType());
  70845. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70846. Path newPath;
  70847. newRelativePath->createPath (newPath, parent);
  70848. if (! newRelativePath->containsAnyDynamicPoints())
  70849. newRelativePath = 0;
  70850. if (strokeType != newStroke || path != newPath)
  70851. {
  70852. damageRect = getBounds();
  70853. path.swapWithPath (newPath);
  70854. strokeNeedsUpdating = true;
  70855. strokeType = newStroke;
  70856. needsRedraw = true;
  70857. }
  70858. relativePath = newRelativePath;
  70859. if (needsRedraw)
  70860. damageRect = damageRect.getUnion (getBounds());
  70861. return damageRect;
  70862. }
  70863. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70864. {
  70865. ValueTree tree (valueTreeType);
  70866. ValueTreeWrapper v (tree);
  70867. v.setID (getName(), 0);
  70868. v.setMainFill (mainFill, 0, 0, 0, imageProvider, 0);
  70869. v.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, 0);
  70870. v.setStrokeType (strokeType, 0);
  70871. if (relativePath != 0)
  70872. {
  70873. relativePath->writeTo (tree, 0);
  70874. }
  70875. else
  70876. {
  70877. RelativePointPath rp (path);
  70878. rp.writeTo (tree, 0);
  70879. }
  70880. return tree;
  70881. }
  70882. END_JUCE_NAMESPACE
  70883. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70884. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70885. BEGIN_JUCE_NAMESPACE
  70886. DrawableText::DrawableText()
  70887. : colour (Colours::black),
  70888. justification (Justification::centredLeft)
  70889. {
  70890. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70891. RelativePoint (50.0f, 0.0f),
  70892. RelativePoint (0.0f, 20.0f)));
  70893. setFont (Font (15.0f), true);
  70894. }
  70895. DrawableText::DrawableText (const DrawableText& other)
  70896. : text (other.text),
  70897. font (other.font),
  70898. colour (other.colour),
  70899. justification (other.justification),
  70900. bounds (other.bounds),
  70901. fontSizeControlPoint (other.fontSizeControlPoint)
  70902. {
  70903. }
  70904. DrawableText::~DrawableText()
  70905. {
  70906. }
  70907. void DrawableText::setText (const String& newText)
  70908. {
  70909. text = newText;
  70910. }
  70911. void DrawableText::setColour (const Colour& newColour)
  70912. {
  70913. colour = newColour;
  70914. }
  70915. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70916. {
  70917. font = newFont;
  70918. if (applySizeAndScale)
  70919. {
  70920. Point<float> corners[3];
  70921. bounds.resolveThreePoints (corners, parent);
  70922. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  70923. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70924. }
  70925. }
  70926. void DrawableText::setJustification (const Justification& newJustification)
  70927. {
  70928. justification = newJustification;
  70929. }
  70930. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70931. {
  70932. bounds = newBounds;
  70933. }
  70934. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70935. {
  70936. fontSizeControlPoint = newPoint;
  70937. }
  70938. void DrawableText::render (const Drawable::RenderingContext& context) const
  70939. {
  70940. Point<float> points[3];
  70941. bounds.resolveThreePoints (points, parent);
  70942. const float w = Line<float> (points[0], points[1]).getLength();
  70943. const float h = Line<float> (points[0], points[2]).getLength();
  70944. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  70945. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  70946. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  70947. Font f (font);
  70948. f.setHeight (fontHeight);
  70949. f.setHorizontalScale (fontWidth / fontHeight);
  70950. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  70951. GlyphArrangement ga;
  70952. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  70953. ga.draw (context.g,
  70954. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70955. w, 0, points[1].getX(), points[1].getY(),
  70956. 0, h, points[2].getX(), points[2].getY())
  70957. .followedBy (context.transform));
  70958. }
  70959. const Rectangle<float> DrawableText::getBounds() const
  70960. {
  70961. return bounds.getBounds (parent);
  70962. }
  70963. bool DrawableText::hitTest (float x, float y) const
  70964. {
  70965. Path p;
  70966. bounds.getPath (p, parent);
  70967. return p.contains (x, y);
  70968. }
  70969. Drawable* DrawableText::createCopy() const
  70970. {
  70971. return new DrawableText (*this);
  70972. }
  70973. void DrawableText::invalidatePoints()
  70974. {
  70975. }
  70976. const Identifier DrawableText::valueTreeType ("Text");
  70977. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  70978. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  70979. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  70980. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  70981. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  70982. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  70983. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70984. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  70985. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70986. : ValueTreeWrapperBase (state_)
  70987. {
  70988. jassert (state.hasType (valueTreeType));
  70989. }
  70990. const String DrawableText::ValueTreeWrapper::getText() const
  70991. {
  70992. return state [text].toString();
  70993. }
  70994. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  70995. {
  70996. state.setProperty (text, newText, undoManager);
  70997. }
  70998. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  70999. {
  71000. return state.getPropertyAsValue (text, undoManager);
  71001. }
  71002. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71003. {
  71004. return Colour::fromString (state [colour].toString());
  71005. }
  71006. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71007. {
  71008. state.setProperty (colour, newColour.toString(), undoManager);
  71009. }
  71010. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71011. {
  71012. return Justification ((int) state [justification]);
  71013. }
  71014. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71015. {
  71016. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71017. }
  71018. const Font DrawableText::ValueTreeWrapper::getFont() const
  71019. {
  71020. return Font::fromString (state [font]);
  71021. }
  71022. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71023. {
  71024. state.setProperty (font, newFont.toString(), undoManager);
  71025. }
  71026. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71027. {
  71028. return state.getPropertyAsValue (font, undoManager);
  71029. }
  71030. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71031. {
  71032. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71033. }
  71034. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71035. {
  71036. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71037. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71038. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71039. }
  71040. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71041. {
  71042. return state [fontSizeAnchor].toString();
  71043. }
  71044. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71045. {
  71046. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71047. }
  71048. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  71049. {
  71050. ValueTreeWrapper v (tree);
  71051. setName (v.getID());
  71052. const RelativeParallelogram newBounds (v.getBoundingBox());
  71053. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71054. const Colour newColour (v.getColour());
  71055. const Justification newJustification (v.getJustification());
  71056. const String newText (v.getText());
  71057. const Font newFont (v.getFont());
  71058. if (text != newText || font != newFont || justification != newJustification
  71059. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71060. {
  71061. const Rectangle<float> damage (getBounds());
  71062. setBoundingBox (newBounds);
  71063. setFontSizeControlPoint (newFontPoint);
  71064. setColour (newColour);
  71065. setFont (newFont, false);
  71066. setJustification (newJustification);
  71067. setText (newText);
  71068. return damage.getUnion (getBounds());
  71069. }
  71070. return Rectangle<float>();
  71071. }
  71072. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  71073. {
  71074. ValueTree tree (valueTreeType);
  71075. ValueTreeWrapper v (tree);
  71076. v.setID (getName(), 0);
  71077. v.setText (text, 0);
  71078. v.setFont (font, 0);
  71079. v.setJustification (justification, 0);
  71080. v.setColour (colour, 0);
  71081. v.setBoundingBox (bounds, 0);
  71082. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71083. return tree;
  71084. }
  71085. END_JUCE_NAMESPACE
  71086. /*** End of inlined file: juce_DrawableText.cpp ***/
  71087. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71088. BEGIN_JUCE_NAMESPACE
  71089. class SVGState
  71090. {
  71091. public:
  71092. SVGState (const XmlElement* const topLevel)
  71093. : topLevelXml (topLevel),
  71094. elementX (0), elementY (0),
  71095. width (512), height (512),
  71096. viewBoxW (0), viewBoxH (0)
  71097. {
  71098. }
  71099. ~SVGState()
  71100. {
  71101. }
  71102. Drawable* parseSVGElement (const XmlElement& xml)
  71103. {
  71104. if (! xml.hasTagName ("svg"))
  71105. return 0;
  71106. DrawableComposite* const drawable = new DrawableComposite();
  71107. drawable->setName (xml.getStringAttribute ("id"));
  71108. SVGState newState (*this);
  71109. if (xml.hasAttribute ("transform"))
  71110. newState.addTransform (xml);
  71111. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71112. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71113. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71114. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71115. if (xml.hasAttribute ("viewBox"))
  71116. {
  71117. const String viewParams (xml.getStringAttribute ("viewBox"));
  71118. int i = 0;
  71119. float vx, vy, vw, vh;
  71120. if (parseCoords (viewParams, vx, vy, i, true)
  71121. && parseCoords (viewParams, vw, vh, i, true)
  71122. && vw > 0
  71123. && vh > 0)
  71124. {
  71125. newState.viewBoxW = vw;
  71126. newState.viewBoxH = vh;
  71127. int placementFlags = 0;
  71128. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71129. if (aspect.containsIgnoreCase ("none"))
  71130. {
  71131. placementFlags = RectanglePlacement::stretchToFit;
  71132. }
  71133. else
  71134. {
  71135. if (aspect.containsIgnoreCase ("slice"))
  71136. placementFlags |= RectanglePlacement::fillDestination;
  71137. if (aspect.containsIgnoreCase ("xMin"))
  71138. placementFlags |= RectanglePlacement::xLeft;
  71139. else if (aspect.containsIgnoreCase ("xMax"))
  71140. placementFlags |= RectanglePlacement::xRight;
  71141. else
  71142. placementFlags |= RectanglePlacement::xMid;
  71143. if (aspect.containsIgnoreCase ("yMin"))
  71144. placementFlags |= RectanglePlacement::yTop;
  71145. else if (aspect.containsIgnoreCase ("yMax"))
  71146. placementFlags |= RectanglePlacement::yBottom;
  71147. else
  71148. placementFlags |= RectanglePlacement::yMid;
  71149. }
  71150. const RectanglePlacement placement (placementFlags);
  71151. newState.transform
  71152. = placement.getTransformToFit (vx, vy, vw, vh,
  71153. 0.0f, 0.0f, newState.width, newState.height)
  71154. .followedBy (newState.transform);
  71155. }
  71156. }
  71157. else
  71158. {
  71159. if (viewBoxW == 0)
  71160. newState.viewBoxW = newState.width;
  71161. if (viewBoxH == 0)
  71162. newState.viewBoxH = newState.height;
  71163. }
  71164. newState.parseSubElements (xml, drawable);
  71165. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71166. return drawable;
  71167. }
  71168. private:
  71169. const XmlElement* const topLevelXml;
  71170. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71171. AffineTransform transform;
  71172. String cssStyleText;
  71173. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71174. {
  71175. forEachXmlChildElement (xml, e)
  71176. {
  71177. Drawable* d = 0;
  71178. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71179. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71180. else if (e->hasTagName ("path")) d = parsePath (*e);
  71181. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71182. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71183. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71184. else if (e->hasTagName ("line")) d = parseLine (*e);
  71185. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71186. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71187. else if (e->hasTagName ("text")) d = parseText (*e);
  71188. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71189. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71190. parentDrawable->insertDrawable (d);
  71191. }
  71192. }
  71193. DrawableComposite* parseSwitch (const XmlElement& xml)
  71194. {
  71195. const XmlElement* const group = xml.getChildByName ("g");
  71196. if (group != 0)
  71197. return parseGroupElement (*group);
  71198. return 0;
  71199. }
  71200. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71201. {
  71202. DrawableComposite* const drawable = new DrawableComposite();
  71203. drawable->setName (xml.getStringAttribute ("id"));
  71204. if (xml.hasAttribute ("transform"))
  71205. {
  71206. SVGState newState (*this);
  71207. newState.addTransform (xml);
  71208. newState.parseSubElements (xml, drawable);
  71209. }
  71210. else
  71211. {
  71212. parseSubElements (xml, drawable);
  71213. }
  71214. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71215. return drawable;
  71216. }
  71217. Drawable* parsePath (const XmlElement& xml) const
  71218. {
  71219. const String d (xml.getStringAttribute ("d").trimStart());
  71220. Path path;
  71221. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71222. path.setUsingNonZeroWinding (false);
  71223. int index = 0;
  71224. float lastX = 0, lastY = 0;
  71225. float lastX2 = 0, lastY2 = 0;
  71226. juce_wchar lastCommandChar = 0;
  71227. bool isRelative = true;
  71228. bool carryOn = true;
  71229. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71230. while (d[index] != 0)
  71231. {
  71232. float x, y, x2, y2, x3, y3;
  71233. if (validCommandChars.containsChar (d[index]))
  71234. {
  71235. lastCommandChar = d [index++];
  71236. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71237. }
  71238. switch (lastCommandChar)
  71239. {
  71240. case 'M':
  71241. case 'm':
  71242. case 'L':
  71243. case 'l':
  71244. if (parseCoords (d, x, y, index, false))
  71245. {
  71246. if (isRelative)
  71247. {
  71248. x += lastX;
  71249. y += lastY;
  71250. }
  71251. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71252. {
  71253. path.startNewSubPath (x, y);
  71254. lastCommandChar = 'l';
  71255. }
  71256. else
  71257. path.lineTo (x, y);
  71258. lastX2 = lastX;
  71259. lastY2 = lastY;
  71260. lastX = x;
  71261. lastY = y;
  71262. }
  71263. else
  71264. {
  71265. ++index;
  71266. }
  71267. break;
  71268. case 'H':
  71269. case 'h':
  71270. if (parseCoord (d, x, index, false, true))
  71271. {
  71272. if (isRelative)
  71273. x += lastX;
  71274. path.lineTo (x, lastY);
  71275. lastX2 = lastX;
  71276. lastX = x;
  71277. }
  71278. else
  71279. {
  71280. ++index;
  71281. }
  71282. break;
  71283. case 'V':
  71284. case 'v':
  71285. if (parseCoord (d, y, index, false, false))
  71286. {
  71287. if (isRelative)
  71288. y += lastY;
  71289. path.lineTo (lastX, y);
  71290. lastY2 = lastY;
  71291. lastY = y;
  71292. }
  71293. else
  71294. {
  71295. ++index;
  71296. }
  71297. break;
  71298. case 'C':
  71299. case 'c':
  71300. if (parseCoords (d, x, y, index, false)
  71301. && parseCoords (d, x2, y2, index, false)
  71302. && parseCoords (d, x3, y3, index, false))
  71303. {
  71304. if (isRelative)
  71305. {
  71306. x += lastX;
  71307. y += lastY;
  71308. x2 += lastX;
  71309. y2 += lastY;
  71310. x3 += lastX;
  71311. y3 += lastY;
  71312. }
  71313. path.cubicTo (x, y, x2, y2, x3, y3);
  71314. lastX2 = x2;
  71315. lastY2 = y2;
  71316. lastX = x3;
  71317. lastY = y3;
  71318. }
  71319. else
  71320. {
  71321. ++index;
  71322. }
  71323. break;
  71324. case 'S':
  71325. case 's':
  71326. if (parseCoords (d, x, y, index, false)
  71327. && parseCoords (d, x3, y3, index, false))
  71328. {
  71329. if (isRelative)
  71330. {
  71331. x += lastX;
  71332. y += lastY;
  71333. x3 += lastX;
  71334. y3 += lastY;
  71335. }
  71336. x2 = lastX + (lastX - lastX2);
  71337. y2 = lastY + (lastY - lastY2);
  71338. path.cubicTo (x2, y2, x, y, x3, y3);
  71339. lastX2 = x;
  71340. lastY2 = y;
  71341. lastX = x3;
  71342. lastY = y3;
  71343. }
  71344. else
  71345. {
  71346. ++index;
  71347. }
  71348. break;
  71349. case 'Q':
  71350. case 'q':
  71351. if (parseCoords (d, x, y, index, false)
  71352. && parseCoords (d, x2, y2, index, false))
  71353. {
  71354. if (isRelative)
  71355. {
  71356. x += lastX;
  71357. y += lastY;
  71358. x2 += lastX;
  71359. y2 += lastY;
  71360. }
  71361. path.quadraticTo (x, y, x2, y2);
  71362. lastX2 = x;
  71363. lastY2 = y;
  71364. lastX = x2;
  71365. lastY = y2;
  71366. }
  71367. else
  71368. {
  71369. ++index;
  71370. }
  71371. break;
  71372. case 'T':
  71373. case 't':
  71374. if (parseCoords (d, x, y, index, false))
  71375. {
  71376. if (isRelative)
  71377. {
  71378. x += lastX;
  71379. y += lastY;
  71380. }
  71381. x2 = lastX + (lastX - lastX2);
  71382. y2 = lastY + (lastY - lastY2);
  71383. path.quadraticTo (x2, y2, x, y);
  71384. lastX2 = x2;
  71385. lastY2 = y2;
  71386. lastX = x;
  71387. lastY = y;
  71388. }
  71389. else
  71390. {
  71391. ++index;
  71392. }
  71393. break;
  71394. case 'A':
  71395. case 'a':
  71396. if (parseCoords (d, x, y, index, false))
  71397. {
  71398. String num;
  71399. if (parseNextNumber (d, num, index, false))
  71400. {
  71401. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71402. if (parseNextNumber (d, num, index, false))
  71403. {
  71404. const bool largeArc = num.getIntValue() != 0;
  71405. if (parseNextNumber (d, num, index, false))
  71406. {
  71407. const bool sweep = num.getIntValue() != 0;
  71408. if (parseCoords (d, x2, y2, index, false))
  71409. {
  71410. if (isRelative)
  71411. {
  71412. x2 += lastX;
  71413. y2 += lastY;
  71414. }
  71415. if (lastX != x2 || lastY != y2)
  71416. {
  71417. double centreX, centreY, startAngle, deltaAngle;
  71418. double rx = x, ry = y;
  71419. endpointToCentreParameters (lastX, lastY, x2, y2,
  71420. angle, largeArc, sweep,
  71421. rx, ry, centreX, centreY,
  71422. startAngle, deltaAngle);
  71423. path.addCentredArc ((float) centreX, (float) centreY,
  71424. (float) rx, (float) ry,
  71425. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71426. false);
  71427. path.lineTo (x2, y2);
  71428. }
  71429. lastX2 = lastX;
  71430. lastY2 = lastY;
  71431. lastX = x2;
  71432. lastY = y2;
  71433. }
  71434. }
  71435. }
  71436. }
  71437. }
  71438. else
  71439. {
  71440. ++index;
  71441. }
  71442. break;
  71443. case 'Z':
  71444. case 'z':
  71445. path.closeSubPath();
  71446. while (CharacterFunctions::isWhitespace (d [index]))
  71447. ++index;
  71448. break;
  71449. default:
  71450. carryOn = false;
  71451. break;
  71452. }
  71453. if (! carryOn)
  71454. break;
  71455. }
  71456. return parseShape (xml, path);
  71457. }
  71458. Drawable* parseRect (const XmlElement& xml) const
  71459. {
  71460. Path rect;
  71461. const bool hasRX = xml.hasAttribute ("rx");
  71462. const bool hasRY = xml.hasAttribute ("ry");
  71463. if (hasRX || hasRY)
  71464. {
  71465. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71466. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71467. if (! hasRX)
  71468. rx = ry;
  71469. else if (! hasRY)
  71470. ry = rx;
  71471. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71472. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71473. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71474. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71475. rx, ry);
  71476. }
  71477. else
  71478. {
  71479. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71480. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71481. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71482. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71483. }
  71484. return parseShape (xml, rect);
  71485. }
  71486. Drawable* parseCircle (const XmlElement& xml) const
  71487. {
  71488. Path circle;
  71489. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71490. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71491. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71492. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71493. return parseShape (xml, circle);
  71494. }
  71495. Drawable* parseEllipse (const XmlElement& xml) const
  71496. {
  71497. Path ellipse;
  71498. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71499. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71500. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71501. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71502. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71503. return parseShape (xml, ellipse);
  71504. }
  71505. Drawable* parseLine (const XmlElement& xml) const
  71506. {
  71507. Path line;
  71508. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71509. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71510. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71511. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71512. line.startNewSubPath (x1, y1);
  71513. line.lineTo (x2, y2);
  71514. return parseShape (xml, line);
  71515. }
  71516. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71517. {
  71518. const String points (xml.getStringAttribute ("points"));
  71519. Path path;
  71520. int index = 0;
  71521. float x, y;
  71522. if (parseCoords (points, x, y, index, true))
  71523. {
  71524. float firstX = x;
  71525. float firstY = y;
  71526. float lastX = 0, lastY = 0;
  71527. path.startNewSubPath (x, y);
  71528. while (parseCoords (points, x, y, index, true))
  71529. {
  71530. lastX = x;
  71531. lastY = y;
  71532. path.lineTo (x, y);
  71533. }
  71534. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71535. path.closeSubPath();
  71536. }
  71537. return parseShape (xml, path);
  71538. }
  71539. Drawable* parseShape (const XmlElement& xml, Path& path,
  71540. const bool shouldParseTransform = true) const
  71541. {
  71542. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71543. {
  71544. SVGState newState (*this);
  71545. newState.addTransform (xml);
  71546. return newState.parseShape (xml, path, false);
  71547. }
  71548. DrawablePath* dp = new DrawablePath();
  71549. dp->setName (xml.getStringAttribute ("id"));
  71550. dp->setFill (Colours::transparentBlack);
  71551. path.applyTransform (transform);
  71552. dp->setPath (path);
  71553. Path::Iterator iter (path);
  71554. bool containsClosedSubPath = false;
  71555. while (iter.next())
  71556. {
  71557. if (iter.elementType == Path::Iterator::closePath)
  71558. {
  71559. containsClosedSubPath = true;
  71560. break;
  71561. }
  71562. }
  71563. dp->setFill (getPathFillType (path,
  71564. getStyleAttribute (&xml, "fill"),
  71565. getStyleAttribute (&xml, "fill-opacity"),
  71566. getStyleAttribute (&xml, "opacity"),
  71567. containsClosedSubPath ? Colours::black
  71568. : Colours::transparentBlack));
  71569. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71570. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71571. {
  71572. dp->setStrokeFill (getPathFillType (path, strokeType,
  71573. getStyleAttribute (&xml, "stroke-opacity"),
  71574. getStyleAttribute (&xml, "opacity"),
  71575. Colours::transparentBlack));
  71576. dp->setStrokeType (getStrokeFor (&xml));
  71577. }
  71578. return dp;
  71579. }
  71580. const XmlElement* findLinkedElement (const XmlElement* e) const
  71581. {
  71582. const String id (e->getStringAttribute ("xlink:href"));
  71583. if (! id.startsWithChar ('#'))
  71584. return 0;
  71585. return findElementForId (topLevelXml, id.substring (1));
  71586. }
  71587. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71588. {
  71589. if (fillXml == 0)
  71590. return;
  71591. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71592. {
  71593. int index = 0;
  71594. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71595. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71596. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71597. double offset = e->getDoubleAttribute ("offset");
  71598. if (e->getStringAttribute ("offset").containsChar ('%'))
  71599. offset *= 0.01;
  71600. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71601. }
  71602. }
  71603. const FillType getPathFillType (const Path& path,
  71604. const String& fill,
  71605. const String& fillOpacity,
  71606. const String& overallOpacity,
  71607. const Colour& defaultColour) const
  71608. {
  71609. float opacity = 1.0f;
  71610. if (overallOpacity.isNotEmpty())
  71611. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71612. if (fillOpacity.isNotEmpty())
  71613. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71614. if (fill.startsWithIgnoreCase ("url"))
  71615. {
  71616. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71617. .upToLastOccurrenceOf (")", false, false).trim());
  71618. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71619. if (fillXml != 0
  71620. && (fillXml->hasTagName ("linearGradient")
  71621. || fillXml->hasTagName ("radialGradient")))
  71622. {
  71623. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71624. ColourGradient gradient;
  71625. addGradientStopsIn (gradient, inheritedFrom);
  71626. addGradientStopsIn (gradient, fillXml);
  71627. if (gradient.getNumColours() > 0)
  71628. {
  71629. gradient.addColour (0.0, gradient.getColour (0));
  71630. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71631. }
  71632. else
  71633. {
  71634. gradient.addColour (0.0, Colours::black);
  71635. gradient.addColour (1.0, Colours::black);
  71636. }
  71637. if (overallOpacity.isNotEmpty())
  71638. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71639. jassert (gradient.getNumColours() > 0);
  71640. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71641. float gradientWidth = viewBoxW;
  71642. float gradientHeight = viewBoxH;
  71643. float dx = 0.0f;
  71644. float dy = 0.0f;
  71645. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71646. if (! userSpace)
  71647. {
  71648. const Rectangle<float> bounds (path.getBounds());
  71649. dx = bounds.getX();
  71650. dy = bounds.getY();
  71651. gradientWidth = bounds.getWidth();
  71652. gradientHeight = bounds.getHeight();
  71653. }
  71654. if (gradient.isRadial)
  71655. {
  71656. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71657. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71658. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71659. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71660. //xxx (the fx, fy focal point isn't handled properly here..)
  71661. }
  71662. else
  71663. {
  71664. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71665. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71666. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71667. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71668. if (gradient.point1 == gradient.point2)
  71669. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71670. }
  71671. FillType type (gradient);
  71672. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71673. .followedBy (transform);
  71674. return type;
  71675. }
  71676. }
  71677. if (fill.equalsIgnoreCase ("none"))
  71678. return Colours::transparentBlack;
  71679. int i = 0;
  71680. const Colour colour (parseColour (fill, i, defaultColour));
  71681. return colour.withMultipliedAlpha (opacity);
  71682. }
  71683. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71684. {
  71685. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71686. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71687. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71688. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71689. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71690. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71691. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71692. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71693. if (join.equalsIgnoreCase ("round"))
  71694. joinStyle = PathStrokeType::curved;
  71695. else if (join.equalsIgnoreCase ("bevel"))
  71696. joinStyle = PathStrokeType::beveled;
  71697. if (cap.equalsIgnoreCase ("round"))
  71698. capStyle = PathStrokeType::rounded;
  71699. else if (cap.equalsIgnoreCase ("square"))
  71700. capStyle = PathStrokeType::square;
  71701. float ox = 0.0f, oy = 0.0f;
  71702. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71703. transform.transformPoints (ox, oy, x, y);
  71704. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71705. joinStyle, capStyle);
  71706. }
  71707. Drawable* parseText (const XmlElement& xml)
  71708. {
  71709. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71710. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71711. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71712. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71713. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71714. //xxx not done text yet!
  71715. forEachXmlChildElement (xml, e)
  71716. {
  71717. if (e->isTextElement())
  71718. {
  71719. const String text (e->getText());
  71720. Path path;
  71721. Drawable* s = parseShape (*e, path);
  71722. delete s; // xxx not finished!
  71723. }
  71724. else if (e->hasTagName ("tspan"))
  71725. {
  71726. Drawable* s = parseText (*e);
  71727. delete s; // xxx not finished!
  71728. }
  71729. }
  71730. return 0;
  71731. }
  71732. void addTransform (const XmlElement& xml)
  71733. {
  71734. transform = parseTransform (xml.getStringAttribute ("transform"))
  71735. .followedBy (transform);
  71736. }
  71737. bool parseCoord (const String& s, float& value, int& index,
  71738. const bool allowUnits, const bool isX) const
  71739. {
  71740. String number;
  71741. if (! parseNextNumber (s, number, index, allowUnits))
  71742. {
  71743. value = 0;
  71744. return false;
  71745. }
  71746. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71747. return true;
  71748. }
  71749. bool parseCoords (const String& s, float& x, float& y,
  71750. int& index, const bool allowUnits) const
  71751. {
  71752. return parseCoord (s, x, index, allowUnits, true)
  71753. && parseCoord (s, y, index, allowUnits, false);
  71754. }
  71755. float getCoordLength (const String& s, const float sizeForProportions) const
  71756. {
  71757. float n = s.getFloatValue();
  71758. const int len = s.length();
  71759. if (len > 2)
  71760. {
  71761. const float dpi = 96.0f;
  71762. const juce_wchar n1 = s [len - 2];
  71763. const juce_wchar n2 = s [len - 1];
  71764. if (n1 == 'i' && n2 == 'n')
  71765. n *= dpi;
  71766. else if (n1 == 'm' && n2 == 'm')
  71767. n *= dpi / 25.4f;
  71768. else if (n1 == 'c' && n2 == 'm')
  71769. n *= dpi / 2.54f;
  71770. else if (n1 == 'p' && n2 == 'c')
  71771. n *= 15.0f;
  71772. else if (n2 == '%')
  71773. n *= 0.01f * sizeForProportions;
  71774. }
  71775. return n;
  71776. }
  71777. void getCoordList (Array <float>& coords, const String& list,
  71778. const bool allowUnits, const bool isX) const
  71779. {
  71780. int index = 0;
  71781. float value;
  71782. while (parseCoord (list, value, index, allowUnits, isX))
  71783. coords.add (value);
  71784. }
  71785. void parseCSSStyle (const XmlElement& xml)
  71786. {
  71787. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71788. }
  71789. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71790. const String& defaultValue = String::empty) const
  71791. {
  71792. if (xml->hasAttribute (attributeName))
  71793. return xml->getStringAttribute (attributeName, defaultValue);
  71794. const String styleAtt (xml->getStringAttribute ("style"));
  71795. if (styleAtt.isNotEmpty())
  71796. {
  71797. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71798. if (value.isNotEmpty())
  71799. return value;
  71800. }
  71801. else if (xml->hasAttribute ("class"))
  71802. {
  71803. const String className ("." + xml->getStringAttribute ("class"));
  71804. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71805. if (index < 0)
  71806. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71807. if (index >= 0)
  71808. {
  71809. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71810. if (openBracket > index)
  71811. {
  71812. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71813. if (closeBracket > openBracket)
  71814. {
  71815. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71816. if (value.isNotEmpty())
  71817. return value;
  71818. }
  71819. }
  71820. }
  71821. }
  71822. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71823. if (xml != 0)
  71824. return getStyleAttribute (xml, attributeName, defaultValue);
  71825. return defaultValue;
  71826. }
  71827. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71828. {
  71829. if (xml->hasAttribute (attributeName))
  71830. return xml->getStringAttribute (attributeName);
  71831. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71832. if (xml != 0)
  71833. return getInheritedAttribute (xml, attributeName);
  71834. return String::empty;
  71835. }
  71836. static bool isIdentifierChar (const juce_wchar c)
  71837. {
  71838. return CharacterFunctions::isLetter (c) || c == '-';
  71839. }
  71840. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71841. {
  71842. int i = 0;
  71843. for (;;)
  71844. {
  71845. i = list.indexOf (i, attributeName);
  71846. if (i < 0)
  71847. break;
  71848. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71849. && ! isIdentifierChar (list [i + attributeName.length()]))
  71850. {
  71851. i = list.indexOfChar (i, ':');
  71852. if (i < 0)
  71853. break;
  71854. int end = list.indexOfChar (i, ';');
  71855. if (end < 0)
  71856. end = 0x7ffff;
  71857. return list.substring (i + 1, end).trim();
  71858. }
  71859. ++i;
  71860. }
  71861. return defaultValue;
  71862. }
  71863. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  71864. {
  71865. const juce_wchar* const s = source;
  71866. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71867. ++index;
  71868. int start = index;
  71869. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  71870. ++index;
  71871. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  71872. ++index;
  71873. if ((s[index] == 'e' || s[index] == 'E')
  71874. && (CharacterFunctions::isDigit (s[index + 1])
  71875. || s[index + 1] == '-'
  71876. || s[index + 1] == '+'))
  71877. {
  71878. index += 2;
  71879. while (CharacterFunctions::isDigit (s[index]))
  71880. ++index;
  71881. }
  71882. if (allowUnits)
  71883. {
  71884. while (CharacterFunctions::isLetter (s[index]))
  71885. ++index;
  71886. }
  71887. if (index == start)
  71888. return false;
  71889. value = String (s + start, index - start);
  71890. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71891. ++index;
  71892. return true;
  71893. }
  71894. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71895. {
  71896. if (s [index] == '#')
  71897. {
  71898. uint32 hex [6];
  71899. zeromem (hex, sizeof (hex));
  71900. int numChars = 0;
  71901. for (int i = 6; --i >= 0;)
  71902. {
  71903. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71904. if (hexValue >= 0)
  71905. hex [numChars++] = hexValue;
  71906. else
  71907. break;
  71908. }
  71909. if (numChars <= 3)
  71910. return Colour ((uint8) (hex [0] * 0x11),
  71911. (uint8) (hex [1] * 0x11),
  71912. (uint8) (hex [2] * 0x11));
  71913. else
  71914. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71915. (uint8) ((hex [2] << 4) + hex [3]),
  71916. (uint8) ((hex [4] << 4) + hex [5]));
  71917. }
  71918. else if (s [index] == 'r'
  71919. && s [index + 1] == 'g'
  71920. && s [index + 2] == 'b')
  71921. {
  71922. const int openBracket = s.indexOfChar (index, '(');
  71923. const int closeBracket = s.indexOfChar (openBracket, ')');
  71924. if (openBracket >= 3 && closeBracket > openBracket)
  71925. {
  71926. index = closeBracket;
  71927. StringArray tokens;
  71928. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71929. tokens.trim();
  71930. tokens.removeEmptyStrings();
  71931. if (tokens[0].containsChar ('%'))
  71932. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71933. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  71934. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  71935. else
  71936. return Colour ((uint8) tokens[0].getIntValue(),
  71937. (uint8) tokens[1].getIntValue(),
  71938. (uint8) tokens[2].getIntValue());
  71939. }
  71940. }
  71941. return Colours::findColourForName (s, defaultColour);
  71942. }
  71943. static const AffineTransform parseTransform (String t)
  71944. {
  71945. AffineTransform result;
  71946. while (t.isNotEmpty())
  71947. {
  71948. StringArray tokens;
  71949. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  71950. .upToFirstOccurrenceOf (")", false, false),
  71951. ", ", String::empty);
  71952. tokens.removeEmptyStrings (true);
  71953. float numbers [6];
  71954. for (int i = 0; i < 6; ++i)
  71955. numbers[i] = tokens[i].getFloatValue();
  71956. AffineTransform trans;
  71957. if (t.startsWithIgnoreCase ("matrix"))
  71958. {
  71959. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  71960. numbers[1], numbers[3], numbers[5]);
  71961. }
  71962. else if (t.startsWithIgnoreCase ("translate"))
  71963. {
  71964. jassert (tokens.size() == 2);
  71965. trans = AffineTransform::translation (numbers[0], numbers[1]);
  71966. }
  71967. else if (t.startsWithIgnoreCase ("scale"))
  71968. {
  71969. if (tokens.size() == 1)
  71970. trans = AffineTransform::scale (numbers[0], numbers[0]);
  71971. else
  71972. trans = AffineTransform::scale (numbers[0], numbers[1]);
  71973. }
  71974. else if (t.startsWithIgnoreCase ("rotate"))
  71975. {
  71976. if (tokens.size() != 3)
  71977. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  71978. else
  71979. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  71980. numbers[1], numbers[2]);
  71981. }
  71982. else if (t.startsWithIgnoreCase ("skewX"))
  71983. {
  71984. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  71985. 0.0f, 1.0f, 0.0f);
  71986. }
  71987. else if (t.startsWithIgnoreCase ("skewY"))
  71988. {
  71989. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  71990. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  71991. }
  71992. result = trans.followedBy (result);
  71993. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  71994. }
  71995. return result;
  71996. }
  71997. static void endpointToCentreParameters (const double x1, const double y1,
  71998. const double x2, const double y2,
  71999. const double angle,
  72000. const bool largeArc, const bool sweep,
  72001. double& rx, double& ry,
  72002. double& centreX, double& centreY,
  72003. double& startAngle, double& deltaAngle)
  72004. {
  72005. const double midX = (x1 - x2) * 0.5;
  72006. const double midY = (y1 - y2) * 0.5;
  72007. const double cosAngle = cos (angle);
  72008. const double sinAngle = sin (angle);
  72009. const double xp = cosAngle * midX + sinAngle * midY;
  72010. const double yp = cosAngle * midY - sinAngle * midX;
  72011. const double xp2 = xp * xp;
  72012. const double yp2 = yp * yp;
  72013. double rx2 = rx * rx;
  72014. double ry2 = ry * ry;
  72015. const double s = (xp2 / rx2) + (yp2 / ry2);
  72016. double c;
  72017. if (s <= 1.0)
  72018. {
  72019. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72020. / (( rx2 * yp2) + (ry2 * xp2))));
  72021. if (largeArc == sweep)
  72022. c = -c;
  72023. }
  72024. else
  72025. {
  72026. const double s2 = std::sqrt (s);
  72027. rx *= s2;
  72028. ry *= s2;
  72029. rx2 = rx * rx;
  72030. ry2 = ry * ry;
  72031. c = 0;
  72032. }
  72033. const double cpx = ((rx * yp) / ry) * c;
  72034. const double cpy = ((-ry * xp) / rx) * c;
  72035. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72036. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72037. const double ux = (xp - cpx) / rx;
  72038. const double uy = (yp - cpy) / ry;
  72039. const double vx = (-xp - cpx) / rx;
  72040. const double vy = (-yp - cpy) / ry;
  72041. const double length = juce_hypot (ux, uy);
  72042. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72043. if (uy < 0)
  72044. startAngle = -startAngle;
  72045. startAngle += double_Pi * 0.5;
  72046. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72047. / (length * juce_hypot (vx, vy))));
  72048. if ((ux * vy) - (uy * vx) < 0)
  72049. deltaAngle = -deltaAngle;
  72050. if (sweep)
  72051. {
  72052. if (deltaAngle < 0)
  72053. deltaAngle += double_Pi * 2.0;
  72054. }
  72055. else
  72056. {
  72057. if (deltaAngle > 0)
  72058. deltaAngle -= double_Pi * 2.0;
  72059. }
  72060. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72061. }
  72062. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72063. {
  72064. forEachXmlChildElement (*parent, e)
  72065. {
  72066. if (e->compareAttribute ("id", id))
  72067. return e;
  72068. const XmlElement* const found = findElementForId (e, id);
  72069. if (found != 0)
  72070. return found;
  72071. }
  72072. return 0;
  72073. }
  72074. SVGState& operator= (const SVGState&);
  72075. };
  72076. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72077. {
  72078. SVGState state (&svgDocument);
  72079. return state.parseSVGElement (svgDocument);
  72080. }
  72081. END_JUCE_NAMESPACE
  72082. /*** End of inlined file: juce_SVGParser.cpp ***/
  72083. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72084. BEGIN_JUCE_NAMESPACE
  72085. #if JUCE_MSVC && JUCE_DEBUG
  72086. #pragma optimize ("t", on)
  72087. #endif
  72088. DropShadowEffect::DropShadowEffect()
  72089. : offsetX (0),
  72090. offsetY (0),
  72091. radius (4),
  72092. opacity (0.6f)
  72093. {
  72094. }
  72095. DropShadowEffect::~DropShadowEffect()
  72096. {
  72097. }
  72098. void DropShadowEffect::setShadowProperties (const float newRadius,
  72099. const float newOpacity,
  72100. const int newShadowOffsetX,
  72101. const int newShadowOffsetY)
  72102. {
  72103. radius = jmax (1.1f, newRadius);
  72104. offsetX = newShadowOffsetX;
  72105. offsetY = newShadowOffsetY;
  72106. opacity = newOpacity;
  72107. }
  72108. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  72109. {
  72110. const int w = image.getWidth();
  72111. const int h = image.getHeight();
  72112. Image shadowImage (Image::SingleChannel, w, h, false);
  72113. const Image::BitmapData srcData (image, false);
  72114. const Image::BitmapData destData (shadowImage, true);
  72115. const int filter = roundToInt (63.0f / radius);
  72116. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72117. for (int x = w; --x >= 0;)
  72118. {
  72119. int shadowAlpha = 0;
  72120. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72121. uint8* shadowPix = destData.data + x;
  72122. for (int y = h; --y >= 0;)
  72123. {
  72124. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72125. *shadowPix = (uint8) shadowAlpha;
  72126. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72127. shadowPix += destData.lineStride;
  72128. }
  72129. }
  72130. for (int y = h; --y >= 0;)
  72131. {
  72132. int shadowAlpha = 0;
  72133. uint8* shadowPix = destData.getLinePointer (y);
  72134. for (int x = w; --x >= 0;)
  72135. {
  72136. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72137. *shadowPix++ = (uint8) shadowAlpha;
  72138. }
  72139. }
  72140. g.setColour (Colours::black.withAlpha (opacity));
  72141. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72142. g.setOpacity (1.0f);
  72143. g.drawImageAt (image, 0, 0);
  72144. }
  72145. #if JUCE_MSVC && JUCE_DEBUG
  72146. #pragma optimize ("", on) // resets optimisations to the project defaults
  72147. #endif
  72148. END_JUCE_NAMESPACE
  72149. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72150. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72151. BEGIN_JUCE_NAMESPACE
  72152. GlowEffect::GlowEffect()
  72153. : radius (2.0f),
  72154. colour (Colours::white)
  72155. {
  72156. }
  72157. GlowEffect::~GlowEffect()
  72158. {
  72159. }
  72160. void GlowEffect::setGlowProperties (const float newRadius,
  72161. const Colour& newColour)
  72162. {
  72163. radius = newRadius;
  72164. colour = newColour;
  72165. }
  72166. void GlowEffect::applyEffect (Image& image, Graphics& g)
  72167. {
  72168. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72169. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72170. blurKernel.createGaussianBlur (radius);
  72171. blurKernel.rescaleAllValues (radius);
  72172. blurKernel.applyToImage (temp, image, image.getBounds());
  72173. g.setColour (colour);
  72174. g.drawImageAt (temp, 0, 0, true);
  72175. g.setOpacity (1.0f);
  72176. g.drawImageAt (image, 0, 0, false);
  72177. }
  72178. END_JUCE_NAMESPACE
  72179. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72180. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72181. BEGIN_JUCE_NAMESPACE
  72182. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  72183. : opacity (opacity_)
  72184. {
  72185. }
  72186. ReduceOpacityEffect::~ReduceOpacityEffect()
  72187. {
  72188. }
  72189. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  72190. {
  72191. opacity = jlimit (0.0f, 1.0f, newOpacity);
  72192. }
  72193. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  72194. {
  72195. g.setOpacity (opacity);
  72196. g.drawImageAt (image, 0, 0);
  72197. }
  72198. END_JUCE_NAMESPACE
  72199. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72200. /*** Start of inlined file: juce_Font.cpp ***/
  72201. BEGIN_JUCE_NAMESPACE
  72202. namespace FontValues
  72203. {
  72204. static float limitFontHeight (const float height) throw()
  72205. {
  72206. return jlimit (0.1f, 10000.0f, height);
  72207. }
  72208. static const float defaultFontHeight = 14.0f;
  72209. static String fallbackFont;
  72210. }
  72211. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  72212. const float kerning_, const float ascent_, const int styleFlags_,
  72213. Typeface* const typeface_) throw()
  72214. : typefaceName (typefaceName_),
  72215. height (height_),
  72216. horizontalScale (horizontalScale_),
  72217. kerning (kerning_),
  72218. ascent (ascent_),
  72219. styleFlags (styleFlags_),
  72220. typeface (typeface_)
  72221. {
  72222. }
  72223. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72224. : typefaceName (other.typefaceName),
  72225. height (other.height),
  72226. horizontalScale (other.horizontalScale),
  72227. kerning (other.kerning),
  72228. ascent (other.ascent),
  72229. styleFlags (other.styleFlags),
  72230. typeface (other.typeface)
  72231. {
  72232. }
  72233. Font::Font()
  72234. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  72235. 1.0f, 0, 0, Font::plain, 0))
  72236. {
  72237. }
  72238. Font::Font (const float fontHeight, const int styleFlags_)
  72239. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  72240. 1.0f, 0, 0, styleFlags_, 0))
  72241. {
  72242. }
  72243. Font::Font (const String& typefaceName_,
  72244. const float fontHeight,
  72245. const int styleFlags_)
  72246. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  72247. 1.0f, 0, 0, styleFlags_, 0))
  72248. {
  72249. }
  72250. Font::Font (const Font& other) throw()
  72251. : font (other.font)
  72252. {
  72253. }
  72254. Font& Font::operator= (const Font& other) throw()
  72255. {
  72256. font = other.font;
  72257. return *this;
  72258. }
  72259. Font::~Font() throw()
  72260. {
  72261. }
  72262. Font::Font (const Typeface::Ptr& typeface)
  72263. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  72264. 1.0f, 0, 0, Font::plain, typeface))
  72265. {
  72266. }
  72267. bool Font::operator== (const Font& other) const throw()
  72268. {
  72269. return font == other.font
  72270. || (font->height == other.font->height
  72271. && font->styleFlags == other.font->styleFlags
  72272. && font->horizontalScale == other.font->horizontalScale
  72273. && font->kerning == other.font->kerning
  72274. && font->typefaceName == other.font->typefaceName);
  72275. }
  72276. bool Font::operator!= (const Font& other) const throw()
  72277. {
  72278. return ! operator== (other);
  72279. }
  72280. void Font::dupeInternalIfShared()
  72281. {
  72282. if (font->getReferenceCount() > 1)
  72283. font = new SharedFontInternal (*font);
  72284. }
  72285. const String Font::getDefaultSansSerifFontName()
  72286. {
  72287. static const String name ("<Sans-Serif>");
  72288. return name;
  72289. }
  72290. const String Font::getDefaultSerifFontName()
  72291. {
  72292. static const String name ("<Serif>");
  72293. return name;
  72294. }
  72295. const String Font::getDefaultMonospacedFontName()
  72296. {
  72297. static const String name ("<Monospaced>");
  72298. return name;
  72299. }
  72300. void Font::setTypefaceName (const String& faceName)
  72301. {
  72302. if (faceName != font->typefaceName)
  72303. {
  72304. dupeInternalIfShared();
  72305. font->typefaceName = faceName;
  72306. font->typeface = 0;
  72307. font->ascent = 0;
  72308. }
  72309. }
  72310. const String Font::getFallbackFontName()
  72311. {
  72312. return FontValues::fallbackFont;
  72313. }
  72314. void Font::setFallbackFontName (const String& name)
  72315. {
  72316. FontValues::fallbackFont = name;
  72317. }
  72318. void Font::setHeight (float newHeight)
  72319. {
  72320. newHeight = FontValues::limitFontHeight (newHeight);
  72321. if (font->height != newHeight)
  72322. {
  72323. dupeInternalIfShared();
  72324. font->height = newHeight;
  72325. }
  72326. }
  72327. void Font::setHeightWithoutChangingWidth (float newHeight)
  72328. {
  72329. newHeight = FontValues::limitFontHeight (newHeight);
  72330. if (font->height != newHeight)
  72331. {
  72332. dupeInternalIfShared();
  72333. font->horizontalScale *= (font->height / newHeight);
  72334. font->height = newHeight;
  72335. }
  72336. }
  72337. void Font::setStyleFlags (const int newFlags)
  72338. {
  72339. if (font->styleFlags != newFlags)
  72340. {
  72341. dupeInternalIfShared();
  72342. font->styleFlags = newFlags;
  72343. font->typeface = 0;
  72344. font->ascent = 0;
  72345. }
  72346. }
  72347. void Font::setSizeAndStyle (float newHeight,
  72348. const int newStyleFlags,
  72349. const float newHorizontalScale,
  72350. const float newKerningAmount)
  72351. {
  72352. newHeight = FontValues::limitFontHeight (newHeight);
  72353. if (font->height != newHeight
  72354. || font->horizontalScale != newHorizontalScale
  72355. || font->kerning != newKerningAmount)
  72356. {
  72357. dupeInternalIfShared();
  72358. font->height = newHeight;
  72359. font->horizontalScale = newHorizontalScale;
  72360. font->kerning = newKerningAmount;
  72361. }
  72362. setStyleFlags (newStyleFlags);
  72363. }
  72364. void Font::setHorizontalScale (const float scaleFactor)
  72365. {
  72366. dupeInternalIfShared();
  72367. font->horizontalScale = scaleFactor;
  72368. }
  72369. void Font::setExtraKerningFactor (const float extraKerning)
  72370. {
  72371. dupeInternalIfShared();
  72372. font->kerning = extraKerning;
  72373. }
  72374. void Font::setBold (const bool shouldBeBold)
  72375. {
  72376. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72377. : (font->styleFlags & ~bold));
  72378. }
  72379. const Font Font::boldened() const
  72380. {
  72381. Font f (*this);
  72382. f.setBold (true);
  72383. return f;
  72384. }
  72385. bool Font::isBold() const throw()
  72386. {
  72387. return (font->styleFlags & bold) != 0;
  72388. }
  72389. void Font::setItalic (const bool shouldBeItalic)
  72390. {
  72391. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72392. : (font->styleFlags & ~italic));
  72393. }
  72394. const Font Font::italicised() const
  72395. {
  72396. Font f (*this);
  72397. f.setItalic (true);
  72398. return f;
  72399. }
  72400. bool Font::isItalic() const throw()
  72401. {
  72402. return (font->styleFlags & italic) != 0;
  72403. }
  72404. void Font::setUnderline (const bool shouldBeUnderlined)
  72405. {
  72406. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72407. : (font->styleFlags & ~underlined));
  72408. }
  72409. bool Font::isUnderlined() const throw()
  72410. {
  72411. return (font->styleFlags & underlined) != 0;
  72412. }
  72413. float Font::getAscent() const
  72414. {
  72415. if (font->ascent == 0)
  72416. font->ascent = getTypeface()->getAscent();
  72417. return font->height * font->ascent;
  72418. }
  72419. float Font::getDescent() const
  72420. {
  72421. return font->height - getAscent();
  72422. }
  72423. int Font::getStringWidth (const String& text) const
  72424. {
  72425. return roundToInt (getStringWidthFloat (text));
  72426. }
  72427. float Font::getStringWidthFloat (const String& text) const
  72428. {
  72429. float w = getTypeface()->getStringWidth (text);
  72430. if (font->kerning != 0)
  72431. w += font->kerning * text.length();
  72432. return w * font->height * font->horizontalScale;
  72433. }
  72434. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72435. {
  72436. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72437. const float scale = font->height * font->horizontalScale;
  72438. const int num = xOffsets.size();
  72439. if (num > 0)
  72440. {
  72441. float* const x = &(xOffsets.getReference(0));
  72442. if (font->kerning != 0)
  72443. {
  72444. for (int i = 0; i < num; ++i)
  72445. x[i] = (x[i] + i * font->kerning) * scale;
  72446. }
  72447. else
  72448. {
  72449. for (int i = 0; i < num; ++i)
  72450. x[i] *= scale;
  72451. }
  72452. }
  72453. }
  72454. void Font::findFonts (Array<Font>& destArray)
  72455. {
  72456. const StringArray names (findAllTypefaceNames());
  72457. for (int i = 0; i < names.size(); ++i)
  72458. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72459. }
  72460. const String Font::toString() const
  72461. {
  72462. String s (getTypefaceName());
  72463. if (s == getDefaultSansSerifFontName())
  72464. s = String::empty;
  72465. else
  72466. s += "; ";
  72467. s += String (getHeight(), 1);
  72468. if (isBold())
  72469. s += " bold";
  72470. if (isItalic())
  72471. s += " italic";
  72472. return s;
  72473. }
  72474. const Font Font::fromString (const String& fontDescription)
  72475. {
  72476. String name;
  72477. const int separator = fontDescription.indexOfChar (';');
  72478. if (separator > 0)
  72479. name = fontDescription.substring (0, separator).trim();
  72480. if (name.isEmpty())
  72481. name = getDefaultSansSerifFontName();
  72482. String sizeAndStyle (fontDescription.substring (separator + 1));
  72483. float height = sizeAndStyle.getFloatValue();
  72484. if (height <= 0)
  72485. height = 10.0f;
  72486. int flags = Font::plain;
  72487. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72488. flags |= Font::bold;
  72489. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72490. flags |= Font::italic;
  72491. return Font (name, height, flags);
  72492. }
  72493. class TypefaceCache : public DeletedAtShutdown
  72494. {
  72495. public:
  72496. TypefaceCache (int numToCache = 10)
  72497. : counter (1)
  72498. {
  72499. while (--numToCache >= 0)
  72500. faces.add (new CachedFace());
  72501. }
  72502. ~TypefaceCache()
  72503. {
  72504. clearSingletonInstance();
  72505. }
  72506. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72507. const Typeface::Ptr findTypefaceFor (const Font& font)
  72508. {
  72509. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72510. const String faceName (font.getTypefaceName());
  72511. int i;
  72512. for (i = faces.size(); --i >= 0;)
  72513. {
  72514. CachedFace* const face = faces.getUnchecked(i);
  72515. if (face->flags == flags
  72516. && face->typefaceName == faceName)
  72517. {
  72518. face->lastUsageCount = ++counter;
  72519. return face->typeFace;
  72520. }
  72521. }
  72522. int replaceIndex = 0;
  72523. int bestLastUsageCount = std::numeric_limits<int>::max();
  72524. for (i = faces.size(); --i >= 0;)
  72525. {
  72526. const int lu = faces.getUnchecked(i)->lastUsageCount;
  72527. if (bestLastUsageCount > lu)
  72528. {
  72529. bestLastUsageCount = lu;
  72530. replaceIndex = i;
  72531. }
  72532. }
  72533. CachedFace* const face = faces.getUnchecked (replaceIndex);
  72534. face->typefaceName = faceName;
  72535. face->flags = flags;
  72536. face->lastUsageCount = ++counter;
  72537. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72538. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  72539. return face->typeFace;
  72540. }
  72541. juce_UseDebuggingNewOperator
  72542. private:
  72543. struct CachedFace
  72544. {
  72545. CachedFace() throw()
  72546. : lastUsageCount (0), flags (-1)
  72547. {
  72548. }
  72549. String typefaceName;
  72550. int lastUsageCount;
  72551. int flags;
  72552. Typeface::Ptr typeFace;
  72553. };
  72554. int counter;
  72555. OwnedArray <CachedFace> faces;
  72556. TypefaceCache (const TypefaceCache&);
  72557. TypefaceCache& operator= (const TypefaceCache&);
  72558. };
  72559. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72560. Typeface* Font::getTypeface() const
  72561. {
  72562. if (font->typeface == 0)
  72563. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72564. return font->typeface;
  72565. }
  72566. END_JUCE_NAMESPACE
  72567. /*** End of inlined file: juce_Font.cpp ***/
  72568. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72569. BEGIN_JUCE_NAMESPACE
  72570. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72571. const juce_wchar character_, const int glyph_)
  72572. : x (x_),
  72573. y (y_),
  72574. w (w_),
  72575. font (font_),
  72576. character (character_),
  72577. glyph (glyph_)
  72578. {
  72579. }
  72580. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72581. : x (other.x),
  72582. y (other.y),
  72583. w (other.w),
  72584. font (other.font),
  72585. character (other.character),
  72586. glyph (other.glyph)
  72587. {
  72588. }
  72589. void PositionedGlyph::draw (const Graphics& g) const
  72590. {
  72591. if (! isWhitespace())
  72592. {
  72593. g.getInternalContext()->setFont (font);
  72594. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72595. }
  72596. }
  72597. void PositionedGlyph::draw (const Graphics& g,
  72598. const AffineTransform& transform) const
  72599. {
  72600. if (! isWhitespace())
  72601. {
  72602. g.getInternalContext()->setFont (font);
  72603. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72604. .followedBy (transform));
  72605. }
  72606. }
  72607. void PositionedGlyph::createPath (Path& path) const
  72608. {
  72609. if (! isWhitespace())
  72610. {
  72611. Typeface* const t = font.getTypeface();
  72612. if (t != 0)
  72613. {
  72614. Path p;
  72615. t->getOutlineForGlyph (glyph, p);
  72616. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72617. .translated (x, y));
  72618. }
  72619. }
  72620. }
  72621. bool PositionedGlyph::hitTest (float px, float py) const
  72622. {
  72623. if (getBounds().contains (px, py) && ! isWhitespace())
  72624. {
  72625. Typeface* const t = font.getTypeface();
  72626. if (t != 0)
  72627. {
  72628. Path p;
  72629. t->getOutlineForGlyph (glyph, p);
  72630. AffineTransform::translation (-x, -y)
  72631. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72632. .transformPoint (px, py);
  72633. return p.contains (px, py);
  72634. }
  72635. }
  72636. return false;
  72637. }
  72638. void PositionedGlyph::moveBy (const float deltaX,
  72639. const float deltaY)
  72640. {
  72641. x += deltaX;
  72642. y += deltaY;
  72643. }
  72644. GlyphArrangement::GlyphArrangement()
  72645. {
  72646. glyphs.ensureStorageAllocated (128);
  72647. }
  72648. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72649. {
  72650. addGlyphArrangement (other);
  72651. }
  72652. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72653. {
  72654. if (this != &other)
  72655. {
  72656. clear();
  72657. addGlyphArrangement (other);
  72658. }
  72659. return *this;
  72660. }
  72661. GlyphArrangement::~GlyphArrangement()
  72662. {
  72663. }
  72664. void GlyphArrangement::clear()
  72665. {
  72666. glyphs.clear();
  72667. }
  72668. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72669. {
  72670. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72671. return *glyphs [index];
  72672. }
  72673. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72674. {
  72675. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72676. glyphs.addCopiesOf (other.glyphs);
  72677. }
  72678. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72679. {
  72680. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72681. }
  72682. void GlyphArrangement::addLineOfText (const Font& font,
  72683. const String& text,
  72684. const float xOffset,
  72685. const float yOffset)
  72686. {
  72687. addCurtailedLineOfText (font, text,
  72688. xOffset, yOffset,
  72689. 1.0e10f, false);
  72690. }
  72691. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72692. const String& text,
  72693. float xOffset,
  72694. const float yOffset,
  72695. const float maxWidthPixels,
  72696. const bool useEllipsis)
  72697. {
  72698. if (text.isNotEmpty())
  72699. {
  72700. Array <int> newGlyphs;
  72701. Array <float> xOffsets;
  72702. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72703. const int textLen = newGlyphs.size();
  72704. const juce_wchar* const unicodeText = text;
  72705. for (int i = 0; i < textLen; ++i)
  72706. {
  72707. const float thisX = xOffsets.getUnchecked (i);
  72708. const float nextX = xOffsets.getUnchecked (i + 1);
  72709. if (nextX > maxWidthPixels + 1.0f)
  72710. {
  72711. // curtail the string if it's too wide..
  72712. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72713. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72714. break;
  72715. }
  72716. else
  72717. {
  72718. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72719. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72720. }
  72721. }
  72722. }
  72723. }
  72724. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72725. const int startIndex, int endIndex)
  72726. {
  72727. int numDeleted = 0;
  72728. if (glyphs.size() > 0)
  72729. {
  72730. Array<int> dotGlyphs;
  72731. Array<float> dotXs;
  72732. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72733. const float dx = dotXs[1];
  72734. float xOffset = 0.0f, yOffset = 0.0f;
  72735. while (endIndex > startIndex)
  72736. {
  72737. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72738. xOffset = pg->x;
  72739. yOffset = pg->y;
  72740. glyphs.remove (endIndex);
  72741. ++numDeleted;
  72742. if (xOffset + dx * 3 <= maxXPos)
  72743. break;
  72744. }
  72745. for (int i = 3; --i >= 0;)
  72746. {
  72747. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72748. font, '.', dotGlyphs.getFirst()));
  72749. --numDeleted;
  72750. xOffset += dx;
  72751. if (xOffset > maxXPos)
  72752. break;
  72753. }
  72754. }
  72755. return numDeleted;
  72756. }
  72757. void GlyphArrangement::addJustifiedText (const Font& font,
  72758. const String& text,
  72759. float x, float y,
  72760. const float maxLineWidth,
  72761. const Justification& horizontalLayout)
  72762. {
  72763. int lineStartIndex = glyphs.size();
  72764. addLineOfText (font, text, x, y);
  72765. const float originalY = y;
  72766. while (lineStartIndex < glyphs.size())
  72767. {
  72768. int i = lineStartIndex;
  72769. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72770. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72771. ++i;
  72772. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72773. int lastWordBreakIndex = -1;
  72774. while (i < glyphs.size())
  72775. {
  72776. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72777. const juce_wchar c = pg->getCharacter();
  72778. if (c == '\r' || c == '\n')
  72779. {
  72780. ++i;
  72781. if (c == '\r' && i < glyphs.size()
  72782. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72783. ++i;
  72784. break;
  72785. }
  72786. else if (pg->isWhitespace())
  72787. {
  72788. lastWordBreakIndex = i + 1;
  72789. }
  72790. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72791. {
  72792. if (lastWordBreakIndex >= 0)
  72793. i = lastWordBreakIndex;
  72794. break;
  72795. }
  72796. ++i;
  72797. }
  72798. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72799. float currentLineEndX = currentLineStartX;
  72800. for (int j = i; --j >= lineStartIndex;)
  72801. {
  72802. if (! glyphs.getUnchecked (j)->isWhitespace())
  72803. {
  72804. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72805. break;
  72806. }
  72807. }
  72808. float deltaX = 0.0f;
  72809. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72810. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72811. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72812. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72813. else if (horizontalLayout.testFlags (Justification::right))
  72814. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72815. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72816. x + deltaX - currentLineStartX, y - originalY);
  72817. lineStartIndex = i;
  72818. y += font.getHeight();
  72819. }
  72820. }
  72821. void GlyphArrangement::addFittedText (const Font& f,
  72822. const String& text,
  72823. const float x, const float y,
  72824. const float width, const float height,
  72825. const Justification& layout,
  72826. int maximumLines,
  72827. const float minimumHorizontalScale)
  72828. {
  72829. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72830. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72831. if (text.containsAnyOf ("\r\n"))
  72832. {
  72833. GlyphArrangement ga;
  72834. ga.addJustifiedText (f, text, x, y, width, layout);
  72835. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72836. float dy = y - bb.getY();
  72837. if (layout.testFlags (Justification::verticallyCentred))
  72838. dy += (height - bb.getHeight()) * 0.5f;
  72839. else if (layout.testFlags (Justification::bottom))
  72840. dy += height - bb.getHeight();
  72841. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72842. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72843. for (int i = 0; i < ga.glyphs.size(); ++i)
  72844. glyphs.add (ga.glyphs.getUnchecked (i));
  72845. ga.glyphs.clear (false);
  72846. return;
  72847. }
  72848. int startIndex = glyphs.size();
  72849. addLineOfText (f, text.trim(), x, y);
  72850. if (glyphs.size() > startIndex)
  72851. {
  72852. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72853. - glyphs.getUnchecked (startIndex)->getLeft();
  72854. if (lineWidth <= 0)
  72855. return;
  72856. if (lineWidth * minimumHorizontalScale < width)
  72857. {
  72858. if (lineWidth > width)
  72859. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72860. width / lineWidth);
  72861. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72862. x, y, width, height, layout);
  72863. }
  72864. else if (maximumLines <= 1)
  72865. {
  72866. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72867. x, y, width, height, f, layout, minimumHorizontalScale);
  72868. }
  72869. else
  72870. {
  72871. Font font (f);
  72872. String txt (text.trim());
  72873. const int length = txt.length();
  72874. const int originalStartIndex = startIndex;
  72875. int numLines = 1;
  72876. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72877. maximumLines = 1;
  72878. maximumLines = jmin (maximumLines, length);
  72879. while (numLines < maximumLines)
  72880. {
  72881. ++numLines;
  72882. const float newFontHeight = height / (float) numLines;
  72883. if (newFontHeight < font.getHeight())
  72884. {
  72885. font.setHeight (jmax (8.0f, newFontHeight));
  72886. removeRangeOfGlyphs (startIndex, -1);
  72887. addLineOfText (font, txt, x, y);
  72888. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72889. - glyphs.getUnchecked (startIndex)->getLeft();
  72890. }
  72891. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72892. break;
  72893. }
  72894. if (numLines < 1)
  72895. numLines = 1;
  72896. float lineY = y;
  72897. float widthPerLine = lineWidth / numLines;
  72898. int lastLineStartIndex = 0;
  72899. for (int line = 0; line < numLines; ++line)
  72900. {
  72901. int i = startIndex;
  72902. lastLineStartIndex = i;
  72903. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72904. if (line == numLines - 1)
  72905. {
  72906. widthPerLine = width;
  72907. i = glyphs.size();
  72908. }
  72909. else
  72910. {
  72911. while (i < glyphs.size())
  72912. {
  72913. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72914. if (lineWidth > widthPerLine)
  72915. {
  72916. // got to a point where the line's too long, so skip forward to find a
  72917. // good place to break it..
  72918. const int searchStartIndex = i;
  72919. while (i < glyphs.size())
  72920. {
  72921. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  72922. {
  72923. if (glyphs.getUnchecked (i)->isWhitespace()
  72924. || glyphs.getUnchecked (i)->getCharacter() == '-')
  72925. {
  72926. ++i;
  72927. break;
  72928. }
  72929. }
  72930. else
  72931. {
  72932. // can't find a suitable break, so try looking backwards..
  72933. i = searchStartIndex;
  72934. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  72935. {
  72936. if (glyphs.getUnchecked (i - back)->isWhitespace()
  72937. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  72938. {
  72939. i -= back - 1;
  72940. break;
  72941. }
  72942. }
  72943. break;
  72944. }
  72945. ++i;
  72946. }
  72947. break;
  72948. }
  72949. ++i;
  72950. }
  72951. int wsStart = i;
  72952. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  72953. --wsStart;
  72954. int wsEnd = i;
  72955. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  72956. ++wsEnd;
  72957. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  72958. i = jmax (wsStart, startIndex + 1);
  72959. }
  72960. i -= fitLineIntoSpace (startIndex, i - startIndex,
  72961. x, lineY, width, font.getHeight(), font,
  72962. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  72963. minimumHorizontalScale);
  72964. startIndex = i;
  72965. lineY += font.getHeight();
  72966. if (startIndex >= glyphs.size())
  72967. break;
  72968. }
  72969. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  72970. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  72971. }
  72972. }
  72973. }
  72974. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  72975. const float dx, const float dy)
  72976. {
  72977. jassert (startIndex >= 0);
  72978. if (dx != 0.0f || dy != 0.0f)
  72979. {
  72980. if (num < 0 || startIndex + num > glyphs.size())
  72981. num = glyphs.size() - startIndex;
  72982. while (--num >= 0)
  72983. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  72984. }
  72985. }
  72986. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  72987. const Justification& justification, float minimumHorizontalScale)
  72988. {
  72989. int numDeleted = 0;
  72990. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  72991. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  72992. if (lineWidth > w)
  72993. {
  72994. if (minimumHorizontalScale < 1.0f)
  72995. {
  72996. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  72997. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  72998. }
  72999. if (lineWidth > w)
  73000. {
  73001. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73002. numGlyphs -= numDeleted;
  73003. }
  73004. }
  73005. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73006. return numDeleted;
  73007. }
  73008. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73009. const float horizontalScaleFactor)
  73010. {
  73011. jassert (startIndex >= 0);
  73012. if (num < 0 || startIndex + num > glyphs.size())
  73013. num = glyphs.size() - startIndex;
  73014. if (num > 0)
  73015. {
  73016. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73017. while (--num >= 0)
  73018. {
  73019. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73020. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73021. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73022. pg->w *= horizontalScaleFactor;
  73023. }
  73024. }
  73025. }
  73026. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73027. {
  73028. jassert (startIndex >= 0);
  73029. if (num < 0 || startIndex + num > glyphs.size())
  73030. num = glyphs.size() - startIndex;
  73031. Rectangle<float> result;
  73032. while (--num >= 0)
  73033. {
  73034. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73035. if (includeWhitespace || ! pg->isWhitespace())
  73036. result = result.getUnion (pg->getBounds());
  73037. }
  73038. return result;
  73039. }
  73040. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73041. const float x, const float y, const float width, const float height,
  73042. const Justification& justification)
  73043. {
  73044. jassert (num >= 0 && startIndex >= 0);
  73045. if (glyphs.size() > 0 && num > 0)
  73046. {
  73047. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73048. | Justification::horizontallyCentred)));
  73049. float deltaX = 0.0f;
  73050. if (justification.testFlags (Justification::horizontallyJustified))
  73051. deltaX = x - bb.getX();
  73052. else if (justification.testFlags (Justification::horizontallyCentred))
  73053. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73054. else if (justification.testFlags (Justification::right))
  73055. deltaX = (x + width) - bb.getRight();
  73056. else
  73057. deltaX = x - bb.getX();
  73058. float deltaY = 0.0f;
  73059. if (justification.testFlags (Justification::top))
  73060. deltaY = y - bb.getY();
  73061. else if (justification.testFlags (Justification::bottom))
  73062. deltaY = (y + height) - bb.getBottom();
  73063. else
  73064. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73065. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73066. if (justification.testFlags (Justification::horizontallyJustified))
  73067. {
  73068. int lineStart = 0;
  73069. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73070. int i;
  73071. for (i = 0; i < num; ++i)
  73072. {
  73073. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73074. if (glyphY != baseY)
  73075. {
  73076. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73077. lineStart = i;
  73078. baseY = glyphY;
  73079. }
  73080. }
  73081. if (i > lineStart)
  73082. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73083. }
  73084. }
  73085. }
  73086. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73087. {
  73088. if (start + num < glyphs.size()
  73089. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73090. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73091. {
  73092. int numSpaces = 0;
  73093. int spacesAtEnd = 0;
  73094. for (int i = 0; i < num; ++i)
  73095. {
  73096. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73097. {
  73098. ++spacesAtEnd;
  73099. ++numSpaces;
  73100. }
  73101. else
  73102. {
  73103. spacesAtEnd = 0;
  73104. }
  73105. }
  73106. numSpaces -= spacesAtEnd;
  73107. if (numSpaces > 0)
  73108. {
  73109. const float startX = glyphs.getUnchecked (start)->getLeft();
  73110. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73111. const float extraPaddingBetweenWords
  73112. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73113. float deltaX = 0.0f;
  73114. for (int i = 0; i < num; ++i)
  73115. {
  73116. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73117. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73118. deltaX += extraPaddingBetweenWords;
  73119. }
  73120. }
  73121. }
  73122. }
  73123. void GlyphArrangement::draw (const Graphics& g) const
  73124. {
  73125. for (int i = 0; i < glyphs.size(); ++i)
  73126. {
  73127. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73128. if (pg->font.isUnderlined())
  73129. {
  73130. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73131. float nextX = pg->x + pg->w;
  73132. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73133. nextX = glyphs.getUnchecked (i + 1)->x;
  73134. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73135. nextX - pg->x, lineThickness);
  73136. }
  73137. pg->draw (g);
  73138. }
  73139. }
  73140. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73141. {
  73142. for (int i = 0; i < glyphs.size(); ++i)
  73143. {
  73144. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73145. if (pg->font.isUnderlined())
  73146. {
  73147. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73148. float nextX = pg->x + pg->w;
  73149. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73150. nextX = glyphs.getUnchecked (i + 1)->x;
  73151. Path p;
  73152. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73153. nextX, pg->y + lineThickness * 2.0f),
  73154. lineThickness);
  73155. g.fillPath (p, transform);
  73156. }
  73157. pg->draw (g, transform);
  73158. }
  73159. }
  73160. void GlyphArrangement::createPath (Path& path) const
  73161. {
  73162. for (int i = 0; i < glyphs.size(); ++i)
  73163. glyphs.getUnchecked (i)->createPath (path);
  73164. }
  73165. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73166. {
  73167. for (int i = 0; i < glyphs.size(); ++i)
  73168. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73169. return i;
  73170. return -1;
  73171. }
  73172. END_JUCE_NAMESPACE
  73173. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73174. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73175. BEGIN_JUCE_NAMESPACE
  73176. class TextLayout::Token
  73177. {
  73178. public:
  73179. String text;
  73180. Font font;
  73181. int x, y, w, h;
  73182. int line, lineHeight;
  73183. bool isWhitespace, isNewLine;
  73184. Token (const String& t,
  73185. const Font& f,
  73186. const bool isWhitespace_)
  73187. : text (t),
  73188. font (f),
  73189. x(0),
  73190. y(0),
  73191. isWhitespace (isWhitespace_)
  73192. {
  73193. w = font.getStringWidth (t);
  73194. h = roundToInt (f.getHeight());
  73195. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73196. }
  73197. Token (const Token& other)
  73198. : text (other.text),
  73199. font (other.font),
  73200. x (other.x),
  73201. y (other.y),
  73202. w (other.w),
  73203. h (other.h),
  73204. line (other.line),
  73205. lineHeight (other.lineHeight),
  73206. isWhitespace (other.isWhitespace),
  73207. isNewLine (other.isNewLine)
  73208. {
  73209. }
  73210. ~Token()
  73211. {
  73212. }
  73213. void draw (Graphics& g,
  73214. const int xOffset,
  73215. const int yOffset)
  73216. {
  73217. if (! isWhitespace)
  73218. {
  73219. g.setFont (font);
  73220. g.drawSingleLineText (text.trimEnd(),
  73221. xOffset + x,
  73222. yOffset + y + (lineHeight - h)
  73223. + roundToInt (font.getAscent()));
  73224. }
  73225. }
  73226. juce_UseDebuggingNewOperator
  73227. };
  73228. TextLayout::TextLayout()
  73229. : totalLines (0)
  73230. {
  73231. tokens.ensureStorageAllocated (64);
  73232. }
  73233. TextLayout::TextLayout (const String& text, const Font& font)
  73234. : totalLines (0)
  73235. {
  73236. tokens.ensureStorageAllocated (64);
  73237. appendText (text, font);
  73238. }
  73239. TextLayout::TextLayout (const TextLayout& other)
  73240. : totalLines (0)
  73241. {
  73242. *this = other;
  73243. }
  73244. TextLayout& TextLayout::operator= (const TextLayout& other)
  73245. {
  73246. if (this != &other)
  73247. {
  73248. clear();
  73249. totalLines = other.totalLines;
  73250. tokens.addCopiesOf (other.tokens);
  73251. }
  73252. return *this;
  73253. }
  73254. TextLayout::~TextLayout()
  73255. {
  73256. clear();
  73257. }
  73258. void TextLayout::clear()
  73259. {
  73260. tokens.clear();
  73261. totalLines = 0;
  73262. }
  73263. bool TextLayout::isEmpty() const
  73264. {
  73265. return tokens.size() == 0;
  73266. }
  73267. void TextLayout::appendText (const String& text, const Font& font)
  73268. {
  73269. const juce_wchar* t = text;
  73270. String currentString;
  73271. int lastCharType = 0;
  73272. for (;;)
  73273. {
  73274. const juce_wchar c = *t++;
  73275. if (c == 0)
  73276. break;
  73277. int charType;
  73278. if (c == '\r' || c == '\n')
  73279. {
  73280. charType = 0;
  73281. }
  73282. else if (CharacterFunctions::isWhitespace (c))
  73283. {
  73284. charType = 2;
  73285. }
  73286. else
  73287. {
  73288. charType = 1;
  73289. }
  73290. if (charType == 0 || charType != lastCharType)
  73291. {
  73292. if (currentString.isNotEmpty())
  73293. {
  73294. tokens.add (new Token (currentString, font,
  73295. lastCharType == 2 || lastCharType == 0));
  73296. }
  73297. currentString = String::charToString (c);
  73298. if (c == '\r' && *t == '\n')
  73299. currentString += *t++;
  73300. }
  73301. else
  73302. {
  73303. currentString += c;
  73304. }
  73305. lastCharType = charType;
  73306. }
  73307. if (currentString.isNotEmpty())
  73308. tokens.add (new Token (currentString, font, lastCharType == 2));
  73309. }
  73310. void TextLayout::setText (const String& text, const Font& font)
  73311. {
  73312. clear();
  73313. appendText (text, font);
  73314. }
  73315. void TextLayout::layout (int maxWidth,
  73316. const Justification& justification,
  73317. const bool attemptToBalanceLineLengths)
  73318. {
  73319. if (attemptToBalanceLineLengths)
  73320. {
  73321. const int originalW = maxWidth;
  73322. int bestWidth = maxWidth;
  73323. float bestLineProportion = 0.0f;
  73324. while (maxWidth > originalW / 2)
  73325. {
  73326. layout (maxWidth, justification, false);
  73327. if (getNumLines() <= 1)
  73328. return;
  73329. const int lastLineW = getLineWidth (getNumLines() - 1);
  73330. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73331. const float prop = lastLineW / (float) lastButOneLineW;
  73332. if (prop > 0.9f)
  73333. return;
  73334. if (prop > bestLineProportion)
  73335. {
  73336. bestLineProportion = prop;
  73337. bestWidth = maxWidth;
  73338. }
  73339. maxWidth -= 10;
  73340. }
  73341. layout (bestWidth, justification, false);
  73342. }
  73343. else
  73344. {
  73345. int x = 0;
  73346. int y = 0;
  73347. int h = 0;
  73348. totalLines = 0;
  73349. int i;
  73350. for (i = 0; i < tokens.size(); ++i)
  73351. {
  73352. Token* const t = tokens.getUnchecked(i);
  73353. t->x = x;
  73354. t->y = y;
  73355. t->line = totalLines;
  73356. x += t->w;
  73357. h = jmax (h, t->h);
  73358. const Token* nextTok = tokens [i + 1];
  73359. if (nextTok == 0)
  73360. break;
  73361. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73362. {
  73363. // finished a line, so go back and update the heights of the things on it
  73364. for (int j = i; j >= 0; --j)
  73365. {
  73366. Token* const tok = tokens.getUnchecked(j);
  73367. if (tok->line == totalLines)
  73368. tok->lineHeight = h;
  73369. else
  73370. break;
  73371. }
  73372. x = 0;
  73373. y += h;
  73374. h = 0;
  73375. ++totalLines;
  73376. }
  73377. }
  73378. // finished a line, so go back and update the heights of the things on it
  73379. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73380. {
  73381. Token* const t = tokens.getUnchecked(j);
  73382. if (t->line == totalLines)
  73383. t->lineHeight = h;
  73384. else
  73385. break;
  73386. }
  73387. ++totalLines;
  73388. if (! justification.testFlags (Justification::left))
  73389. {
  73390. int totalW = getWidth();
  73391. for (i = totalLines; --i >= 0;)
  73392. {
  73393. const int lineW = getLineWidth (i);
  73394. int dx = 0;
  73395. if (justification.testFlags (Justification::horizontallyCentred))
  73396. dx = (totalW - lineW) / 2;
  73397. else if (justification.testFlags (Justification::right))
  73398. dx = totalW - lineW;
  73399. for (int j = tokens.size(); --j >= 0;)
  73400. {
  73401. Token* const t = tokens.getUnchecked(j);
  73402. if (t->line == i)
  73403. t->x += dx;
  73404. }
  73405. }
  73406. }
  73407. }
  73408. }
  73409. int TextLayout::getLineWidth (const int lineNumber) const
  73410. {
  73411. int maxW = 0;
  73412. for (int i = tokens.size(); --i >= 0;)
  73413. {
  73414. const Token* const t = tokens.getUnchecked(i);
  73415. if (t->line == lineNumber && ! t->isWhitespace)
  73416. maxW = jmax (maxW, t->x + t->w);
  73417. }
  73418. return maxW;
  73419. }
  73420. int TextLayout::getWidth() const
  73421. {
  73422. int maxW = 0;
  73423. for (int i = tokens.size(); --i >= 0;)
  73424. {
  73425. const Token* const t = tokens.getUnchecked(i);
  73426. if (! t->isWhitespace)
  73427. maxW = jmax (maxW, t->x + t->w);
  73428. }
  73429. return maxW;
  73430. }
  73431. int TextLayout::getHeight() const
  73432. {
  73433. int maxH = 0;
  73434. for (int i = tokens.size(); --i >= 0;)
  73435. {
  73436. const Token* const t = tokens.getUnchecked(i);
  73437. if (! t->isWhitespace)
  73438. maxH = jmax (maxH, t->y + t->h);
  73439. }
  73440. return maxH;
  73441. }
  73442. void TextLayout::draw (Graphics& g,
  73443. const int xOffset,
  73444. const int yOffset) const
  73445. {
  73446. for (int i = tokens.size(); --i >= 0;)
  73447. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73448. }
  73449. void TextLayout::drawWithin (Graphics& g,
  73450. int x, int y, int w, int h,
  73451. const Justification& justification) const
  73452. {
  73453. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73454. x, y, w, h);
  73455. draw (g, x, y);
  73456. }
  73457. END_JUCE_NAMESPACE
  73458. /*** End of inlined file: juce_TextLayout.cpp ***/
  73459. /*** Start of inlined file: juce_Typeface.cpp ***/
  73460. BEGIN_JUCE_NAMESPACE
  73461. Typeface::Typeface (const String& name_) throw()
  73462. : name (name_)
  73463. {
  73464. }
  73465. Typeface::~Typeface()
  73466. {
  73467. }
  73468. class CustomTypeface::GlyphInfo
  73469. {
  73470. public:
  73471. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73472. : character (character_), path (path_), width (width_)
  73473. {
  73474. }
  73475. ~GlyphInfo() throw()
  73476. {
  73477. }
  73478. struct KerningPair
  73479. {
  73480. juce_wchar character2;
  73481. float kerningAmount;
  73482. };
  73483. void addKerningPair (const juce_wchar subsequentCharacter,
  73484. const float extraKerningAmount) throw()
  73485. {
  73486. KerningPair kp;
  73487. kp.character2 = subsequentCharacter;
  73488. kp.kerningAmount = extraKerningAmount;
  73489. kerningPairs.add (kp);
  73490. }
  73491. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73492. {
  73493. if (subsequentCharacter != 0)
  73494. {
  73495. for (int i = kerningPairs.size(); --i >= 0;)
  73496. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73497. return width + kerningPairs.getReference(i).kerningAmount;
  73498. }
  73499. return width;
  73500. }
  73501. const juce_wchar character;
  73502. const Path path;
  73503. float width;
  73504. Array <KerningPair> kerningPairs;
  73505. juce_UseDebuggingNewOperator
  73506. private:
  73507. GlyphInfo (const GlyphInfo&);
  73508. GlyphInfo& operator= (const GlyphInfo&);
  73509. };
  73510. CustomTypeface::CustomTypeface()
  73511. : Typeface (String::empty)
  73512. {
  73513. clear();
  73514. }
  73515. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73516. : Typeface (String::empty)
  73517. {
  73518. clear();
  73519. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  73520. BufferedInputStream in (&gzin, 32768, false);
  73521. name = in.readString();
  73522. isBold = in.readBool();
  73523. isItalic = in.readBool();
  73524. ascent = in.readFloat();
  73525. defaultCharacter = (juce_wchar) in.readShort();
  73526. int i, numChars = in.readInt();
  73527. for (i = 0; i < numChars; ++i)
  73528. {
  73529. const juce_wchar c = (juce_wchar) in.readShort();
  73530. const float width = in.readFloat();
  73531. Path p;
  73532. p.loadPathFromStream (in);
  73533. addGlyph (c, p, width);
  73534. }
  73535. const int numKerningPairs = in.readInt();
  73536. for (i = 0; i < numKerningPairs; ++i)
  73537. {
  73538. const juce_wchar char1 = (juce_wchar) in.readShort();
  73539. const juce_wchar char2 = (juce_wchar) in.readShort();
  73540. addKerningPair (char1, char2, in.readFloat());
  73541. }
  73542. }
  73543. CustomTypeface::~CustomTypeface()
  73544. {
  73545. }
  73546. void CustomTypeface::clear()
  73547. {
  73548. defaultCharacter = 0;
  73549. ascent = 1.0f;
  73550. isBold = isItalic = false;
  73551. zeromem (lookupTable, sizeof (lookupTable));
  73552. glyphs.clear();
  73553. }
  73554. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73555. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73556. {
  73557. name = name_;
  73558. defaultCharacter = defaultCharacter_;
  73559. ascent = ascent_;
  73560. isBold = isBold_;
  73561. isItalic = isItalic_;
  73562. }
  73563. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73564. {
  73565. // Check that you're not trying to add the same character twice..
  73566. jassert (findGlyph (character, false) == 0);
  73567. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  73568. lookupTable [character] = (short) glyphs.size();
  73569. glyphs.add (new GlyphInfo (character, path, width));
  73570. }
  73571. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73572. {
  73573. if (extraAmount != 0)
  73574. {
  73575. GlyphInfo* const g = findGlyph (char1, true);
  73576. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73577. if (g != 0)
  73578. g->addKerningPair (char2, extraAmount);
  73579. }
  73580. }
  73581. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73582. {
  73583. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  73584. return glyphs [(int) lookupTable [(int) character]];
  73585. for (int i = 0; i < glyphs.size(); ++i)
  73586. {
  73587. GlyphInfo* const g = glyphs.getUnchecked(i);
  73588. if (g->character == character)
  73589. return g;
  73590. }
  73591. if (loadIfNeeded && loadGlyphIfPossible (character))
  73592. return findGlyph (character, false);
  73593. return 0;
  73594. }
  73595. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73596. {
  73597. GlyphInfo* glyph = findGlyph (character, true);
  73598. if (glyph == 0)
  73599. {
  73600. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73601. glyph = findGlyph (L' ', true);
  73602. if (glyph == 0)
  73603. {
  73604. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73605. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73606. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73607. {
  73608. //xxx
  73609. }
  73610. if (glyph == 0)
  73611. glyph = findGlyph (defaultCharacter, true);
  73612. }
  73613. }
  73614. return glyph;
  73615. }
  73616. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73617. {
  73618. return false;
  73619. }
  73620. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73621. {
  73622. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73623. for (int i = 0; i < numCharacters; ++i)
  73624. {
  73625. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73626. Array <int> glyphIndexes;
  73627. Array <float> offsets;
  73628. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73629. const int glyphIndex = glyphIndexes.getFirst();
  73630. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73631. {
  73632. const float glyphWidth = offsets[1];
  73633. Path p;
  73634. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73635. addGlyph (c, p, glyphWidth);
  73636. for (int j = glyphs.size() - 1; --j >= 0;)
  73637. {
  73638. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73639. glyphIndexes.clearQuick();
  73640. offsets.clearQuick();
  73641. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73642. if (offsets.size() > 1)
  73643. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73644. }
  73645. }
  73646. }
  73647. }
  73648. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73649. {
  73650. GZIPCompressorOutputStream out (&outputStream);
  73651. out.writeString (name);
  73652. out.writeBool (isBold);
  73653. out.writeBool (isItalic);
  73654. out.writeFloat (ascent);
  73655. out.writeShort ((short) (unsigned short) defaultCharacter);
  73656. out.writeInt (glyphs.size());
  73657. int i, numKerningPairs = 0;
  73658. for (i = 0; i < glyphs.size(); ++i)
  73659. {
  73660. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73661. out.writeShort ((short) (unsigned short) g->character);
  73662. out.writeFloat (g->width);
  73663. g->path.writePathToStream (out);
  73664. numKerningPairs += g->kerningPairs.size();
  73665. }
  73666. out.writeInt (numKerningPairs);
  73667. for (i = 0; i < glyphs.size(); ++i)
  73668. {
  73669. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73670. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73671. {
  73672. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73673. out.writeShort ((short) (unsigned short) g->character);
  73674. out.writeShort ((short) (unsigned short) p.character2);
  73675. out.writeFloat (p.kerningAmount);
  73676. }
  73677. }
  73678. return true;
  73679. }
  73680. float CustomTypeface::getAscent() const
  73681. {
  73682. return ascent;
  73683. }
  73684. float CustomTypeface::getDescent() const
  73685. {
  73686. return 1.0f - ascent;
  73687. }
  73688. float CustomTypeface::getStringWidth (const String& text)
  73689. {
  73690. float x = 0;
  73691. const juce_wchar* t = text;
  73692. while (*t != 0)
  73693. {
  73694. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73695. if (glyph != 0)
  73696. x += glyph->getHorizontalSpacing (*t);
  73697. }
  73698. return x;
  73699. }
  73700. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73701. {
  73702. xOffsets.add (0);
  73703. float x = 0;
  73704. const juce_wchar* t = text;
  73705. while (*t != 0)
  73706. {
  73707. const juce_wchar c = *t++;
  73708. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  73709. if (glyph != 0)
  73710. {
  73711. x += glyph->getHorizontalSpacing (*t);
  73712. resultGlyphs.add ((int) glyph->character);
  73713. xOffsets.add (x);
  73714. }
  73715. }
  73716. }
  73717. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73718. {
  73719. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  73720. if (glyph != 0)
  73721. {
  73722. path = glyph->path;
  73723. return true;
  73724. }
  73725. return false;
  73726. }
  73727. END_JUCE_NAMESPACE
  73728. /*** End of inlined file: juce_Typeface.cpp ***/
  73729. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73730. BEGIN_JUCE_NAMESPACE
  73731. AffineTransform::AffineTransform() throw()
  73732. : mat00 (1.0f),
  73733. mat01 (0),
  73734. mat02 (0),
  73735. mat10 (0),
  73736. mat11 (1.0f),
  73737. mat12 (0)
  73738. {
  73739. }
  73740. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73741. : mat00 (other.mat00),
  73742. mat01 (other.mat01),
  73743. mat02 (other.mat02),
  73744. mat10 (other.mat10),
  73745. mat11 (other.mat11),
  73746. mat12 (other.mat12)
  73747. {
  73748. }
  73749. AffineTransform::AffineTransform (const float mat00_,
  73750. const float mat01_,
  73751. const float mat02_,
  73752. const float mat10_,
  73753. const float mat11_,
  73754. const float mat12_) throw()
  73755. : mat00 (mat00_),
  73756. mat01 (mat01_),
  73757. mat02 (mat02_),
  73758. mat10 (mat10_),
  73759. mat11 (mat11_),
  73760. mat12 (mat12_)
  73761. {
  73762. }
  73763. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73764. {
  73765. mat00 = other.mat00;
  73766. mat01 = other.mat01;
  73767. mat02 = other.mat02;
  73768. mat10 = other.mat10;
  73769. mat11 = other.mat11;
  73770. mat12 = other.mat12;
  73771. return *this;
  73772. }
  73773. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73774. {
  73775. return mat00 == other.mat00
  73776. && mat01 == other.mat01
  73777. && mat02 == other.mat02
  73778. && mat10 == other.mat10
  73779. && mat11 == other.mat11
  73780. && mat12 == other.mat12;
  73781. }
  73782. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73783. {
  73784. return ! operator== (other);
  73785. }
  73786. bool AffineTransform::isIdentity() const throw()
  73787. {
  73788. return (mat01 == 0)
  73789. && (mat02 == 0)
  73790. && (mat10 == 0)
  73791. && (mat12 == 0)
  73792. && (mat00 == 1.0f)
  73793. && (mat11 == 1.0f);
  73794. }
  73795. const AffineTransform AffineTransform::identity;
  73796. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73797. {
  73798. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73799. other.mat00 * mat01 + other.mat01 * mat11,
  73800. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73801. other.mat10 * mat00 + other.mat11 * mat10,
  73802. other.mat10 * mat01 + other.mat11 * mat11,
  73803. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73804. }
  73805. const AffineTransform AffineTransform::followedBy (const float omat00,
  73806. const float omat01,
  73807. const float omat02,
  73808. const float omat10,
  73809. const float omat11,
  73810. const float omat12) const throw()
  73811. {
  73812. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  73813. omat00 * mat01 + omat01 * mat11,
  73814. omat00 * mat02 + omat01 * mat12 + omat02,
  73815. omat10 * mat00 + omat11 * mat10,
  73816. omat10 * mat01 + omat11 * mat11,
  73817. omat10 * mat02 + omat11 * mat12 + omat12);
  73818. }
  73819. const AffineTransform AffineTransform::translated (const float dx,
  73820. const float dy) const throw()
  73821. {
  73822. return AffineTransform (mat00, mat01, mat02 + dx,
  73823. mat10, mat11, mat12 + dy);
  73824. }
  73825. const AffineTransform AffineTransform::translation (const float dx,
  73826. const float dy) throw()
  73827. {
  73828. return AffineTransform (1.0f, 0, dx,
  73829. 0, 1.0f, dy);
  73830. }
  73831. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73832. {
  73833. const float cosRad = std::cos (rad);
  73834. const float sinRad = std::sin (rad);
  73835. return followedBy (cosRad, -sinRad, 0,
  73836. sinRad, cosRad, 0);
  73837. }
  73838. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73839. {
  73840. const float cosRad = std::cos (rad);
  73841. const float sinRad = std::sin (rad);
  73842. return AffineTransform (cosRad, -sinRad, 0,
  73843. sinRad, cosRad, 0);
  73844. }
  73845. const AffineTransform AffineTransform::rotated (const float angle,
  73846. const float pivotX,
  73847. const float pivotY) const throw()
  73848. {
  73849. return translated (-pivotX, -pivotY)
  73850. .rotated (angle)
  73851. .translated (pivotX, pivotY);
  73852. }
  73853. const AffineTransform AffineTransform::rotation (const float angle,
  73854. const float pivotX,
  73855. const float pivotY) throw()
  73856. {
  73857. return translation (-pivotX, -pivotY)
  73858. .rotated (angle)
  73859. .translated (pivotX, pivotY);
  73860. }
  73861. const AffineTransform AffineTransform::scaled (const float factorX,
  73862. const float factorY) const throw()
  73863. {
  73864. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73865. factorY * mat10, factorY * mat11, factorY * mat12);
  73866. }
  73867. const AffineTransform AffineTransform::scale (const float factorX,
  73868. const float factorY) throw()
  73869. {
  73870. return AffineTransform (factorX, 0, 0,
  73871. 0, factorY, 0);
  73872. }
  73873. const AffineTransform AffineTransform::sheared (const float shearX,
  73874. const float shearY) const throw()
  73875. {
  73876. return followedBy (1.0f, shearX, 0,
  73877. shearY, 1.0f, 0);
  73878. }
  73879. const AffineTransform AffineTransform::inverted() const throw()
  73880. {
  73881. double determinant = (mat00 * mat11 - mat10 * mat01);
  73882. if (determinant != 0.0)
  73883. {
  73884. determinant = 1.0 / determinant;
  73885. const float dst00 = (float) (mat11 * determinant);
  73886. const float dst10 = (float) (-mat10 * determinant);
  73887. const float dst01 = (float) (-mat01 * determinant);
  73888. const float dst11 = (float) (mat00 * determinant);
  73889. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73890. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73891. }
  73892. else
  73893. {
  73894. // singularity..
  73895. return *this;
  73896. }
  73897. }
  73898. bool AffineTransform::isSingularity() const throw()
  73899. {
  73900. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  73901. }
  73902. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73903. const float x10, const float y10,
  73904. const float x01, const float y01) throw()
  73905. {
  73906. return AffineTransform (x10 - x00, x01 - x00, x00,
  73907. y10 - y00, y01 - y00, y00);
  73908. }
  73909. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73910. const float sx2, const float sy2, const float tx2, const float ty2,
  73911. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73912. {
  73913. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73914. .inverted()
  73915. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73916. }
  73917. bool AffineTransform::isOnlyTranslation() const throw()
  73918. {
  73919. return (mat01 == 0)
  73920. && (mat10 == 0)
  73921. && (mat00 == 1.0f)
  73922. && (mat11 == 1.0f);
  73923. }
  73924. END_JUCE_NAMESPACE
  73925. /*** End of inlined file: juce_AffineTransform.cpp ***/
  73926. /*** Start of inlined file: juce_BorderSize.cpp ***/
  73927. BEGIN_JUCE_NAMESPACE
  73928. BorderSize::BorderSize() throw()
  73929. : top (0),
  73930. left (0),
  73931. bottom (0),
  73932. right (0)
  73933. {
  73934. }
  73935. BorderSize::BorderSize (const BorderSize& other) throw()
  73936. : top (other.top),
  73937. left (other.left),
  73938. bottom (other.bottom),
  73939. right (other.right)
  73940. {
  73941. }
  73942. BorderSize::BorderSize (const int topGap,
  73943. const int leftGap,
  73944. const int bottomGap,
  73945. const int rightGap) throw()
  73946. : top (topGap),
  73947. left (leftGap),
  73948. bottom (bottomGap),
  73949. right (rightGap)
  73950. {
  73951. }
  73952. BorderSize::BorderSize (const int allGaps) throw()
  73953. : top (allGaps),
  73954. left (allGaps),
  73955. bottom (allGaps),
  73956. right (allGaps)
  73957. {
  73958. }
  73959. BorderSize::~BorderSize() throw()
  73960. {
  73961. }
  73962. void BorderSize::setTop (const int newTopGap) throw()
  73963. {
  73964. top = newTopGap;
  73965. }
  73966. void BorderSize::setLeft (const int newLeftGap) throw()
  73967. {
  73968. left = newLeftGap;
  73969. }
  73970. void BorderSize::setBottom (const int newBottomGap) throw()
  73971. {
  73972. bottom = newBottomGap;
  73973. }
  73974. void BorderSize::setRight (const int newRightGap) throw()
  73975. {
  73976. right = newRightGap;
  73977. }
  73978. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  73979. {
  73980. return Rectangle<int> (r.getX() + left,
  73981. r.getY() + top,
  73982. r.getWidth() - (left + right),
  73983. r.getHeight() - (top + bottom));
  73984. }
  73985. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  73986. {
  73987. r.setBounds (r.getX() + left,
  73988. r.getY() + top,
  73989. r.getWidth() - (left + right),
  73990. r.getHeight() - (top + bottom));
  73991. }
  73992. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  73993. {
  73994. return Rectangle<int> (r.getX() - left,
  73995. r.getY() - top,
  73996. r.getWidth() + (left + right),
  73997. r.getHeight() + (top + bottom));
  73998. }
  73999. void BorderSize::addTo (Rectangle<int>& r) const throw()
  74000. {
  74001. r.setBounds (r.getX() - left,
  74002. r.getY() - top,
  74003. r.getWidth() + (left + right),
  74004. r.getHeight() + (top + bottom));
  74005. }
  74006. bool BorderSize::operator== (const BorderSize& other) const throw()
  74007. {
  74008. return top == other.top
  74009. && left == other.left
  74010. && bottom == other.bottom
  74011. && right == other.right;
  74012. }
  74013. bool BorderSize::operator!= (const BorderSize& other) const throw()
  74014. {
  74015. return ! operator== (other);
  74016. }
  74017. END_JUCE_NAMESPACE
  74018. /*** End of inlined file: juce_BorderSize.cpp ***/
  74019. /*** Start of inlined file: juce_Path.cpp ***/
  74020. BEGIN_JUCE_NAMESPACE
  74021. // tests that some co-ords aren't NaNs
  74022. #define CHECK_COORDS_ARE_VALID(x, y) \
  74023. jassert (x == x && y == y);
  74024. namespace PathHelpers
  74025. {
  74026. static const float ellipseAngularIncrement = 0.05f;
  74027. static const String nextToken (const juce_wchar*& t)
  74028. {
  74029. while (CharacterFunctions::isWhitespace (*t))
  74030. ++t;
  74031. const juce_wchar* const start = t;
  74032. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  74033. ++t;
  74034. return String (start, (int) (t - start));
  74035. }
  74036. }
  74037. const float Path::lineMarker = 100001.0f;
  74038. const float Path::moveMarker = 100002.0f;
  74039. const float Path::quadMarker = 100003.0f;
  74040. const float Path::cubicMarker = 100004.0f;
  74041. const float Path::closeSubPathMarker = 100005.0f;
  74042. Path::Path()
  74043. : numElements (0),
  74044. pathXMin (0),
  74045. pathXMax (0),
  74046. pathYMin (0),
  74047. pathYMax (0),
  74048. useNonZeroWinding (true)
  74049. {
  74050. }
  74051. Path::~Path()
  74052. {
  74053. }
  74054. Path::Path (const Path& other)
  74055. : numElements (other.numElements),
  74056. pathXMin (other.pathXMin),
  74057. pathXMax (other.pathXMax),
  74058. pathYMin (other.pathYMin),
  74059. pathYMax (other.pathYMax),
  74060. useNonZeroWinding (other.useNonZeroWinding)
  74061. {
  74062. if (numElements > 0)
  74063. {
  74064. data.setAllocatedSize ((int) numElements);
  74065. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74066. }
  74067. }
  74068. Path& Path::operator= (const Path& other)
  74069. {
  74070. if (this != &other)
  74071. {
  74072. data.ensureAllocatedSize ((int) other.numElements);
  74073. numElements = other.numElements;
  74074. pathXMin = other.pathXMin;
  74075. pathXMax = other.pathXMax;
  74076. pathYMin = other.pathYMin;
  74077. pathYMax = other.pathYMax;
  74078. useNonZeroWinding = other.useNonZeroWinding;
  74079. if (numElements > 0)
  74080. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74081. }
  74082. return *this;
  74083. }
  74084. bool Path::operator== (const Path& other) const throw()
  74085. {
  74086. return ! operator!= (other);
  74087. }
  74088. bool Path::operator!= (const Path& other) const throw()
  74089. {
  74090. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74091. return true;
  74092. for (size_t i = 0; i < numElements; ++i)
  74093. if (data.elements[i] != other.data.elements[i])
  74094. return true;
  74095. return false;
  74096. }
  74097. void Path::clear() throw()
  74098. {
  74099. numElements = 0;
  74100. pathXMin = 0;
  74101. pathYMin = 0;
  74102. pathYMax = 0;
  74103. pathXMax = 0;
  74104. }
  74105. void Path::swapWithPath (Path& other) throw()
  74106. {
  74107. data.swapWith (other.data);
  74108. swapVariables <size_t> (numElements, other.numElements);
  74109. swapVariables <float> (pathXMin, other.pathXMin);
  74110. swapVariables <float> (pathXMax, other.pathXMax);
  74111. swapVariables <float> (pathYMin, other.pathYMin);
  74112. swapVariables <float> (pathYMax, other.pathYMax);
  74113. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74114. }
  74115. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74116. {
  74117. useNonZeroWinding = isNonZero;
  74118. }
  74119. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74120. const bool preserveProportions) throw()
  74121. {
  74122. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74123. }
  74124. bool Path::isEmpty() const throw()
  74125. {
  74126. size_t i = 0;
  74127. while (i < numElements)
  74128. {
  74129. const float type = data.elements [i++];
  74130. if (type == moveMarker)
  74131. {
  74132. i += 2;
  74133. }
  74134. else if (type == lineMarker
  74135. || type == quadMarker
  74136. || type == cubicMarker)
  74137. {
  74138. return false;
  74139. }
  74140. }
  74141. return true;
  74142. }
  74143. const Rectangle<float> Path::getBounds() const throw()
  74144. {
  74145. return Rectangle<float> (pathXMin, pathYMin,
  74146. pathXMax - pathXMin,
  74147. pathYMax - pathYMin);
  74148. }
  74149. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74150. {
  74151. return getBounds().transformed (transform);
  74152. }
  74153. void Path::startNewSubPath (const float x, const float y)
  74154. {
  74155. CHECK_COORDS_ARE_VALID (x, y);
  74156. if (numElements == 0)
  74157. {
  74158. pathXMin = pathXMax = x;
  74159. pathYMin = pathYMax = y;
  74160. }
  74161. else
  74162. {
  74163. pathXMin = jmin (pathXMin, x);
  74164. pathXMax = jmax (pathXMax, x);
  74165. pathYMin = jmin (pathYMin, y);
  74166. pathYMax = jmax (pathYMax, y);
  74167. }
  74168. data.ensureAllocatedSize ((int) numElements + 3);
  74169. data.elements [numElements++] = moveMarker;
  74170. data.elements [numElements++] = x;
  74171. data.elements [numElements++] = y;
  74172. }
  74173. void Path::startNewSubPath (const Point<float>& start)
  74174. {
  74175. startNewSubPath (start.getX(), start.getY());
  74176. }
  74177. void Path::lineTo (const float x, const float y)
  74178. {
  74179. CHECK_COORDS_ARE_VALID (x, y);
  74180. if (numElements == 0)
  74181. startNewSubPath (0, 0);
  74182. data.ensureAllocatedSize ((int) numElements + 3);
  74183. data.elements [numElements++] = lineMarker;
  74184. data.elements [numElements++] = x;
  74185. data.elements [numElements++] = y;
  74186. pathXMin = jmin (pathXMin, x);
  74187. pathXMax = jmax (pathXMax, x);
  74188. pathYMin = jmin (pathYMin, y);
  74189. pathYMax = jmax (pathYMax, y);
  74190. }
  74191. void Path::lineTo (const Point<float>& end)
  74192. {
  74193. lineTo (end.getX(), end.getY());
  74194. }
  74195. void Path::quadraticTo (const float x1, const float y1,
  74196. const float x2, const float y2)
  74197. {
  74198. CHECK_COORDS_ARE_VALID (x1, y1);
  74199. CHECK_COORDS_ARE_VALID (x2, y2);
  74200. if (numElements == 0)
  74201. startNewSubPath (0, 0);
  74202. data.ensureAllocatedSize ((int) numElements + 5);
  74203. data.elements [numElements++] = quadMarker;
  74204. data.elements [numElements++] = x1;
  74205. data.elements [numElements++] = y1;
  74206. data.elements [numElements++] = x2;
  74207. data.elements [numElements++] = y2;
  74208. pathXMin = jmin (pathXMin, x1, x2);
  74209. pathXMax = jmax (pathXMax, x1, x2);
  74210. pathYMin = jmin (pathYMin, y1, y2);
  74211. pathYMax = jmax (pathYMax, y1, y2);
  74212. }
  74213. void Path::quadraticTo (const Point<float>& controlPoint,
  74214. const Point<float>& endPoint)
  74215. {
  74216. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74217. endPoint.getX(), endPoint.getY());
  74218. }
  74219. void Path::cubicTo (const float x1, const float y1,
  74220. const float x2, const float y2,
  74221. const float x3, const float y3)
  74222. {
  74223. CHECK_COORDS_ARE_VALID (x1, y1);
  74224. CHECK_COORDS_ARE_VALID (x2, y2);
  74225. CHECK_COORDS_ARE_VALID (x3, y3);
  74226. if (numElements == 0)
  74227. startNewSubPath (0, 0);
  74228. data.ensureAllocatedSize ((int) numElements + 7);
  74229. data.elements [numElements++] = cubicMarker;
  74230. data.elements [numElements++] = x1;
  74231. data.elements [numElements++] = y1;
  74232. data.elements [numElements++] = x2;
  74233. data.elements [numElements++] = y2;
  74234. data.elements [numElements++] = x3;
  74235. data.elements [numElements++] = y3;
  74236. pathXMin = jmin (pathXMin, x1, x2, x3);
  74237. pathXMax = jmax (pathXMax, x1, x2, x3);
  74238. pathYMin = jmin (pathYMin, y1, y2, y3);
  74239. pathYMax = jmax (pathYMax, y1, y2, y3);
  74240. }
  74241. void Path::cubicTo (const Point<float>& controlPoint1,
  74242. const Point<float>& controlPoint2,
  74243. const Point<float>& endPoint)
  74244. {
  74245. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74246. controlPoint2.getX(), controlPoint2.getY(),
  74247. endPoint.getX(), endPoint.getY());
  74248. }
  74249. void Path::closeSubPath()
  74250. {
  74251. if (numElements > 0
  74252. && data.elements [numElements - 1] != closeSubPathMarker)
  74253. {
  74254. data.ensureAllocatedSize ((int) numElements + 1);
  74255. data.elements [numElements++] = closeSubPathMarker;
  74256. }
  74257. }
  74258. const Point<float> Path::getCurrentPosition() const
  74259. {
  74260. size_t i = numElements - 1;
  74261. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74262. {
  74263. while (i >= 0)
  74264. {
  74265. if (data.elements[i] == moveMarker)
  74266. {
  74267. i += 2;
  74268. break;
  74269. }
  74270. --i;
  74271. }
  74272. }
  74273. if (i > 0)
  74274. return Point<float> (data.elements [i - 1], data.elements [i]);
  74275. return Point<float>();
  74276. }
  74277. void Path::addRectangle (const float x, const float y,
  74278. const float w, const float h)
  74279. {
  74280. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74281. if (w < 0)
  74282. swapVariables (x1, x2);
  74283. if (h < 0)
  74284. swapVariables (y1, y2);
  74285. data.ensureAllocatedSize ((int) numElements + 13);
  74286. if (numElements == 0)
  74287. {
  74288. pathXMin = x1;
  74289. pathXMax = x2;
  74290. pathYMin = y1;
  74291. pathYMax = y2;
  74292. }
  74293. else
  74294. {
  74295. pathXMin = jmin (pathXMin, x1);
  74296. pathXMax = jmax (pathXMax, x2);
  74297. pathYMin = jmin (pathYMin, y1);
  74298. pathYMax = jmax (pathYMax, y2);
  74299. }
  74300. data.elements [numElements++] = moveMarker;
  74301. data.elements [numElements++] = x1;
  74302. data.elements [numElements++] = y2;
  74303. data.elements [numElements++] = lineMarker;
  74304. data.elements [numElements++] = x1;
  74305. data.elements [numElements++] = y1;
  74306. data.elements [numElements++] = lineMarker;
  74307. data.elements [numElements++] = x2;
  74308. data.elements [numElements++] = y1;
  74309. data.elements [numElements++] = lineMarker;
  74310. data.elements [numElements++] = x2;
  74311. data.elements [numElements++] = y2;
  74312. data.elements [numElements++] = closeSubPathMarker;
  74313. }
  74314. void Path::addRoundedRectangle (const float x, const float y,
  74315. const float w, const float h,
  74316. float csx,
  74317. float csy)
  74318. {
  74319. csx = jmin (csx, w * 0.5f);
  74320. csy = jmin (csy, h * 0.5f);
  74321. const float cs45x = csx * 0.45f;
  74322. const float cs45y = csy * 0.45f;
  74323. const float x2 = x + w;
  74324. const float y2 = y + h;
  74325. startNewSubPath (x + csx, y);
  74326. lineTo (x2 - csx, y);
  74327. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74328. lineTo (x2, y2 - csy);
  74329. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74330. lineTo (x + csx, y2);
  74331. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74332. lineTo (x, y + csy);
  74333. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74334. closeSubPath();
  74335. }
  74336. void Path::addRoundedRectangle (const float x, const float y,
  74337. const float w, const float h,
  74338. float cs)
  74339. {
  74340. addRoundedRectangle (x, y, w, h, cs, cs);
  74341. }
  74342. void Path::addTriangle (const float x1, const float y1,
  74343. const float x2, const float y2,
  74344. const float x3, const float y3)
  74345. {
  74346. startNewSubPath (x1, y1);
  74347. lineTo (x2, y2);
  74348. lineTo (x3, y3);
  74349. closeSubPath();
  74350. }
  74351. void Path::addQuadrilateral (const float x1, const float y1,
  74352. const float x2, const float y2,
  74353. const float x3, const float y3,
  74354. const float x4, const float y4)
  74355. {
  74356. startNewSubPath (x1, y1);
  74357. lineTo (x2, y2);
  74358. lineTo (x3, y3);
  74359. lineTo (x4, y4);
  74360. closeSubPath();
  74361. }
  74362. void Path::addEllipse (const float x, const float y,
  74363. const float w, const float h)
  74364. {
  74365. const float hw = w * 0.5f;
  74366. const float hw55 = hw * 0.55f;
  74367. const float hh = h * 0.5f;
  74368. const float hh45 = hh * 0.55f;
  74369. const float cx = x + hw;
  74370. const float cy = y + hh;
  74371. startNewSubPath (cx, cy - hh);
  74372. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  74373. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  74374. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  74375. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  74376. closeSubPath();
  74377. }
  74378. void Path::addArc (const float x, const float y,
  74379. const float w, const float h,
  74380. const float fromRadians,
  74381. const float toRadians,
  74382. const bool startAsNewSubPath)
  74383. {
  74384. const float radiusX = w / 2.0f;
  74385. const float radiusY = h / 2.0f;
  74386. addCentredArc (x + radiusX,
  74387. y + radiusY,
  74388. radiusX, radiusY,
  74389. 0.0f,
  74390. fromRadians, toRadians,
  74391. startAsNewSubPath);
  74392. }
  74393. void Path::addCentredArc (const float centreX, const float centreY,
  74394. const float radiusX, const float radiusY,
  74395. const float rotationOfEllipse,
  74396. const float fromRadians,
  74397. const float toRadians,
  74398. const bool startAsNewSubPath)
  74399. {
  74400. if (radiusX > 0.0f && radiusY > 0.0f)
  74401. {
  74402. const Point<float> centre (centreX, centreY);
  74403. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74404. float angle = fromRadians;
  74405. if (startAsNewSubPath)
  74406. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74407. if (fromRadians < toRadians)
  74408. {
  74409. if (startAsNewSubPath)
  74410. angle += PathHelpers::ellipseAngularIncrement;
  74411. while (angle < toRadians)
  74412. {
  74413. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74414. angle += PathHelpers::ellipseAngularIncrement;
  74415. }
  74416. }
  74417. else
  74418. {
  74419. if (startAsNewSubPath)
  74420. angle -= PathHelpers::ellipseAngularIncrement;
  74421. while (angle > toRadians)
  74422. {
  74423. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74424. angle -= PathHelpers::ellipseAngularIncrement;
  74425. }
  74426. }
  74427. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74428. }
  74429. }
  74430. void Path::addPieSegment (const float x, const float y,
  74431. const float width, const float height,
  74432. const float fromRadians,
  74433. const float toRadians,
  74434. const float innerCircleProportionalSize)
  74435. {
  74436. float radiusX = width * 0.5f;
  74437. float radiusY = height * 0.5f;
  74438. const Point<float> centre (x + radiusX, y + radiusY);
  74439. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74440. addArc (x, y, width, height, fromRadians, toRadians);
  74441. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74442. {
  74443. closeSubPath();
  74444. if (innerCircleProportionalSize > 0)
  74445. {
  74446. radiusX *= innerCircleProportionalSize;
  74447. radiusY *= innerCircleProportionalSize;
  74448. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74449. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74450. }
  74451. }
  74452. else
  74453. {
  74454. if (innerCircleProportionalSize > 0)
  74455. {
  74456. radiusX *= innerCircleProportionalSize;
  74457. radiusY *= innerCircleProportionalSize;
  74458. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74459. }
  74460. else
  74461. {
  74462. lineTo (centre);
  74463. }
  74464. }
  74465. closeSubPath();
  74466. }
  74467. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74468. {
  74469. const Line<float> reversed (line.reversed());
  74470. lineThickness *= 0.5f;
  74471. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74472. lineTo (line.getPointAlongLine (0, -lineThickness));
  74473. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74474. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74475. closeSubPath();
  74476. }
  74477. void Path::addArrow (const Line<float>& line, float lineThickness,
  74478. float arrowheadWidth, float arrowheadLength)
  74479. {
  74480. const Line<float> reversed (line.reversed());
  74481. lineThickness *= 0.5f;
  74482. arrowheadWidth *= 0.5f;
  74483. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74484. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74485. lineTo (line.getPointAlongLine (0, -lineThickness));
  74486. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74487. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74488. lineTo (line.getEnd());
  74489. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74490. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74491. closeSubPath();
  74492. }
  74493. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74494. const float radius, const float startAngle)
  74495. {
  74496. jassert (numberOfSides > 1); // this would be silly.
  74497. if (numberOfSides > 1)
  74498. {
  74499. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74500. for (int i = 0; i < numberOfSides; ++i)
  74501. {
  74502. const float angle = startAngle + i * angleBetweenPoints;
  74503. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74504. if (i == 0)
  74505. startNewSubPath (p);
  74506. else
  74507. lineTo (p);
  74508. }
  74509. closeSubPath();
  74510. }
  74511. }
  74512. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74513. const float innerRadius, const float outerRadius, const float startAngle)
  74514. {
  74515. jassert (numberOfPoints > 1); // this would be silly.
  74516. if (numberOfPoints > 1)
  74517. {
  74518. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74519. for (int i = 0; i < numberOfPoints; ++i)
  74520. {
  74521. const float angle = startAngle + i * angleBetweenPoints;
  74522. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74523. if (i == 0)
  74524. startNewSubPath (p);
  74525. else
  74526. lineTo (p);
  74527. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74528. }
  74529. closeSubPath();
  74530. }
  74531. }
  74532. void Path::addBubble (float x, float y,
  74533. float w, float h,
  74534. float cs,
  74535. float tipX,
  74536. float tipY,
  74537. int whichSide,
  74538. float arrowPos,
  74539. float arrowWidth)
  74540. {
  74541. if (w > 1.0f && h > 1.0f)
  74542. {
  74543. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74544. const float cs2 = 2.0f * cs;
  74545. startNewSubPath (x + cs, y);
  74546. if (whichSide == 0)
  74547. {
  74548. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74549. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74550. lineTo (arrowX1, y);
  74551. lineTo (tipX, tipY);
  74552. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74553. }
  74554. lineTo (x + w - cs, y);
  74555. if (cs > 0.0f)
  74556. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74557. if (whichSide == 3)
  74558. {
  74559. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74560. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74561. lineTo (x + w, arrowY1);
  74562. lineTo (tipX, tipY);
  74563. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74564. }
  74565. lineTo (x + w, y + h - cs);
  74566. if (cs > 0.0f)
  74567. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74568. if (whichSide == 2)
  74569. {
  74570. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74571. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74572. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74573. lineTo (tipX, tipY);
  74574. lineTo (arrowX1, y + h);
  74575. }
  74576. lineTo (x + cs, y + h);
  74577. if (cs > 0.0f)
  74578. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74579. if (whichSide == 1)
  74580. {
  74581. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74582. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74583. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74584. lineTo (tipX, tipY);
  74585. lineTo (x, arrowY1);
  74586. }
  74587. lineTo (x, y + cs);
  74588. if (cs > 0.0f)
  74589. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74590. closeSubPath();
  74591. }
  74592. }
  74593. void Path::addPath (const Path& other)
  74594. {
  74595. size_t i = 0;
  74596. while (i < other.numElements)
  74597. {
  74598. const float type = other.data.elements [i++];
  74599. if (type == moveMarker)
  74600. {
  74601. startNewSubPath (other.data.elements [i],
  74602. other.data.elements [i + 1]);
  74603. i += 2;
  74604. }
  74605. else if (type == lineMarker)
  74606. {
  74607. lineTo (other.data.elements [i],
  74608. other.data.elements [i + 1]);
  74609. i += 2;
  74610. }
  74611. else if (type == quadMarker)
  74612. {
  74613. quadraticTo (other.data.elements [i],
  74614. other.data.elements [i + 1],
  74615. other.data.elements [i + 2],
  74616. other.data.elements [i + 3]);
  74617. i += 4;
  74618. }
  74619. else if (type == cubicMarker)
  74620. {
  74621. cubicTo (other.data.elements [i],
  74622. other.data.elements [i + 1],
  74623. other.data.elements [i + 2],
  74624. other.data.elements [i + 3],
  74625. other.data.elements [i + 4],
  74626. other.data.elements [i + 5]);
  74627. i += 6;
  74628. }
  74629. else if (type == closeSubPathMarker)
  74630. {
  74631. closeSubPath();
  74632. }
  74633. else
  74634. {
  74635. // something's gone wrong with the element list!
  74636. jassertfalse;
  74637. }
  74638. }
  74639. }
  74640. void Path::addPath (const Path& other,
  74641. const AffineTransform& transformToApply)
  74642. {
  74643. size_t i = 0;
  74644. while (i < other.numElements)
  74645. {
  74646. const float type = other.data.elements [i++];
  74647. if (type == closeSubPathMarker)
  74648. {
  74649. closeSubPath();
  74650. }
  74651. else
  74652. {
  74653. float x = other.data.elements [i++];
  74654. float y = other.data.elements [i++];
  74655. transformToApply.transformPoint (x, y);
  74656. if (type == moveMarker)
  74657. {
  74658. startNewSubPath (x, y);
  74659. }
  74660. else if (type == lineMarker)
  74661. {
  74662. lineTo (x, y);
  74663. }
  74664. else if (type == quadMarker)
  74665. {
  74666. float x2 = other.data.elements [i++];
  74667. float y2 = other.data.elements [i++];
  74668. transformToApply.transformPoint (x2, y2);
  74669. quadraticTo (x, y, x2, y2);
  74670. }
  74671. else if (type == cubicMarker)
  74672. {
  74673. float x2 = other.data.elements [i++];
  74674. float y2 = other.data.elements [i++];
  74675. float x3 = other.data.elements [i++];
  74676. float y3 = other.data.elements [i++];
  74677. transformToApply.transformPoints (x2, y2, x3, y3);
  74678. cubicTo (x, y, x2, y2, x3, y3);
  74679. }
  74680. else
  74681. {
  74682. // something's gone wrong with the element list!
  74683. jassertfalse;
  74684. }
  74685. }
  74686. }
  74687. }
  74688. void Path::applyTransform (const AffineTransform& transform) throw()
  74689. {
  74690. size_t i = 0;
  74691. pathYMin = pathXMin = 0;
  74692. pathYMax = pathXMax = 0;
  74693. bool setMaxMin = false;
  74694. while (i < numElements)
  74695. {
  74696. const float type = data.elements [i++];
  74697. if (type == moveMarker)
  74698. {
  74699. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74700. if (setMaxMin)
  74701. {
  74702. pathXMin = jmin (pathXMin, data.elements [i]);
  74703. pathXMax = jmax (pathXMax, data.elements [i]);
  74704. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74705. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74706. }
  74707. else
  74708. {
  74709. pathXMin = pathXMax = data.elements [i];
  74710. pathYMin = pathYMax = data.elements [i + 1];
  74711. setMaxMin = true;
  74712. }
  74713. i += 2;
  74714. }
  74715. else if (type == lineMarker)
  74716. {
  74717. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74718. pathXMin = jmin (pathXMin, data.elements [i]);
  74719. pathXMax = jmax (pathXMax, data.elements [i]);
  74720. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74721. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74722. i += 2;
  74723. }
  74724. else if (type == quadMarker)
  74725. {
  74726. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74727. data.elements [i + 2], data.elements [i + 3]);
  74728. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74729. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74730. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74731. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74732. i += 4;
  74733. }
  74734. else if (type == cubicMarker)
  74735. {
  74736. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74737. data.elements [i + 2], data.elements [i + 3],
  74738. data.elements [i + 4], data.elements [i + 5]);
  74739. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74740. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74741. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74742. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74743. i += 6;
  74744. }
  74745. }
  74746. }
  74747. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74748. const float w, const float h,
  74749. const bool preserveProportions,
  74750. const Justification& justification) const
  74751. {
  74752. Rectangle<float> bounds (getBounds());
  74753. if (preserveProportions)
  74754. {
  74755. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74756. return AffineTransform::identity;
  74757. float newW, newH;
  74758. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74759. if (srcRatio > h / w)
  74760. {
  74761. newW = h / srcRatio;
  74762. newH = h;
  74763. }
  74764. else
  74765. {
  74766. newW = w;
  74767. newH = w * srcRatio;
  74768. }
  74769. float newXCentre = x;
  74770. float newYCentre = y;
  74771. if (justification.testFlags (Justification::left))
  74772. newXCentre += newW * 0.5f;
  74773. else if (justification.testFlags (Justification::right))
  74774. newXCentre += w - newW * 0.5f;
  74775. else
  74776. newXCentre += w * 0.5f;
  74777. if (justification.testFlags (Justification::top))
  74778. newYCentre += newH * 0.5f;
  74779. else if (justification.testFlags (Justification::bottom))
  74780. newYCentre += h - newH * 0.5f;
  74781. else
  74782. newYCentre += h * 0.5f;
  74783. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74784. bounds.getHeight() * -0.5f - bounds.getY())
  74785. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74786. .translated (newXCentre, newYCentre);
  74787. }
  74788. else
  74789. {
  74790. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74791. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74792. .translated (x, y);
  74793. }
  74794. }
  74795. bool Path::contains (const float x, const float y, const float tolerence) const
  74796. {
  74797. if (x <= pathXMin || x >= pathXMax
  74798. || y <= pathYMin || y >= pathYMax)
  74799. return false;
  74800. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74801. int positiveCrossings = 0;
  74802. int negativeCrossings = 0;
  74803. while (i.next())
  74804. {
  74805. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74806. {
  74807. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74808. if (intersectX <= x)
  74809. {
  74810. if (i.y1 < i.y2)
  74811. ++positiveCrossings;
  74812. else
  74813. ++negativeCrossings;
  74814. }
  74815. }
  74816. }
  74817. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74818. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74819. }
  74820. bool Path::contains (const Point<float>& point, const float tolerence) const
  74821. {
  74822. return contains (point.getX(), point.getY(), tolerence);
  74823. }
  74824. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  74825. {
  74826. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74827. Point<float> intersection;
  74828. while (i.next())
  74829. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74830. return true;
  74831. return false;
  74832. }
  74833. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74834. {
  74835. Line<float> result (line);
  74836. const bool startInside = contains (line.getStart());
  74837. const bool endInside = contains (line.getEnd());
  74838. if (startInside == endInside)
  74839. {
  74840. if (keepSectionOutsidePath == startInside)
  74841. result = Line<float>();
  74842. }
  74843. else
  74844. {
  74845. PathFlatteningIterator i (*this, AffineTransform::identity);
  74846. Point<float> intersection;
  74847. while (i.next())
  74848. {
  74849. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74850. {
  74851. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74852. result.setStart (intersection);
  74853. else
  74854. result.setEnd (intersection);
  74855. }
  74856. }
  74857. }
  74858. return result;
  74859. }
  74860. float Path::getLength (const AffineTransform& transform) const
  74861. {
  74862. float length = 0;
  74863. PathFlatteningIterator i (*this, transform);
  74864. while (i.next())
  74865. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74866. return length;
  74867. }
  74868. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74869. {
  74870. PathFlatteningIterator i (*this, transform);
  74871. while (i.next())
  74872. {
  74873. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74874. const float lineLength = line.getLength();
  74875. if (distanceFromStart <= lineLength)
  74876. return line.getPointAlongLine (distanceFromStart);
  74877. distanceFromStart -= lineLength;
  74878. }
  74879. return Point<float> (i.x2, i.y2);
  74880. }
  74881. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74882. const AffineTransform& transform) const
  74883. {
  74884. PathFlatteningIterator i (*this, transform);
  74885. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74886. float length = 0;
  74887. Point<float> pointOnLine;
  74888. while (i.next())
  74889. {
  74890. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74891. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74892. if (distance < bestDistance)
  74893. {
  74894. bestDistance = distance;
  74895. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74896. pointOnPath = pointOnLine;
  74897. }
  74898. length += line.getLength();
  74899. }
  74900. return bestPosition;
  74901. }
  74902. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74903. {
  74904. if (cornerRadius <= 0.01f)
  74905. return *this;
  74906. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74907. size_t n = 0;
  74908. bool lastWasLine = false, firstWasLine = false;
  74909. Path p;
  74910. while (n < numElements)
  74911. {
  74912. const float type = data.elements [n++];
  74913. if (type == moveMarker)
  74914. {
  74915. indexOfPathStart = p.numElements;
  74916. indexOfPathStartThis = n - 1;
  74917. const float x = data.elements [n++];
  74918. const float y = data.elements [n++];
  74919. p.startNewSubPath (x, y);
  74920. lastWasLine = false;
  74921. firstWasLine = (data.elements [n] == lineMarker);
  74922. }
  74923. else if (type == lineMarker || type == closeSubPathMarker)
  74924. {
  74925. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74926. if (type == lineMarker)
  74927. {
  74928. endX = data.elements [n++];
  74929. endY = data.elements [n++];
  74930. if (n > 8)
  74931. {
  74932. startX = data.elements [n - 8];
  74933. startY = data.elements [n - 7];
  74934. joinX = data.elements [n - 5];
  74935. joinY = data.elements [n - 4];
  74936. }
  74937. }
  74938. else
  74939. {
  74940. endX = data.elements [indexOfPathStartThis + 1];
  74941. endY = data.elements [indexOfPathStartThis + 2];
  74942. if (n > 6)
  74943. {
  74944. startX = data.elements [n - 6];
  74945. startY = data.elements [n - 5];
  74946. joinX = data.elements [n - 3];
  74947. joinY = data.elements [n - 2];
  74948. }
  74949. }
  74950. if (lastWasLine)
  74951. {
  74952. const double len1 = juce_hypot (startX - joinX,
  74953. startY - joinY);
  74954. if (len1 > 0)
  74955. {
  74956. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74957. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74958. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74959. }
  74960. const double len2 = juce_hypot (endX - joinX,
  74961. endY - joinY);
  74962. if (len2 > 0)
  74963. {
  74964. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74965. p.quadraticTo (joinX, joinY,
  74966. (float) (joinX + (endX - joinX) * propNeeded),
  74967. (float) (joinY + (endY - joinY) * propNeeded));
  74968. }
  74969. p.lineTo (endX, endY);
  74970. }
  74971. else if (type == lineMarker)
  74972. {
  74973. p.lineTo (endX, endY);
  74974. lastWasLine = true;
  74975. }
  74976. if (type == closeSubPathMarker)
  74977. {
  74978. if (firstWasLine)
  74979. {
  74980. startX = data.elements [n - 3];
  74981. startY = data.elements [n - 2];
  74982. joinX = endX;
  74983. joinY = endY;
  74984. endX = data.elements [indexOfPathStartThis + 4];
  74985. endY = data.elements [indexOfPathStartThis + 5];
  74986. const double len1 = juce_hypot (startX - joinX,
  74987. startY - joinY);
  74988. if (len1 > 0)
  74989. {
  74990. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74991. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74992. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74993. }
  74994. const double len2 = juce_hypot (endX - joinX,
  74995. endY - joinY);
  74996. if (len2 > 0)
  74997. {
  74998. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74999. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75000. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75001. p.quadraticTo (joinX, joinY, endX, endY);
  75002. p.data.elements [indexOfPathStart + 1] = endX;
  75003. p.data.elements [indexOfPathStart + 2] = endY;
  75004. }
  75005. }
  75006. p.closeSubPath();
  75007. }
  75008. }
  75009. else if (type == quadMarker)
  75010. {
  75011. lastWasLine = false;
  75012. const float x1 = data.elements [n++];
  75013. const float y1 = data.elements [n++];
  75014. const float x2 = data.elements [n++];
  75015. const float y2 = data.elements [n++];
  75016. p.quadraticTo (x1, y1, x2, y2);
  75017. }
  75018. else if (type == cubicMarker)
  75019. {
  75020. lastWasLine = false;
  75021. const float x1 = data.elements [n++];
  75022. const float y1 = data.elements [n++];
  75023. const float x2 = data.elements [n++];
  75024. const float y2 = data.elements [n++];
  75025. const float x3 = data.elements [n++];
  75026. const float y3 = data.elements [n++];
  75027. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75028. }
  75029. }
  75030. return p;
  75031. }
  75032. void Path::loadPathFromStream (InputStream& source)
  75033. {
  75034. while (! source.isExhausted())
  75035. {
  75036. switch (source.readByte())
  75037. {
  75038. case 'm':
  75039. {
  75040. const float x = source.readFloat();
  75041. const float y = source.readFloat();
  75042. startNewSubPath (x, y);
  75043. break;
  75044. }
  75045. case 'l':
  75046. {
  75047. const float x = source.readFloat();
  75048. const float y = source.readFloat();
  75049. lineTo (x, y);
  75050. break;
  75051. }
  75052. case 'q':
  75053. {
  75054. const float x1 = source.readFloat();
  75055. const float y1 = source.readFloat();
  75056. const float x2 = source.readFloat();
  75057. const float y2 = source.readFloat();
  75058. quadraticTo (x1, y1, x2, y2);
  75059. break;
  75060. }
  75061. case 'b':
  75062. {
  75063. const float x1 = source.readFloat();
  75064. const float y1 = source.readFloat();
  75065. const float x2 = source.readFloat();
  75066. const float y2 = source.readFloat();
  75067. const float x3 = source.readFloat();
  75068. const float y3 = source.readFloat();
  75069. cubicTo (x1, y1, x2, y2, x3, y3);
  75070. break;
  75071. }
  75072. case 'c':
  75073. closeSubPath();
  75074. break;
  75075. case 'n':
  75076. useNonZeroWinding = true;
  75077. break;
  75078. case 'z':
  75079. useNonZeroWinding = false;
  75080. break;
  75081. case 'e':
  75082. return; // end of path marker
  75083. default:
  75084. jassertfalse; // illegal char in the stream
  75085. break;
  75086. }
  75087. }
  75088. }
  75089. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75090. {
  75091. MemoryInputStream in (pathData, numberOfBytes, false);
  75092. loadPathFromStream (in);
  75093. }
  75094. void Path::writePathToStream (OutputStream& dest) const
  75095. {
  75096. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75097. size_t i = 0;
  75098. while (i < numElements)
  75099. {
  75100. const float type = data.elements [i++];
  75101. if (type == moveMarker)
  75102. {
  75103. dest.writeByte ('m');
  75104. dest.writeFloat (data.elements [i++]);
  75105. dest.writeFloat (data.elements [i++]);
  75106. }
  75107. else if (type == lineMarker)
  75108. {
  75109. dest.writeByte ('l');
  75110. dest.writeFloat (data.elements [i++]);
  75111. dest.writeFloat (data.elements [i++]);
  75112. }
  75113. else if (type == quadMarker)
  75114. {
  75115. dest.writeByte ('q');
  75116. dest.writeFloat (data.elements [i++]);
  75117. dest.writeFloat (data.elements [i++]);
  75118. dest.writeFloat (data.elements [i++]);
  75119. dest.writeFloat (data.elements [i++]);
  75120. }
  75121. else if (type == cubicMarker)
  75122. {
  75123. dest.writeByte ('b');
  75124. dest.writeFloat (data.elements [i++]);
  75125. dest.writeFloat (data.elements [i++]);
  75126. dest.writeFloat (data.elements [i++]);
  75127. dest.writeFloat (data.elements [i++]);
  75128. dest.writeFloat (data.elements [i++]);
  75129. dest.writeFloat (data.elements [i++]);
  75130. }
  75131. else if (type == closeSubPathMarker)
  75132. {
  75133. dest.writeByte ('c');
  75134. }
  75135. }
  75136. dest.writeByte ('e'); // marks the end-of-path
  75137. }
  75138. const String Path::toString() const
  75139. {
  75140. MemoryOutputStream s (2048);
  75141. if (! useNonZeroWinding)
  75142. s << 'a';
  75143. size_t i = 0;
  75144. float lastMarker = 0.0f;
  75145. while (i < numElements)
  75146. {
  75147. const float marker = data.elements [i++];
  75148. char markerChar = 0;
  75149. int numCoords = 0;
  75150. if (marker == moveMarker)
  75151. {
  75152. markerChar = 'm';
  75153. numCoords = 2;
  75154. }
  75155. else if (marker == lineMarker)
  75156. {
  75157. markerChar = 'l';
  75158. numCoords = 2;
  75159. }
  75160. else if (marker == quadMarker)
  75161. {
  75162. markerChar = 'q';
  75163. numCoords = 4;
  75164. }
  75165. else if (marker == cubicMarker)
  75166. {
  75167. markerChar = 'c';
  75168. numCoords = 6;
  75169. }
  75170. else
  75171. {
  75172. jassert (marker == closeSubPathMarker);
  75173. markerChar = 'z';
  75174. }
  75175. if (marker != lastMarker)
  75176. {
  75177. if (s.getDataSize() != 0)
  75178. s << ' ';
  75179. s << markerChar;
  75180. lastMarker = marker;
  75181. }
  75182. while (--numCoords >= 0 && i < numElements)
  75183. {
  75184. String coord (data.elements [i++], 3);
  75185. while (coord.endsWithChar ('0') && coord != "0")
  75186. coord = coord.dropLastCharacters (1);
  75187. if (coord.endsWithChar ('.'))
  75188. coord = coord.dropLastCharacters (1);
  75189. if (s.getDataSize() != 0)
  75190. s << ' ';
  75191. s << coord;
  75192. }
  75193. }
  75194. return s.toUTF8();
  75195. }
  75196. void Path::restoreFromString (const String& stringVersion)
  75197. {
  75198. clear();
  75199. setUsingNonZeroWinding (true);
  75200. const juce_wchar* t = stringVersion;
  75201. juce_wchar marker = 'm';
  75202. int numValues = 2;
  75203. float values [6];
  75204. for (;;)
  75205. {
  75206. const String token (PathHelpers::nextToken (t));
  75207. const juce_wchar firstChar = token[0];
  75208. int startNum = 0;
  75209. if (firstChar == 0)
  75210. break;
  75211. if (firstChar == 'm' || firstChar == 'l')
  75212. {
  75213. marker = firstChar;
  75214. numValues = 2;
  75215. }
  75216. else if (firstChar == 'q')
  75217. {
  75218. marker = firstChar;
  75219. numValues = 4;
  75220. }
  75221. else if (firstChar == 'c')
  75222. {
  75223. marker = firstChar;
  75224. numValues = 6;
  75225. }
  75226. else if (firstChar == 'z')
  75227. {
  75228. marker = firstChar;
  75229. numValues = 0;
  75230. }
  75231. else if (firstChar == 'a')
  75232. {
  75233. setUsingNonZeroWinding (false);
  75234. continue;
  75235. }
  75236. else
  75237. {
  75238. ++startNum;
  75239. values [0] = token.getFloatValue();
  75240. }
  75241. for (int i = startNum; i < numValues; ++i)
  75242. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75243. switch (marker)
  75244. {
  75245. case 'm': startNewSubPath (values[0], values[1]); break;
  75246. case 'l': lineTo (values[0], values[1]); break;
  75247. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75248. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75249. case 'z': closeSubPath(); break;
  75250. default: jassertfalse; break; // illegal string format?
  75251. }
  75252. }
  75253. }
  75254. Path::Iterator::Iterator (const Path& path_)
  75255. : path (path_),
  75256. index (0)
  75257. {
  75258. }
  75259. Path::Iterator::~Iterator()
  75260. {
  75261. }
  75262. bool Path::Iterator::next()
  75263. {
  75264. const float* const elements = path.data.elements;
  75265. if (index < path.numElements)
  75266. {
  75267. const float type = elements [index++];
  75268. if (type == moveMarker)
  75269. {
  75270. elementType = startNewSubPath;
  75271. x1 = elements [index++];
  75272. y1 = elements [index++];
  75273. }
  75274. else if (type == lineMarker)
  75275. {
  75276. elementType = lineTo;
  75277. x1 = elements [index++];
  75278. y1 = elements [index++];
  75279. }
  75280. else if (type == quadMarker)
  75281. {
  75282. elementType = quadraticTo;
  75283. x1 = elements [index++];
  75284. y1 = elements [index++];
  75285. x2 = elements [index++];
  75286. y2 = elements [index++];
  75287. }
  75288. else if (type == cubicMarker)
  75289. {
  75290. elementType = cubicTo;
  75291. x1 = elements [index++];
  75292. y1 = elements [index++];
  75293. x2 = elements [index++];
  75294. y2 = elements [index++];
  75295. x3 = elements [index++];
  75296. y3 = elements [index++];
  75297. }
  75298. else if (type == closeSubPathMarker)
  75299. {
  75300. elementType = closePath;
  75301. }
  75302. return true;
  75303. }
  75304. return false;
  75305. }
  75306. END_JUCE_NAMESPACE
  75307. /*** End of inlined file: juce_Path.cpp ***/
  75308. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75309. BEGIN_JUCE_NAMESPACE
  75310. #if JUCE_MSVC && JUCE_DEBUG
  75311. #pragma optimize ("t", on)
  75312. #endif
  75313. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75314. const AffineTransform& transform_,
  75315. float tolerence_)
  75316. : x2 (0),
  75317. y2 (0),
  75318. closesSubPath (false),
  75319. subPathIndex (-1),
  75320. path (path_),
  75321. transform (transform_),
  75322. points (path_.data.elements),
  75323. tolerence (tolerence_ * tolerence_),
  75324. subPathCloseX (0),
  75325. subPathCloseY (0),
  75326. isIdentityTransform (transform_.isIdentity()),
  75327. stackBase (32),
  75328. index (0),
  75329. stackSize (32)
  75330. {
  75331. stackPos = stackBase;
  75332. }
  75333. PathFlatteningIterator::~PathFlatteningIterator()
  75334. {
  75335. }
  75336. bool PathFlatteningIterator::next()
  75337. {
  75338. x1 = x2;
  75339. y1 = y2;
  75340. float x3 = 0;
  75341. float y3 = 0;
  75342. float x4 = 0;
  75343. float y4 = 0;
  75344. float type;
  75345. for (;;)
  75346. {
  75347. if (stackPos == stackBase)
  75348. {
  75349. if (index >= path.numElements)
  75350. {
  75351. return false;
  75352. }
  75353. else
  75354. {
  75355. type = points [index++];
  75356. if (type != Path::closeSubPathMarker)
  75357. {
  75358. x2 = points [index++];
  75359. y2 = points [index++];
  75360. if (type == Path::quadMarker)
  75361. {
  75362. x3 = points [index++];
  75363. y3 = points [index++];
  75364. if (! isIdentityTransform)
  75365. transform.transformPoints (x2, y2, x3, y3);
  75366. }
  75367. else if (type == Path::cubicMarker)
  75368. {
  75369. x3 = points [index++];
  75370. y3 = points [index++];
  75371. x4 = points [index++];
  75372. y4 = points [index++];
  75373. if (! isIdentityTransform)
  75374. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75375. }
  75376. else
  75377. {
  75378. if (! isIdentityTransform)
  75379. transform.transformPoint (x2, y2);
  75380. }
  75381. }
  75382. }
  75383. }
  75384. else
  75385. {
  75386. type = *--stackPos;
  75387. if (type != Path::closeSubPathMarker)
  75388. {
  75389. x2 = *--stackPos;
  75390. y2 = *--stackPos;
  75391. if (type == Path::quadMarker)
  75392. {
  75393. x3 = *--stackPos;
  75394. y3 = *--stackPos;
  75395. }
  75396. else if (type == Path::cubicMarker)
  75397. {
  75398. x3 = *--stackPos;
  75399. y3 = *--stackPos;
  75400. x4 = *--stackPos;
  75401. y4 = *--stackPos;
  75402. }
  75403. }
  75404. }
  75405. if (type == Path::lineMarker)
  75406. {
  75407. ++subPathIndex;
  75408. closesSubPath = (stackPos == stackBase)
  75409. && (index < path.numElements)
  75410. && (points [index] == Path::closeSubPathMarker)
  75411. && x2 == subPathCloseX
  75412. && y2 == subPathCloseY;
  75413. return true;
  75414. }
  75415. else if (type == Path::quadMarker)
  75416. {
  75417. const size_t offset = (size_t) (stackPos - stackBase);
  75418. if (offset >= stackSize - 10)
  75419. {
  75420. stackSize <<= 1;
  75421. stackBase.realloc (stackSize);
  75422. stackPos = stackBase + offset;
  75423. }
  75424. const float dx1 = x1 - x2;
  75425. const float dy1 = y1 - y2;
  75426. const float dx2 = x2 - x3;
  75427. const float dy2 = y2 - y3;
  75428. const float m1x = (x1 + x2) * 0.5f;
  75429. const float m1y = (y1 + y2) * 0.5f;
  75430. const float m2x = (x2 + x3) * 0.5f;
  75431. const float m2y = (y2 + y3) * 0.5f;
  75432. const float m3x = (m1x + m2x) * 0.5f;
  75433. const float m3y = (m1y + m2y) * 0.5f;
  75434. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  75435. {
  75436. *stackPos++ = y3;
  75437. *stackPos++ = x3;
  75438. *stackPos++ = m2y;
  75439. *stackPos++ = m2x;
  75440. *stackPos++ = Path::quadMarker;
  75441. *stackPos++ = m3y;
  75442. *stackPos++ = m3x;
  75443. *stackPos++ = m1y;
  75444. *stackPos++ = m1x;
  75445. *stackPos++ = Path::quadMarker;
  75446. }
  75447. else
  75448. {
  75449. *stackPos++ = y3;
  75450. *stackPos++ = x3;
  75451. *stackPos++ = Path::lineMarker;
  75452. *stackPos++ = m3y;
  75453. *stackPos++ = m3x;
  75454. *stackPos++ = Path::lineMarker;
  75455. }
  75456. jassert (stackPos < stackBase + stackSize);
  75457. }
  75458. else if (type == Path::cubicMarker)
  75459. {
  75460. const size_t offset = (size_t) (stackPos - stackBase);
  75461. if (offset >= stackSize - 16)
  75462. {
  75463. stackSize <<= 1;
  75464. stackBase.realloc (stackSize);
  75465. stackPos = stackBase + offset;
  75466. }
  75467. const float dx1 = x1 - x2;
  75468. const float dy1 = y1 - y2;
  75469. const float dx2 = x2 - x3;
  75470. const float dy2 = y2 - y3;
  75471. const float dx3 = x3 - x4;
  75472. const float dy3 = y3 - y4;
  75473. const float m1x = (x1 + x2) * 0.5f;
  75474. const float m1y = (y1 + y2) * 0.5f;
  75475. const float m2x = (x3 + x2) * 0.5f;
  75476. const float m2y = (y3 + y2) * 0.5f;
  75477. const float m3x = (x3 + x4) * 0.5f;
  75478. const float m3y = (y3 + y4) * 0.5f;
  75479. const float m4x = (m1x + m2x) * 0.5f;
  75480. const float m4y = (m1y + m2y) * 0.5f;
  75481. const float m5x = (m3x + m2x) * 0.5f;
  75482. const float m5y = (m3y + m2y) * 0.5f;
  75483. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  75484. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  75485. {
  75486. *stackPos++ = y4;
  75487. *stackPos++ = x4;
  75488. *stackPos++ = m3y;
  75489. *stackPos++ = m3x;
  75490. *stackPos++ = m5y;
  75491. *stackPos++ = m5x;
  75492. *stackPos++ = Path::cubicMarker;
  75493. *stackPos++ = (m4y + m5y) * 0.5f;
  75494. *stackPos++ = (m4x + m5x) * 0.5f;
  75495. *stackPos++ = m4y;
  75496. *stackPos++ = m4x;
  75497. *stackPos++ = m1y;
  75498. *stackPos++ = m1x;
  75499. *stackPos++ = Path::cubicMarker;
  75500. }
  75501. else
  75502. {
  75503. *stackPos++ = y4;
  75504. *stackPos++ = x4;
  75505. *stackPos++ = Path::lineMarker;
  75506. *stackPos++ = m5y;
  75507. *stackPos++ = m5x;
  75508. *stackPos++ = Path::lineMarker;
  75509. *stackPos++ = m4y;
  75510. *stackPos++ = m4x;
  75511. *stackPos++ = Path::lineMarker;
  75512. }
  75513. }
  75514. else if (type == Path::closeSubPathMarker)
  75515. {
  75516. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75517. {
  75518. x1 = x2;
  75519. y1 = y2;
  75520. x2 = subPathCloseX;
  75521. y2 = subPathCloseY;
  75522. closesSubPath = true;
  75523. return true;
  75524. }
  75525. }
  75526. else
  75527. {
  75528. jassert (type == Path::moveMarker);
  75529. subPathIndex = -1;
  75530. subPathCloseX = x1 = x2;
  75531. subPathCloseY = y1 = y2;
  75532. }
  75533. }
  75534. }
  75535. #if JUCE_MSVC && JUCE_DEBUG
  75536. #pragma optimize ("", on) // resets optimisations to the project defaults
  75537. #endif
  75538. END_JUCE_NAMESPACE
  75539. /*** End of inlined file: juce_PathIterator.cpp ***/
  75540. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75541. BEGIN_JUCE_NAMESPACE
  75542. PathStrokeType::PathStrokeType (const float strokeThickness,
  75543. const JointStyle jointStyle_,
  75544. const EndCapStyle endStyle_) throw()
  75545. : thickness (strokeThickness),
  75546. jointStyle (jointStyle_),
  75547. endStyle (endStyle_)
  75548. {
  75549. }
  75550. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75551. : thickness (other.thickness),
  75552. jointStyle (other.jointStyle),
  75553. endStyle (other.endStyle)
  75554. {
  75555. }
  75556. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75557. {
  75558. thickness = other.thickness;
  75559. jointStyle = other.jointStyle;
  75560. endStyle = other.endStyle;
  75561. return *this;
  75562. }
  75563. PathStrokeType::~PathStrokeType() throw()
  75564. {
  75565. }
  75566. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75567. {
  75568. return thickness == other.thickness
  75569. && jointStyle == other.jointStyle
  75570. && endStyle == other.endStyle;
  75571. }
  75572. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75573. {
  75574. return ! operator== (other);
  75575. }
  75576. namespace PathStrokeHelpers
  75577. {
  75578. static bool lineIntersection (const float x1, const float y1,
  75579. const float x2, const float y2,
  75580. const float x3, const float y3,
  75581. const float x4, const float y4,
  75582. float& intersectionX,
  75583. float& intersectionY,
  75584. float& distanceBeyondLine1EndSquared) throw()
  75585. {
  75586. if (x2 != x3 || y2 != y3)
  75587. {
  75588. const float dx1 = x2 - x1;
  75589. const float dy1 = y2 - y1;
  75590. const float dx2 = x4 - x3;
  75591. const float dy2 = y4 - y3;
  75592. const float divisor = dx1 * dy2 - dx2 * dy1;
  75593. if (divisor == 0)
  75594. {
  75595. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75596. {
  75597. if (dy1 == 0 && dy2 != 0)
  75598. {
  75599. const float along = (y1 - y3) / dy2;
  75600. intersectionX = x3 + along * dx2;
  75601. intersectionY = y1;
  75602. distanceBeyondLine1EndSquared = intersectionX - x2;
  75603. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75604. if ((x2 > x1) == (intersectionX < x2))
  75605. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75606. return along >= 0 && along <= 1.0f;
  75607. }
  75608. else if (dy2 == 0 && dy1 != 0)
  75609. {
  75610. const float along = (y3 - y1) / dy1;
  75611. intersectionX = x1 + along * dx1;
  75612. intersectionY = y3;
  75613. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75614. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75615. if (along < 1.0f)
  75616. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75617. return along >= 0 && along <= 1.0f;
  75618. }
  75619. else if (dx1 == 0 && dx2 != 0)
  75620. {
  75621. const float along = (x1 - x3) / dx2;
  75622. intersectionX = x1;
  75623. intersectionY = y3 + along * dy2;
  75624. distanceBeyondLine1EndSquared = intersectionY - y2;
  75625. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75626. if ((y2 > y1) == (intersectionY < y2))
  75627. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75628. return along >= 0 && along <= 1.0f;
  75629. }
  75630. else if (dx2 == 0 && dx1 != 0)
  75631. {
  75632. const float along = (x3 - x1) / dx1;
  75633. intersectionX = x3;
  75634. intersectionY = y1 + along * dy1;
  75635. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75636. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75637. if (along < 1.0f)
  75638. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75639. return along >= 0 && along <= 1.0f;
  75640. }
  75641. }
  75642. intersectionX = 0.5f * (x2 + x3);
  75643. intersectionY = 0.5f * (y2 + y3);
  75644. distanceBeyondLine1EndSquared = 0.0f;
  75645. return false;
  75646. }
  75647. else
  75648. {
  75649. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75650. intersectionX = x1 + along1 * dx1;
  75651. intersectionY = y1 + along1 * dy1;
  75652. if (along1 >= 0 && along1 <= 1.0f)
  75653. {
  75654. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75655. if (along2 >= 0 && along2 <= divisor)
  75656. {
  75657. distanceBeyondLine1EndSquared = 0.0f;
  75658. return true;
  75659. }
  75660. }
  75661. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75662. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75663. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75664. if (along1 < 1.0f)
  75665. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75666. return false;
  75667. }
  75668. }
  75669. intersectionX = x2;
  75670. intersectionY = y2;
  75671. distanceBeyondLine1EndSquared = 0.0f;
  75672. return true;
  75673. }
  75674. static void addEdgeAndJoint (Path& destPath,
  75675. const PathStrokeType::JointStyle style,
  75676. const float maxMiterExtensionSquared, const float width,
  75677. const float x1, const float y1,
  75678. const float x2, const float y2,
  75679. const float x3, const float y3,
  75680. const float x4, const float y4,
  75681. const float midX, const float midY)
  75682. {
  75683. if (style == PathStrokeType::beveled
  75684. || (x3 == x4 && y3 == y4)
  75685. || (x1 == x2 && y1 == y2))
  75686. {
  75687. destPath.lineTo (x2, y2);
  75688. destPath.lineTo (x3, y3);
  75689. }
  75690. else
  75691. {
  75692. float jx, jy, distanceBeyondLine1EndSquared;
  75693. // if they intersect, use this point..
  75694. if (lineIntersection (x1, y1, x2, y2,
  75695. x3, y3, x4, y4,
  75696. jx, jy, distanceBeyondLine1EndSquared))
  75697. {
  75698. destPath.lineTo (jx, jy);
  75699. }
  75700. else
  75701. {
  75702. if (style == PathStrokeType::mitered)
  75703. {
  75704. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75705. && distanceBeyondLine1EndSquared > 0.0f)
  75706. {
  75707. destPath.lineTo (jx, jy);
  75708. }
  75709. else
  75710. {
  75711. // the end sticks out too far, so just use a blunt joint
  75712. destPath.lineTo (x2, y2);
  75713. destPath.lineTo (x3, y3);
  75714. }
  75715. }
  75716. else
  75717. {
  75718. // curved joints
  75719. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75720. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75721. const float angleIncrement = 0.1f;
  75722. destPath.lineTo (x2, y2);
  75723. if (std::abs (angle1 - angle2) > angleIncrement)
  75724. {
  75725. if (angle2 > angle1 + float_Pi
  75726. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75727. {
  75728. if (angle2 > angle1)
  75729. angle2 -= float_Pi * 2.0f;
  75730. jassert (angle1 <= angle2 + float_Pi);
  75731. angle1 -= angleIncrement;
  75732. while (angle1 > angle2)
  75733. {
  75734. destPath.lineTo (midX + width * std::sin (angle1),
  75735. midY + width * std::cos (angle1));
  75736. angle1 -= angleIncrement;
  75737. }
  75738. }
  75739. else
  75740. {
  75741. if (angle1 > angle2)
  75742. angle1 -= float_Pi * 2.0f;
  75743. jassert (angle1 >= angle2 - float_Pi);
  75744. angle1 += angleIncrement;
  75745. while (angle1 < angle2)
  75746. {
  75747. destPath.lineTo (midX + width * std::sin (angle1),
  75748. midY + width * std::cos (angle1));
  75749. angle1 += angleIncrement;
  75750. }
  75751. }
  75752. }
  75753. destPath.lineTo (x3, y3);
  75754. }
  75755. }
  75756. }
  75757. }
  75758. static void addLineEnd (Path& destPath,
  75759. const PathStrokeType::EndCapStyle style,
  75760. const float x1, const float y1,
  75761. const float x2, const float y2,
  75762. const float width)
  75763. {
  75764. if (style == PathStrokeType::butt)
  75765. {
  75766. destPath.lineTo (x2, y2);
  75767. }
  75768. else
  75769. {
  75770. float offx1, offy1, offx2, offy2;
  75771. float dx = x2 - x1;
  75772. float dy = y2 - y1;
  75773. const float len = juce_hypotf (dx, dy);
  75774. if (len == 0)
  75775. {
  75776. offx1 = offx2 = x1;
  75777. offy1 = offy2 = y1;
  75778. }
  75779. else
  75780. {
  75781. const float offset = width / len;
  75782. dx *= offset;
  75783. dy *= offset;
  75784. offx1 = x1 + dy;
  75785. offy1 = y1 - dx;
  75786. offx2 = x2 + dy;
  75787. offy2 = y2 - dx;
  75788. }
  75789. if (style == PathStrokeType::square)
  75790. {
  75791. // sqaure ends
  75792. destPath.lineTo (offx1, offy1);
  75793. destPath.lineTo (offx2, offy2);
  75794. destPath.lineTo (x2, y2);
  75795. }
  75796. else
  75797. {
  75798. // rounded ends
  75799. const float midx = (offx1 + offx2) * 0.5f;
  75800. const float midy = (offy1 + offy2) * 0.5f;
  75801. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75802. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75803. midx, midy);
  75804. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75805. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75806. x2, y2);
  75807. }
  75808. }
  75809. }
  75810. struct Arrowhead
  75811. {
  75812. float startWidth, startLength;
  75813. float endWidth, endLength;
  75814. };
  75815. static void addArrowhead (Path& destPath,
  75816. const float x1, const float y1,
  75817. const float x2, const float y2,
  75818. const float tipX, const float tipY,
  75819. const float width,
  75820. const float arrowheadWidth)
  75821. {
  75822. Line<float> line (x1, y1, x2, y2);
  75823. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75824. destPath.lineTo (tipX, tipY);
  75825. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75826. destPath.lineTo (x2, y2);
  75827. }
  75828. struct LineSection
  75829. {
  75830. float x1, y1, x2, y2; // original line
  75831. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75832. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75833. };
  75834. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75835. {
  75836. while (amountAtEnd > 0 && subPath.size() > 0)
  75837. {
  75838. LineSection& l = subPath.getReference (subPath.size() - 1);
  75839. float dx = l.rx2 - l.rx1;
  75840. float dy = l.ry2 - l.ry1;
  75841. const float len = juce_hypotf (dx, dy);
  75842. if (len <= amountAtEnd && subPath.size() > 1)
  75843. {
  75844. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75845. prev.x2 = l.x2;
  75846. prev.y2 = l.y2;
  75847. subPath.removeLast();
  75848. amountAtEnd -= len;
  75849. }
  75850. else
  75851. {
  75852. const float prop = jmin (0.9999f, amountAtEnd / len);
  75853. dx *= prop;
  75854. dy *= prop;
  75855. l.rx1 += dx;
  75856. l.ry1 += dy;
  75857. l.lx2 += dx;
  75858. l.ly2 += dy;
  75859. break;
  75860. }
  75861. }
  75862. while (amountAtStart > 0 && subPath.size() > 0)
  75863. {
  75864. LineSection& l = subPath.getReference (0);
  75865. float dx = l.rx2 - l.rx1;
  75866. float dy = l.ry2 - l.ry1;
  75867. const float len = juce_hypotf (dx, dy);
  75868. if (len <= amountAtStart && subPath.size() > 1)
  75869. {
  75870. LineSection& next = subPath.getReference (1);
  75871. next.x1 = l.x1;
  75872. next.y1 = l.y1;
  75873. subPath.remove (0);
  75874. amountAtStart -= len;
  75875. }
  75876. else
  75877. {
  75878. const float prop = jmin (0.9999f, amountAtStart / len);
  75879. dx *= prop;
  75880. dy *= prop;
  75881. l.rx2 -= dx;
  75882. l.ry2 -= dy;
  75883. l.lx1 -= dx;
  75884. l.ly1 -= dy;
  75885. break;
  75886. }
  75887. }
  75888. }
  75889. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75890. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75891. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75892. const Arrowhead* const arrowhead)
  75893. {
  75894. jassert (subPath.size() > 0);
  75895. if (arrowhead != 0)
  75896. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75897. const LineSection& firstLine = subPath.getReference (0);
  75898. float lastX1 = firstLine.lx1;
  75899. float lastY1 = firstLine.ly1;
  75900. float lastX2 = firstLine.lx2;
  75901. float lastY2 = firstLine.ly2;
  75902. if (isClosed)
  75903. {
  75904. destPath.startNewSubPath (lastX1, lastY1);
  75905. }
  75906. else
  75907. {
  75908. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75909. if (arrowhead != 0)
  75910. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75911. width, arrowhead->startWidth);
  75912. else
  75913. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75914. }
  75915. int i;
  75916. for (i = 1; i < subPath.size(); ++i)
  75917. {
  75918. const LineSection& l = subPath.getReference (i);
  75919. addEdgeAndJoint (destPath, jointStyle,
  75920. maxMiterExtensionSquared, width,
  75921. lastX1, lastY1, lastX2, lastY2,
  75922. l.lx1, l.ly1, l.lx2, l.ly2,
  75923. l.x1, l.y1);
  75924. lastX1 = l.lx1;
  75925. lastY1 = l.ly1;
  75926. lastX2 = l.lx2;
  75927. lastY2 = l.ly2;
  75928. }
  75929. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75930. if (isClosed)
  75931. {
  75932. const LineSection& l = subPath.getReference (0);
  75933. addEdgeAndJoint (destPath, jointStyle,
  75934. maxMiterExtensionSquared, width,
  75935. lastX1, lastY1, lastX2, lastY2,
  75936. l.lx1, l.ly1, l.lx2, l.ly2,
  75937. l.x1, l.y1);
  75938. destPath.closeSubPath();
  75939. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75940. }
  75941. else
  75942. {
  75943. destPath.lineTo (lastX2, lastY2);
  75944. if (arrowhead != 0)
  75945. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75946. width, arrowhead->endWidth);
  75947. else
  75948. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75949. }
  75950. lastX1 = lastLine.rx1;
  75951. lastY1 = lastLine.ry1;
  75952. lastX2 = lastLine.rx2;
  75953. lastY2 = lastLine.ry2;
  75954. for (i = subPath.size() - 1; --i >= 0;)
  75955. {
  75956. const LineSection& l = subPath.getReference (i);
  75957. addEdgeAndJoint (destPath, jointStyle,
  75958. maxMiterExtensionSquared, width,
  75959. lastX1, lastY1, lastX2, lastY2,
  75960. l.rx1, l.ry1, l.rx2, l.ry2,
  75961. l.x2, l.y2);
  75962. lastX1 = l.rx1;
  75963. lastY1 = l.ry1;
  75964. lastX2 = l.rx2;
  75965. lastY2 = l.ry2;
  75966. }
  75967. if (isClosed)
  75968. {
  75969. addEdgeAndJoint (destPath, jointStyle,
  75970. maxMiterExtensionSquared, width,
  75971. lastX1, lastY1, lastX2, lastY2,
  75972. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  75973. lastLine.x2, lastLine.y2);
  75974. }
  75975. else
  75976. {
  75977. // do the last line
  75978. destPath.lineTo (lastX2, lastY2);
  75979. }
  75980. destPath.closeSubPath();
  75981. }
  75982. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  75983. const PathStrokeType::EndCapStyle endStyle,
  75984. Path& destPath, const Path& source,
  75985. const AffineTransform& transform,
  75986. const float extraAccuracy, const Arrowhead* const arrowhead)
  75987. {
  75988. if (thickness <= 0)
  75989. {
  75990. destPath.clear();
  75991. return;
  75992. }
  75993. const Path* sourcePath = &source;
  75994. Path temp;
  75995. if (sourcePath == &destPath)
  75996. {
  75997. destPath.swapWithPath (temp);
  75998. sourcePath = &temp;
  75999. }
  76000. else
  76001. {
  76002. destPath.clear();
  76003. }
  76004. destPath.setUsingNonZeroWinding (true);
  76005. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76006. const float width = 0.5f * thickness;
  76007. // Iterate the path, creating a list of the
  76008. // left/right-hand lines along either side of it...
  76009. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  76010. Array <LineSection> subPath;
  76011. subPath.ensureStorageAllocated (512);
  76012. LineSection l;
  76013. l.x1 = 0;
  76014. l.y1 = 0;
  76015. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  76016. while (it.next())
  76017. {
  76018. if (it.subPathIndex == 0)
  76019. {
  76020. if (subPath.size() > 0)
  76021. {
  76022. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76023. subPath.clearQuick();
  76024. }
  76025. l.x1 = it.x1;
  76026. l.y1 = it.y1;
  76027. }
  76028. l.x2 = it.x2;
  76029. l.y2 = it.y2;
  76030. float dx = l.x2 - l.x1;
  76031. float dy = l.y2 - l.y1;
  76032. const float hypotSquared = dx*dx + dy*dy;
  76033. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76034. {
  76035. const float len = std::sqrt (hypotSquared);
  76036. if (len == 0)
  76037. {
  76038. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76039. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76040. }
  76041. else
  76042. {
  76043. const float offset = width / len;
  76044. dx *= offset;
  76045. dy *= offset;
  76046. l.rx2 = l.x1 - dy;
  76047. l.ry2 = l.y1 + dx;
  76048. l.lx1 = l.x1 + dy;
  76049. l.ly1 = l.y1 - dx;
  76050. l.lx2 = l.x2 + dy;
  76051. l.ly2 = l.y2 - dx;
  76052. l.rx1 = l.x2 - dy;
  76053. l.ry1 = l.y2 + dx;
  76054. }
  76055. subPath.add (l);
  76056. if (it.closesSubPath)
  76057. {
  76058. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76059. subPath.clearQuick();
  76060. }
  76061. else
  76062. {
  76063. l.x1 = it.x2;
  76064. l.y1 = it.y2;
  76065. }
  76066. }
  76067. }
  76068. if (subPath.size() > 0)
  76069. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76070. }
  76071. }
  76072. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76073. const AffineTransform& transform, const float extraAccuracy) const
  76074. {
  76075. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76076. transform, extraAccuracy, 0);
  76077. }
  76078. void PathStrokeType::createDashedStroke (Path& destPath,
  76079. const Path& sourcePath,
  76080. const float* dashLengths,
  76081. int numDashLengths,
  76082. const AffineTransform& transform,
  76083. const float extraAccuracy) const
  76084. {
  76085. if (thickness <= 0)
  76086. return;
  76087. // this should really be an even number..
  76088. jassert ((numDashLengths & 1) == 0);
  76089. Path newDestPath;
  76090. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  76091. bool first = true;
  76092. int dashNum = 0;
  76093. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76094. float dx = 0.0f, dy = 0.0f;
  76095. for (;;)
  76096. {
  76097. const bool isSolid = ((dashNum & 1) == 0);
  76098. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76099. jassert (dashLen > 0); // must be a positive increment!
  76100. if (dashLen <= 0)
  76101. break;
  76102. pos += dashLen;
  76103. while (pos > lineEndPos)
  76104. {
  76105. if (! it.next())
  76106. {
  76107. if (isSolid && ! first)
  76108. newDestPath.lineTo (it.x2, it.y2);
  76109. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76110. return;
  76111. }
  76112. if (isSolid && ! first)
  76113. newDestPath.lineTo (it.x1, it.y1);
  76114. else
  76115. newDestPath.startNewSubPath (it.x1, it.y1);
  76116. dx = it.x2 - it.x1;
  76117. dy = it.y2 - it.y1;
  76118. lineLen = juce_hypotf (dx, dy);
  76119. lineEndPos += lineLen;
  76120. first = it.closesSubPath;
  76121. }
  76122. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76123. if (isSolid)
  76124. newDestPath.lineTo (it.x1 + dx * alpha,
  76125. it.y1 + dy * alpha);
  76126. else
  76127. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76128. it.y1 + dy * alpha);
  76129. }
  76130. }
  76131. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76132. const Path& sourcePath,
  76133. const float arrowheadStartWidth, const float arrowheadStartLength,
  76134. const float arrowheadEndWidth, const float arrowheadEndLength,
  76135. const AffineTransform& transform,
  76136. const float extraAccuracy) const
  76137. {
  76138. PathStrokeHelpers::Arrowhead head;
  76139. head.startWidth = arrowheadStartWidth;
  76140. head.startLength = arrowheadStartLength;
  76141. head.endWidth = arrowheadEndWidth;
  76142. head.endLength = arrowheadEndLength;
  76143. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76144. destPath, sourcePath, transform, extraAccuracy, &head);
  76145. }
  76146. END_JUCE_NAMESPACE
  76147. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76148. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76149. BEGIN_JUCE_NAMESPACE
  76150. PositionedRectangle::PositionedRectangle() throw()
  76151. : x (0.0),
  76152. y (0.0),
  76153. w (0.0),
  76154. h (0.0),
  76155. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76156. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76157. wMode (absoluteSize),
  76158. hMode (absoluteSize)
  76159. {
  76160. }
  76161. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76162. : x (other.x),
  76163. y (other.y),
  76164. w (other.w),
  76165. h (other.h),
  76166. xMode (other.xMode),
  76167. yMode (other.yMode),
  76168. wMode (other.wMode),
  76169. hMode (other.hMode)
  76170. {
  76171. }
  76172. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76173. {
  76174. x = other.x;
  76175. y = other.y;
  76176. w = other.w;
  76177. h = other.h;
  76178. xMode = other.xMode;
  76179. yMode = other.yMode;
  76180. wMode = other.wMode;
  76181. hMode = other.hMode;
  76182. return *this;
  76183. }
  76184. PositionedRectangle::~PositionedRectangle() throw()
  76185. {
  76186. }
  76187. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76188. {
  76189. return x == other.x
  76190. && y == other.y
  76191. && w == other.w
  76192. && h == other.h
  76193. && xMode == other.xMode
  76194. && yMode == other.yMode
  76195. && wMode == other.wMode
  76196. && hMode == other.hMode;
  76197. }
  76198. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76199. {
  76200. return ! operator== (other);
  76201. }
  76202. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76203. {
  76204. StringArray tokens;
  76205. tokens.addTokens (stringVersion, false);
  76206. decodePosString (tokens [0], xMode, x);
  76207. decodePosString (tokens [1], yMode, y);
  76208. decodeSizeString (tokens [2], wMode, w);
  76209. decodeSizeString (tokens [3], hMode, h);
  76210. }
  76211. const String PositionedRectangle::toString() const throw()
  76212. {
  76213. String s;
  76214. s.preallocateStorage (12);
  76215. addPosDescription (s, xMode, x);
  76216. s << ' ';
  76217. addPosDescription (s, yMode, y);
  76218. s << ' ';
  76219. addSizeDescription (s, wMode, w);
  76220. s << ' ';
  76221. addSizeDescription (s, hMode, h);
  76222. return s;
  76223. }
  76224. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76225. {
  76226. jassert (! target.isEmpty());
  76227. double x_, y_, w_, h_;
  76228. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76229. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76230. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76231. roundToInt (w_), roundToInt (h_));
  76232. }
  76233. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76234. double& x_, double& y_,
  76235. double& w_, double& h_) const throw()
  76236. {
  76237. jassert (! target.isEmpty());
  76238. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76239. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76240. }
  76241. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76242. {
  76243. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76244. }
  76245. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76246. const Rectangle<int>& target) throw()
  76247. {
  76248. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76249. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76250. }
  76251. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76252. const double newW, const double newH,
  76253. const Rectangle<int>& target) throw()
  76254. {
  76255. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76256. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76257. }
  76258. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76259. {
  76260. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76261. updateFrom (comp.getBounds(), Rectangle<int>());
  76262. else
  76263. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76264. }
  76265. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76266. {
  76267. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76268. }
  76269. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76270. {
  76271. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76272. | absoluteFromParentBottomRight
  76273. | absoluteFromParentCentre
  76274. | proportionOfParentSize));
  76275. }
  76276. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76277. {
  76278. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76279. }
  76280. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76281. {
  76282. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76283. | absoluteFromParentBottomRight
  76284. | absoluteFromParentCentre
  76285. | proportionOfParentSize));
  76286. }
  76287. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76288. {
  76289. return (SizeMode) wMode;
  76290. }
  76291. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76292. {
  76293. return (SizeMode) hMode;
  76294. }
  76295. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76296. const PositionMode xMode_,
  76297. const AnchorPoint yAnchor,
  76298. const PositionMode yMode_,
  76299. const SizeMode widthMode,
  76300. const SizeMode heightMode,
  76301. const Rectangle<int>& target) throw()
  76302. {
  76303. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76304. {
  76305. double tx, tw;
  76306. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76307. xMode = (uint8) (xAnchor | xMode_);
  76308. wMode = (uint8) widthMode;
  76309. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76310. }
  76311. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76312. {
  76313. double ty, th;
  76314. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76315. yMode = (uint8) (yAnchor | yMode_);
  76316. hMode = (uint8) heightMode;
  76317. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76318. }
  76319. }
  76320. bool PositionedRectangle::isPositionAbsolute() const throw()
  76321. {
  76322. return xMode == absoluteFromParentTopLeft
  76323. && yMode == absoluteFromParentTopLeft
  76324. && wMode == absoluteSize
  76325. && hMode == absoluteSize;
  76326. }
  76327. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76328. {
  76329. if ((mode & proportionOfParentSize) != 0)
  76330. {
  76331. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76332. }
  76333. else
  76334. {
  76335. s << (roundToInt (value * 100.0) / 100.0);
  76336. if ((mode & absoluteFromParentBottomRight) != 0)
  76337. s << 'R';
  76338. else if ((mode & absoluteFromParentCentre) != 0)
  76339. s << 'C';
  76340. }
  76341. if ((mode & anchorAtRightOrBottom) != 0)
  76342. s << 'r';
  76343. else if ((mode & anchorAtCentre) != 0)
  76344. s << 'c';
  76345. }
  76346. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76347. {
  76348. if (mode == proportionalSize)
  76349. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76350. else if (mode == parentSizeMinusAbsolute)
  76351. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76352. else
  76353. s << (roundToInt (value * 100.0) / 100.0);
  76354. }
  76355. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76356. {
  76357. if (s.containsChar ('r'))
  76358. mode = anchorAtRightOrBottom;
  76359. else if (s.containsChar ('c'))
  76360. mode = anchorAtCentre;
  76361. else
  76362. mode = anchorAtLeftOrTop;
  76363. if (s.containsChar ('%'))
  76364. {
  76365. mode |= proportionOfParentSize;
  76366. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76367. }
  76368. else
  76369. {
  76370. if (s.containsChar ('R'))
  76371. mode |= absoluteFromParentBottomRight;
  76372. else if (s.containsChar ('C'))
  76373. mode |= absoluteFromParentCentre;
  76374. else
  76375. mode |= absoluteFromParentTopLeft;
  76376. value = s.removeCharacters ("rcRC").getDoubleValue();
  76377. }
  76378. }
  76379. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76380. {
  76381. if (s.containsChar ('%'))
  76382. {
  76383. mode = proportionalSize;
  76384. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76385. }
  76386. else if (s.containsChar ('M'))
  76387. {
  76388. mode = parentSizeMinusAbsolute;
  76389. value = s.getDoubleValue();
  76390. }
  76391. else
  76392. {
  76393. mode = absoluteSize;
  76394. value = s.getDoubleValue();
  76395. }
  76396. }
  76397. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76398. const double x_, const double w_,
  76399. const uint8 xMode_, const uint8 wMode_,
  76400. const int parentPos,
  76401. const int parentSize) const throw()
  76402. {
  76403. if (wMode_ == proportionalSize)
  76404. wOut = roundToInt (w_ * parentSize);
  76405. else if (wMode_ == parentSizeMinusAbsolute)
  76406. wOut = jmax (0, parentSize - roundToInt (w_));
  76407. else
  76408. wOut = roundToInt (w_);
  76409. if ((xMode_ & proportionOfParentSize) != 0)
  76410. xOut = parentPos + x_ * parentSize;
  76411. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76412. xOut = (parentPos + parentSize) - x_;
  76413. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76414. xOut = x_ + (parentPos + parentSize / 2);
  76415. else
  76416. xOut = x_ + parentPos;
  76417. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76418. xOut -= wOut;
  76419. else if ((xMode_ & anchorAtCentre) != 0)
  76420. xOut -= wOut / 2;
  76421. }
  76422. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76423. double x_, const double w_,
  76424. const uint8 xMode_, const uint8 wMode_,
  76425. const int parentPos,
  76426. const int parentSize) const throw()
  76427. {
  76428. if (wMode_ == proportionalSize)
  76429. {
  76430. if (parentSize > 0)
  76431. wOut = w_ / parentSize;
  76432. }
  76433. else if (wMode_ == parentSizeMinusAbsolute)
  76434. wOut = parentSize - w_;
  76435. else
  76436. wOut = w_;
  76437. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76438. x_ += w_;
  76439. else if ((xMode_ & anchorAtCentre) != 0)
  76440. x_ += w_ / 2;
  76441. if ((xMode_ & proportionOfParentSize) != 0)
  76442. {
  76443. if (parentSize > 0)
  76444. xOut = (x_ - parentPos) / parentSize;
  76445. }
  76446. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76447. xOut = (parentPos + parentSize) - x_;
  76448. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76449. xOut = x_ - (parentPos + parentSize / 2);
  76450. else
  76451. xOut = x_ - parentPos;
  76452. }
  76453. END_JUCE_NAMESPACE
  76454. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76455. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76456. BEGIN_JUCE_NAMESPACE
  76457. RectangleList::RectangleList() throw()
  76458. {
  76459. }
  76460. RectangleList::RectangleList (const Rectangle<int>& rect)
  76461. {
  76462. if (! rect.isEmpty())
  76463. rects.add (rect);
  76464. }
  76465. RectangleList::RectangleList (const RectangleList& other)
  76466. : rects (other.rects)
  76467. {
  76468. }
  76469. RectangleList& RectangleList::operator= (const RectangleList& other)
  76470. {
  76471. rects = other.rects;
  76472. return *this;
  76473. }
  76474. RectangleList::~RectangleList()
  76475. {
  76476. }
  76477. void RectangleList::clear()
  76478. {
  76479. rects.clearQuick();
  76480. }
  76481. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76482. {
  76483. if (((unsigned int) index) < (unsigned int) rects.size())
  76484. return rects.getReference (index);
  76485. return Rectangle<int>();
  76486. }
  76487. bool RectangleList::isEmpty() const throw()
  76488. {
  76489. return rects.size() == 0;
  76490. }
  76491. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76492. : current (0),
  76493. owner (list),
  76494. index (list.rects.size())
  76495. {
  76496. }
  76497. RectangleList::Iterator::~Iterator()
  76498. {
  76499. }
  76500. bool RectangleList::Iterator::next() throw()
  76501. {
  76502. if (--index >= 0)
  76503. {
  76504. current = & (owner.rects.getReference (index));
  76505. return true;
  76506. }
  76507. return false;
  76508. }
  76509. void RectangleList::add (const Rectangle<int>& rect)
  76510. {
  76511. if (! rect.isEmpty())
  76512. {
  76513. if (rects.size() == 0)
  76514. {
  76515. rects.add (rect);
  76516. }
  76517. else
  76518. {
  76519. bool anyOverlaps = false;
  76520. int i;
  76521. for (i = rects.size(); --i >= 0;)
  76522. {
  76523. Rectangle<int>& ourRect = rects.getReference (i);
  76524. if (rect.intersects (ourRect))
  76525. {
  76526. if (rect.contains (ourRect))
  76527. rects.remove (i);
  76528. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76529. anyOverlaps = true;
  76530. }
  76531. }
  76532. if (anyOverlaps && rects.size() > 0)
  76533. {
  76534. RectangleList r (rect);
  76535. for (i = rects.size(); --i >= 0;)
  76536. {
  76537. const Rectangle<int>& ourRect = rects.getReference (i);
  76538. if (rect.intersects (ourRect))
  76539. {
  76540. r.subtract (ourRect);
  76541. if (r.rects.size() == 0)
  76542. return;
  76543. }
  76544. }
  76545. for (i = r.getNumRectangles(); --i >= 0;)
  76546. rects.add (r.rects.getReference (i));
  76547. }
  76548. else
  76549. {
  76550. rects.add (rect);
  76551. }
  76552. }
  76553. }
  76554. }
  76555. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76556. {
  76557. if (! rect.isEmpty())
  76558. rects.add (rect);
  76559. }
  76560. void RectangleList::add (const int x, const int y, const int w, const int h)
  76561. {
  76562. if (rects.size() == 0)
  76563. {
  76564. if (w > 0 && h > 0)
  76565. rects.add (Rectangle<int> (x, y, w, h));
  76566. }
  76567. else
  76568. {
  76569. add (Rectangle<int> (x, y, w, h));
  76570. }
  76571. }
  76572. void RectangleList::add (const RectangleList& other)
  76573. {
  76574. for (int i = 0; i < other.rects.size(); ++i)
  76575. add (other.rects.getReference (i));
  76576. }
  76577. void RectangleList::subtract (const Rectangle<int>& rect)
  76578. {
  76579. const int originalNumRects = rects.size();
  76580. if (originalNumRects > 0)
  76581. {
  76582. const int x1 = rect.x;
  76583. const int y1 = rect.y;
  76584. const int x2 = x1 + rect.w;
  76585. const int y2 = y1 + rect.h;
  76586. for (int i = getNumRectangles(); --i >= 0;)
  76587. {
  76588. Rectangle<int>& r = rects.getReference (i);
  76589. const int rx1 = r.x;
  76590. const int ry1 = r.y;
  76591. const int rx2 = rx1 + r.w;
  76592. const int ry2 = ry1 + r.h;
  76593. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76594. {
  76595. if (x1 > rx1 && x1 < rx2)
  76596. {
  76597. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76598. {
  76599. r.w = x1 - rx1;
  76600. }
  76601. else
  76602. {
  76603. r.x = x1;
  76604. r.w = rx2 - x1;
  76605. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76606. i += 2;
  76607. }
  76608. }
  76609. else if (x2 > rx1 && x2 < rx2)
  76610. {
  76611. r.x = x2;
  76612. r.w = rx2 - x2;
  76613. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76614. {
  76615. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76616. i += 2;
  76617. }
  76618. }
  76619. else if (y1 > ry1 && y1 < ry2)
  76620. {
  76621. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76622. {
  76623. r.h = y1 - ry1;
  76624. }
  76625. else
  76626. {
  76627. r.y = y1;
  76628. r.h = ry2 - y1;
  76629. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76630. i += 2;
  76631. }
  76632. }
  76633. else if (y2 > ry1 && y2 < ry2)
  76634. {
  76635. r.y = y2;
  76636. r.h = ry2 - y2;
  76637. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76638. {
  76639. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76640. i += 2;
  76641. }
  76642. }
  76643. else
  76644. {
  76645. rects.remove (i);
  76646. }
  76647. }
  76648. }
  76649. }
  76650. }
  76651. bool RectangleList::subtract (const RectangleList& otherList)
  76652. {
  76653. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76654. subtract (otherList.rects.getReference (i));
  76655. return rects.size() > 0;
  76656. }
  76657. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76658. {
  76659. bool notEmpty = false;
  76660. if (rect.isEmpty())
  76661. {
  76662. clear();
  76663. }
  76664. else
  76665. {
  76666. for (int i = rects.size(); --i >= 0;)
  76667. {
  76668. Rectangle<int>& r = rects.getReference (i);
  76669. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76670. rects.remove (i);
  76671. else
  76672. notEmpty = true;
  76673. }
  76674. }
  76675. return notEmpty;
  76676. }
  76677. bool RectangleList::clipTo (const RectangleList& other)
  76678. {
  76679. if (rects.size() == 0)
  76680. return false;
  76681. RectangleList result;
  76682. for (int j = 0; j < rects.size(); ++j)
  76683. {
  76684. const Rectangle<int>& rect = rects.getReference (j);
  76685. for (int i = other.rects.size(); --i >= 0;)
  76686. {
  76687. Rectangle<int> r (other.rects.getReference (i));
  76688. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76689. result.rects.add (r);
  76690. }
  76691. }
  76692. swapWith (result);
  76693. return ! isEmpty();
  76694. }
  76695. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76696. {
  76697. destRegion.clear();
  76698. if (! rect.isEmpty())
  76699. {
  76700. for (int i = rects.size(); --i >= 0;)
  76701. {
  76702. Rectangle<int> r (rects.getReference (i));
  76703. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76704. destRegion.rects.add (r);
  76705. }
  76706. }
  76707. return destRegion.rects.size() > 0;
  76708. }
  76709. void RectangleList::swapWith (RectangleList& otherList) throw()
  76710. {
  76711. rects.swapWithArray (otherList.rects);
  76712. }
  76713. void RectangleList::consolidate()
  76714. {
  76715. int i;
  76716. for (i = 0; i < getNumRectangles() - 1; ++i)
  76717. {
  76718. Rectangle<int>& r = rects.getReference (i);
  76719. const int rx1 = r.x;
  76720. const int ry1 = r.y;
  76721. const int rx2 = rx1 + r.w;
  76722. const int ry2 = ry1 + r.h;
  76723. for (int j = rects.size(); --j > i;)
  76724. {
  76725. Rectangle<int>& r2 = rects.getReference (j);
  76726. const int jrx1 = r2.x;
  76727. const int jry1 = r2.y;
  76728. const int jrx2 = jrx1 + r2.w;
  76729. const int jry2 = jry1 + r2.h;
  76730. // if the vertical edges of any blocks are touching and their horizontals don't
  76731. // line up, split them horizontally..
  76732. if (jrx1 == rx2 || jrx2 == rx1)
  76733. {
  76734. if (jry1 > ry1 && jry1 < ry2)
  76735. {
  76736. r.h = jry1 - ry1;
  76737. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76738. i = -1;
  76739. break;
  76740. }
  76741. if (jry2 > ry1 && jry2 < ry2)
  76742. {
  76743. r.h = jry2 - ry1;
  76744. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76745. i = -1;
  76746. break;
  76747. }
  76748. else if (ry1 > jry1 && ry1 < jry2)
  76749. {
  76750. r2.h = ry1 - jry1;
  76751. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76752. i = -1;
  76753. break;
  76754. }
  76755. else if (ry2 > jry1 && ry2 < jry2)
  76756. {
  76757. r2.h = ry2 - jry1;
  76758. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76759. i = -1;
  76760. break;
  76761. }
  76762. }
  76763. }
  76764. }
  76765. for (i = 0; i < rects.size() - 1; ++i)
  76766. {
  76767. Rectangle<int>& r = rects.getReference (i);
  76768. for (int j = rects.size(); --j > i;)
  76769. {
  76770. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76771. {
  76772. rects.remove (j);
  76773. i = -1;
  76774. break;
  76775. }
  76776. }
  76777. }
  76778. }
  76779. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76780. {
  76781. for (int i = getNumRectangles(); --i >= 0;)
  76782. if (rects.getReference (i).contains (x, y))
  76783. return true;
  76784. return false;
  76785. }
  76786. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76787. {
  76788. if (rects.size() > 1)
  76789. {
  76790. RectangleList r (rectangleToCheck);
  76791. for (int i = rects.size(); --i >= 0;)
  76792. {
  76793. r.subtract (rects.getReference (i));
  76794. if (r.rects.size() == 0)
  76795. return true;
  76796. }
  76797. }
  76798. else if (rects.size() > 0)
  76799. {
  76800. return rects.getReference (0).contains (rectangleToCheck);
  76801. }
  76802. return false;
  76803. }
  76804. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76805. {
  76806. for (int i = rects.size(); --i >= 0;)
  76807. if (rects.getReference (i).intersects (rectangleToCheck))
  76808. return true;
  76809. return false;
  76810. }
  76811. bool RectangleList::intersects (const RectangleList& other) const throw()
  76812. {
  76813. for (int i = rects.size(); --i >= 0;)
  76814. if (other.intersectsRectangle (rects.getReference (i)))
  76815. return true;
  76816. return false;
  76817. }
  76818. const Rectangle<int> RectangleList::getBounds() const throw()
  76819. {
  76820. if (rects.size() <= 1)
  76821. {
  76822. if (rects.size() == 0)
  76823. return Rectangle<int>();
  76824. else
  76825. return rects.getReference (0);
  76826. }
  76827. else
  76828. {
  76829. const Rectangle<int>& r = rects.getReference (0);
  76830. int minX = r.x;
  76831. int minY = r.y;
  76832. int maxX = minX + r.w;
  76833. int maxY = minY + r.h;
  76834. for (int i = rects.size(); --i > 0;)
  76835. {
  76836. const Rectangle<int>& r2 = rects.getReference (i);
  76837. minX = jmin (minX, r2.x);
  76838. minY = jmin (minY, r2.y);
  76839. maxX = jmax (maxX, r2.getRight());
  76840. maxY = jmax (maxY, r2.getBottom());
  76841. }
  76842. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76843. }
  76844. }
  76845. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76846. {
  76847. for (int i = rects.size(); --i >= 0;)
  76848. {
  76849. Rectangle<int>& r = rects.getReference (i);
  76850. r.x += dx;
  76851. r.y += dy;
  76852. }
  76853. }
  76854. const Path RectangleList::toPath() const
  76855. {
  76856. Path p;
  76857. for (int i = rects.size(); --i >= 0;)
  76858. {
  76859. const Rectangle<int>& r = rects.getReference (i);
  76860. p.addRectangle ((float) r.x,
  76861. (float) r.y,
  76862. (float) r.w,
  76863. (float) r.h);
  76864. }
  76865. return p;
  76866. }
  76867. END_JUCE_NAMESPACE
  76868. /*** End of inlined file: juce_RectangleList.cpp ***/
  76869. /*** Start of inlined file: juce_Image.cpp ***/
  76870. BEGIN_JUCE_NAMESPACE
  76871. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76872. : format (format_), width (width_), height (height_)
  76873. {
  76874. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76875. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76876. }
  76877. Image::SharedImage::~SharedImage()
  76878. {
  76879. }
  76880. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76881. {
  76882. return imageData + lineStride * y + pixelStride * x;
  76883. }
  76884. class SoftwareSharedImage : public Image::SharedImage
  76885. {
  76886. public:
  76887. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76888. : Image::SharedImage (format_, width_, height_)
  76889. {
  76890. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76891. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76892. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76893. imageData = imageDataAllocated;
  76894. }
  76895. ~SoftwareSharedImage()
  76896. {
  76897. }
  76898. Image::ImageType getType() const
  76899. {
  76900. return Image::SoftwareImage;
  76901. }
  76902. LowLevelGraphicsContext* createLowLevelContext()
  76903. {
  76904. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76905. }
  76906. SharedImage* clone()
  76907. {
  76908. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76909. memcpy (s->imageData, imageData, lineStride * height);
  76910. return s;
  76911. }
  76912. private:
  76913. HeapBlock<uint8> imageDataAllocated;
  76914. };
  76915. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76916. {
  76917. return new SoftwareSharedImage (format, width, height, clearImage);
  76918. }
  76919. class SubsectionSharedImage : public Image::SharedImage
  76920. {
  76921. public:
  76922. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76923. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76924. image (image_), area (area_)
  76925. {
  76926. pixelStride = image_->getPixelStride();
  76927. lineStride = image_->getLineStride();
  76928. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76929. }
  76930. ~SubsectionSharedImage() {}
  76931. Image::ImageType getType() const
  76932. {
  76933. return Image::SoftwareImage;
  76934. }
  76935. LowLevelGraphicsContext* createLowLevelContext()
  76936. {
  76937. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76938. g->clipToRectangle (area);
  76939. g->setOrigin (area.getX(), area.getY());
  76940. return g;
  76941. }
  76942. SharedImage* clone()
  76943. {
  76944. return new SubsectionSharedImage (image->clone(), area);
  76945. }
  76946. private:
  76947. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76948. const Rectangle<int> area;
  76949. SubsectionSharedImage (const SubsectionSharedImage&);
  76950. SubsectionSharedImage& operator= (const SubsectionSharedImage&);
  76951. };
  76952. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76953. {
  76954. if (area.contains (getBounds()))
  76955. return *this;
  76956. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76957. if (validArea.isEmpty())
  76958. return Image::null;
  76959. return Image (new SubsectionSharedImage (image, validArea));
  76960. }
  76961. Image::Image()
  76962. {
  76963. }
  76964. Image::Image (SharedImage* const instance)
  76965. : image (instance)
  76966. {
  76967. }
  76968. Image::Image (const PixelFormat format,
  76969. const int width, const int height,
  76970. const bool clearImage, const ImageType type)
  76971. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76972. : new SoftwareSharedImage (format, width, height, clearImage))
  76973. {
  76974. }
  76975. Image::Image (const Image& other)
  76976. : image (other.image)
  76977. {
  76978. }
  76979. Image& Image::operator= (const Image& other)
  76980. {
  76981. image = other.image;
  76982. return *this;
  76983. }
  76984. Image::~Image()
  76985. {
  76986. }
  76987. const Image Image::null;
  76988. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76989. {
  76990. return image == 0 ? 0 : image->createLowLevelContext();
  76991. }
  76992. void Image::duplicateIfShared()
  76993. {
  76994. if (image != 0 && image->getReferenceCount() > 1)
  76995. image = image->clone();
  76996. }
  76997. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76998. {
  76999. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  77000. return *this;
  77001. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  77002. Graphics g (newImage);
  77003. g.setImageResamplingQuality (quality);
  77004. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  77005. return newImage;
  77006. }
  77007. const Image Image::convertedToFormat (PixelFormat newFormat) const
  77008. {
  77009. if (image == 0 || newFormat == image->format)
  77010. return *this;
  77011. Image newImage (newFormat, image->width, image->height, false, image->getType());
  77012. if (newFormat == SingleChannel)
  77013. {
  77014. if (! hasAlphaChannel())
  77015. {
  77016. newImage.clear (getBounds(), Colours::black);
  77017. }
  77018. else
  77019. {
  77020. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  77021. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  77022. for (int y = 0; y < image->height; ++y)
  77023. {
  77024. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  77025. uint8* dst = destData.getLinePointer (y);
  77026. for (int x = image->width; --x >= 0;)
  77027. {
  77028. *dst++ = src->getAlpha();
  77029. ++src;
  77030. }
  77031. }
  77032. }
  77033. }
  77034. else
  77035. {
  77036. if (hasAlphaChannel())
  77037. newImage.clear (getBounds());
  77038. Graphics g (newImage);
  77039. g.drawImageAt (*this, 0, 0);
  77040. }
  77041. return newImage;
  77042. }
  77043. const var Image::getTag() const
  77044. {
  77045. return image == 0 ? var::null : image->userTag;
  77046. }
  77047. void Image::setTag (const var& newTag)
  77048. {
  77049. if (image != 0)
  77050. image->userTag = newTag;
  77051. }
  77052. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  77053. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77054. pixelFormat (image.getFormat()),
  77055. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77056. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77057. width (w),
  77058. height (h)
  77059. {
  77060. jassert (data != 0);
  77061. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77062. }
  77063. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  77064. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77065. pixelFormat (image.getFormat()),
  77066. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77067. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77068. width (w),
  77069. height (h)
  77070. {
  77071. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77072. }
  77073. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  77074. : data (image.image == 0 ? 0 : image.image->imageData),
  77075. pixelFormat (image.getFormat()),
  77076. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77077. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77078. width (image.getWidth()),
  77079. height (image.getHeight())
  77080. {
  77081. }
  77082. Image::BitmapData::~BitmapData()
  77083. {
  77084. }
  77085. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77086. {
  77087. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77088. const uint8* const pixel = getPixelPointer (x, y);
  77089. switch (pixelFormat)
  77090. {
  77091. case Image::ARGB:
  77092. {
  77093. PixelARGB p (*(const PixelARGB*) pixel);
  77094. p.unpremultiply();
  77095. return Colour (p.getARGB());
  77096. }
  77097. case Image::RGB:
  77098. return Colour (((const PixelRGB*) pixel)->getARGB());
  77099. case Image::SingleChannel:
  77100. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  77101. default:
  77102. jassertfalse;
  77103. break;
  77104. }
  77105. return Colour();
  77106. }
  77107. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77108. {
  77109. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77110. uint8* const pixel = getPixelPointer (x, y);
  77111. const PixelARGB col (colour.getPixelARGB());
  77112. switch (pixelFormat)
  77113. {
  77114. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77115. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77116. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77117. default: jassertfalse; break;
  77118. }
  77119. }
  77120. void Image::setPixelData (int x, int y, int w, int h,
  77121. const uint8* const sourcePixelData, const int sourceLineStride)
  77122. {
  77123. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77124. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77125. {
  77126. const BitmapData dest (*this, x, y, w, h, true);
  77127. for (int i = 0; i < h; ++i)
  77128. {
  77129. memcpy (dest.getLinePointer(i),
  77130. sourcePixelData + sourceLineStride * i,
  77131. w * dest.pixelStride);
  77132. }
  77133. }
  77134. }
  77135. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77136. {
  77137. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77138. if (! clipped.isEmpty())
  77139. {
  77140. const PixelARGB col (colourToClearTo.getPixelARGB());
  77141. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77142. uint8* dest = destData.data;
  77143. int dh = clipped.getHeight();
  77144. while (--dh >= 0)
  77145. {
  77146. uint8* line = dest;
  77147. dest += destData.lineStride;
  77148. if (isARGB())
  77149. {
  77150. for (int x = clipped.getWidth(); --x >= 0;)
  77151. {
  77152. ((PixelARGB*) line)->set (col);
  77153. line += destData.pixelStride;
  77154. }
  77155. }
  77156. else if (isRGB())
  77157. {
  77158. for (int x = clipped.getWidth(); --x >= 0;)
  77159. {
  77160. ((PixelRGB*) line)->set (col);
  77161. line += destData.pixelStride;
  77162. }
  77163. }
  77164. else
  77165. {
  77166. for (int x = clipped.getWidth(); --x >= 0;)
  77167. {
  77168. *line = col.getAlpha();
  77169. line += destData.pixelStride;
  77170. }
  77171. }
  77172. }
  77173. }
  77174. }
  77175. const Colour Image::getPixelAt (const int x, const int y) const
  77176. {
  77177. if (((unsigned int) x) < (unsigned int) getWidth()
  77178. && ((unsigned int) y) < (unsigned int) getHeight())
  77179. {
  77180. const BitmapData srcData (*this, x, y, 1, 1);
  77181. return srcData.getPixelColour (0, 0);
  77182. }
  77183. return Colour();
  77184. }
  77185. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77186. {
  77187. if (((unsigned int) x) < (unsigned int) getWidth()
  77188. && ((unsigned int) y) < (unsigned int) getHeight())
  77189. {
  77190. const BitmapData destData (*this, x, y, 1, 1, true);
  77191. destData.setPixelColour (0, 0, colour);
  77192. }
  77193. }
  77194. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77195. {
  77196. if (((unsigned int) x) < (unsigned int) getWidth()
  77197. && ((unsigned int) y) < (unsigned int) getHeight()
  77198. && hasAlphaChannel())
  77199. {
  77200. const BitmapData destData (*this, x, y, 1, 1, true);
  77201. if (isARGB())
  77202. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77203. else
  77204. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77205. }
  77206. }
  77207. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77208. {
  77209. if (hasAlphaChannel())
  77210. {
  77211. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77212. if (isARGB())
  77213. {
  77214. for (int y = 0; y < destData.height; ++y)
  77215. {
  77216. uint8* p = destData.getLinePointer (y);
  77217. for (int x = 0; x < destData.width; ++x)
  77218. {
  77219. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77220. p += destData.pixelStride;
  77221. }
  77222. }
  77223. }
  77224. else
  77225. {
  77226. for (int y = 0; y < destData.height; ++y)
  77227. {
  77228. uint8* p = destData.getLinePointer (y);
  77229. for (int x = 0; x < destData.width; ++x)
  77230. {
  77231. *p = (uint8) (*p * amountToMultiplyBy);
  77232. p += destData.pixelStride;
  77233. }
  77234. }
  77235. }
  77236. }
  77237. else
  77238. {
  77239. jassertfalse; // can't do this without an alpha-channel!
  77240. }
  77241. }
  77242. void Image::desaturate()
  77243. {
  77244. if (isARGB() || isRGB())
  77245. {
  77246. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77247. if (isARGB())
  77248. {
  77249. for (int y = 0; y < destData.height; ++y)
  77250. {
  77251. uint8* p = destData.getLinePointer (y);
  77252. for (int x = 0; x < destData.width; ++x)
  77253. {
  77254. ((PixelARGB*) p)->desaturate();
  77255. p += destData.pixelStride;
  77256. }
  77257. }
  77258. }
  77259. else
  77260. {
  77261. for (int y = 0; y < destData.height; ++y)
  77262. {
  77263. uint8* p = destData.getLinePointer (y);
  77264. for (int x = 0; x < destData.width; ++x)
  77265. {
  77266. ((PixelRGB*) p)->desaturate();
  77267. p += destData.pixelStride;
  77268. }
  77269. }
  77270. }
  77271. }
  77272. }
  77273. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77274. {
  77275. if (hasAlphaChannel())
  77276. {
  77277. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77278. SparseSet<int> pixelsOnRow;
  77279. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77280. for (int y = 0; y < srcData.height; ++y)
  77281. {
  77282. pixelsOnRow.clear();
  77283. const uint8* lineData = srcData.getLinePointer (y);
  77284. if (isARGB())
  77285. {
  77286. for (int x = 0; x < srcData.width; ++x)
  77287. {
  77288. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77289. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77290. lineData += srcData.pixelStride;
  77291. }
  77292. }
  77293. else
  77294. {
  77295. for (int x = 0; x < srcData.width; ++x)
  77296. {
  77297. if (*lineData >= threshold)
  77298. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77299. lineData += srcData.pixelStride;
  77300. }
  77301. }
  77302. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77303. {
  77304. const Range<int> range (pixelsOnRow.getRange (i));
  77305. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77306. }
  77307. result.consolidate();
  77308. }
  77309. }
  77310. else
  77311. {
  77312. result.add (0, 0, getWidth(), getHeight());
  77313. }
  77314. }
  77315. void Image::moveImageSection (int dx, int dy,
  77316. int sx, int sy,
  77317. int w, int h)
  77318. {
  77319. if (dx < 0)
  77320. {
  77321. w += dx;
  77322. sx -= dx;
  77323. dx = 0;
  77324. }
  77325. if (dy < 0)
  77326. {
  77327. h += dy;
  77328. sy -= dy;
  77329. dy = 0;
  77330. }
  77331. if (sx < 0)
  77332. {
  77333. w += sx;
  77334. dx -= sx;
  77335. sx = 0;
  77336. }
  77337. if (sy < 0)
  77338. {
  77339. h += sy;
  77340. dy -= sy;
  77341. sy = 0;
  77342. }
  77343. const int minX = jmin (dx, sx);
  77344. const int minY = jmin (dy, sy);
  77345. w = jmin (w, getWidth() - jmax (sx, dx));
  77346. h = jmin (h, getHeight() - jmax (sy, dy));
  77347. if (w > 0 && h > 0)
  77348. {
  77349. const int maxX = jmax (dx, sx) + w;
  77350. const int maxY = jmax (dy, sy) + h;
  77351. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77352. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77353. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77354. const int lineSize = destData.pixelStride * w;
  77355. if (dy > sy)
  77356. {
  77357. while (--h >= 0)
  77358. {
  77359. const int offset = h * destData.lineStride;
  77360. memmove (dst + offset, src + offset, lineSize);
  77361. }
  77362. }
  77363. else if (dst != src)
  77364. {
  77365. while (--h >= 0)
  77366. {
  77367. memmove (dst, src, lineSize);
  77368. dst += destData.lineStride;
  77369. src += destData.lineStride;
  77370. }
  77371. }
  77372. }
  77373. }
  77374. END_JUCE_NAMESPACE
  77375. /*** End of inlined file: juce_Image.cpp ***/
  77376. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77377. BEGIN_JUCE_NAMESPACE
  77378. class ImageCache::Pimpl : public Timer,
  77379. public DeletedAtShutdown
  77380. {
  77381. public:
  77382. Pimpl()
  77383. : cacheTimeout (5000)
  77384. {
  77385. }
  77386. ~Pimpl()
  77387. {
  77388. clearSingletonInstance();
  77389. }
  77390. const Image getFromHashCode (const int64 hashCode)
  77391. {
  77392. const ScopedLock sl (lock);
  77393. for (int i = images.size(); --i >= 0;)
  77394. {
  77395. Item* const item = images.getUnchecked(i);
  77396. if (item->hashCode == hashCode)
  77397. return item->image;
  77398. }
  77399. return Image::null;
  77400. }
  77401. void addImageToCache (const Image& image, const int64 hashCode)
  77402. {
  77403. if (image.isValid())
  77404. {
  77405. if (! isTimerRunning())
  77406. startTimer (2000);
  77407. Item* const item = new Item();
  77408. item->hashCode = hashCode;
  77409. item->image = image;
  77410. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77411. const ScopedLock sl (lock);
  77412. images.add (item);
  77413. }
  77414. }
  77415. void timerCallback()
  77416. {
  77417. const uint32 now = Time::getApproximateMillisecondCounter();
  77418. const ScopedLock sl (lock);
  77419. for (int i = images.size(); --i >= 0;)
  77420. {
  77421. Item* const item = images.getUnchecked(i);
  77422. if (item->image.getReferenceCount() <= 1)
  77423. {
  77424. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77425. images.remove (i);
  77426. }
  77427. else
  77428. {
  77429. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77430. }
  77431. }
  77432. if (images.size() == 0)
  77433. stopTimer();
  77434. }
  77435. struct Item
  77436. {
  77437. Image image;
  77438. int64 hashCode;
  77439. uint32 lastUseTime;
  77440. };
  77441. int cacheTimeout;
  77442. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77443. private:
  77444. OwnedArray<Item> images;
  77445. CriticalSection lock;
  77446. Pimpl (const Pimpl&);
  77447. Pimpl& operator= (const Pimpl&);
  77448. };
  77449. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77450. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77451. {
  77452. if (Pimpl::getInstanceWithoutCreating() != 0)
  77453. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77454. return Image::null;
  77455. }
  77456. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77457. {
  77458. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77459. }
  77460. const Image ImageCache::getFromFile (const File& file)
  77461. {
  77462. const int64 hashCode = file.hashCode64();
  77463. Image image (getFromHashCode (hashCode));
  77464. if (image.isNull())
  77465. {
  77466. image = ImageFileFormat::loadFrom (file);
  77467. addImageToCache (image, hashCode);
  77468. }
  77469. return image;
  77470. }
  77471. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77472. {
  77473. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77474. Image image (getFromHashCode (hashCode));
  77475. if (image.isNull())
  77476. {
  77477. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77478. addImageToCache (image, hashCode);
  77479. }
  77480. return image;
  77481. }
  77482. void ImageCache::setCacheTimeout (const int millisecs)
  77483. {
  77484. Pimpl::getInstance()->cacheTimeout = millisecs;
  77485. }
  77486. END_JUCE_NAMESPACE
  77487. /*** End of inlined file: juce_ImageCache.cpp ***/
  77488. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77489. BEGIN_JUCE_NAMESPACE
  77490. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77491. : values (size_ * size_),
  77492. size (size_)
  77493. {
  77494. clear();
  77495. }
  77496. ImageConvolutionKernel::~ImageConvolutionKernel()
  77497. {
  77498. }
  77499. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77500. {
  77501. if (((unsigned int) x) < (unsigned int) size
  77502. && ((unsigned int) y) < (unsigned int) size)
  77503. {
  77504. return values [x + y * size];
  77505. }
  77506. else
  77507. {
  77508. jassertfalse;
  77509. return 0;
  77510. }
  77511. }
  77512. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77513. {
  77514. if (((unsigned int) x) < (unsigned int) size
  77515. && ((unsigned int) y) < (unsigned int) size)
  77516. {
  77517. values [x + y * size] = value;
  77518. }
  77519. else
  77520. {
  77521. jassertfalse;
  77522. }
  77523. }
  77524. void ImageConvolutionKernel::clear()
  77525. {
  77526. for (int i = size * size; --i >= 0;)
  77527. values[i] = 0;
  77528. }
  77529. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77530. {
  77531. double currentTotal = 0.0;
  77532. for (int i = size * size; --i >= 0;)
  77533. currentTotal += values[i];
  77534. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77535. }
  77536. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77537. {
  77538. for (int i = size * size; --i >= 0;)
  77539. values[i] *= multiplier;
  77540. }
  77541. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77542. {
  77543. const double radiusFactor = -1.0 / (radius * radius * 2);
  77544. const int centre = size >> 1;
  77545. for (int y = size; --y >= 0;)
  77546. {
  77547. for (int x = size; --x >= 0;)
  77548. {
  77549. const int cx = x - centre;
  77550. const int cy = y - centre;
  77551. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77552. }
  77553. }
  77554. setOverallSum (1.0f);
  77555. }
  77556. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77557. const Image& sourceImage,
  77558. const Rectangle<int>& destinationArea) const
  77559. {
  77560. if (sourceImage == destImage)
  77561. {
  77562. destImage.duplicateIfShared();
  77563. }
  77564. else
  77565. {
  77566. if (sourceImage.getWidth() != destImage.getWidth()
  77567. || sourceImage.getHeight() != destImage.getHeight()
  77568. || sourceImage.getFormat() != destImage.getFormat())
  77569. {
  77570. jassertfalse;
  77571. return;
  77572. }
  77573. }
  77574. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77575. if (area.isEmpty())
  77576. return;
  77577. const int right = area.getRight();
  77578. const int bottom = area.getBottom();
  77579. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77580. uint8* line = destData.data;
  77581. const Image::BitmapData srcData (sourceImage, false);
  77582. if (destData.pixelStride == 4)
  77583. {
  77584. for (int y = area.getY(); y < bottom; ++y)
  77585. {
  77586. uint8* dest = line;
  77587. line += destData.lineStride;
  77588. for (int x = area.getX(); x < right; ++x)
  77589. {
  77590. float c1 = 0;
  77591. float c2 = 0;
  77592. float c3 = 0;
  77593. float c4 = 0;
  77594. for (int yy = 0; yy < size; ++yy)
  77595. {
  77596. const int sy = y + yy - (size >> 1);
  77597. if (sy >= srcData.height)
  77598. break;
  77599. if (sy >= 0)
  77600. {
  77601. int sx = x - (size >> 1);
  77602. const uint8* src = srcData.getPixelPointer (sx, sy);
  77603. for (int xx = 0; xx < size; ++xx)
  77604. {
  77605. if (sx >= srcData.width)
  77606. break;
  77607. if (sx >= 0)
  77608. {
  77609. const float kernelMult = values [xx + yy * size];
  77610. c1 += kernelMult * *src++;
  77611. c2 += kernelMult * *src++;
  77612. c3 += kernelMult * *src++;
  77613. c4 += kernelMult * *src++;
  77614. }
  77615. else
  77616. {
  77617. src += 4;
  77618. }
  77619. ++sx;
  77620. }
  77621. }
  77622. }
  77623. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77624. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77625. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77626. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77627. }
  77628. }
  77629. }
  77630. else if (destData.pixelStride == 3)
  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. for (int yy = 0; yy < size; ++yy)
  77642. {
  77643. const int sy = y + yy - (size >> 1);
  77644. if (sy >= srcData.height)
  77645. break;
  77646. if (sy >= 0)
  77647. {
  77648. int sx = x - (size >> 1);
  77649. const uint8* src = srcData.getPixelPointer (sx, sy);
  77650. for (int xx = 0; xx < size; ++xx)
  77651. {
  77652. if (sx >= srcData.width)
  77653. break;
  77654. if (sx >= 0)
  77655. {
  77656. const float kernelMult = values [xx + yy * size];
  77657. c1 += kernelMult * *src++;
  77658. c2 += kernelMult * *src++;
  77659. c3 += kernelMult * *src++;
  77660. }
  77661. else
  77662. {
  77663. src += 3;
  77664. }
  77665. ++sx;
  77666. }
  77667. }
  77668. }
  77669. *dest++ = (uint8) roundToInt (c1);
  77670. *dest++ = (uint8) roundToInt (c2);
  77671. *dest++ = (uint8) roundToInt (c3);
  77672. }
  77673. }
  77674. }
  77675. }
  77676. END_JUCE_NAMESPACE
  77677. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77678. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77679. BEGIN_JUCE_NAMESPACE
  77680. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77681. {
  77682. static PNGImageFormat png;
  77683. static JPEGImageFormat jpg;
  77684. static GIFImageFormat gif;
  77685. ImageFileFormat* formats[4];
  77686. int numFormats = 0;
  77687. formats [numFormats++] = &png;
  77688. formats [numFormats++] = &jpg;
  77689. formats [numFormats++] = &gif;
  77690. const int64 streamPos = input.getPosition();
  77691. for (int i = 0; i < numFormats; ++i)
  77692. {
  77693. const bool found = formats[i]->canUnderstand (input);
  77694. input.setPosition (streamPos);
  77695. if (found)
  77696. return formats[i];
  77697. }
  77698. return 0;
  77699. }
  77700. const Image ImageFileFormat::loadFrom (InputStream& input)
  77701. {
  77702. ImageFileFormat* const format = findImageFormatForStream (input);
  77703. if (format != 0)
  77704. return format->decodeImage (input);
  77705. return Image::null;
  77706. }
  77707. const Image ImageFileFormat::loadFrom (const File& file)
  77708. {
  77709. InputStream* const in = file.createInputStream();
  77710. if (in != 0)
  77711. {
  77712. BufferedInputStream b (in, 8192, true);
  77713. return loadFrom (b);
  77714. }
  77715. return Image::null;
  77716. }
  77717. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77718. {
  77719. if (rawData != 0 && numBytes > 4)
  77720. {
  77721. MemoryInputStream stream (rawData, numBytes, false);
  77722. return loadFrom (stream);
  77723. }
  77724. return Image::null;
  77725. }
  77726. END_JUCE_NAMESPACE
  77727. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77728. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77729. BEGIN_JUCE_NAMESPACE
  77730. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77731. const Image juce_loadWithCoreImage (InputStream& input);
  77732. #else
  77733. class GIFLoader
  77734. {
  77735. public:
  77736. GIFLoader (InputStream& in)
  77737. : input (in),
  77738. dataBlockIsZero (false),
  77739. fresh (false),
  77740. finished (false)
  77741. {
  77742. currentBit = lastBit = lastByteIndex = 0;
  77743. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77744. firstcode = oldcode = 0;
  77745. clearCode = end_code = 0;
  77746. int imageWidth, imageHeight;
  77747. int transparent = -1;
  77748. if (! getSizeFromHeader (imageWidth, imageHeight))
  77749. return;
  77750. if ((imageWidth <= 0) || (imageHeight <= 0))
  77751. return;
  77752. unsigned char buf [16];
  77753. if (in.read (buf, 3) != 3)
  77754. return;
  77755. int numColours = 2 << (buf[0] & 7);
  77756. if ((buf[0] & 0x80) != 0)
  77757. readPalette (numColours);
  77758. for (;;)
  77759. {
  77760. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77761. break;
  77762. if (buf[0] == '!')
  77763. {
  77764. if (input.read (buf, 1) != 1)
  77765. break;
  77766. if (processExtension (buf[0], transparent) < 0)
  77767. break;
  77768. continue;
  77769. }
  77770. if (buf[0] != ',')
  77771. continue;
  77772. if (input.read (buf, 9) != 9)
  77773. break;
  77774. imageWidth = makeWord (buf[4], buf[5]);
  77775. imageHeight = makeWord (buf[6], buf[7]);
  77776. numColours = 2 << (buf[8] & 7);
  77777. if ((buf[8] & 0x80) != 0)
  77778. if (! readPalette (numColours))
  77779. break;
  77780. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77781. imageWidth, imageHeight, (transparent >= 0));
  77782. readImage ((buf[8] & 0x40) != 0, transparent);
  77783. break;
  77784. }
  77785. }
  77786. ~GIFLoader() {}
  77787. Image image;
  77788. private:
  77789. InputStream& input;
  77790. uint8 buffer [300];
  77791. uint8 palette [256][4];
  77792. bool dataBlockIsZero, fresh, finished;
  77793. int currentBit, lastBit, lastByteIndex;
  77794. int codeSize, setCodeSize;
  77795. int maxCode, maxCodeSize;
  77796. int firstcode, oldcode;
  77797. int clearCode, end_code;
  77798. enum { maxGifCode = 1 << 12 };
  77799. int table [2] [maxGifCode];
  77800. int stack [2 * maxGifCode];
  77801. int *sp;
  77802. bool getSizeFromHeader (int& w, int& h)
  77803. {
  77804. char b[8];
  77805. if (input.read (b, 6) == 6)
  77806. {
  77807. if ((strncmp ("GIF87a", b, 6) == 0)
  77808. || (strncmp ("GIF89a", b, 6) == 0))
  77809. {
  77810. if (input.read (b, 4) == 4)
  77811. {
  77812. w = makeWord (b[0], b[1]);
  77813. h = makeWord (b[2], b[3]);
  77814. return true;
  77815. }
  77816. }
  77817. }
  77818. return false;
  77819. }
  77820. bool readPalette (const int numCols)
  77821. {
  77822. unsigned char rgb[4];
  77823. for (int i = 0; i < numCols; ++i)
  77824. {
  77825. input.read (rgb, 3);
  77826. palette [i][0] = rgb[0];
  77827. palette [i][1] = rgb[1];
  77828. palette [i][2] = rgb[2];
  77829. palette [i][3] = 0xff;
  77830. }
  77831. return true;
  77832. }
  77833. int readDataBlock (unsigned char* dest)
  77834. {
  77835. unsigned char n;
  77836. if (input.read (&n, 1) == 1)
  77837. {
  77838. dataBlockIsZero = (n == 0);
  77839. if (dataBlockIsZero || (input.read (dest, n) == n))
  77840. return n;
  77841. }
  77842. return -1;
  77843. }
  77844. int processExtension (const int type, int& transparent)
  77845. {
  77846. unsigned char b [300];
  77847. int n = 0;
  77848. if (type == 0xf9)
  77849. {
  77850. n = readDataBlock (b);
  77851. if (n < 0)
  77852. return 1;
  77853. if ((b[0] & 0x1) != 0)
  77854. transparent = b[3];
  77855. }
  77856. do
  77857. {
  77858. n = readDataBlock (b);
  77859. }
  77860. while (n > 0);
  77861. return n;
  77862. }
  77863. int readLZWByte (const bool initialise, const int inputCodeSize)
  77864. {
  77865. int code, incode, i;
  77866. if (initialise)
  77867. {
  77868. setCodeSize = inputCodeSize;
  77869. codeSize = setCodeSize + 1;
  77870. clearCode = 1 << setCodeSize;
  77871. end_code = clearCode + 1;
  77872. maxCodeSize = 2 * clearCode;
  77873. maxCode = clearCode + 2;
  77874. getCode (0, true);
  77875. fresh = true;
  77876. for (i = 0; i < clearCode; ++i)
  77877. {
  77878. table[0][i] = 0;
  77879. table[1][i] = i;
  77880. }
  77881. for (; i < maxGifCode; ++i)
  77882. {
  77883. table[0][i] = 0;
  77884. table[1][i] = 0;
  77885. }
  77886. sp = stack;
  77887. return 0;
  77888. }
  77889. else if (fresh)
  77890. {
  77891. fresh = false;
  77892. do
  77893. {
  77894. firstcode = oldcode
  77895. = getCode (codeSize, false);
  77896. }
  77897. while (firstcode == clearCode);
  77898. return firstcode;
  77899. }
  77900. if (sp > stack)
  77901. return *--sp;
  77902. while ((code = getCode (codeSize, false)) >= 0)
  77903. {
  77904. if (code == clearCode)
  77905. {
  77906. for (i = 0; i < clearCode; ++i)
  77907. {
  77908. table[0][i] = 0;
  77909. table[1][i] = i;
  77910. }
  77911. for (; i < maxGifCode; ++i)
  77912. {
  77913. table[0][i] = 0;
  77914. table[1][i] = 0;
  77915. }
  77916. codeSize = setCodeSize + 1;
  77917. maxCodeSize = 2 * clearCode;
  77918. maxCode = clearCode + 2;
  77919. sp = stack;
  77920. firstcode = oldcode = getCode (codeSize, false);
  77921. return firstcode;
  77922. }
  77923. else if (code == end_code)
  77924. {
  77925. if (dataBlockIsZero)
  77926. return -2;
  77927. unsigned char buf [260];
  77928. int n;
  77929. while ((n = readDataBlock (buf)) > 0)
  77930. {}
  77931. if (n != 0)
  77932. return -2;
  77933. }
  77934. incode = code;
  77935. if (code >= maxCode)
  77936. {
  77937. *sp++ = firstcode;
  77938. code = oldcode;
  77939. }
  77940. while (code >= clearCode)
  77941. {
  77942. *sp++ = table[1][code];
  77943. if (code == table[0][code])
  77944. return -2;
  77945. code = table[0][code];
  77946. }
  77947. *sp++ = firstcode = table[1][code];
  77948. if ((code = maxCode) < maxGifCode)
  77949. {
  77950. table[0][code] = oldcode;
  77951. table[1][code] = firstcode;
  77952. ++maxCode;
  77953. if ((maxCode >= maxCodeSize)
  77954. && (maxCodeSize < maxGifCode))
  77955. {
  77956. maxCodeSize <<= 1;
  77957. ++codeSize;
  77958. }
  77959. }
  77960. oldcode = incode;
  77961. if (sp > stack)
  77962. return *--sp;
  77963. }
  77964. return code;
  77965. }
  77966. int getCode (const int codeSize_, const bool initialise)
  77967. {
  77968. if (initialise)
  77969. {
  77970. currentBit = 0;
  77971. lastBit = 0;
  77972. finished = false;
  77973. return 0;
  77974. }
  77975. if ((currentBit + codeSize_) >= lastBit)
  77976. {
  77977. if (finished)
  77978. return -1;
  77979. buffer[0] = buffer [lastByteIndex - 2];
  77980. buffer[1] = buffer [lastByteIndex - 1];
  77981. const int n = readDataBlock (&buffer[2]);
  77982. if (n == 0)
  77983. finished = true;
  77984. lastByteIndex = 2 + n;
  77985. currentBit = (currentBit - lastBit) + 16;
  77986. lastBit = (2 + n) * 8 ;
  77987. }
  77988. int result = 0;
  77989. int i = currentBit;
  77990. for (int j = 0; j < codeSize_; ++j)
  77991. {
  77992. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77993. ++i;
  77994. }
  77995. currentBit += codeSize_;
  77996. return result;
  77997. }
  77998. bool readImage (const int interlace, const int transparent)
  77999. {
  78000. unsigned char c;
  78001. if (input.read (&c, 1) != 1
  78002. || readLZWByte (true, c) < 0)
  78003. return false;
  78004. if (transparent >= 0)
  78005. {
  78006. palette [transparent][0] = 0;
  78007. palette [transparent][1] = 0;
  78008. palette [transparent][2] = 0;
  78009. palette [transparent][3] = 0;
  78010. }
  78011. int index;
  78012. int xpos = 0, ypos = 0, pass = 0;
  78013. const Image::BitmapData destData (image, true);
  78014. uint8* p = destData.data;
  78015. const bool hasAlpha = image.hasAlphaChannel();
  78016. while ((index = readLZWByte (false, c)) >= 0)
  78017. {
  78018. const uint8* const paletteEntry = palette [index];
  78019. if (hasAlpha)
  78020. {
  78021. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  78022. paletteEntry[0],
  78023. paletteEntry[1],
  78024. paletteEntry[2]);
  78025. ((PixelARGB*) p)->premultiply();
  78026. }
  78027. else
  78028. {
  78029. ((PixelRGB*) p)->setARGB (0,
  78030. paletteEntry[0],
  78031. paletteEntry[1],
  78032. paletteEntry[2]);
  78033. }
  78034. p += destData.pixelStride;
  78035. ++xpos;
  78036. if (xpos == destData.width)
  78037. {
  78038. xpos = 0;
  78039. if (interlace)
  78040. {
  78041. switch (pass)
  78042. {
  78043. case 0:
  78044. case 1: ypos += 8; break;
  78045. case 2: ypos += 4; break;
  78046. case 3: ypos += 2; break;
  78047. }
  78048. while (ypos >= destData.height)
  78049. {
  78050. ++pass;
  78051. switch (pass)
  78052. {
  78053. case 1: ypos = 4; break;
  78054. case 2: ypos = 2; break;
  78055. case 3: ypos = 1; break;
  78056. default: return true;
  78057. }
  78058. }
  78059. }
  78060. else
  78061. {
  78062. ++ypos;
  78063. }
  78064. p = destData.getPixelPointer (xpos, ypos);
  78065. }
  78066. if (ypos >= destData.height)
  78067. break;
  78068. }
  78069. return true;
  78070. }
  78071. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  78072. GIFLoader (const GIFLoader&);
  78073. GIFLoader& operator= (const GIFLoader&);
  78074. };
  78075. #endif
  78076. GIFImageFormat::GIFImageFormat() {}
  78077. GIFImageFormat::~GIFImageFormat() {}
  78078. const String GIFImageFormat::getFormatName() { return "GIF"; }
  78079. bool GIFImageFormat::canUnderstand (InputStream& in)
  78080. {
  78081. char header [4];
  78082. return (in.read (header, sizeof (header)) == sizeof (header))
  78083. && header[0] == 'G'
  78084. && header[1] == 'I'
  78085. && header[2] == 'F';
  78086. }
  78087. const Image GIFImageFormat::decodeImage (InputStream& in)
  78088. {
  78089. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  78090. return juce_loadWithCoreImage (in);
  78091. #else
  78092. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78093. return loader->image;
  78094. #endif
  78095. }
  78096. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78097. {
  78098. jassertfalse; // writing isn't implemented for GIFs!
  78099. return false;
  78100. }
  78101. END_JUCE_NAMESPACE
  78102. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78103. #endif
  78104. //==============================================================================
  78105. // some files include lots of library code, so leave them to the end to avoid cluttering
  78106. // up the build for the clean files.
  78107. #if JUCE_BUILD_CORE
  78108. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78109. namespace zlibNamespace
  78110. {
  78111. #if JUCE_INCLUDE_ZLIB_CODE
  78112. #undef OS_CODE
  78113. #undef fdopen
  78114. /*** Start of inlined file: zlib.h ***/
  78115. #ifndef ZLIB_H
  78116. #define ZLIB_H
  78117. /*** Start of inlined file: zconf.h ***/
  78118. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78119. #ifndef ZCONF_H
  78120. #define ZCONF_H
  78121. // *** Just a few hacks here to make it compile nicely with Juce..
  78122. #define Z_PREFIX 1
  78123. #undef __MACTYPES__
  78124. #ifdef _MSC_VER
  78125. #pragma warning (disable : 4131 4127 4244 4267)
  78126. #endif
  78127. /*
  78128. * If you *really* need a unique prefix for all types and library functions,
  78129. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78130. */
  78131. #ifdef Z_PREFIX
  78132. # define deflateInit_ z_deflateInit_
  78133. # define deflate z_deflate
  78134. # define deflateEnd z_deflateEnd
  78135. # define inflateInit_ z_inflateInit_
  78136. # define inflate z_inflate
  78137. # define inflateEnd z_inflateEnd
  78138. # define inflatePrime z_inflatePrime
  78139. # define inflateGetHeader z_inflateGetHeader
  78140. # define adler32_combine z_adler32_combine
  78141. # define crc32_combine z_crc32_combine
  78142. # define deflateInit2_ z_deflateInit2_
  78143. # define deflateSetDictionary z_deflateSetDictionary
  78144. # define deflateCopy z_deflateCopy
  78145. # define deflateReset z_deflateReset
  78146. # define deflateParams z_deflateParams
  78147. # define deflateBound z_deflateBound
  78148. # define deflatePrime z_deflatePrime
  78149. # define inflateInit2_ z_inflateInit2_
  78150. # define inflateSetDictionary z_inflateSetDictionary
  78151. # define inflateSync z_inflateSync
  78152. # define inflateSyncPoint z_inflateSyncPoint
  78153. # define inflateCopy z_inflateCopy
  78154. # define inflateReset z_inflateReset
  78155. # define inflateBack z_inflateBack
  78156. # define inflateBackEnd z_inflateBackEnd
  78157. # define compress z_compress
  78158. # define compress2 z_compress2
  78159. # define compressBound z_compressBound
  78160. # define uncompress z_uncompress
  78161. # define adler32 z_adler32
  78162. # define crc32 z_crc32
  78163. # define get_crc_table z_get_crc_table
  78164. # define zError z_zError
  78165. # define alloc_func z_alloc_func
  78166. # define free_func z_free_func
  78167. # define in_func z_in_func
  78168. # define out_func z_out_func
  78169. # define Byte z_Byte
  78170. # define uInt z_uInt
  78171. # define uLong z_uLong
  78172. # define Bytef z_Bytef
  78173. # define charf z_charf
  78174. # define intf z_intf
  78175. # define uIntf z_uIntf
  78176. # define uLongf z_uLongf
  78177. # define voidpf z_voidpf
  78178. # define voidp z_voidp
  78179. #endif
  78180. #if defined(__MSDOS__) && !defined(MSDOS)
  78181. # define MSDOS
  78182. #endif
  78183. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78184. # define OS2
  78185. #endif
  78186. #if defined(_WINDOWS) && !defined(WINDOWS)
  78187. # define WINDOWS
  78188. #endif
  78189. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78190. # ifndef WIN32
  78191. # define WIN32
  78192. # endif
  78193. #endif
  78194. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78195. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78196. # ifndef SYS16BIT
  78197. # define SYS16BIT
  78198. # endif
  78199. # endif
  78200. #endif
  78201. /*
  78202. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78203. * than 64k bytes at a time (needed on systems with 16-bit int).
  78204. */
  78205. #ifdef SYS16BIT
  78206. # define MAXSEG_64K
  78207. #endif
  78208. #ifdef MSDOS
  78209. # define UNALIGNED_OK
  78210. #endif
  78211. #ifdef __STDC_VERSION__
  78212. # ifndef STDC
  78213. # define STDC
  78214. # endif
  78215. # if __STDC_VERSION__ >= 199901L
  78216. # ifndef STDC99
  78217. # define STDC99
  78218. # endif
  78219. # endif
  78220. #endif
  78221. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78222. # define STDC
  78223. #endif
  78224. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78225. # define STDC
  78226. #endif
  78227. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78228. # define STDC
  78229. #endif
  78230. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78231. # define STDC
  78232. #endif
  78233. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78234. # define STDC
  78235. #endif
  78236. #ifndef STDC
  78237. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78238. # define const /* note: need a more gentle solution here */
  78239. # endif
  78240. #endif
  78241. /* Some Mac compilers merge all .h files incorrectly: */
  78242. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78243. # define NO_DUMMY_DECL
  78244. #endif
  78245. /* Maximum value for memLevel in deflateInit2 */
  78246. #ifndef MAX_MEM_LEVEL
  78247. # ifdef MAXSEG_64K
  78248. # define MAX_MEM_LEVEL 8
  78249. # else
  78250. # define MAX_MEM_LEVEL 9
  78251. # endif
  78252. #endif
  78253. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78254. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78255. * created by gzip. (Files created by minigzip can still be extracted by
  78256. * gzip.)
  78257. */
  78258. #ifndef MAX_WBITS
  78259. # define MAX_WBITS 15 /* 32K LZ77 window */
  78260. #endif
  78261. /* The memory requirements for deflate are (in bytes):
  78262. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78263. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78264. plus a few kilobytes for small objects. For example, if you want to reduce
  78265. the default memory requirements from 256K to 128K, compile with
  78266. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78267. Of course this will generally degrade compression (there's no free lunch).
  78268. The memory requirements for inflate are (in bytes) 1 << windowBits
  78269. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78270. for small objects.
  78271. */
  78272. /* Type declarations */
  78273. #ifndef OF /* function prototypes */
  78274. # ifdef STDC
  78275. # define OF(args) args
  78276. # else
  78277. # define OF(args) ()
  78278. # endif
  78279. #endif
  78280. /* The following definitions for FAR are needed only for MSDOS mixed
  78281. * model programming (small or medium model with some far allocations).
  78282. * This was tested only with MSC; for other MSDOS compilers you may have
  78283. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78284. * just define FAR to be empty.
  78285. */
  78286. #ifdef SYS16BIT
  78287. # if defined(M_I86SM) || defined(M_I86MM)
  78288. /* MSC small or medium model */
  78289. # define SMALL_MEDIUM
  78290. # ifdef _MSC_VER
  78291. # define FAR _far
  78292. # else
  78293. # define FAR far
  78294. # endif
  78295. # endif
  78296. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78297. /* Turbo C small or medium model */
  78298. # define SMALL_MEDIUM
  78299. # ifdef __BORLANDC__
  78300. # define FAR _far
  78301. # else
  78302. # define FAR far
  78303. # endif
  78304. # endif
  78305. #endif
  78306. #if defined(WINDOWS) || defined(WIN32)
  78307. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78308. * This is not mandatory, but it offers a little performance increase.
  78309. */
  78310. # ifdef ZLIB_DLL
  78311. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78312. # ifdef ZLIB_INTERNAL
  78313. # define ZEXTERN extern __declspec(dllexport)
  78314. # else
  78315. # define ZEXTERN extern __declspec(dllimport)
  78316. # endif
  78317. # endif
  78318. # endif /* ZLIB_DLL */
  78319. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78320. * define ZLIB_WINAPI.
  78321. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78322. */
  78323. # ifdef ZLIB_WINAPI
  78324. # ifdef FAR
  78325. # undef FAR
  78326. # endif
  78327. # include <windows.h>
  78328. /* No need for _export, use ZLIB.DEF instead. */
  78329. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78330. # define ZEXPORT WINAPI
  78331. # ifdef WIN32
  78332. # define ZEXPORTVA WINAPIV
  78333. # else
  78334. # define ZEXPORTVA FAR CDECL
  78335. # endif
  78336. # endif
  78337. #endif
  78338. #if defined (__BEOS__)
  78339. # ifdef ZLIB_DLL
  78340. # ifdef ZLIB_INTERNAL
  78341. # define ZEXPORT __declspec(dllexport)
  78342. # define ZEXPORTVA __declspec(dllexport)
  78343. # else
  78344. # define ZEXPORT __declspec(dllimport)
  78345. # define ZEXPORTVA __declspec(dllimport)
  78346. # endif
  78347. # endif
  78348. #endif
  78349. #ifndef ZEXTERN
  78350. # define ZEXTERN extern
  78351. #endif
  78352. #ifndef ZEXPORT
  78353. # define ZEXPORT
  78354. #endif
  78355. #ifndef ZEXPORTVA
  78356. # define ZEXPORTVA
  78357. #endif
  78358. #ifndef FAR
  78359. # define FAR
  78360. #endif
  78361. #if !defined(__MACTYPES__)
  78362. typedef unsigned char Byte; /* 8 bits */
  78363. #endif
  78364. typedef unsigned int uInt; /* 16 bits or more */
  78365. typedef unsigned long uLong; /* 32 bits or more */
  78366. #ifdef SMALL_MEDIUM
  78367. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78368. # define Bytef Byte FAR
  78369. #else
  78370. typedef Byte FAR Bytef;
  78371. #endif
  78372. typedef char FAR charf;
  78373. typedef int FAR intf;
  78374. typedef uInt FAR uIntf;
  78375. typedef uLong FAR uLongf;
  78376. #ifdef STDC
  78377. typedef void const *voidpc;
  78378. typedef void FAR *voidpf;
  78379. typedef void *voidp;
  78380. #else
  78381. typedef Byte const *voidpc;
  78382. typedef Byte FAR *voidpf;
  78383. typedef Byte *voidp;
  78384. #endif
  78385. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78386. # include <sys/types.h> /* for off_t */
  78387. # include <unistd.h> /* for SEEK_* and off_t */
  78388. # ifdef VMS
  78389. # include <unixio.h> /* for off_t */
  78390. # endif
  78391. # define z_off_t off_t
  78392. #endif
  78393. #ifndef SEEK_SET
  78394. # define SEEK_SET 0 /* Seek from beginning of file. */
  78395. # define SEEK_CUR 1 /* Seek from current position. */
  78396. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78397. #endif
  78398. #ifndef z_off_t
  78399. # define z_off_t long
  78400. #endif
  78401. #if defined(__OS400__)
  78402. # define NO_vsnprintf
  78403. #endif
  78404. #if defined(__MVS__)
  78405. # define NO_vsnprintf
  78406. # ifdef FAR
  78407. # undef FAR
  78408. # endif
  78409. #endif
  78410. /* MVS linker does not support external names larger than 8 bytes */
  78411. #if defined(__MVS__)
  78412. # pragma map(deflateInit_,"DEIN")
  78413. # pragma map(deflateInit2_,"DEIN2")
  78414. # pragma map(deflateEnd,"DEEND")
  78415. # pragma map(deflateBound,"DEBND")
  78416. # pragma map(inflateInit_,"ININ")
  78417. # pragma map(inflateInit2_,"ININ2")
  78418. # pragma map(inflateEnd,"INEND")
  78419. # pragma map(inflateSync,"INSY")
  78420. # pragma map(inflateSetDictionary,"INSEDI")
  78421. # pragma map(compressBound,"CMBND")
  78422. # pragma map(inflate_table,"INTABL")
  78423. # pragma map(inflate_fast,"INFA")
  78424. # pragma map(inflate_copyright,"INCOPY")
  78425. #endif
  78426. #endif /* ZCONF_H */
  78427. /*** End of inlined file: zconf.h ***/
  78428. #ifdef __cplusplus
  78429. //extern "C" {
  78430. #endif
  78431. #define ZLIB_VERSION "1.2.3"
  78432. #define ZLIB_VERNUM 0x1230
  78433. /*
  78434. The 'zlib' compression library provides in-memory compression and
  78435. decompression functions, including integrity checks of the uncompressed
  78436. data. This version of the library supports only one compression method
  78437. (deflation) but other algorithms will be added later and will have the same
  78438. stream interface.
  78439. Compression can be done in a single step if the buffers are large
  78440. enough (for example if an input file is mmap'ed), or can be done by
  78441. repeated calls of the compression function. In the latter case, the
  78442. application must provide more input and/or consume the output
  78443. (providing more output space) before each call.
  78444. The compressed data format used by default by the in-memory functions is
  78445. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78446. around a deflate stream, which is itself documented in RFC 1951.
  78447. The library also supports reading and writing files in gzip (.gz) format
  78448. with an interface similar to that of stdio using the functions that start
  78449. with "gz". The gzip format is different from the zlib format. gzip is a
  78450. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78451. This library can optionally read and write gzip streams in memory as well.
  78452. The zlib format was designed to be compact and fast for use in memory
  78453. and on communications channels. The gzip format was designed for single-
  78454. file compression on file systems, has a larger header than zlib to maintain
  78455. directory information, and uses a different, slower check method than zlib.
  78456. The library does not install any signal handler. The decoder checks
  78457. the consistency of the compressed data, so the library should never
  78458. crash even in case of corrupted input.
  78459. */
  78460. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78461. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78462. struct internal_state;
  78463. typedef struct z_stream_s {
  78464. Bytef *next_in; /* next input byte */
  78465. uInt avail_in; /* number of bytes available at next_in */
  78466. uLong total_in; /* total nb of input bytes read so far */
  78467. Bytef *next_out; /* next output byte should be put there */
  78468. uInt avail_out; /* remaining free space at next_out */
  78469. uLong total_out; /* total nb of bytes output so far */
  78470. char *msg; /* last error message, NULL if no error */
  78471. struct internal_state FAR *state; /* not visible by applications */
  78472. alloc_func zalloc; /* used to allocate the internal state */
  78473. free_func zfree; /* used to free the internal state */
  78474. voidpf opaque; /* private data object passed to zalloc and zfree */
  78475. int data_type; /* best guess about the data type: binary or text */
  78476. uLong adler; /* adler32 value of the uncompressed data */
  78477. uLong reserved; /* reserved for future use */
  78478. } z_stream;
  78479. typedef z_stream FAR *z_streamp;
  78480. /*
  78481. gzip header information passed to and from zlib routines. See RFC 1952
  78482. for more details on the meanings of these fields.
  78483. */
  78484. typedef struct gz_header_s {
  78485. int text; /* true if compressed data believed to be text */
  78486. uLong time; /* modification time */
  78487. int xflags; /* extra flags (not used when writing a gzip file) */
  78488. int os; /* operating system */
  78489. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78490. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78491. uInt extra_max; /* space at extra (only when reading header) */
  78492. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78493. uInt name_max; /* space at name (only when reading header) */
  78494. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78495. uInt comm_max; /* space at comment (only when reading header) */
  78496. int hcrc; /* true if there was or will be a header crc */
  78497. int done; /* true when done reading gzip header (not used
  78498. when writing a gzip file) */
  78499. } gz_header;
  78500. typedef gz_header FAR *gz_headerp;
  78501. /*
  78502. The application must update next_in and avail_in when avail_in has
  78503. dropped to zero. It must update next_out and avail_out when avail_out
  78504. has dropped to zero. The application must initialize zalloc, zfree and
  78505. opaque before calling the init function. All other fields are set by the
  78506. compression library and must not be updated by the application.
  78507. The opaque value provided by the application will be passed as the first
  78508. parameter for calls of zalloc and zfree. This can be useful for custom
  78509. memory management. The compression library attaches no meaning to the
  78510. opaque value.
  78511. zalloc must return Z_NULL if there is not enough memory for the object.
  78512. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78513. thread safe.
  78514. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78515. exactly 65536 bytes, but will not be required to allocate more than this
  78516. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78517. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78518. have their offset normalized to zero. The default allocation function
  78519. provided by this library ensures this (see zutil.c). To reduce memory
  78520. requirements and avoid any allocation of 64K objects, at the expense of
  78521. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78522. The fields total_in and total_out can be used for statistics or
  78523. progress reports. After compression, total_in holds the total size of
  78524. the uncompressed data and may be saved for use in the decompressor
  78525. (particularly if the decompressor wants to decompress everything in
  78526. a single step).
  78527. */
  78528. /* constants */
  78529. #define Z_NO_FLUSH 0
  78530. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78531. #define Z_SYNC_FLUSH 2
  78532. #define Z_FULL_FLUSH 3
  78533. #define Z_FINISH 4
  78534. #define Z_BLOCK 5
  78535. /* Allowed flush values; see deflate() and inflate() below for details */
  78536. #define Z_OK 0
  78537. #define Z_STREAM_END 1
  78538. #define Z_NEED_DICT 2
  78539. #define Z_ERRNO (-1)
  78540. #define Z_STREAM_ERROR (-2)
  78541. #define Z_DATA_ERROR (-3)
  78542. #define Z_MEM_ERROR (-4)
  78543. #define Z_BUF_ERROR (-5)
  78544. #define Z_VERSION_ERROR (-6)
  78545. /* Return codes for the compression/decompression functions. Negative
  78546. * values are errors, positive values are used for special but normal events.
  78547. */
  78548. #define Z_NO_COMPRESSION 0
  78549. #define Z_BEST_SPEED 1
  78550. #define Z_BEST_COMPRESSION 9
  78551. #define Z_DEFAULT_COMPRESSION (-1)
  78552. /* compression levels */
  78553. #define Z_FILTERED 1
  78554. #define Z_HUFFMAN_ONLY 2
  78555. #define Z_RLE 3
  78556. #define Z_FIXED 4
  78557. #define Z_DEFAULT_STRATEGY 0
  78558. /* compression strategy; see deflateInit2() below for details */
  78559. #define Z_BINARY 0
  78560. #define Z_TEXT 1
  78561. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78562. #define Z_UNKNOWN 2
  78563. /* Possible values of the data_type field (though see inflate()) */
  78564. #define Z_DEFLATED 8
  78565. /* The deflate compression method (the only one supported in this version) */
  78566. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78567. #define zlib_version zlibVersion()
  78568. /* for compatibility with versions < 1.0.2 */
  78569. /* basic functions */
  78570. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78571. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78572. If the first character differs, the library code actually used is
  78573. not compatible with the zlib.h header file used by the application.
  78574. This check is automatically made by deflateInit and inflateInit.
  78575. */
  78576. /*
  78577. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78578. Initializes the internal stream state for compression. The fields
  78579. zalloc, zfree and opaque must be initialized before by the caller.
  78580. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78581. use default allocation functions.
  78582. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78583. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78584. all (the input data is simply copied a block at a time).
  78585. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78586. compression (currently equivalent to level 6).
  78587. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78588. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78589. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78590. with the version assumed by the caller (ZLIB_VERSION).
  78591. msg is set to null if there is no error message. deflateInit does not
  78592. perform any compression: this will be done by deflate().
  78593. */
  78594. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78595. /*
  78596. deflate compresses as much data as possible, and stops when the input
  78597. buffer becomes empty or the output buffer becomes full. It may introduce some
  78598. output latency (reading input without producing any output) except when
  78599. forced to flush.
  78600. The detailed semantics are as follows. deflate performs one or both of the
  78601. following actions:
  78602. - Compress more input starting at next_in and update next_in and avail_in
  78603. accordingly. If not all input can be processed (because there is not
  78604. enough room in the output buffer), next_in and avail_in are updated and
  78605. processing will resume at this point for the next call of deflate().
  78606. - Provide more output starting at next_out and update next_out and avail_out
  78607. accordingly. This action is forced if the parameter flush is non zero.
  78608. Forcing flush frequently degrades the compression ratio, so this parameter
  78609. should be set only when necessary (in interactive applications).
  78610. Some output may be provided even if flush is not set.
  78611. Before the call of deflate(), the application should ensure that at least
  78612. one of the actions is possible, by providing more input and/or consuming
  78613. more output, and updating avail_in or avail_out accordingly; avail_out
  78614. should never be zero before the call. The application can consume the
  78615. compressed output when it wants, for example when the output buffer is full
  78616. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78617. and with zero avail_out, it must be called again after making room in the
  78618. output buffer because there might be more output pending.
  78619. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78620. decide how much data to accumualte before producing output, in order to
  78621. maximize compression.
  78622. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78623. flushed to the output buffer and the output is aligned on a byte boundary, so
  78624. that the decompressor can get all input data available so far. (In particular
  78625. avail_in is zero after the call if enough output space has been provided
  78626. before the call.) Flushing may degrade compression for some compression
  78627. algorithms and so it should be used only when necessary.
  78628. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78629. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78630. restart from this point if previous compressed data has been damaged or if
  78631. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78632. compression.
  78633. If deflate returns with avail_out == 0, this function must be called again
  78634. with the same value of the flush parameter and more output space (updated
  78635. avail_out), until the flush is complete (deflate returns with non-zero
  78636. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78637. avail_out is greater than six to avoid repeated flush markers due to
  78638. avail_out == 0 on return.
  78639. If the parameter flush is set to Z_FINISH, pending input is processed,
  78640. pending output is flushed and deflate returns with Z_STREAM_END if there
  78641. was enough output space; if deflate returns with Z_OK, this function must be
  78642. called again with Z_FINISH and more output space (updated avail_out) but no
  78643. more input data, until it returns with Z_STREAM_END or an error. After
  78644. deflate has returned Z_STREAM_END, the only possible operations on the
  78645. stream are deflateReset or deflateEnd.
  78646. Z_FINISH can be used immediately after deflateInit if all the compression
  78647. is to be done in a single step. In this case, avail_out must be at least
  78648. the value returned by deflateBound (see below). If deflate does not return
  78649. Z_STREAM_END, then it must be called again as described above.
  78650. deflate() sets strm->adler to the adler32 checksum of all input read
  78651. so far (that is, total_in bytes).
  78652. deflate() may update strm->data_type if it can make a good guess about
  78653. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78654. binary. This field is only for information purposes and does not affect
  78655. the compression algorithm in any manner.
  78656. deflate() returns Z_OK if some progress has been made (more input
  78657. processed or more output produced), Z_STREAM_END if all input has been
  78658. consumed and all output has been produced (only when flush is set to
  78659. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78660. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78661. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78662. fatal, and deflate() can be called again with more input and more output
  78663. space to continue compressing.
  78664. */
  78665. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78666. /*
  78667. All dynamically allocated data structures for this stream are freed.
  78668. This function discards any unprocessed input and does not flush any
  78669. pending output.
  78670. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78671. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78672. prematurely (some input or output was discarded). In the error case,
  78673. msg may be set but then points to a static string (which must not be
  78674. deallocated).
  78675. */
  78676. /*
  78677. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78678. Initializes the internal stream state for decompression. The fields
  78679. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78680. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78681. value depends on the compression method), inflateInit determines the
  78682. compression method from the zlib header and allocates all data structures
  78683. accordingly; otherwise the allocation will be deferred to the first call of
  78684. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78685. use default allocation functions.
  78686. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78687. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78688. version assumed by the caller. msg is set to null if there is no error
  78689. message. inflateInit does not perform any decompression apart from reading
  78690. the zlib header if present: this will be done by inflate(). (So next_in and
  78691. avail_in may be modified, but next_out and avail_out are unchanged.)
  78692. */
  78693. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78694. /*
  78695. inflate decompresses as much data as possible, and stops when the input
  78696. buffer becomes empty or the output buffer becomes full. It may introduce
  78697. some output latency (reading input without producing any output) except when
  78698. forced to flush.
  78699. The detailed semantics are as follows. inflate performs one or both of the
  78700. following actions:
  78701. - Decompress more input starting at next_in and update next_in and avail_in
  78702. accordingly. If not all input can be processed (because there is not
  78703. enough room in the output buffer), next_in is updated and processing
  78704. will resume at this point for the next call of inflate().
  78705. - Provide more output starting at next_out and update next_out and avail_out
  78706. accordingly. inflate() provides as much output as possible, until there
  78707. is no more input data or no more space in the output buffer (see below
  78708. about the flush parameter).
  78709. Before the call of inflate(), the application should ensure that at least
  78710. one of the actions is possible, by providing more input and/or consuming
  78711. more output, and updating the next_* and avail_* values accordingly.
  78712. The application can consume the uncompressed output when it wants, for
  78713. example when the output buffer is full (avail_out == 0), or after each
  78714. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78715. must be called again after making room in the output buffer because there
  78716. might be more output pending.
  78717. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78718. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78719. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78720. if and when it gets to the next deflate block boundary. When decoding the
  78721. zlib or gzip format, this will cause inflate() to return immediately after
  78722. the header and before the first block. When doing a raw inflate, inflate()
  78723. will go ahead and process the first block, and will return when it gets to
  78724. the end of that block, or when it runs out of data.
  78725. The Z_BLOCK option assists in appending to or combining deflate streams.
  78726. Also to assist in this, on return inflate() will set strm->data_type to the
  78727. number of unused bits in the last byte taken from strm->next_in, plus 64
  78728. if inflate() is currently decoding the last block in the deflate stream,
  78729. plus 128 if inflate() returned immediately after decoding an end-of-block
  78730. code or decoding the complete header up to just before the first byte of the
  78731. deflate stream. The end-of-block will not be indicated until all of the
  78732. uncompressed data from that block has been written to strm->next_out. The
  78733. number of unused bits may in general be greater than seven, except when
  78734. bit 7 of data_type is set, in which case the number of unused bits will be
  78735. less than eight.
  78736. inflate() should normally be called until it returns Z_STREAM_END or an
  78737. error. However if all decompression is to be performed in a single step
  78738. (a single call of inflate), the parameter flush should be set to
  78739. Z_FINISH. In this case all pending input is processed and all pending
  78740. output is flushed; avail_out must be large enough to hold all the
  78741. uncompressed data. (The size of the uncompressed data may have been saved
  78742. by the compressor for this purpose.) The next operation on this stream must
  78743. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78744. is never required, but can be used to inform inflate that a faster approach
  78745. may be used for the single inflate() call.
  78746. In this implementation, inflate() always flushes as much output as
  78747. possible to the output buffer, and always uses the faster approach on the
  78748. first call. So the only effect of the flush parameter in this implementation
  78749. is on the return value of inflate(), as noted below, or when it returns early
  78750. because Z_BLOCK is used.
  78751. If a preset dictionary is needed after this call (see inflateSetDictionary
  78752. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78753. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78754. strm->adler to the adler32 checksum of all output produced so far (that is,
  78755. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78756. below. At the end of the stream, inflate() checks that its computed adler32
  78757. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78758. only if the checksum is correct.
  78759. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78760. deflate data. The header type is detected automatically. Any information
  78761. contained in the gzip header is not retained, so applications that need that
  78762. information should instead use raw inflate, see inflateInit2() below, or
  78763. inflateBack() and perform their own processing of the gzip header and
  78764. trailer.
  78765. inflate() returns Z_OK if some progress has been made (more input processed
  78766. or more output produced), Z_STREAM_END if the end of the compressed data has
  78767. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78768. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78769. corrupted (input stream not conforming to the zlib format or incorrect check
  78770. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78771. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78772. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78773. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78774. inflate() can be called again with more input and more output space to
  78775. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78776. call inflateSync() to look for a good compression block if a partial recovery
  78777. of the data is desired.
  78778. */
  78779. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78780. /*
  78781. All dynamically allocated data structures for this stream are freed.
  78782. This function discards any unprocessed input and does not flush any
  78783. pending output.
  78784. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78785. was inconsistent. In the error case, msg may be set but then points to a
  78786. static string (which must not be deallocated).
  78787. */
  78788. /* Advanced functions */
  78789. /*
  78790. The following functions are needed only in some special applications.
  78791. */
  78792. /*
  78793. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78794. int level,
  78795. int method,
  78796. int windowBits,
  78797. int memLevel,
  78798. int strategy));
  78799. This is another version of deflateInit with more compression options. The
  78800. fields next_in, zalloc, zfree and opaque must be initialized before by
  78801. the caller.
  78802. The method parameter is the compression method. It must be Z_DEFLATED in
  78803. this version of the library.
  78804. The windowBits parameter is the base two logarithm of the window size
  78805. (the size of the history buffer). It should be in the range 8..15 for this
  78806. version of the library. Larger values of this parameter result in better
  78807. compression at the expense of memory usage. The default value is 15 if
  78808. deflateInit is used instead.
  78809. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78810. determines the window size. deflate() will then generate raw deflate data
  78811. with no zlib header or trailer, and will not compute an adler32 check value.
  78812. windowBits can also be greater than 15 for optional gzip encoding. Add
  78813. 16 to windowBits to write a simple gzip header and trailer around the
  78814. compressed data instead of a zlib wrapper. The gzip header will have no
  78815. file name, no extra data, no comment, no modification time (set to zero),
  78816. no header crc, and the operating system will be set to 255 (unknown). If a
  78817. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78818. The memLevel parameter specifies how much memory should be allocated
  78819. for the internal compression state. memLevel=1 uses minimum memory but
  78820. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78821. for optimal speed. The default value is 8. See zconf.h for total memory
  78822. usage as a function of windowBits and memLevel.
  78823. The strategy parameter is used to tune the compression algorithm. Use the
  78824. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78825. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78826. string match), or Z_RLE to limit match distances to one (run-length
  78827. encoding). Filtered data consists mostly of small values with a somewhat
  78828. random distribution. In this case, the compression algorithm is tuned to
  78829. compress them better. The effect of Z_FILTERED is to force more Huffman
  78830. coding and less string matching; it is somewhat intermediate between
  78831. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78832. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78833. parameter only affects the compression ratio but not the correctness of the
  78834. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78835. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78836. applications.
  78837. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78838. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78839. method). msg is set to null if there is no error message. deflateInit2 does
  78840. not perform any compression: this will be done by deflate().
  78841. */
  78842. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78843. const Bytef *dictionary,
  78844. uInt dictLength));
  78845. /*
  78846. Initializes the compression dictionary from the given byte sequence
  78847. without producing any compressed output. This function must be called
  78848. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78849. call of deflate. The compressor and decompressor must use exactly the same
  78850. dictionary (see inflateSetDictionary).
  78851. The dictionary should consist of strings (byte sequences) that are likely
  78852. to be encountered later in the data to be compressed, with the most commonly
  78853. used strings preferably put towards the end of the dictionary. Using a
  78854. dictionary is most useful when the data to be compressed is short and can be
  78855. predicted with good accuracy; the data can then be compressed better than
  78856. with the default empty dictionary.
  78857. Depending on the size of the compression data structures selected by
  78858. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78859. discarded, for example if the dictionary is larger than the window size in
  78860. deflate or deflate2. Thus the strings most likely to be useful should be
  78861. put at the end of the dictionary, not at the front. In addition, the
  78862. current implementation of deflate will use at most the window size minus
  78863. 262 bytes of the provided dictionary.
  78864. Upon return of this function, strm->adler is set to the adler32 value
  78865. of the dictionary; the decompressor may later use this value to determine
  78866. which dictionary has been used by the compressor. (The adler32 value
  78867. applies to the whole dictionary even if only a subset of the dictionary is
  78868. actually used by the compressor.) If a raw deflate was requested, then the
  78869. adler32 value is not computed and strm->adler is not set.
  78870. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78871. parameter is invalid (such as NULL dictionary) or the stream state is
  78872. inconsistent (for example if deflate has already been called for this stream
  78873. or if the compression method is bsort). deflateSetDictionary does not
  78874. perform any compression: this will be done by deflate().
  78875. */
  78876. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78877. z_streamp source));
  78878. /*
  78879. Sets the destination stream as a complete copy of the source stream.
  78880. This function can be useful when several compression strategies will be
  78881. tried, for example when there are several ways of pre-processing the input
  78882. data with a filter. The streams that will be discarded should then be freed
  78883. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78884. compression state which can be quite large, so this strategy is slow and
  78885. can consume lots of memory.
  78886. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78887. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78888. (such as zalloc being NULL). msg is left unchanged in both source and
  78889. destination.
  78890. */
  78891. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78892. /*
  78893. This function is equivalent to deflateEnd followed by deflateInit,
  78894. but does not free and reallocate all the internal compression state.
  78895. The stream will keep the same compression level and any other attributes
  78896. that may have been set by deflateInit2.
  78897. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78898. stream state was inconsistent (such as zalloc or state being NULL).
  78899. */
  78900. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78901. int level,
  78902. int strategy));
  78903. /*
  78904. Dynamically update the compression level and compression strategy. The
  78905. interpretation of level and strategy is as in deflateInit2. This can be
  78906. used to switch between compression and straight copy of the input data, or
  78907. to switch to a different kind of input data requiring a different
  78908. strategy. If the compression level is changed, the input available so far
  78909. is compressed with the old level (and may be flushed); the new level will
  78910. take effect only at the next call of deflate().
  78911. Before the call of deflateParams, the stream state must be set as for
  78912. a call of deflate(), since the currently available input may have to
  78913. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78914. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78915. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78916. if strm->avail_out was zero.
  78917. */
  78918. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78919. int good_length,
  78920. int max_lazy,
  78921. int nice_length,
  78922. int max_chain));
  78923. /*
  78924. Fine tune deflate's internal compression parameters. This should only be
  78925. used by someone who understands the algorithm used by zlib's deflate for
  78926. searching for the best matching string, and even then only by the most
  78927. fanatic optimizer trying to squeeze out the last compressed bit for their
  78928. specific input data. Read the deflate.c source code for the meaning of the
  78929. max_lazy, good_length, nice_length, and max_chain parameters.
  78930. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78931. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78932. */
  78933. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78934. uLong sourceLen));
  78935. /*
  78936. deflateBound() returns an upper bound on the compressed size after
  78937. deflation of sourceLen bytes. It must be called after deflateInit()
  78938. or deflateInit2(). This would be used to allocate an output buffer
  78939. for deflation in a single pass, and so would be called before deflate().
  78940. */
  78941. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78942. int bits,
  78943. int value));
  78944. /*
  78945. deflatePrime() inserts bits in the deflate output stream. The intent
  78946. is that this function is used to start off the deflate output with the
  78947. bits leftover from a previous deflate stream when appending to it. As such,
  78948. this function can only be used for raw deflate, and must be used before the
  78949. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78950. less than or equal to 16, and that many of the least significant bits of
  78951. value will be inserted in the output.
  78952. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78953. stream state was inconsistent.
  78954. */
  78955. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78956. gz_headerp head));
  78957. /*
  78958. deflateSetHeader() provides gzip header information for when a gzip
  78959. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78960. after deflateInit2() or deflateReset() and before the first call of
  78961. deflate(). The text, time, os, extra field, name, and comment information
  78962. in the provided gz_header structure are written to the gzip header (xflag is
  78963. ignored -- the extra flags are set according to the compression level). The
  78964. caller must assure that, if not Z_NULL, name and comment are terminated with
  78965. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78966. available there. If hcrc is true, a gzip header crc is included. Note that
  78967. the current versions of the command-line version of gzip (up through version
  78968. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78969. gzip file" and give up.
  78970. If deflateSetHeader is not used, the default gzip header has text false,
  78971. the time set to zero, and os set to 255, with no extra, name, or comment
  78972. fields. The gzip header is returned to the default state by deflateReset().
  78973. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78974. stream state was inconsistent.
  78975. */
  78976. /*
  78977. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78978. int windowBits));
  78979. This is another version of inflateInit with an extra parameter. The
  78980. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78981. before by the caller.
  78982. The windowBits parameter is the base two logarithm of the maximum window
  78983. size (the size of the history buffer). It should be in the range 8..15 for
  78984. this version of the library. The default value is 15 if inflateInit is used
  78985. instead. windowBits must be greater than or equal to the windowBits value
  78986. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78987. deflateInit2() was not used. If a compressed stream with a larger window
  78988. size is given as input, inflate() will return with the error code
  78989. Z_DATA_ERROR instead of trying to allocate a larger window.
  78990. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78991. determines the window size. inflate() will then process raw deflate data,
  78992. not looking for a zlib or gzip header, not generating a check value, and not
  78993. looking for any check values for comparison at the end of the stream. This
  78994. is for use with other formats that use the deflate compressed data format
  78995. such as zip. Those formats provide their own check values. If a custom
  78996. format is developed using the raw deflate format for compressed data, it is
  78997. recommended that a check value such as an adler32 or a crc32 be applied to
  78998. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78999. most applications, the zlib format should be used as is. Note that comments
  79000. above on the use in deflateInit2() applies to the magnitude of windowBits.
  79001. windowBits can also be greater than 15 for optional gzip decoding. Add
  79002. 32 to windowBits to enable zlib and gzip decoding with automatic header
  79003. detection, or add 16 to decode only the gzip format (the zlib format will
  79004. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  79005. a crc32 instead of an adler32.
  79006. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79007. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  79008. is set to null if there is no error message. inflateInit2 does not perform
  79009. any decompression apart from reading the zlib header if present: this will
  79010. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  79011. and avail_out are unchanged.)
  79012. */
  79013. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  79014. const Bytef *dictionary,
  79015. uInt dictLength));
  79016. /*
  79017. Initializes the decompression dictionary from the given uncompressed byte
  79018. sequence. This function must be called immediately after a call of inflate,
  79019. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  79020. can be determined from the adler32 value returned by that call of inflate.
  79021. The compressor and decompressor must use exactly the same dictionary (see
  79022. deflateSetDictionary). For raw inflate, this function can be called
  79023. immediately after inflateInit2() or inflateReset() and before any call of
  79024. inflate() to set the dictionary. The application must insure that the
  79025. dictionary that was used for compression is provided.
  79026. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  79027. parameter is invalid (such as NULL dictionary) or the stream state is
  79028. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  79029. expected one (incorrect adler32 value). inflateSetDictionary does not
  79030. perform any decompression: this will be done by subsequent calls of
  79031. inflate().
  79032. */
  79033. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  79034. /*
  79035. Skips invalid compressed data until a full flush point (see above the
  79036. description of deflate with Z_FULL_FLUSH) can be found, or until all
  79037. available input is skipped. No output is provided.
  79038. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  79039. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  79040. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  79041. case, the application may save the current current value of total_in which
  79042. indicates where valid compressed data was found. In the error case, the
  79043. application may repeatedly call inflateSync, providing more input each time,
  79044. until success or end of the input data.
  79045. */
  79046. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  79047. z_streamp source));
  79048. /*
  79049. Sets the destination stream as a complete copy of the source stream.
  79050. This function can be useful when randomly accessing a large stream. The
  79051. first pass through the stream can periodically record the inflate state,
  79052. allowing restarting inflate at those points when randomly accessing the
  79053. stream.
  79054. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79055. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79056. (such as zalloc being NULL). msg is left unchanged in both source and
  79057. destination.
  79058. */
  79059. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  79060. /*
  79061. This function is equivalent to inflateEnd followed by inflateInit,
  79062. but does not free and reallocate all the internal decompression state.
  79063. The stream will keep attributes that may have been set by inflateInit2.
  79064. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79065. stream state was inconsistent (such as zalloc or state being NULL).
  79066. */
  79067. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  79068. int bits,
  79069. int value));
  79070. /*
  79071. This function inserts bits in the inflate input stream. The intent is
  79072. that this function is used to start inflating at a bit position in the
  79073. middle of a byte. The provided bits will be used before any bytes are used
  79074. from next_in. This function should only be used with raw inflate, and
  79075. should be used before the first inflate() call after inflateInit2() or
  79076. inflateReset(). bits must be less than or equal to 16, and that many of the
  79077. least significant bits of value will be inserted in the input.
  79078. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79079. stream state was inconsistent.
  79080. */
  79081. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  79082. gz_headerp head));
  79083. /*
  79084. inflateGetHeader() requests that gzip header information be stored in the
  79085. provided gz_header structure. inflateGetHeader() may be called after
  79086. inflateInit2() or inflateReset(), and before the first call of inflate().
  79087. As inflate() processes the gzip stream, head->done is zero until the header
  79088. is completed, at which time head->done is set to one. If a zlib stream is
  79089. being decoded, then head->done is set to -1 to indicate that there will be
  79090. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79091. force inflate() to return immediately after header processing is complete
  79092. and before any actual data is decompressed.
  79093. The text, time, xflags, and os fields are filled in with the gzip header
  79094. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79095. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79096. contains the maximum number of bytes to write to extra. Once done is true,
  79097. extra_len contains the actual extra field length, and extra contains the
  79098. extra field, or that field truncated if extra_max is less than extra_len.
  79099. If name is not Z_NULL, then up to name_max characters are written there,
  79100. terminated with a zero unless the length is greater than name_max. If
  79101. comment is not Z_NULL, then up to comm_max characters are written there,
  79102. terminated with a zero unless the length is greater than comm_max. When
  79103. any of extra, name, or comment are not Z_NULL and the respective field is
  79104. not present in the header, then that field is set to Z_NULL to signal its
  79105. absence. This allows the use of deflateSetHeader() with the returned
  79106. structure to duplicate the header. However if those fields are set to
  79107. allocated memory, then the application will need to save those pointers
  79108. elsewhere so that they can be eventually freed.
  79109. If inflateGetHeader is not used, then the header information is simply
  79110. discarded. The header is always checked for validity, including the header
  79111. CRC if present. inflateReset() will reset the process to discard the header
  79112. information. The application would need to call inflateGetHeader() again to
  79113. retrieve the header from the next gzip stream.
  79114. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79115. stream state was inconsistent.
  79116. */
  79117. /*
  79118. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79119. unsigned char FAR *window));
  79120. Initialize the internal stream state for decompression using inflateBack()
  79121. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79122. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79123. derived memory allocation routines are used. windowBits is the base two
  79124. logarithm of the window size, in the range 8..15. window is a caller
  79125. supplied buffer of that size. Except for special applications where it is
  79126. assured that deflate was used with small window sizes, windowBits must be 15
  79127. and a 32K byte window must be supplied to be able to decompress general
  79128. deflate streams.
  79129. See inflateBack() for the usage of these routines.
  79130. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79131. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79132. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79133. match the version of the header file.
  79134. */
  79135. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79136. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79137. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79138. in_func in, void FAR *in_desc,
  79139. out_func out, void FAR *out_desc));
  79140. /*
  79141. inflateBack() does a raw inflate with a single call using a call-back
  79142. interface for input and output. This is more efficient than inflate() for
  79143. file i/o applications in that it avoids copying between the output and the
  79144. sliding window by simply making the window itself the output buffer. This
  79145. function trusts the application to not change the output buffer passed by
  79146. the output function, at least until inflateBack() returns.
  79147. inflateBackInit() must be called first to allocate the internal state
  79148. and to initialize the state with the user-provided window buffer.
  79149. inflateBack() may then be used multiple times to inflate a complete, raw
  79150. deflate stream with each call. inflateBackEnd() is then called to free
  79151. the allocated state.
  79152. A raw deflate stream is one with no zlib or gzip header or trailer.
  79153. This routine would normally be used in a utility that reads zip or gzip
  79154. files and writes out uncompressed files. The utility would decode the
  79155. header and process the trailer on its own, hence this routine expects
  79156. only the raw deflate stream to decompress. This is different from the
  79157. normal behavior of inflate(), which expects either a zlib or gzip header and
  79158. trailer around the deflate stream.
  79159. inflateBack() uses two subroutines supplied by the caller that are then
  79160. called by inflateBack() for input and output. inflateBack() calls those
  79161. routines until it reads a complete deflate stream and writes out all of the
  79162. uncompressed data, or until it encounters an error. The function's
  79163. parameters and return types are defined above in the in_func and out_func
  79164. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79165. number of bytes of provided input, and a pointer to that input in buf. If
  79166. there is no input available, in() must return zero--buf is ignored in that
  79167. case--and inflateBack() will return a buffer error. inflateBack() will call
  79168. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79169. should return zero on success, or non-zero on failure. If out() returns
  79170. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79171. are permitted to change the contents of the window provided to
  79172. inflateBackInit(), which is also the buffer that out() uses to write from.
  79173. The length written by out() will be at most the window size. Any non-zero
  79174. amount of input may be provided by in().
  79175. For convenience, inflateBack() can be provided input on the first call by
  79176. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79177. in() will be called. Therefore strm->next_in must be initialized before
  79178. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79179. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79180. must also be initialized, and then if strm->avail_in is not zero, input will
  79181. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79182. The in_desc and out_desc parameters of inflateBack() is passed as the
  79183. first parameter of in() and out() respectively when they are called. These
  79184. descriptors can be optionally used to pass any information that the caller-
  79185. supplied in() and out() functions need to do their job.
  79186. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79187. pass back any unused input that was provided by the last in() call. The
  79188. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79189. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79190. error in the deflate stream (in which case strm->msg is set to indicate the
  79191. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79192. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79193. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79194. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79195. out() returning non-zero. (in() will always be called before out(), so
  79196. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79197. that inflateBack() cannot return Z_OK.
  79198. */
  79199. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79200. /*
  79201. All memory allocated by inflateBackInit() is freed.
  79202. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79203. state was inconsistent.
  79204. */
  79205. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79206. /* Return flags indicating compile-time options.
  79207. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79208. 1.0: size of uInt
  79209. 3.2: size of uLong
  79210. 5.4: size of voidpf (pointer)
  79211. 7.6: size of z_off_t
  79212. Compiler, assembler, and debug options:
  79213. 8: DEBUG
  79214. 9: ASMV or ASMINF -- use ASM code
  79215. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79216. 11: 0 (reserved)
  79217. One-time table building (smaller code, but not thread-safe if true):
  79218. 12: BUILDFIXED -- build static block decoding tables when needed
  79219. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79220. 14,15: 0 (reserved)
  79221. Library content (indicates missing functionality):
  79222. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79223. deflate code when not needed)
  79224. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79225. and decode gzip streams (to avoid linking crc code)
  79226. 18-19: 0 (reserved)
  79227. Operation variations (changes in library functionality):
  79228. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79229. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79230. 22,23: 0 (reserved)
  79231. The sprintf variant used by gzprintf (zero is best):
  79232. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79233. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79234. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79235. Remainder:
  79236. 27-31: 0 (reserved)
  79237. */
  79238. /* utility functions */
  79239. /*
  79240. The following utility functions are implemented on top of the
  79241. basic stream-oriented functions. To simplify the interface, some
  79242. default options are assumed (compression level and memory usage,
  79243. standard memory allocation functions). The source code of these
  79244. utility functions can easily be modified if you need special options.
  79245. */
  79246. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79247. const Bytef *source, uLong sourceLen));
  79248. /*
  79249. Compresses the source buffer into the destination buffer. sourceLen is
  79250. the byte length of the source buffer. Upon entry, destLen is the total
  79251. size of the destination buffer, which must be at least the value returned
  79252. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79253. compressed buffer.
  79254. This function can be used to compress a whole file at once if the
  79255. input file is mmap'ed.
  79256. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79257. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79258. buffer.
  79259. */
  79260. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79261. const Bytef *source, uLong sourceLen,
  79262. int level));
  79263. /*
  79264. Compresses the source buffer into the destination buffer. The level
  79265. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79266. length of the source buffer. Upon entry, destLen is the total size of the
  79267. destination buffer, which must be at least the value returned by
  79268. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79269. compressed buffer.
  79270. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79271. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79272. Z_STREAM_ERROR if the level parameter is invalid.
  79273. */
  79274. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79275. /*
  79276. compressBound() returns an upper bound on the compressed size after
  79277. compress() or compress2() on sourceLen bytes. It would be used before
  79278. a compress() or compress2() call to allocate the destination buffer.
  79279. */
  79280. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79281. const Bytef *source, uLong sourceLen));
  79282. /*
  79283. Decompresses the source buffer into the destination buffer. sourceLen is
  79284. the byte length of the source buffer. Upon entry, destLen is the total
  79285. size of the destination buffer, which must be large enough to hold the
  79286. entire uncompressed data. (The size of the uncompressed data must have
  79287. been saved previously by the compressor and transmitted to the decompressor
  79288. by some mechanism outside the scope of this compression library.)
  79289. Upon exit, destLen is the actual size of the compressed buffer.
  79290. This function can be used to decompress a whole file at once if the
  79291. input file is mmap'ed.
  79292. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79293. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79294. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79295. */
  79296. typedef voidp gzFile;
  79297. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79298. /*
  79299. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79300. is as in fopen ("rb" or "wb") but can also include a compression level
  79301. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79302. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79303. as in "wb1R". (See the description of deflateInit2 for more information
  79304. about the strategy parameter.)
  79305. gzopen can be used to read a file which is not in gzip format; in this
  79306. case gzread will directly read from the file without decompression.
  79307. gzopen returns NULL if the file could not be opened or if there was
  79308. insufficient memory to allocate the (de)compression state; errno
  79309. can be checked to distinguish the two cases (if errno is zero, the
  79310. zlib error is Z_MEM_ERROR). */
  79311. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79312. /*
  79313. gzdopen() associates a gzFile with the file descriptor fd. File
  79314. descriptors are obtained from calls like open, dup, creat, pipe or
  79315. fileno (in the file has been previously opened with fopen).
  79316. The mode parameter is as in gzopen.
  79317. The next call of gzclose on the returned gzFile will also close the
  79318. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79319. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79320. gzdopen returns NULL if there was insufficient memory to allocate
  79321. the (de)compression state.
  79322. */
  79323. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79324. /*
  79325. Dynamically update the compression level or strategy. See the description
  79326. of deflateInit2 for the meaning of these parameters.
  79327. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79328. opened for writing.
  79329. */
  79330. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79331. /*
  79332. Reads the given number of uncompressed bytes from the compressed file.
  79333. If the input file was not in gzip format, gzread copies the given number
  79334. of bytes into the buffer.
  79335. gzread returns the number of uncompressed bytes actually read (0 for
  79336. end of file, -1 for error). */
  79337. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79338. voidpc buf, unsigned len));
  79339. /*
  79340. Writes the given number of uncompressed bytes into the compressed file.
  79341. gzwrite returns the number of uncompressed bytes actually written
  79342. (0 in case of error).
  79343. */
  79344. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79345. /*
  79346. Converts, formats, and writes the args to the compressed file under
  79347. control of the format string, as in fprintf. gzprintf returns the number of
  79348. uncompressed bytes actually written (0 in case of error). The number of
  79349. uncompressed bytes written is limited to 4095. The caller should assure that
  79350. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79351. return an error (0) with nothing written. In this case, there may also be a
  79352. buffer overflow with unpredictable consequences, which is possible only if
  79353. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79354. because the secure snprintf() or vsnprintf() functions were not available.
  79355. */
  79356. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79357. /*
  79358. Writes the given null-terminated string to the compressed file, excluding
  79359. the terminating null character.
  79360. gzputs returns the number of characters written, or -1 in case of error.
  79361. */
  79362. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79363. /*
  79364. Reads bytes from the compressed file until len-1 characters are read, or
  79365. a newline character is read and transferred to buf, or an end-of-file
  79366. condition is encountered. The string is then terminated with a null
  79367. character.
  79368. gzgets returns buf, or Z_NULL in case of error.
  79369. */
  79370. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79371. /*
  79372. Writes c, converted to an unsigned char, into the compressed file.
  79373. gzputc returns the value that was written, or -1 in case of error.
  79374. */
  79375. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79376. /*
  79377. Reads one byte from the compressed file. gzgetc returns this byte
  79378. or -1 in case of end of file or error.
  79379. */
  79380. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79381. /*
  79382. Push one character back onto the stream to be read again later.
  79383. Only one character of push-back is allowed. gzungetc() returns the
  79384. character pushed, or -1 on failure. gzungetc() will fail if a
  79385. character has been pushed but not read yet, or if c is -1. The pushed
  79386. character will be discarded if the stream is repositioned with gzseek()
  79387. or gzrewind().
  79388. */
  79389. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79390. /*
  79391. Flushes all pending output into the compressed file. The parameter
  79392. flush is as in the deflate() function. The return value is the zlib
  79393. error number (see function gzerror below). gzflush returns Z_OK if
  79394. the flush parameter is Z_FINISH and all output could be flushed.
  79395. gzflush should be called only when strictly necessary because it can
  79396. degrade compression.
  79397. */
  79398. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79399. z_off_t offset, int whence));
  79400. /*
  79401. Sets the starting position for the next gzread or gzwrite on the
  79402. given compressed file. The offset represents a number of bytes in the
  79403. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79404. the value SEEK_END is not supported.
  79405. If the file is opened for reading, this function is emulated but can be
  79406. extremely slow. If the file is opened for writing, only forward seeks are
  79407. supported; gzseek then compresses a sequence of zeroes up to the new
  79408. starting position.
  79409. gzseek returns the resulting offset location as measured in bytes from
  79410. the beginning of the uncompressed stream, or -1 in case of error, in
  79411. particular if the file is opened for writing and the new starting position
  79412. would be before the current position.
  79413. */
  79414. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79415. /*
  79416. Rewinds the given file. This function is supported only for reading.
  79417. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79418. */
  79419. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79420. /*
  79421. Returns the starting position for the next gzread or gzwrite on the
  79422. given compressed file. This position represents a number of bytes in the
  79423. uncompressed data stream.
  79424. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79425. */
  79426. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79427. /*
  79428. Returns 1 when EOF has previously been detected reading the given
  79429. input stream, otherwise zero.
  79430. */
  79431. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79432. /*
  79433. Returns 1 if file is being read directly without decompression, otherwise
  79434. zero.
  79435. */
  79436. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79437. /*
  79438. Flushes all pending output if necessary, closes the compressed file
  79439. and deallocates all the (de)compression state. The return value is the zlib
  79440. error number (see function gzerror below).
  79441. */
  79442. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79443. /*
  79444. Returns the error message for the last error which occurred on the
  79445. given compressed file. errnum is set to zlib error number. If an
  79446. error occurred in the file system and not in the compression library,
  79447. errnum is set to Z_ERRNO and the application may consult errno
  79448. to get the exact error code.
  79449. */
  79450. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79451. /*
  79452. Clears the error and end-of-file flags for file. This is analogous to the
  79453. clearerr() function in stdio. This is useful for continuing to read a gzip
  79454. file that is being written concurrently.
  79455. */
  79456. /* checksum functions */
  79457. /*
  79458. These functions are not related to compression but are exported
  79459. anyway because they might be useful in applications using the
  79460. compression library.
  79461. */
  79462. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79463. /*
  79464. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79465. return the updated checksum. If buf is NULL, this function returns
  79466. the required initial value for the checksum.
  79467. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79468. much faster. Usage example:
  79469. uLong adler = adler32(0L, Z_NULL, 0);
  79470. while (read_buffer(buffer, length) != EOF) {
  79471. adler = adler32(adler, buffer, length);
  79472. }
  79473. if (adler != original_adler) error();
  79474. */
  79475. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79476. z_off_t len2));
  79477. /*
  79478. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79479. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79480. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79481. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79482. */
  79483. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79484. /*
  79485. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79486. updated CRC-32. If buf is NULL, this function returns the required initial
  79487. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79488. performed within this function so it shouldn't be done by the application.
  79489. Usage example:
  79490. uLong crc = crc32(0L, Z_NULL, 0);
  79491. while (read_buffer(buffer, length) != EOF) {
  79492. crc = crc32(crc, buffer, length);
  79493. }
  79494. if (crc != original_crc) error();
  79495. */
  79496. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79497. /*
  79498. Combine two CRC-32 check values into one. For two sequences of bytes,
  79499. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79500. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79501. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79502. len2.
  79503. */
  79504. /* various hacks, don't look :) */
  79505. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79506. * and the compiler's view of z_stream:
  79507. */
  79508. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79509. const char *version, int stream_size));
  79510. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79511. const char *version, int stream_size));
  79512. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79513. int windowBits, int memLevel,
  79514. int strategy, const char *version,
  79515. int stream_size));
  79516. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79517. const char *version, int stream_size));
  79518. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79519. unsigned char FAR *window,
  79520. const char *version,
  79521. int stream_size));
  79522. #define deflateInit(strm, level) \
  79523. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79524. #define inflateInit(strm) \
  79525. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79526. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79527. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79528. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79529. #define inflateInit2(strm, windowBits) \
  79530. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79531. #define inflateBackInit(strm, windowBits, window) \
  79532. inflateBackInit_((strm), (windowBits), (window), \
  79533. ZLIB_VERSION, sizeof(z_stream))
  79534. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79535. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79536. #endif
  79537. ZEXTERN const char * ZEXPORT zError OF((int));
  79538. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79539. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79540. #ifdef __cplusplus
  79541. //}
  79542. #endif
  79543. #endif /* ZLIB_H */
  79544. /*** End of inlined file: zlib.h ***/
  79545. #undef OS_CODE
  79546. #else
  79547. #include <zlib.h>
  79548. #endif
  79549. }
  79550. BEGIN_JUCE_NAMESPACE
  79551. // internal helper object that holds the zlib structures so they don't have to be
  79552. // included publicly.
  79553. class GZIPCompressorHelper
  79554. {
  79555. public:
  79556. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  79557. : data (0),
  79558. dataSize (0),
  79559. compLevel (compressionLevel),
  79560. strategy (0),
  79561. setParams (true),
  79562. streamIsValid (false),
  79563. finished (false),
  79564. shouldFinish (false)
  79565. {
  79566. using namespace zlibNamespace;
  79567. zerostruct (stream);
  79568. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79569. nowrap ? -MAX_WBITS : MAX_WBITS,
  79570. 8, strategy) == Z_OK);
  79571. }
  79572. ~GZIPCompressorHelper()
  79573. {
  79574. using namespace zlibNamespace;
  79575. if (streamIsValid)
  79576. deflateEnd (&stream);
  79577. }
  79578. bool needsInput() const throw()
  79579. {
  79580. return dataSize <= 0;
  79581. }
  79582. void setInput (const uint8* const newData, const int size) throw()
  79583. {
  79584. data = newData;
  79585. dataSize = size;
  79586. }
  79587. int doNextBlock (uint8* const dest, const int destSize) throw()
  79588. {
  79589. using namespace zlibNamespace;
  79590. if (streamIsValid)
  79591. {
  79592. stream.next_in = const_cast <uint8*> (data);
  79593. stream.next_out = dest;
  79594. stream.avail_in = dataSize;
  79595. stream.avail_out = destSize;
  79596. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79597. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79598. setParams = false;
  79599. switch (result)
  79600. {
  79601. case Z_STREAM_END:
  79602. finished = true;
  79603. // Deliberate fall-through..
  79604. case Z_OK:
  79605. data += dataSize - stream.avail_in;
  79606. dataSize = stream.avail_in;
  79607. return destSize - stream.avail_out;
  79608. default:
  79609. break;
  79610. }
  79611. }
  79612. return 0;
  79613. }
  79614. private:
  79615. zlibNamespace::z_stream stream;
  79616. const uint8* data;
  79617. int dataSize, compLevel, strategy;
  79618. bool setParams, streamIsValid;
  79619. public:
  79620. bool finished, shouldFinish;
  79621. };
  79622. const int gzipCompBufferSize = 32768;
  79623. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79624. int compressionLevel,
  79625. const bool deleteDestStream,
  79626. const bool noWrap)
  79627. : destStream (destStream_),
  79628. streamToDelete (deleteDestStream ? destStream_ : 0),
  79629. buffer (gzipCompBufferSize)
  79630. {
  79631. if (compressionLevel < 1 || compressionLevel > 9)
  79632. compressionLevel = -1;
  79633. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  79634. }
  79635. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79636. {
  79637. flush();
  79638. }
  79639. void GZIPCompressorOutputStream::flush()
  79640. {
  79641. if (! helper->finished)
  79642. {
  79643. helper->shouldFinish = true;
  79644. while (! helper->finished)
  79645. doNextBlock();
  79646. }
  79647. destStream->flush();
  79648. }
  79649. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79650. {
  79651. if (! helper->finished)
  79652. {
  79653. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79654. while (! helper->needsInput())
  79655. {
  79656. if (! doNextBlock())
  79657. return false;
  79658. }
  79659. }
  79660. return true;
  79661. }
  79662. bool GZIPCompressorOutputStream::doNextBlock()
  79663. {
  79664. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  79665. if (len > 0)
  79666. return destStream->write (buffer, len);
  79667. else
  79668. return true;
  79669. }
  79670. int64 GZIPCompressorOutputStream::getPosition()
  79671. {
  79672. return destStream->getPosition();
  79673. }
  79674. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79675. {
  79676. jassertfalse; // can't do it!
  79677. return false;
  79678. }
  79679. END_JUCE_NAMESPACE
  79680. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79681. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79682. #if JUCE_MSVC
  79683. #pragma warning (push)
  79684. #pragma warning (disable: 4309 4305)
  79685. #endif
  79686. namespace zlibNamespace
  79687. {
  79688. #if JUCE_INCLUDE_ZLIB_CODE
  79689. #undef OS_CODE
  79690. #undef fdopen
  79691. #define ZLIB_INTERNAL
  79692. #define NO_DUMMY_DECL
  79693. /*** Start of inlined file: adler32.c ***/
  79694. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79695. #define ZLIB_INTERNAL
  79696. #define BASE 65521UL /* largest prime smaller than 65536 */
  79697. #define NMAX 5552
  79698. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79699. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79700. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79701. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79702. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79703. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79704. /* use NO_DIVIDE if your processor does not do division in hardware */
  79705. #ifdef NO_DIVIDE
  79706. # define MOD(a) \
  79707. do { \
  79708. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79709. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79710. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79711. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79712. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79713. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79714. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79715. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79716. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79717. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79718. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79719. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79720. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79721. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79722. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79723. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79724. if (a >= BASE) a -= BASE; \
  79725. } while (0)
  79726. # define MOD4(a) \
  79727. do { \
  79728. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79729. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79730. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79731. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79732. if (a >= BASE) a -= BASE; \
  79733. } while (0)
  79734. #else
  79735. # define MOD(a) a %= BASE
  79736. # define MOD4(a) a %= BASE
  79737. #endif
  79738. /* ========================================================================= */
  79739. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79740. {
  79741. unsigned long sum2;
  79742. unsigned n;
  79743. /* split Adler-32 into component sums */
  79744. sum2 = (adler >> 16) & 0xffff;
  79745. adler &= 0xffff;
  79746. /* in case user likes doing a byte at a time, keep it fast */
  79747. if (len == 1) {
  79748. adler += buf[0];
  79749. if (adler >= BASE)
  79750. adler -= BASE;
  79751. sum2 += adler;
  79752. if (sum2 >= BASE)
  79753. sum2 -= BASE;
  79754. return adler | (sum2 << 16);
  79755. }
  79756. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79757. if (buf == Z_NULL)
  79758. return 1L;
  79759. /* in case short lengths are provided, keep it somewhat fast */
  79760. if (len < 16) {
  79761. while (len--) {
  79762. adler += *buf++;
  79763. sum2 += adler;
  79764. }
  79765. if (adler >= BASE)
  79766. adler -= BASE;
  79767. MOD4(sum2); /* only added so many BASE's */
  79768. return adler | (sum2 << 16);
  79769. }
  79770. /* do length NMAX blocks -- requires just one modulo operation */
  79771. while (len >= NMAX) {
  79772. len -= NMAX;
  79773. n = NMAX / 16; /* NMAX is divisible by 16 */
  79774. do {
  79775. DO16(buf); /* 16 sums unrolled */
  79776. buf += 16;
  79777. } while (--n);
  79778. MOD(adler);
  79779. MOD(sum2);
  79780. }
  79781. /* do remaining bytes (less than NMAX, still just one modulo) */
  79782. if (len) { /* avoid modulos if none remaining */
  79783. while (len >= 16) {
  79784. len -= 16;
  79785. DO16(buf);
  79786. buf += 16;
  79787. }
  79788. while (len--) {
  79789. adler += *buf++;
  79790. sum2 += adler;
  79791. }
  79792. MOD(adler);
  79793. MOD(sum2);
  79794. }
  79795. /* return recombined sums */
  79796. return adler | (sum2 << 16);
  79797. }
  79798. /* ========================================================================= */
  79799. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79800. {
  79801. unsigned long sum1;
  79802. unsigned long sum2;
  79803. unsigned rem;
  79804. /* the derivation of this formula is left as an exercise for the reader */
  79805. rem = (unsigned)(len2 % BASE);
  79806. sum1 = adler1 & 0xffff;
  79807. sum2 = rem * sum1;
  79808. MOD(sum2);
  79809. sum1 += (adler2 & 0xffff) + BASE - 1;
  79810. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79811. if (sum1 > BASE) sum1 -= BASE;
  79812. if (sum1 > BASE) sum1 -= BASE;
  79813. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79814. if (sum2 > BASE) sum2 -= BASE;
  79815. return sum1 | (sum2 << 16);
  79816. }
  79817. /*** End of inlined file: adler32.c ***/
  79818. /*** Start of inlined file: compress.c ***/
  79819. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79820. #define ZLIB_INTERNAL
  79821. /* ===========================================================================
  79822. Compresses the source buffer into the destination buffer. The level
  79823. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79824. length of the source buffer. Upon entry, destLen is the total size of the
  79825. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79826. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79827. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79828. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79829. Z_STREAM_ERROR if the level parameter is invalid.
  79830. */
  79831. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79832. uLong sourceLen, int level)
  79833. {
  79834. z_stream stream;
  79835. int err;
  79836. stream.next_in = (Bytef*)source;
  79837. stream.avail_in = (uInt)sourceLen;
  79838. #ifdef MAXSEG_64K
  79839. /* Check for source > 64K on 16-bit machine: */
  79840. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79841. #endif
  79842. stream.next_out = dest;
  79843. stream.avail_out = (uInt)*destLen;
  79844. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79845. stream.zalloc = (alloc_func)0;
  79846. stream.zfree = (free_func)0;
  79847. stream.opaque = (voidpf)0;
  79848. err = deflateInit(&stream, level);
  79849. if (err != Z_OK) return err;
  79850. err = deflate(&stream, Z_FINISH);
  79851. if (err != Z_STREAM_END) {
  79852. deflateEnd(&stream);
  79853. return err == Z_OK ? Z_BUF_ERROR : err;
  79854. }
  79855. *destLen = stream.total_out;
  79856. err = deflateEnd(&stream);
  79857. return err;
  79858. }
  79859. /* ===========================================================================
  79860. */
  79861. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79862. {
  79863. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79864. }
  79865. /* ===========================================================================
  79866. If the default memLevel or windowBits for deflateInit() is changed, then
  79867. this function needs to be updated.
  79868. */
  79869. uLong ZEXPORT compressBound (uLong sourceLen)
  79870. {
  79871. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79872. }
  79873. /*** End of inlined file: compress.c ***/
  79874. #undef DO1
  79875. #undef DO8
  79876. /*** Start of inlined file: crc32.c ***/
  79877. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79878. /*
  79879. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79880. protection on the static variables used to control the first-use generation
  79881. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79882. first call get_crc_table() to initialize the tables before allowing more than
  79883. one thread to use crc32().
  79884. */
  79885. #ifdef MAKECRCH
  79886. # include <stdio.h>
  79887. # ifndef DYNAMIC_CRC_TABLE
  79888. # define DYNAMIC_CRC_TABLE
  79889. # endif /* !DYNAMIC_CRC_TABLE */
  79890. #endif /* MAKECRCH */
  79891. /*** Start of inlined file: zutil.h ***/
  79892. /* WARNING: this file should *not* be used by applications. It is
  79893. part of the implementation of the compression library and is
  79894. subject to change. Applications should only use zlib.h.
  79895. */
  79896. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79897. #ifndef ZUTIL_H
  79898. #define ZUTIL_H
  79899. #define ZLIB_INTERNAL
  79900. #ifdef STDC
  79901. # ifndef _WIN32_WCE
  79902. # include <stddef.h>
  79903. # endif
  79904. # include <string.h>
  79905. # include <stdlib.h>
  79906. #endif
  79907. #ifdef NO_ERRNO_H
  79908. # ifdef _WIN32_WCE
  79909. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79910. * errno. We define it as a global variable to simplify porting.
  79911. * Its value is always 0 and should not be used. We rename it to
  79912. * avoid conflict with other libraries that use the same workaround.
  79913. */
  79914. # define errno z_errno
  79915. # endif
  79916. extern int errno;
  79917. #else
  79918. # ifndef _WIN32_WCE
  79919. # include <errno.h>
  79920. # endif
  79921. #endif
  79922. #ifndef local
  79923. # define local static
  79924. #endif
  79925. /* compile with -Dlocal if your debugger can't find static symbols */
  79926. typedef unsigned char uch;
  79927. typedef uch FAR uchf;
  79928. typedef unsigned short ush;
  79929. typedef ush FAR ushf;
  79930. typedef unsigned long ulg;
  79931. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79932. /* (size given to avoid silly warnings with Visual C++) */
  79933. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79934. #define ERR_RETURN(strm,err) \
  79935. return (strm->msg = (char*)ERR_MSG(err), (err))
  79936. /* To be used only when the state is known to be valid */
  79937. /* common constants */
  79938. #ifndef DEF_WBITS
  79939. # define DEF_WBITS MAX_WBITS
  79940. #endif
  79941. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79942. #if MAX_MEM_LEVEL >= 8
  79943. # define DEF_MEM_LEVEL 8
  79944. #else
  79945. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79946. #endif
  79947. /* default memLevel */
  79948. #define STORED_BLOCK 0
  79949. #define STATIC_TREES 1
  79950. #define DYN_TREES 2
  79951. /* The three kinds of block type */
  79952. #define MIN_MATCH 3
  79953. #define MAX_MATCH 258
  79954. /* The minimum and maximum match lengths */
  79955. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79956. /* target dependencies */
  79957. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79958. # define OS_CODE 0x00
  79959. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79960. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79961. /* Allow compilation with ANSI keywords only enabled */
  79962. void _Cdecl farfree( void *block );
  79963. void *_Cdecl farmalloc( unsigned long nbytes );
  79964. # else
  79965. # include <alloc.h>
  79966. # endif
  79967. # else /* MSC or DJGPP */
  79968. # include <malloc.h>
  79969. # endif
  79970. #endif
  79971. #ifdef AMIGA
  79972. # define OS_CODE 0x01
  79973. #endif
  79974. #if defined(VAXC) || defined(VMS)
  79975. # define OS_CODE 0x02
  79976. # define F_OPEN(name, mode) \
  79977. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79978. #endif
  79979. #if defined(ATARI) || defined(atarist)
  79980. # define OS_CODE 0x05
  79981. #endif
  79982. #ifdef OS2
  79983. # define OS_CODE 0x06
  79984. # ifdef M_I86
  79985. #include <malloc.h>
  79986. # endif
  79987. #endif
  79988. #if defined(MACOS) || TARGET_OS_MAC
  79989. # define OS_CODE 0x07
  79990. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79991. # include <unix.h> /* for fdopen */
  79992. # else
  79993. # ifndef fdopen
  79994. # define fdopen(fd,mode) NULL /* No fdopen() */
  79995. # endif
  79996. # endif
  79997. #endif
  79998. #ifdef TOPS20
  79999. # define OS_CODE 0x0a
  80000. #endif
  80001. #ifdef WIN32
  80002. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  80003. # define OS_CODE 0x0b
  80004. # endif
  80005. #endif
  80006. #ifdef __50SERIES /* Prime/PRIMOS */
  80007. # define OS_CODE 0x0f
  80008. #endif
  80009. #if defined(_BEOS_) || defined(RISCOS)
  80010. # define fdopen(fd,mode) NULL /* No fdopen() */
  80011. #endif
  80012. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  80013. # if defined(_WIN32_WCE)
  80014. # define fdopen(fd,mode) NULL /* No fdopen() */
  80015. # ifndef _PTRDIFF_T_DEFINED
  80016. typedef int ptrdiff_t;
  80017. # define _PTRDIFF_T_DEFINED
  80018. # endif
  80019. # else
  80020. # define fdopen(fd,type) _fdopen(fd,type)
  80021. # endif
  80022. #endif
  80023. /* common defaults */
  80024. #ifndef OS_CODE
  80025. # define OS_CODE 0x03 /* assume Unix */
  80026. #endif
  80027. #ifndef F_OPEN
  80028. # define F_OPEN(name, mode) fopen((name), (mode))
  80029. #endif
  80030. /* functions */
  80031. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  80032. # ifndef HAVE_VSNPRINTF
  80033. # define HAVE_VSNPRINTF
  80034. # endif
  80035. #endif
  80036. #if defined(__CYGWIN__)
  80037. # ifndef HAVE_VSNPRINTF
  80038. # define HAVE_VSNPRINTF
  80039. # endif
  80040. #endif
  80041. #ifndef HAVE_VSNPRINTF
  80042. # ifdef MSDOS
  80043. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  80044. but for now we just assume it doesn't. */
  80045. # define NO_vsnprintf
  80046. # endif
  80047. # ifdef __TURBOC__
  80048. # define NO_vsnprintf
  80049. # endif
  80050. # ifdef WIN32
  80051. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  80052. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  80053. # define vsnprintf _vsnprintf
  80054. # endif
  80055. # endif
  80056. # ifdef __SASC
  80057. # define NO_vsnprintf
  80058. # endif
  80059. #endif
  80060. #ifdef VMS
  80061. # define NO_vsnprintf
  80062. #endif
  80063. #if defined(pyr)
  80064. # define NO_MEMCPY
  80065. #endif
  80066. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  80067. /* Use our own functions for small and medium model with MSC <= 5.0.
  80068. * You may have to use the same strategy for Borland C (untested).
  80069. * The __SC__ check is for Symantec.
  80070. */
  80071. # define NO_MEMCPY
  80072. #endif
  80073. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  80074. # define HAVE_MEMCPY
  80075. #endif
  80076. #ifdef HAVE_MEMCPY
  80077. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  80078. # define zmemcpy _fmemcpy
  80079. # define zmemcmp _fmemcmp
  80080. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  80081. # else
  80082. # define zmemcpy memcpy
  80083. # define zmemcmp memcmp
  80084. # define zmemzero(dest, len) memset(dest, 0, len)
  80085. # endif
  80086. #else
  80087. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80088. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80089. extern void zmemzero OF((Bytef* dest, uInt len));
  80090. #endif
  80091. /* Diagnostic functions */
  80092. #ifdef DEBUG
  80093. # include <stdio.h>
  80094. extern int z_verbose;
  80095. extern void z_error OF((const char *m));
  80096. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80097. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80098. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80099. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80100. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80101. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80102. #else
  80103. # define Assert(cond,msg)
  80104. # define Trace(x)
  80105. # define Tracev(x)
  80106. # define Tracevv(x)
  80107. # define Tracec(c,x)
  80108. # define Tracecv(c,x)
  80109. #endif
  80110. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80111. void zcfree OF((voidpf opaque, voidpf ptr));
  80112. #define ZALLOC(strm, items, size) \
  80113. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80114. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80115. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80116. #endif /* ZUTIL_H */
  80117. /*** End of inlined file: zutil.h ***/
  80118. /* for STDC and FAR definitions */
  80119. #define local static
  80120. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80121. #ifndef NOBYFOUR
  80122. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80123. # include <limits.h>
  80124. # define BYFOUR
  80125. # if (UINT_MAX == 0xffffffffUL)
  80126. typedef unsigned int u4;
  80127. # else
  80128. # if (ULONG_MAX == 0xffffffffUL)
  80129. typedef unsigned long u4;
  80130. # else
  80131. # if (USHRT_MAX == 0xffffffffUL)
  80132. typedef unsigned short u4;
  80133. # else
  80134. # undef BYFOUR /* can't find a four-byte integer type! */
  80135. # endif
  80136. # endif
  80137. # endif
  80138. # endif /* STDC */
  80139. #endif /* !NOBYFOUR */
  80140. /* Definitions for doing the crc four data bytes at a time. */
  80141. #ifdef BYFOUR
  80142. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80143. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80144. local unsigned long crc32_little OF((unsigned long,
  80145. const unsigned char FAR *, unsigned));
  80146. local unsigned long crc32_big OF((unsigned long,
  80147. const unsigned char FAR *, unsigned));
  80148. # define TBLS 8
  80149. #else
  80150. # define TBLS 1
  80151. #endif /* BYFOUR */
  80152. /* Local functions for crc concatenation */
  80153. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80154. unsigned long vec));
  80155. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80156. #ifdef DYNAMIC_CRC_TABLE
  80157. local volatile int crc_table_empty = 1;
  80158. local unsigned long FAR crc_table[TBLS][256];
  80159. local void make_crc_table OF((void));
  80160. #ifdef MAKECRCH
  80161. local void write_table OF((FILE *, const unsigned long FAR *));
  80162. #endif /* MAKECRCH */
  80163. /*
  80164. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80165. 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.
  80166. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80167. with the lowest powers in the most significant bit. Then adding polynomials
  80168. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80169. one. If we call the above polynomial p, and represent a byte as the
  80170. polynomial q, also with the lowest power in the most significant bit (so the
  80171. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80172. where a mod b means the remainder after dividing a by b.
  80173. This calculation is done using the shift-register method of multiplying and
  80174. taking the remainder. The register is initialized to zero, and for each
  80175. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80176. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80177. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80178. out is a one). We start with the highest power (least significant bit) of
  80179. q and repeat for all eight bits of q.
  80180. The first table is simply the CRC of all possible eight bit values. This is
  80181. all the information needed to generate CRCs on data a byte at a time for all
  80182. combinations of CRC register values and incoming bytes. The remaining tables
  80183. allow for word-at-a-time CRC calculation for both big-endian and little-
  80184. endian machines, where a word is four bytes.
  80185. */
  80186. local void make_crc_table()
  80187. {
  80188. unsigned long c;
  80189. int n, k;
  80190. unsigned long poly; /* polynomial exclusive-or pattern */
  80191. /* terms of polynomial defining this crc (except x^32): */
  80192. static volatile int first = 1; /* flag to limit concurrent making */
  80193. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80194. /* See if another task is already doing this (not thread-safe, but better
  80195. than nothing -- significantly reduces duration of vulnerability in
  80196. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80197. if (first) {
  80198. first = 0;
  80199. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80200. poly = 0UL;
  80201. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80202. poly |= 1UL << (31 - p[n]);
  80203. /* generate a crc for every 8-bit value */
  80204. for (n = 0; n < 256; n++) {
  80205. c = (unsigned long)n;
  80206. for (k = 0; k < 8; k++)
  80207. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80208. crc_table[0][n] = c;
  80209. }
  80210. #ifdef BYFOUR
  80211. /* generate crc for each value followed by one, two, and three zeros,
  80212. and then the byte reversal of those as well as the first table */
  80213. for (n = 0; n < 256; n++) {
  80214. c = crc_table[0][n];
  80215. crc_table[4][n] = REV(c);
  80216. for (k = 1; k < 4; k++) {
  80217. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80218. crc_table[k][n] = c;
  80219. crc_table[k + 4][n] = REV(c);
  80220. }
  80221. }
  80222. #endif /* BYFOUR */
  80223. crc_table_empty = 0;
  80224. }
  80225. else { /* not first */
  80226. /* wait for the other guy to finish (not efficient, but rare) */
  80227. while (crc_table_empty)
  80228. ;
  80229. }
  80230. #ifdef MAKECRCH
  80231. /* write out CRC tables to crc32.h */
  80232. {
  80233. FILE *out;
  80234. out = fopen("crc32.h", "w");
  80235. if (out == NULL) return;
  80236. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80237. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80238. fprintf(out, "local const unsigned long FAR ");
  80239. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80240. write_table(out, crc_table[0]);
  80241. # ifdef BYFOUR
  80242. fprintf(out, "#ifdef BYFOUR\n");
  80243. for (k = 1; k < 8; k++) {
  80244. fprintf(out, " },\n {\n");
  80245. write_table(out, crc_table[k]);
  80246. }
  80247. fprintf(out, "#endif\n");
  80248. # endif /* BYFOUR */
  80249. fprintf(out, " }\n};\n");
  80250. fclose(out);
  80251. }
  80252. #endif /* MAKECRCH */
  80253. }
  80254. #ifdef MAKECRCH
  80255. local void write_table(out, table)
  80256. FILE *out;
  80257. const unsigned long FAR *table;
  80258. {
  80259. int n;
  80260. for (n = 0; n < 256; n++)
  80261. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80262. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80263. }
  80264. #endif /* MAKECRCH */
  80265. #else /* !DYNAMIC_CRC_TABLE */
  80266. /* ========================================================================
  80267. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80268. */
  80269. /*** Start of inlined file: crc32.h ***/
  80270. local const unsigned long FAR crc_table[TBLS][256] =
  80271. {
  80272. {
  80273. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80274. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80275. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80276. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80277. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80278. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80279. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80280. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80281. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80282. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80283. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80284. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80285. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80286. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80287. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80288. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80289. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80290. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80291. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80292. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80293. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80294. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80295. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80296. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80297. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80298. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80299. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80300. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80301. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80302. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80303. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80304. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80305. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80306. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80307. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80308. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80309. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80310. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80311. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80312. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80313. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80314. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80315. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80316. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80317. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80318. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80319. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80320. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80321. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80322. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80323. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80324. 0x2d02ef8dUL
  80325. #ifdef BYFOUR
  80326. },
  80327. {
  80328. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80329. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80330. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80331. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80332. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80333. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80334. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80335. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80336. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80337. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80338. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80339. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80340. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80341. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80342. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80343. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80344. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80345. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80346. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80347. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80348. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80349. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80350. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80351. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80352. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80353. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80354. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80355. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80356. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80357. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80358. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80359. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80360. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80361. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80362. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80363. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80364. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80365. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80366. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80367. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80368. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80369. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80370. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80371. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80372. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80373. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80374. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80375. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80376. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80377. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80378. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80379. 0x9324fd72UL
  80380. },
  80381. {
  80382. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80383. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80384. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80385. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80386. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80387. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80388. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80389. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80390. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80391. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80392. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80393. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80394. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80395. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80396. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80397. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80398. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80399. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80400. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80401. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80402. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80403. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80404. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80405. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80406. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80407. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80408. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80409. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80410. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80411. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80412. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80413. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80414. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80415. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80416. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80417. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80418. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80419. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80420. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80421. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80422. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80423. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80424. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80425. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80426. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80427. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80428. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80429. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80430. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80431. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80432. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80433. 0xbe9834edUL
  80434. },
  80435. {
  80436. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80437. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80438. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80439. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80440. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80441. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80442. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80443. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80444. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80445. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80446. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80447. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80448. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80449. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80450. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80451. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80452. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80453. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80454. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80455. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80456. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80457. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80458. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80459. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80460. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80461. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80462. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80463. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80464. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80465. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80466. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80467. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80468. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80469. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80470. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80471. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80472. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80473. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80474. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80475. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80476. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80477. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80478. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80479. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80480. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80481. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80482. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80483. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80484. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80485. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80486. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80487. 0xde0506f1UL
  80488. },
  80489. {
  80490. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80491. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80492. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80493. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80494. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80495. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80496. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80497. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80498. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80499. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80500. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80501. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80502. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80503. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80504. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80505. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80506. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80507. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80508. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80509. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80510. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80511. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80512. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80513. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80514. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80515. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80516. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80517. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80518. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80519. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80520. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80521. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80522. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80523. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80524. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80525. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80526. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80527. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80528. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80529. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80530. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80531. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80532. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80533. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80534. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80535. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80536. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80537. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80538. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80539. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80540. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80541. 0x8def022dUL
  80542. },
  80543. {
  80544. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80545. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80546. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80547. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80548. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80549. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80550. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80551. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80552. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80553. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80554. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80555. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80556. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80557. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80558. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80559. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80560. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80561. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80562. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80563. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80564. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80565. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80566. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80567. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80568. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80569. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80570. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80571. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80572. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80573. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80574. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80575. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80576. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80577. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80578. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80579. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80580. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80581. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80582. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80583. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80584. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80585. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80586. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80587. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80588. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80589. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80590. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80591. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80592. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80593. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80594. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80595. 0x72fd2493UL
  80596. },
  80597. {
  80598. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80599. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80600. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80601. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80602. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80603. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80604. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80605. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80606. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80607. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80608. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80609. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80610. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80611. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80612. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80613. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80614. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80615. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80616. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80617. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80618. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80619. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80620. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80621. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80622. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80623. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80624. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80625. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80626. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80627. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80628. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80629. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80630. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80631. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80632. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80633. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80634. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80635. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80636. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80637. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80638. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80639. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80640. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80641. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80642. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80643. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80644. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80645. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80646. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80647. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80648. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80649. 0xed3498beUL
  80650. },
  80651. {
  80652. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80653. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80654. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80655. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80656. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80657. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80658. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80659. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80660. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80661. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80662. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80663. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80664. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80665. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80666. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80667. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80668. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80669. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80670. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80671. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80672. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80673. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80674. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80675. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80676. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80677. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80678. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80679. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80680. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80681. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80682. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80683. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80684. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80685. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80686. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80687. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80688. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80689. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80690. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80691. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80692. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80693. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80694. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80695. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80696. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80697. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80698. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80699. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80700. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80701. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80702. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80703. 0xf10605deUL
  80704. #endif
  80705. }
  80706. };
  80707. /*** End of inlined file: crc32.h ***/
  80708. #endif /* DYNAMIC_CRC_TABLE */
  80709. /* =========================================================================
  80710. * This function can be used by asm versions of crc32()
  80711. */
  80712. const unsigned long FAR * ZEXPORT get_crc_table()
  80713. {
  80714. #ifdef DYNAMIC_CRC_TABLE
  80715. if (crc_table_empty)
  80716. make_crc_table();
  80717. #endif /* DYNAMIC_CRC_TABLE */
  80718. return (const unsigned long FAR *)crc_table;
  80719. }
  80720. /* ========================================================================= */
  80721. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80722. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80723. /* ========================================================================= */
  80724. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80725. {
  80726. if (buf == Z_NULL) return 0UL;
  80727. #ifdef DYNAMIC_CRC_TABLE
  80728. if (crc_table_empty)
  80729. make_crc_table();
  80730. #endif /* DYNAMIC_CRC_TABLE */
  80731. #ifdef BYFOUR
  80732. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80733. u4 endian;
  80734. endian = 1;
  80735. if (*((unsigned char *)(&endian)))
  80736. return crc32_little(crc, buf, len);
  80737. else
  80738. return crc32_big(crc, buf, len);
  80739. }
  80740. #endif /* BYFOUR */
  80741. crc = crc ^ 0xffffffffUL;
  80742. while (len >= 8) {
  80743. DO8;
  80744. len -= 8;
  80745. }
  80746. if (len) do {
  80747. DO1;
  80748. } while (--len);
  80749. return crc ^ 0xffffffffUL;
  80750. }
  80751. #ifdef BYFOUR
  80752. /* ========================================================================= */
  80753. #define DOLIT4 c ^= *buf4++; \
  80754. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80755. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80756. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80757. /* ========================================================================= */
  80758. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80759. {
  80760. register u4 c;
  80761. register const u4 FAR *buf4;
  80762. c = (u4)crc;
  80763. c = ~c;
  80764. while (len && ((ptrdiff_t)buf & 3)) {
  80765. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80766. len--;
  80767. }
  80768. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80769. while (len >= 32) {
  80770. DOLIT32;
  80771. len -= 32;
  80772. }
  80773. while (len >= 4) {
  80774. DOLIT4;
  80775. len -= 4;
  80776. }
  80777. buf = (const unsigned char FAR *)buf4;
  80778. if (len) do {
  80779. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80780. } while (--len);
  80781. c = ~c;
  80782. return (unsigned long)c;
  80783. }
  80784. /* ========================================================================= */
  80785. #define DOBIG4 c ^= *++buf4; \
  80786. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80787. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80788. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80789. /* ========================================================================= */
  80790. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80791. {
  80792. register u4 c;
  80793. register const u4 FAR *buf4;
  80794. c = REV((u4)crc);
  80795. c = ~c;
  80796. while (len && ((ptrdiff_t)buf & 3)) {
  80797. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80798. len--;
  80799. }
  80800. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80801. buf4--;
  80802. while (len >= 32) {
  80803. DOBIG32;
  80804. len -= 32;
  80805. }
  80806. while (len >= 4) {
  80807. DOBIG4;
  80808. len -= 4;
  80809. }
  80810. buf4++;
  80811. buf = (const unsigned char FAR *)buf4;
  80812. if (len) do {
  80813. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80814. } while (--len);
  80815. c = ~c;
  80816. return (unsigned long)(REV(c));
  80817. }
  80818. #endif /* BYFOUR */
  80819. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80820. /* ========================================================================= */
  80821. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80822. {
  80823. unsigned long sum;
  80824. sum = 0;
  80825. while (vec) {
  80826. if (vec & 1)
  80827. sum ^= *mat;
  80828. vec >>= 1;
  80829. mat++;
  80830. }
  80831. return sum;
  80832. }
  80833. /* ========================================================================= */
  80834. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80835. {
  80836. int n;
  80837. for (n = 0; n < GF2_DIM; n++)
  80838. square[n] = gf2_matrix_times(mat, mat[n]);
  80839. }
  80840. /* ========================================================================= */
  80841. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80842. {
  80843. int n;
  80844. unsigned long row;
  80845. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80846. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80847. /* degenerate case */
  80848. if (len2 == 0)
  80849. return crc1;
  80850. /* put operator for one zero bit in odd */
  80851. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80852. row = 1;
  80853. for (n = 1; n < GF2_DIM; n++) {
  80854. odd[n] = row;
  80855. row <<= 1;
  80856. }
  80857. /* put operator for two zero bits in even */
  80858. gf2_matrix_square(even, odd);
  80859. /* put operator for four zero bits in odd */
  80860. gf2_matrix_square(odd, even);
  80861. /* apply len2 zeros to crc1 (first square will put the operator for one
  80862. zero byte, eight zero bits, in even) */
  80863. do {
  80864. /* apply zeros operator for this bit of len2 */
  80865. gf2_matrix_square(even, odd);
  80866. if (len2 & 1)
  80867. crc1 = gf2_matrix_times(even, crc1);
  80868. len2 >>= 1;
  80869. /* if no more bits set, then done */
  80870. if (len2 == 0)
  80871. break;
  80872. /* another iteration of the loop with odd and even swapped */
  80873. gf2_matrix_square(odd, even);
  80874. if (len2 & 1)
  80875. crc1 = gf2_matrix_times(odd, crc1);
  80876. len2 >>= 1;
  80877. /* if no more bits set, then done */
  80878. } while (len2 != 0);
  80879. /* return combined crc */
  80880. crc1 ^= crc2;
  80881. return crc1;
  80882. }
  80883. /*** End of inlined file: crc32.c ***/
  80884. /*** Start of inlined file: deflate.c ***/
  80885. /*
  80886. * ALGORITHM
  80887. *
  80888. * The "deflation" process depends on being able to identify portions
  80889. * of the input text which are identical to earlier input (within a
  80890. * sliding window trailing behind the input currently being processed).
  80891. *
  80892. * The most straightforward technique turns out to be the fastest for
  80893. * most input files: try all possible matches and select the longest.
  80894. * The key feature of this algorithm is that insertions into the string
  80895. * dictionary are very simple and thus fast, and deletions are avoided
  80896. * completely. Insertions are performed at each input character, whereas
  80897. * string matches are performed only when the previous match ends. So it
  80898. * is preferable to spend more time in matches to allow very fast string
  80899. * insertions and avoid deletions. The matching algorithm for small
  80900. * strings is inspired from that of Rabin & Karp. A brute force approach
  80901. * is used to find longer strings when a small match has been found.
  80902. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80903. * (by Leonid Broukhis).
  80904. * A previous version of this file used a more sophisticated algorithm
  80905. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80906. * time, but has a larger average cost, uses more memory and is patented.
  80907. * However the F&G algorithm may be faster for some highly redundant
  80908. * files if the parameter max_chain_length (described below) is too large.
  80909. *
  80910. * ACKNOWLEDGEMENTS
  80911. *
  80912. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80913. * I found it in 'freeze' written by Leonid Broukhis.
  80914. * Thanks to many people for bug reports and testing.
  80915. *
  80916. * REFERENCES
  80917. *
  80918. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80919. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80920. *
  80921. * A description of the Rabin and Karp algorithm is given in the book
  80922. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80923. *
  80924. * Fiala,E.R., and Greene,D.H.
  80925. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80926. *
  80927. */
  80928. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80929. /*** Start of inlined file: deflate.h ***/
  80930. /* WARNING: this file should *not* be used by applications. It is
  80931. part of the implementation of the compression library and is
  80932. subject to change. Applications should only use zlib.h.
  80933. */
  80934. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80935. #ifndef DEFLATE_H
  80936. #define DEFLATE_H
  80937. /* define NO_GZIP when compiling if you want to disable gzip header and
  80938. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80939. the crc code when it is not needed. For shared libraries, gzip encoding
  80940. should be left enabled. */
  80941. #ifndef NO_GZIP
  80942. # define GZIP
  80943. #endif
  80944. #define NO_DUMMY_DECL
  80945. /* ===========================================================================
  80946. * Internal compression state.
  80947. */
  80948. #define LENGTH_CODES 29
  80949. /* number of length codes, not counting the special END_BLOCK code */
  80950. #define LITERALS 256
  80951. /* number of literal bytes 0..255 */
  80952. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80953. /* number of Literal or Length codes, including the END_BLOCK code */
  80954. #define D_CODES 30
  80955. /* number of distance codes */
  80956. #define BL_CODES 19
  80957. /* number of codes used to transfer the bit lengths */
  80958. #define HEAP_SIZE (2*L_CODES+1)
  80959. /* maximum heap size */
  80960. #define MAX_BITS 15
  80961. /* All codes must not exceed MAX_BITS bits */
  80962. #define INIT_STATE 42
  80963. #define EXTRA_STATE 69
  80964. #define NAME_STATE 73
  80965. #define COMMENT_STATE 91
  80966. #define HCRC_STATE 103
  80967. #define BUSY_STATE 113
  80968. #define FINISH_STATE 666
  80969. /* Stream status */
  80970. /* Data structure describing a single value and its code string. */
  80971. typedef struct ct_data_s {
  80972. union {
  80973. ush freq; /* frequency count */
  80974. ush code; /* bit string */
  80975. } fc;
  80976. union {
  80977. ush dad; /* father node in Huffman tree */
  80978. ush len; /* length of bit string */
  80979. } dl;
  80980. } FAR ct_data;
  80981. #define Freq fc.freq
  80982. #define Code fc.code
  80983. #define Dad dl.dad
  80984. #define Len dl.len
  80985. typedef struct static_tree_desc_s static_tree_desc;
  80986. typedef struct tree_desc_s {
  80987. ct_data *dyn_tree; /* the dynamic tree */
  80988. int max_code; /* largest code with non zero frequency */
  80989. static_tree_desc *stat_desc; /* the corresponding static tree */
  80990. } FAR tree_desc;
  80991. typedef ush Pos;
  80992. typedef Pos FAR Posf;
  80993. typedef unsigned IPos;
  80994. /* A Pos is an index in the character window. We use short instead of int to
  80995. * save space in the various tables. IPos is used only for parameter passing.
  80996. */
  80997. typedef struct internal_state {
  80998. z_streamp strm; /* pointer back to this zlib stream */
  80999. int status; /* as the name implies */
  81000. Bytef *pending_buf; /* output still pending */
  81001. ulg pending_buf_size; /* size of pending_buf */
  81002. Bytef *pending_out; /* next pending byte to output to the stream */
  81003. uInt pending; /* nb of bytes in the pending buffer */
  81004. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81005. gz_headerp gzhead; /* gzip header information to write */
  81006. uInt gzindex; /* where in extra, name, or comment */
  81007. Byte method; /* STORED (for zip only) or DEFLATED */
  81008. int last_flush; /* value of flush param for previous deflate call */
  81009. /* used by deflate.c: */
  81010. uInt w_size; /* LZ77 window size (32K by default) */
  81011. uInt w_bits; /* log2(w_size) (8..16) */
  81012. uInt w_mask; /* w_size - 1 */
  81013. Bytef *window;
  81014. /* Sliding window. Input bytes are read into the second half of the window,
  81015. * and move to the first half later to keep a dictionary of at least wSize
  81016. * bytes. With this organization, matches are limited to a distance of
  81017. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  81018. * performed with a length multiple of the block size. Also, it limits
  81019. * the window size to 64K, which is quite useful on MSDOS.
  81020. * To do: use the user input buffer as sliding window.
  81021. */
  81022. ulg window_size;
  81023. /* Actual size of window: 2*wSize, except when the user input buffer
  81024. * is directly used as sliding window.
  81025. */
  81026. Posf *prev;
  81027. /* Link to older string with same hash index. To limit the size of this
  81028. * array to 64K, this link is maintained only for the last 32K strings.
  81029. * An index in this array is thus a window index modulo 32K.
  81030. */
  81031. Posf *head; /* Heads of the hash chains or NIL. */
  81032. uInt ins_h; /* hash index of string to be inserted */
  81033. uInt hash_size; /* number of elements in hash table */
  81034. uInt hash_bits; /* log2(hash_size) */
  81035. uInt hash_mask; /* hash_size-1 */
  81036. uInt hash_shift;
  81037. /* Number of bits by which ins_h must be shifted at each input
  81038. * step. It must be such that after MIN_MATCH steps, the oldest
  81039. * byte no longer takes part in the hash key, that is:
  81040. * hash_shift * MIN_MATCH >= hash_bits
  81041. */
  81042. long block_start;
  81043. /* Window position at the beginning of the current output block. Gets
  81044. * negative when the window is moved backwards.
  81045. */
  81046. uInt match_length; /* length of best match */
  81047. IPos prev_match; /* previous match */
  81048. int match_available; /* set if previous match exists */
  81049. uInt strstart; /* start of string to insert */
  81050. uInt match_start; /* start of matching string */
  81051. uInt lookahead; /* number of valid bytes ahead in window */
  81052. uInt prev_length;
  81053. /* Length of the best match at previous step. Matches not greater than this
  81054. * are discarded. This is used in the lazy match evaluation.
  81055. */
  81056. uInt max_chain_length;
  81057. /* To speed up deflation, hash chains are never searched beyond this
  81058. * length. A higher limit improves compression ratio but degrades the
  81059. * speed.
  81060. */
  81061. uInt max_lazy_match;
  81062. /* Attempt to find a better match only when the current match is strictly
  81063. * smaller than this value. This mechanism is used only for compression
  81064. * levels >= 4.
  81065. */
  81066. # define max_insert_length max_lazy_match
  81067. /* Insert new strings in the hash table only if the match length is not
  81068. * greater than this length. This saves time but degrades compression.
  81069. * max_insert_length is used only for compression levels <= 3.
  81070. */
  81071. int level; /* compression level (1..9) */
  81072. int strategy; /* favor or force Huffman coding*/
  81073. uInt good_match;
  81074. /* Use a faster search when the previous match is longer than this */
  81075. int nice_match; /* Stop searching when current match exceeds this */
  81076. /* used by trees.c: */
  81077. /* Didn't use ct_data typedef below to supress compiler warning */
  81078. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  81079. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  81080. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  81081. struct tree_desc_s l_desc; /* desc. for literal tree */
  81082. struct tree_desc_s d_desc; /* desc. for distance tree */
  81083. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  81084. ush bl_count[MAX_BITS+1];
  81085. /* number of codes at each bit length for an optimal tree */
  81086. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81087. int heap_len; /* number of elements in the heap */
  81088. int heap_max; /* element of largest frequency */
  81089. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81090. * The same heap array is used to build all trees.
  81091. */
  81092. uch depth[2*L_CODES+1];
  81093. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81094. */
  81095. uchf *l_buf; /* buffer for literals or lengths */
  81096. uInt lit_bufsize;
  81097. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81098. * limiting lit_bufsize to 64K:
  81099. * - frequencies can be kept in 16 bit counters
  81100. * - if compression is not successful for the first block, all input
  81101. * data is still in the window so we can still emit a stored block even
  81102. * when input comes from standard input. (This can also be done for
  81103. * all blocks if lit_bufsize is not greater than 32K.)
  81104. * - if compression is not successful for a file smaller than 64K, we can
  81105. * even emit a stored file instead of a stored block (saving 5 bytes).
  81106. * This is applicable only for zip (not gzip or zlib).
  81107. * - creating new Huffman trees less frequently may not provide fast
  81108. * adaptation to changes in the input data statistics. (Take for
  81109. * example a binary file with poorly compressible code followed by
  81110. * a highly compressible string table.) Smaller buffer sizes give
  81111. * fast adaptation but have of course the overhead of transmitting
  81112. * trees more frequently.
  81113. * - I can't count above 4
  81114. */
  81115. uInt last_lit; /* running index in l_buf */
  81116. ushf *d_buf;
  81117. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81118. * the same number of elements. To use different lengths, an extra flag
  81119. * array would be necessary.
  81120. */
  81121. ulg opt_len; /* bit length of current block with optimal trees */
  81122. ulg static_len; /* bit length of current block with static trees */
  81123. uInt matches; /* number of string matches in current block */
  81124. int last_eob_len; /* bit length of EOB code for last block */
  81125. #ifdef DEBUG
  81126. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81127. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81128. #endif
  81129. ush bi_buf;
  81130. /* Output buffer. bits are inserted starting at the bottom (least
  81131. * significant bits).
  81132. */
  81133. int bi_valid;
  81134. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81135. * are always zero.
  81136. */
  81137. } FAR deflate_state;
  81138. /* Output a byte on the stream.
  81139. * IN assertion: there is enough room in pending_buf.
  81140. */
  81141. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81142. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81143. /* Minimum amount of lookahead, except at the end of the input file.
  81144. * See deflate.c for comments about the MIN_MATCH+1.
  81145. */
  81146. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81147. /* In order to simplify the code, particularly on 16 bit machines, match
  81148. * distances are limited to MAX_DIST instead of WSIZE.
  81149. */
  81150. /* in trees.c */
  81151. void _tr_init OF((deflate_state *s));
  81152. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81153. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81154. int eof));
  81155. void _tr_align OF((deflate_state *s));
  81156. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81157. int eof));
  81158. #define d_code(dist) \
  81159. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81160. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81161. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81162. * used.
  81163. */
  81164. #ifndef DEBUG
  81165. /* Inline versions of _tr_tally for speed: */
  81166. #if defined(GEN_TREES_H) || !defined(STDC)
  81167. extern uch _length_code[];
  81168. extern uch _dist_code[];
  81169. #else
  81170. extern const uch _length_code[];
  81171. extern const uch _dist_code[];
  81172. #endif
  81173. # define _tr_tally_lit(s, c, flush) \
  81174. { uch cc = (c); \
  81175. s->d_buf[s->last_lit] = 0; \
  81176. s->l_buf[s->last_lit++] = cc; \
  81177. s->dyn_ltree[cc].Freq++; \
  81178. flush = (s->last_lit == s->lit_bufsize-1); \
  81179. }
  81180. # define _tr_tally_dist(s, distance, length, flush) \
  81181. { uch len = (length); \
  81182. ush dist = (distance); \
  81183. s->d_buf[s->last_lit] = dist; \
  81184. s->l_buf[s->last_lit++] = len; \
  81185. dist--; \
  81186. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81187. s->dyn_dtree[d_code(dist)].Freq++; \
  81188. flush = (s->last_lit == s->lit_bufsize-1); \
  81189. }
  81190. #else
  81191. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81192. # define _tr_tally_dist(s, distance, length, flush) \
  81193. flush = _tr_tally(s, distance, length)
  81194. #endif
  81195. #endif /* DEFLATE_H */
  81196. /*** End of inlined file: deflate.h ***/
  81197. const char deflate_copyright[] =
  81198. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81199. /*
  81200. If you use the zlib library in a product, an acknowledgment is welcome
  81201. in the documentation of your product. If for some reason you cannot
  81202. include such an acknowledgment, I would appreciate that you keep this
  81203. copyright string in the executable of your product.
  81204. */
  81205. /* ===========================================================================
  81206. * Function prototypes.
  81207. */
  81208. typedef enum {
  81209. need_more, /* block not completed, need more input or more output */
  81210. block_done, /* block flush performed */
  81211. finish_started, /* finish started, need only more output at next deflate */
  81212. finish_done /* finish done, accept no more input or output */
  81213. } block_state;
  81214. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81215. /* Compression function. Returns the block state after the call. */
  81216. local void fill_window OF((deflate_state *s));
  81217. local block_state deflate_stored OF((deflate_state *s, int flush));
  81218. local block_state deflate_fast OF((deflate_state *s, int flush));
  81219. #ifndef FASTEST
  81220. local block_state deflate_slow OF((deflate_state *s, int flush));
  81221. #endif
  81222. local void lm_init OF((deflate_state *s));
  81223. local void putShortMSB OF((deflate_state *s, uInt b));
  81224. local void flush_pending OF((z_streamp strm));
  81225. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81226. #ifndef FASTEST
  81227. #ifdef ASMV
  81228. void match_init OF((void)); /* asm code initialization */
  81229. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81230. #else
  81231. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81232. #endif
  81233. #endif
  81234. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81235. #ifdef DEBUG
  81236. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81237. int length));
  81238. #endif
  81239. /* ===========================================================================
  81240. * Local data
  81241. */
  81242. #define NIL 0
  81243. /* Tail of hash chains */
  81244. #ifndef TOO_FAR
  81245. # define TOO_FAR 4096
  81246. #endif
  81247. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81248. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81249. /* Minimum amount of lookahead, except at the end of the input file.
  81250. * See deflate.c for comments about the MIN_MATCH+1.
  81251. */
  81252. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81253. * the desired pack level (0..9). The values given below have been tuned to
  81254. * exclude worst case performance for pathological files. Better values may be
  81255. * found for specific files.
  81256. */
  81257. typedef struct config_s {
  81258. ush good_length; /* reduce lazy search above this match length */
  81259. ush max_lazy; /* do not perform lazy search above this match length */
  81260. ush nice_length; /* quit search above this match length */
  81261. ush max_chain;
  81262. compress_func func;
  81263. } config;
  81264. #ifdef FASTEST
  81265. local const config configuration_table[2] = {
  81266. /* good lazy nice chain */
  81267. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81268. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81269. #else
  81270. local const config configuration_table[10] = {
  81271. /* good lazy nice chain */
  81272. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81273. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81274. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81275. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81276. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81277. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81278. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81279. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81280. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81281. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81282. #endif
  81283. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81284. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81285. * meaning.
  81286. */
  81287. #define EQUAL 0
  81288. /* result of memcmp for equal strings */
  81289. #ifndef NO_DUMMY_DECL
  81290. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81291. #endif
  81292. /* ===========================================================================
  81293. * Update a hash value with the given input byte
  81294. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81295. * input characters, so that a running hash key can be computed from the
  81296. * previous key instead of complete recalculation each time.
  81297. */
  81298. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81299. /* ===========================================================================
  81300. * Insert string str in the dictionary and set match_head to the previous head
  81301. * of the hash chain (the most recent string with same hash key). Return
  81302. * the previous length of the hash chain.
  81303. * If this file is compiled with -DFASTEST, the compression level is forced
  81304. * to 1, and no hash chains are maintained.
  81305. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81306. * input characters and the first MIN_MATCH bytes of str are valid
  81307. * (except for the last MIN_MATCH-1 bytes of the input file).
  81308. */
  81309. #ifdef FASTEST
  81310. #define INSERT_STRING(s, str, match_head) \
  81311. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81312. match_head = s->head[s->ins_h], \
  81313. s->head[s->ins_h] = (Pos)(str))
  81314. #else
  81315. #define INSERT_STRING(s, str, match_head) \
  81316. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81317. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81318. s->head[s->ins_h] = (Pos)(str))
  81319. #endif
  81320. /* ===========================================================================
  81321. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81322. * prev[] will be initialized on the fly.
  81323. */
  81324. #define CLEAR_HASH(s) \
  81325. s->head[s->hash_size-1] = NIL; \
  81326. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81327. /* ========================================================================= */
  81328. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81329. {
  81330. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81331. Z_DEFAULT_STRATEGY, version, stream_size);
  81332. /* To do: ignore strm->next_in if we use it as window */
  81333. }
  81334. /* ========================================================================= */
  81335. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81336. {
  81337. deflate_state *s;
  81338. int wrap = 1;
  81339. static const char my_version[] = ZLIB_VERSION;
  81340. ushf *overlay;
  81341. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81342. * output size for (length,distance) codes is <= 24 bits.
  81343. */
  81344. if (version == Z_NULL || version[0] != my_version[0] ||
  81345. stream_size != sizeof(z_stream)) {
  81346. return Z_VERSION_ERROR;
  81347. }
  81348. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81349. strm->msg = Z_NULL;
  81350. if (strm->zalloc == (alloc_func)0) {
  81351. strm->zalloc = zcalloc;
  81352. strm->opaque = (voidpf)0;
  81353. }
  81354. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81355. #ifdef FASTEST
  81356. if (level != 0) level = 1;
  81357. #else
  81358. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81359. #endif
  81360. if (windowBits < 0) { /* suppress zlib wrapper */
  81361. wrap = 0;
  81362. windowBits = -windowBits;
  81363. }
  81364. #ifdef GZIP
  81365. else if (windowBits > 15) {
  81366. wrap = 2; /* write gzip wrapper instead */
  81367. windowBits -= 16;
  81368. }
  81369. #endif
  81370. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81371. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81372. strategy < 0 || strategy > Z_FIXED) {
  81373. return Z_STREAM_ERROR;
  81374. }
  81375. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81376. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81377. if (s == Z_NULL) return Z_MEM_ERROR;
  81378. strm->state = (struct internal_state FAR *)s;
  81379. s->strm = strm;
  81380. s->wrap = wrap;
  81381. s->gzhead = Z_NULL;
  81382. s->w_bits = windowBits;
  81383. s->w_size = 1 << s->w_bits;
  81384. s->w_mask = s->w_size - 1;
  81385. s->hash_bits = memLevel + 7;
  81386. s->hash_size = 1 << s->hash_bits;
  81387. s->hash_mask = s->hash_size - 1;
  81388. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81389. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81390. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81391. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81392. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81393. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81394. s->pending_buf = (uchf *) overlay;
  81395. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81396. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81397. s->pending_buf == Z_NULL) {
  81398. s->status = FINISH_STATE;
  81399. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81400. deflateEnd (strm);
  81401. return Z_MEM_ERROR;
  81402. }
  81403. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81404. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81405. s->level = level;
  81406. s->strategy = strategy;
  81407. s->method = (Byte)method;
  81408. return deflateReset(strm);
  81409. }
  81410. /* ========================================================================= */
  81411. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81412. {
  81413. deflate_state *s;
  81414. uInt length = dictLength;
  81415. uInt n;
  81416. IPos hash_head = 0;
  81417. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81418. strm->state->wrap == 2 ||
  81419. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81420. return Z_STREAM_ERROR;
  81421. s = strm->state;
  81422. if (s->wrap)
  81423. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81424. if (length < MIN_MATCH) return Z_OK;
  81425. if (length > MAX_DIST(s)) {
  81426. length = MAX_DIST(s);
  81427. dictionary += dictLength - length; /* use the tail of the dictionary */
  81428. }
  81429. zmemcpy(s->window, dictionary, length);
  81430. s->strstart = length;
  81431. s->block_start = (long)length;
  81432. /* Insert all strings in the hash table (except for the last two bytes).
  81433. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81434. * call of fill_window.
  81435. */
  81436. s->ins_h = s->window[0];
  81437. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81438. for (n = 0; n <= length - MIN_MATCH; n++) {
  81439. INSERT_STRING(s, n, hash_head);
  81440. }
  81441. if (hash_head) hash_head = 0; /* to make compiler happy */
  81442. return Z_OK;
  81443. }
  81444. /* ========================================================================= */
  81445. int ZEXPORT deflateReset (z_streamp strm)
  81446. {
  81447. deflate_state *s;
  81448. if (strm == Z_NULL || strm->state == Z_NULL ||
  81449. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81450. return Z_STREAM_ERROR;
  81451. }
  81452. strm->total_in = strm->total_out = 0;
  81453. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81454. strm->data_type = Z_UNKNOWN;
  81455. s = (deflate_state *)strm->state;
  81456. s->pending = 0;
  81457. s->pending_out = s->pending_buf;
  81458. if (s->wrap < 0) {
  81459. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81460. }
  81461. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81462. strm->adler =
  81463. #ifdef GZIP
  81464. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81465. #endif
  81466. adler32(0L, Z_NULL, 0);
  81467. s->last_flush = Z_NO_FLUSH;
  81468. _tr_init(s);
  81469. lm_init(s);
  81470. return Z_OK;
  81471. }
  81472. /* ========================================================================= */
  81473. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81474. {
  81475. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81476. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81477. strm->state->gzhead = head;
  81478. return Z_OK;
  81479. }
  81480. /* ========================================================================= */
  81481. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81482. {
  81483. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81484. strm->state->bi_valid = bits;
  81485. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81486. return Z_OK;
  81487. }
  81488. /* ========================================================================= */
  81489. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81490. {
  81491. deflate_state *s;
  81492. compress_func func;
  81493. int err = Z_OK;
  81494. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81495. s = strm->state;
  81496. #ifdef FASTEST
  81497. if (level != 0) level = 1;
  81498. #else
  81499. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81500. #endif
  81501. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81502. return Z_STREAM_ERROR;
  81503. }
  81504. func = configuration_table[s->level].func;
  81505. if (func != configuration_table[level].func && strm->total_in != 0) {
  81506. /* Flush the last buffer: */
  81507. err = deflate(strm, Z_PARTIAL_FLUSH);
  81508. }
  81509. if (s->level != level) {
  81510. s->level = level;
  81511. s->max_lazy_match = configuration_table[level].max_lazy;
  81512. s->good_match = configuration_table[level].good_length;
  81513. s->nice_match = configuration_table[level].nice_length;
  81514. s->max_chain_length = configuration_table[level].max_chain;
  81515. }
  81516. s->strategy = strategy;
  81517. return err;
  81518. }
  81519. /* ========================================================================= */
  81520. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81521. {
  81522. deflate_state *s;
  81523. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81524. s = strm->state;
  81525. s->good_match = good_length;
  81526. s->max_lazy_match = max_lazy;
  81527. s->nice_match = nice_length;
  81528. s->max_chain_length = max_chain;
  81529. return Z_OK;
  81530. }
  81531. /* =========================================================================
  81532. * For the default windowBits of 15 and memLevel of 8, this function returns
  81533. * a close to exact, as well as small, upper bound on the compressed size.
  81534. * They are coded as constants here for a reason--if the #define's are
  81535. * changed, then this function needs to be changed as well. The return
  81536. * value for 15 and 8 only works for those exact settings.
  81537. *
  81538. * For any setting other than those defaults for windowBits and memLevel,
  81539. * the value returned is a conservative worst case for the maximum expansion
  81540. * resulting from using fixed blocks instead of stored blocks, which deflate
  81541. * can emit on compressed data for some combinations of the parameters.
  81542. *
  81543. * This function could be more sophisticated to provide closer upper bounds
  81544. * for every combination of windowBits and memLevel, as well as wrap.
  81545. * But even the conservative upper bound of about 14% expansion does not
  81546. * seem onerous for output buffer allocation.
  81547. */
  81548. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81549. {
  81550. deflate_state *s;
  81551. uLong destLen;
  81552. /* conservative upper bound */
  81553. destLen = sourceLen +
  81554. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81555. /* if can't get parameters, return conservative bound */
  81556. if (strm == Z_NULL || strm->state == Z_NULL)
  81557. return destLen;
  81558. /* if not default parameters, return conservative bound */
  81559. s = strm->state;
  81560. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81561. return destLen;
  81562. /* default settings: return tight bound for that case */
  81563. return compressBound(sourceLen);
  81564. }
  81565. /* =========================================================================
  81566. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81567. * IN assertion: the stream state is correct and there is enough room in
  81568. * pending_buf.
  81569. */
  81570. local void putShortMSB (deflate_state *s, uInt b)
  81571. {
  81572. put_byte(s, (Byte)(b >> 8));
  81573. put_byte(s, (Byte)(b & 0xff));
  81574. }
  81575. /* =========================================================================
  81576. * Flush as much pending output as possible. All deflate() output goes
  81577. * through this function so some applications may wish to modify it
  81578. * to avoid allocating a large strm->next_out buffer and copying into it.
  81579. * (See also read_buf()).
  81580. */
  81581. local void flush_pending (z_streamp strm)
  81582. {
  81583. unsigned len = strm->state->pending;
  81584. if (len > strm->avail_out) len = strm->avail_out;
  81585. if (len == 0) return;
  81586. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81587. strm->next_out += len;
  81588. strm->state->pending_out += len;
  81589. strm->total_out += len;
  81590. strm->avail_out -= len;
  81591. strm->state->pending -= len;
  81592. if (strm->state->pending == 0) {
  81593. strm->state->pending_out = strm->state->pending_buf;
  81594. }
  81595. }
  81596. /* ========================================================================= */
  81597. int ZEXPORT deflate (z_streamp strm, int flush)
  81598. {
  81599. int old_flush; /* value of flush param for previous deflate call */
  81600. deflate_state *s;
  81601. if (strm == Z_NULL || strm->state == Z_NULL ||
  81602. flush > Z_FINISH || flush < 0) {
  81603. return Z_STREAM_ERROR;
  81604. }
  81605. s = strm->state;
  81606. if (strm->next_out == Z_NULL ||
  81607. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81608. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81609. ERR_RETURN(strm, Z_STREAM_ERROR);
  81610. }
  81611. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81612. s->strm = strm; /* just in case */
  81613. old_flush = s->last_flush;
  81614. s->last_flush = flush;
  81615. /* Write the header */
  81616. if (s->status == INIT_STATE) {
  81617. #ifdef GZIP
  81618. if (s->wrap == 2) {
  81619. strm->adler = crc32(0L, Z_NULL, 0);
  81620. put_byte(s, 31);
  81621. put_byte(s, 139);
  81622. put_byte(s, 8);
  81623. if (s->gzhead == NULL) {
  81624. put_byte(s, 0);
  81625. put_byte(s, 0);
  81626. put_byte(s, 0);
  81627. put_byte(s, 0);
  81628. put_byte(s, 0);
  81629. put_byte(s, s->level == 9 ? 2 :
  81630. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81631. 4 : 0));
  81632. put_byte(s, OS_CODE);
  81633. s->status = BUSY_STATE;
  81634. }
  81635. else {
  81636. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81637. (s->gzhead->hcrc ? 2 : 0) +
  81638. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81639. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81640. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81641. );
  81642. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81643. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81644. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81645. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81646. put_byte(s, s->level == 9 ? 2 :
  81647. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81648. 4 : 0));
  81649. put_byte(s, s->gzhead->os & 0xff);
  81650. if (s->gzhead->extra != NULL) {
  81651. put_byte(s, s->gzhead->extra_len & 0xff);
  81652. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81653. }
  81654. if (s->gzhead->hcrc)
  81655. strm->adler = crc32(strm->adler, s->pending_buf,
  81656. s->pending);
  81657. s->gzindex = 0;
  81658. s->status = EXTRA_STATE;
  81659. }
  81660. }
  81661. else
  81662. #endif
  81663. {
  81664. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81665. uInt level_flags;
  81666. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81667. level_flags = 0;
  81668. else if (s->level < 6)
  81669. level_flags = 1;
  81670. else if (s->level == 6)
  81671. level_flags = 2;
  81672. else
  81673. level_flags = 3;
  81674. header |= (level_flags << 6);
  81675. if (s->strstart != 0) header |= PRESET_DICT;
  81676. header += 31 - (header % 31);
  81677. s->status = BUSY_STATE;
  81678. putShortMSB(s, header);
  81679. /* Save the adler32 of the preset dictionary: */
  81680. if (s->strstart != 0) {
  81681. putShortMSB(s, (uInt)(strm->adler >> 16));
  81682. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81683. }
  81684. strm->adler = adler32(0L, Z_NULL, 0);
  81685. }
  81686. }
  81687. #ifdef GZIP
  81688. if (s->status == EXTRA_STATE) {
  81689. if (s->gzhead->extra != NULL) {
  81690. uInt beg = s->pending; /* start of bytes to update crc */
  81691. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81692. if (s->pending == s->pending_buf_size) {
  81693. if (s->gzhead->hcrc && s->pending > beg)
  81694. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81695. s->pending - beg);
  81696. flush_pending(strm);
  81697. beg = s->pending;
  81698. if (s->pending == s->pending_buf_size)
  81699. break;
  81700. }
  81701. put_byte(s, s->gzhead->extra[s->gzindex]);
  81702. s->gzindex++;
  81703. }
  81704. if (s->gzhead->hcrc && s->pending > beg)
  81705. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81706. s->pending - beg);
  81707. if (s->gzindex == s->gzhead->extra_len) {
  81708. s->gzindex = 0;
  81709. s->status = NAME_STATE;
  81710. }
  81711. }
  81712. else
  81713. s->status = NAME_STATE;
  81714. }
  81715. if (s->status == NAME_STATE) {
  81716. if (s->gzhead->name != NULL) {
  81717. uInt beg = s->pending; /* start of bytes to update crc */
  81718. int val;
  81719. do {
  81720. if (s->pending == s->pending_buf_size) {
  81721. if (s->gzhead->hcrc && s->pending > beg)
  81722. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81723. s->pending - beg);
  81724. flush_pending(strm);
  81725. beg = s->pending;
  81726. if (s->pending == s->pending_buf_size) {
  81727. val = 1;
  81728. break;
  81729. }
  81730. }
  81731. val = s->gzhead->name[s->gzindex++];
  81732. put_byte(s, val);
  81733. } while (val != 0);
  81734. if (s->gzhead->hcrc && s->pending > beg)
  81735. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81736. s->pending - beg);
  81737. if (val == 0) {
  81738. s->gzindex = 0;
  81739. s->status = COMMENT_STATE;
  81740. }
  81741. }
  81742. else
  81743. s->status = COMMENT_STATE;
  81744. }
  81745. if (s->status == COMMENT_STATE) {
  81746. if (s->gzhead->comment != NULL) {
  81747. uInt beg = s->pending; /* start of bytes to update crc */
  81748. int val;
  81749. do {
  81750. if (s->pending == s->pending_buf_size) {
  81751. if (s->gzhead->hcrc && s->pending > beg)
  81752. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81753. s->pending - beg);
  81754. flush_pending(strm);
  81755. beg = s->pending;
  81756. if (s->pending == s->pending_buf_size) {
  81757. val = 1;
  81758. break;
  81759. }
  81760. }
  81761. val = s->gzhead->comment[s->gzindex++];
  81762. put_byte(s, val);
  81763. } while (val != 0);
  81764. if (s->gzhead->hcrc && s->pending > beg)
  81765. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81766. s->pending - beg);
  81767. if (val == 0)
  81768. s->status = HCRC_STATE;
  81769. }
  81770. else
  81771. s->status = HCRC_STATE;
  81772. }
  81773. if (s->status == HCRC_STATE) {
  81774. if (s->gzhead->hcrc) {
  81775. if (s->pending + 2 > s->pending_buf_size)
  81776. flush_pending(strm);
  81777. if (s->pending + 2 <= s->pending_buf_size) {
  81778. put_byte(s, (Byte)(strm->adler & 0xff));
  81779. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81780. strm->adler = crc32(0L, Z_NULL, 0);
  81781. s->status = BUSY_STATE;
  81782. }
  81783. }
  81784. else
  81785. s->status = BUSY_STATE;
  81786. }
  81787. #endif
  81788. /* Flush as much pending output as possible */
  81789. if (s->pending != 0) {
  81790. flush_pending(strm);
  81791. if (strm->avail_out == 0) {
  81792. /* Since avail_out is 0, deflate will be called again with
  81793. * more output space, but possibly with both pending and
  81794. * avail_in equal to zero. There won't be anything to do,
  81795. * but this is not an error situation so make sure we
  81796. * return OK instead of BUF_ERROR at next call of deflate:
  81797. */
  81798. s->last_flush = -1;
  81799. return Z_OK;
  81800. }
  81801. /* Make sure there is something to do and avoid duplicate consecutive
  81802. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81803. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81804. */
  81805. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81806. flush != Z_FINISH) {
  81807. ERR_RETURN(strm, Z_BUF_ERROR);
  81808. }
  81809. /* User must not provide more input after the first FINISH: */
  81810. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81811. ERR_RETURN(strm, Z_BUF_ERROR);
  81812. }
  81813. /* Start a new block or continue the current one.
  81814. */
  81815. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81816. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81817. block_state bstate;
  81818. bstate = (*(configuration_table[s->level].func))(s, flush);
  81819. if (bstate == finish_started || bstate == finish_done) {
  81820. s->status = FINISH_STATE;
  81821. }
  81822. if (bstate == need_more || bstate == finish_started) {
  81823. if (strm->avail_out == 0) {
  81824. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81825. }
  81826. return Z_OK;
  81827. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81828. * of deflate should use the same flush parameter to make sure
  81829. * that the flush is complete. So we don't have to output an
  81830. * empty block here, this will be done at next call. This also
  81831. * ensures that for a very small output buffer, we emit at most
  81832. * one empty block.
  81833. */
  81834. }
  81835. if (bstate == block_done) {
  81836. if (flush == Z_PARTIAL_FLUSH) {
  81837. _tr_align(s);
  81838. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81839. _tr_stored_block(s, (char*)0, 0L, 0);
  81840. /* For a full flush, this empty block will be recognized
  81841. * as a special marker by inflate_sync().
  81842. */
  81843. if (flush == Z_FULL_FLUSH) {
  81844. CLEAR_HASH(s); /* forget history */
  81845. }
  81846. }
  81847. flush_pending(strm);
  81848. if (strm->avail_out == 0) {
  81849. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81850. return Z_OK;
  81851. }
  81852. }
  81853. }
  81854. Assert(strm->avail_out > 0, "bug2");
  81855. if (flush != Z_FINISH) return Z_OK;
  81856. if (s->wrap <= 0) return Z_STREAM_END;
  81857. /* Write the trailer */
  81858. #ifdef GZIP
  81859. if (s->wrap == 2) {
  81860. put_byte(s, (Byte)(strm->adler & 0xff));
  81861. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81862. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81863. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81864. put_byte(s, (Byte)(strm->total_in & 0xff));
  81865. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81866. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81867. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81868. }
  81869. else
  81870. #endif
  81871. {
  81872. putShortMSB(s, (uInt)(strm->adler >> 16));
  81873. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81874. }
  81875. flush_pending(strm);
  81876. /* If avail_out is zero, the application will call deflate again
  81877. * to flush the rest.
  81878. */
  81879. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81880. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81881. }
  81882. /* ========================================================================= */
  81883. int ZEXPORT deflateEnd (z_streamp strm)
  81884. {
  81885. int status;
  81886. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81887. status = strm->state->status;
  81888. if (status != INIT_STATE &&
  81889. status != EXTRA_STATE &&
  81890. status != NAME_STATE &&
  81891. status != COMMENT_STATE &&
  81892. status != HCRC_STATE &&
  81893. status != BUSY_STATE &&
  81894. status != FINISH_STATE) {
  81895. return Z_STREAM_ERROR;
  81896. }
  81897. /* Deallocate in reverse order of allocations: */
  81898. TRY_FREE(strm, strm->state->pending_buf);
  81899. TRY_FREE(strm, strm->state->head);
  81900. TRY_FREE(strm, strm->state->prev);
  81901. TRY_FREE(strm, strm->state->window);
  81902. ZFREE(strm, strm->state);
  81903. strm->state = Z_NULL;
  81904. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81905. }
  81906. /* =========================================================================
  81907. * Copy the source state to the destination state.
  81908. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81909. * doesn't have enough memory anyway to duplicate compression states).
  81910. */
  81911. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81912. {
  81913. #ifdef MAXSEG_64K
  81914. return Z_STREAM_ERROR;
  81915. #else
  81916. deflate_state *ds;
  81917. deflate_state *ss;
  81918. ushf *overlay;
  81919. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81920. return Z_STREAM_ERROR;
  81921. }
  81922. ss = source->state;
  81923. zmemcpy(dest, source, sizeof(z_stream));
  81924. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81925. if (ds == Z_NULL) return Z_MEM_ERROR;
  81926. dest->state = (struct internal_state FAR *) ds;
  81927. zmemcpy(ds, ss, sizeof(deflate_state));
  81928. ds->strm = dest;
  81929. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81930. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81931. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81932. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81933. ds->pending_buf = (uchf *) overlay;
  81934. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81935. ds->pending_buf == Z_NULL) {
  81936. deflateEnd (dest);
  81937. return Z_MEM_ERROR;
  81938. }
  81939. /* following zmemcpy do not work for 16-bit MSDOS */
  81940. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81941. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81942. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81943. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81944. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81945. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81946. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81947. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81948. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81949. ds->bl_desc.dyn_tree = ds->bl_tree;
  81950. return Z_OK;
  81951. #endif /* MAXSEG_64K */
  81952. }
  81953. /* ===========================================================================
  81954. * Read a new buffer from the current input stream, update the adler32
  81955. * and total number of bytes read. All deflate() input goes through
  81956. * this function so some applications may wish to modify it to avoid
  81957. * allocating a large strm->next_in buffer and copying from it.
  81958. * (See also flush_pending()).
  81959. */
  81960. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81961. {
  81962. unsigned len = strm->avail_in;
  81963. if (len > size) len = size;
  81964. if (len == 0) return 0;
  81965. strm->avail_in -= len;
  81966. if (strm->state->wrap == 1) {
  81967. strm->adler = adler32(strm->adler, strm->next_in, len);
  81968. }
  81969. #ifdef GZIP
  81970. else if (strm->state->wrap == 2) {
  81971. strm->adler = crc32(strm->adler, strm->next_in, len);
  81972. }
  81973. #endif
  81974. zmemcpy(buf, strm->next_in, len);
  81975. strm->next_in += len;
  81976. strm->total_in += len;
  81977. return (int)len;
  81978. }
  81979. /* ===========================================================================
  81980. * Initialize the "longest match" routines for a new zlib stream
  81981. */
  81982. local void lm_init (deflate_state *s)
  81983. {
  81984. s->window_size = (ulg)2L*s->w_size;
  81985. CLEAR_HASH(s);
  81986. /* Set the default configuration parameters:
  81987. */
  81988. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81989. s->good_match = configuration_table[s->level].good_length;
  81990. s->nice_match = configuration_table[s->level].nice_length;
  81991. s->max_chain_length = configuration_table[s->level].max_chain;
  81992. s->strstart = 0;
  81993. s->block_start = 0L;
  81994. s->lookahead = 0;
  81995. s->match_length = s->prev_length = MIN_MATCH-1;
  81996. s->match_available = 0;
  81997. s->ins_h = 0;
  81998. #ifndef FASTEST
  81999. #ifdef ASMV
  82000. match_init(); /* initialize the asm code */
  82001. #endif
  82002. #endif
  82003. }
  82004. #ifndef FASTEST
  82005. /* ===========================================================================
  82006. * Set match_start to the longest match starting at the given string and
  82007. * return its length. Matches shorter or equal to prev_length are discarded,
  82008. * in which case the result is equal to prev_length and match_start is
  82009. * garbage.
  82010. * IN assertions: cur_match is the head of the hash chain for the current
  82011. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  82012. * OUT assertion: the match length is not greater than s->lookahead.
  82013. */
  82014. #ifndef ASMV
  82015. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  82016. * match.S. The code will be functionally equivalent.
  82017. */
  82018. local uInt longest_match(deflate_state *s, IPos cur_match)
  82019. {
  82020. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  82021. register Bytef *scan = s->window + s->strstart; /* current string */
  82022. register Bytef *match; /* matched string */
  82023. register int len; /* length of current match */
  82024. int best_len = s->prev_length; /* best match length so far */
  82025. int nice_match = s->nice_match; /* stop if match long enough */
  82026. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  82027. s->strstart - (IPos)MAX_DIST(s) : NIL;
  82028. /* Stop when cur_match becomes <= limit. To simplify the code,
  82029. * we prevent matches with the string of window index 0.
  82030. */
  82031. Posf *prev = s->prev;
  82032. uInt wmask = s->w_mask;
  82033. #ifdef UNALIGNED_OK
  82034. /* Compare two bytes at a time. Note: this is not always beneficial.
  82035. * Try with and without -DUNALIGNED_OK to check.
  82036. */
  82037. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  82038. register ush scan_start = *(ushf*)scan;
  82039. register ush scan_end = *(ushf*)(scan+best_len-1);
  82040. #else
  82041. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82042. register Byte scan_end1 = scan[best_len-1];
  82043. register Byte scan_end = scan[best_len];
  82044. #endif
  82045. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82046. * It is easy to get rid of this optimization if necessary.
  82047. */
  82048. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82049. /* Do not waste too much time if we already have a good match: */
  82050. if (s->prev_length >= s->good_match) {
  82051. chain_length >>= 2;
  82052. }
  82053. /* Do not look for matches beyond the end of the input. This is necessary
  82054. * to make deflate deterministic.
  82055. */
  82056. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  82057. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82058. do {
  82059. Assert(cur_match < s->strstart, "no future");
  82060. match = s->window + cur_match;
  82061. /* Skip to next match if the match length cannot increase
  82062. * or if the match length is less than 2. Note that the checks below
  82063. * for insufficient lookahead only occur occasionally for performance
  82064. * reasons. Therefore uninitialized memory will be accessed, and
  82065. * conditional jumps will be made that depend on those values.
  82066. * However the length of the match is limited to the lookahead, so
  82067. * the output of deflate is not affected by the uninitialized values.
  82068. */
  82069. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  82070. /* This code assumes sizeof(unsigned short) == 2. Do not use
  82071. * UNALIGNED_OK if your compiler uses a different size.
  82072. */
  82073. if (*(ushf*)(match+best_len-1) != scan_end ||
  82074. *(ushf*)match != scan_start) continue;
  82075. /* It is not necessary to compare scan[2] and match[2] since they are
  82076. * always equal when the other bytes match, given that the hash keys
  82077. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  82078. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  82079. * lookahead only every 4th comparison; the 128th check will be made
  82080. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  82081. * necessary to put more guard bytes at the end of the window, or
  82082. * to check more often for insufficient lookahead.
  82083. */
  82084. Assert(scan[2] == match[2], "scan[2]?");
  82085. scan++, match++;
  82086. do {
  82087. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82088. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82089. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82090. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82091. scan < strend);
  82092. /* The funny "do {}" generates better code on most compilers */
  82093. /* Here, scan <= window+strstart+257 */
  82094. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82095. if (*scan == *match) scan++;
  82096. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82097. scan = strend - (MAX_MATCH-1);
  82098. #else /* UNALIGNED_OK */
  82099. if (match[best_len] != scan_end ||
  82100. match[best_len-1] != scan_end1 ||
  82101. *match != *scan ||
  82102. *++match != scan[1]) continue;
  82103. /* The check at best_len-1 can be removed because it will be made
  82104. * again later. (This heuristic is not always a win.)
  82105. * It is not necessary to compare scan[2] and match[2] since they
  82106. * are always equal when the other bytes match, given that
  82107. * the hash keys are equal and that HASH_BITS >= 8.
  82108. */
  82109. scan += 2, match++;
  82110. Assert(*scan == *match, "match[2]?");
  82111. /* We check for insufficient lookahead only every 8th comparison;
  82112. * the 256th check will be made at strstart+258.
  82113. */
  82114. do {
  82115. } while (*++scan == *++match && *++scan == *++match &&
  82116. *++scan == *++match && *++scan == *++match &&
  82117. *++scan == *++match && *++scan == *++match &&
  82118. *++scan == *++match && *++scan == *++match &&
  82119. scan < strend);
  82120. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82121. len = MAX_MATCH - (int)(strend - scan);
  82122. scan = strend - MAX_MATCH;
  82123. #endif /* UNALIGNED_OK */
  82124. if (len > best_len) {
  82125. s->match_start = cur_match;
  82126. best_len = len;
  82127. if (len >= nice_match) break;
  82128. #ifdef UNALIGNED_OK
  82129. scan_end = *(ushf*)(scan+best_len-1);
  82130. #else
  82131. scan_end1 = scan[best_len-1];
  82132. scan_end = scan[best_len];
  82133. #endif
  82134. }
  82135. } while ((cur_match = prev[cur_match & wmask]) > limit
  82136. && --chain_length != 0);
  82137. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82138. return s->lookahead;
  82139. }
  82140. #endif /* ASMV */
  82141. #endif /* FASTEST */
  82142. /* ---------------------------------------------------------------------------
  82143. * Optimized version for level == 1 or strategy == Z_RLE only
  82144. */
  82145. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82146. {
  82147. register Bytef *scan = s->window + s->strstart; /* current string */
  82148. register Bytef *match; /* matched string */
  82149. register int len; /* length of current match */
  82150. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82151. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82152. * It is easy to get rid of this optimization if necessary.
  82153. */
  82154. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82155. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82156. Assert(cur_match < s->strstart, "no future");
  82157. match = s->window + cur_match;
  82158. /* Return failure if the match length is less than 2:
  82159. */
  82160. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82161. /* The check at best_len-1 can be removed because it will be made
  82162. * again later. (This heuristic is not always a win.)
  82163. * It is not necessary to compare scan[2] and match[2] since they
  82164. * are always equal when the other bytes match, given that
  82165. * the hash keys are equal and that HASH_BITS >= 8.
  82166. */
  82167. scan += 2, match += 2;
  82168. Assert(*scan == *match, "match[2]?");
  82169. /* We check for insufficient lookahead only every 8th comparison;
  82170. * the 256th check will be made at strstart+258.
  82171. */
  82172. do {
  82173. } while (*++scan == *++match && *++scan == *++match &&
  82174. *++scan == *++match && *++scan == *++match &&
  82175. *++scan == *++match && *++scan == *++match &&
  82176. *++scan == *++match && *++scan == *++match &&
  82177. scan < strend);
  82178. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82179. len = MAX_MATCH - (int)(strend - scan);
  82180. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82181. s->match_start = cur_match;
  82182. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82183. }
  82184. #ifdef DEBUG
  82185. /* ===========================================================================
  82186. * Check that the match at match_start is indeed a match.
  82187. */
  82188. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82189. {
  82190. /* check that the match is indeed a match */
  82191. if (zmemcmp(s->window + match,
  82192. s->window + start, length) != EQUAL) {
  82193. fprintf(stderr, " start %u, match %u, length %d\n",
  82194. start, match, length);
  82195. do {
  82196. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82197. } while (--length != 0);
  82198. z_error("invalid match");
  82199. }
  82200. if (z_verbose > 1) {
  82201. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82202. do { putc(s->window[start++], stderr); } while (--length != 0);
  82203. }
  82204. }
  82205. #else
  82206. # define check_match(s, start, match, length)
  82207. #endif /* DEBUG */
  82208. /* ===========================================================================
  82209. * Fill the window when the lookahead becomes insufficient.
  82210. * Updates strstart and lookahead.
  82211. *
  82212. * IN assertion: lookahead < MIN_LOOKAHEAD
  82213. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82214. * At least one byte has been read, or avail_in == 0; reads are
  82215. * performed for at least two bytes (required for the zip translate_eol
  82216. * option -- not supported here).
  82217. */
  82218. local void fill_window (deflate_state *s)
  82219. {
  82220. register unsigned n, m;
  82221. register Posf *p;
  82222. unsigned more; /* Amount of free space at the end of the window. */
  82223. uInt wsize = s->w_size;
  82224. do {
  82225. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82226. /* Deal with !@#$% 64K limit: */
  82227. if (sizeof(int) <= 2) {
  82228. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82229. more = wsize;
  82230. } else if (more == (unsigned)(-1)) {
  82231. /* Very unlikely, but possible on 16 bit machine if
  82232. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82233. */
  82234. more--;
  82235. }
  82236. }
  82237. /* If the window is almost full and there is insufficient lookahead,
  82238. * move the upper half to the lower one to make room in the upper half.
  82239. */
  82240. if (s->strstart >= wsize+MAX_DIST(s)) {
  82241. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82242. s->match_start -= wsize;
  82243. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82244. s->block_start -= (long) wsize;
  82245. /* Slide the hash table (could be avoided with 32 bit values
  82246. at the expense of memory usage). We slide even when level == 0
  82247. to keep the hash table consistent if we switch back to level > 0
  82248. later. (Using level 0 permanently is not an optimal usage of
  82249. zlib, so we don't care about this pathological case.)
  82250. */
  82251. /* %%% avoid this when Z_RLE */
  82252. n = s->hash_size;
  82253. p = &s->head[n];
  82254. do {
  82255. m = *--p;
  82256. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82257. } while (--n);
  82258. n = wsize;
  82259. #ifndef FASTEST
  82260. p = &s->prev[n];
  82261. do {
  82262. m = *--p;
  82263. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82264. /* If n is not on any hash chain, prev[n] is garbage but
  82265. * its value will never be used.
  82266. */
  82267. } while (--n);
  82268. #endif
  82269. more += wsize;
  82270. }
  82271. if (s->strm->avail_in == 0) return;
  82272. /* If there was no sliding:
  82273. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82274. * more == window_size - lookahead - strstart
  82275. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82276. * => more >= window_size - 2*WSIZE + 2
  82277. * In the BIG_MEM or MMAP case (not yet supported),
  82278. * window_size == input_size + MIN_LOOKAHEAD &&
  82279. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82280. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82281. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82282. */
  82283. Assert(more >= 2, "more < 2");
  82284. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82285. s->lookahead += n;
  82286. /* Initialize the hash value now that we have some input: */
  82287. if (s->lookahead >= MIN_MATCH) {
  82288. s->ins_h = s->window[s->strstart];
  82289. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82290. #if MIN_MATCH != 3
  82291. Call UPDATE_HASH() MIN_MATCH-3 more times
  82292. #endif
  82293. }
  82294. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82295. * but this is not important since only literal bytes will be emitted.
  82296. */
  82297. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82298. }
  82299. /* ===========================================================================
  82300. * Flush the current block, with given end-of-file flag.
  82301. * IN assertion: strstart is set to the end of the current match.
  82302. */
  82303. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82304. _tr_flush_block(s, (s->block_start >= 0L ? \
  82305. (charf *)&s->window[(unsigned)s->block_start] : \
  82306. (charf *)Z_NULL), \
  82307. (ulg)((long)s->strstart - s->block_start), \
  82308. (eof)); \
  82309. s->block_start = s->strstart; \
  82310. flush_pending(s->strm); \
  82311. Tracev((stderr,"[FLUSH]")); \
  82312. }
  82313. /* Same but force premature exit if necessary. */
  82314. #define FLUSH_BLOCK(s, eof) { \
  82315. FLUSH_BLOCK_ONLY(s, eof); \
  82316. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82317. }
  82318. /* ===========================================================================
  82319. * Copy without compression as much as possible from the input stream, return
  82320. * the current block state.
  82321. * This function does not insert new strings in the dictionary since
  82322. * uncompressible data is probably not useful. This function is used
  82323. * only for the level=0 compression option.
  82324. * NOTE: this function should be optimized to avoid extra copying from
  82325. * window to pending_buf.
  82326. */
  82327. local block_state deflate_stored(deflate_state *s, int flush)
  82328. {
  82329. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82330. * to pending_buf_size, and each stored block has a 5 byte header:
  82331. */
  82332. ulg max_block_size = 0xffff;
  82333. ulg max_start;
  82334. if (max_block_size > s->pending_buf_size - 5) {
  82335. max_block_size = s->pending_buf_size - 5;
  82336. }
  82337. /* Copy as much as possible from input to output: */
  82338. for (;;) {
  82339. /* Fill the window as much as possible: */
  82340. if (s->lookahead <= 1) {
  82341. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82342. s->block_start >= (long)s->w_size, "slide too late");
  82343. fill_window(s);
  82344. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82345. if (s->lookahead == 0) break; /* flush the current block */
  82346. }
  82347. Assert(s->block_start >= 0L, "block gone");
  82348. s->strstart += s->lookahead;
  82349. s->lookahead = 0;
  82350. /* Emit a stored block if pending_buf will be full: */
  82351. max_start = s->block_start + max_block_size;
  82352. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82353. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82354. s->lookahead = (uInt)(s->strstart - max_start);
  82355. s->strstart = (uInt)max_start;
  82356. FLUSH_BLOCK(s, 0);
  82357. }
  82358. /* Flush if we may have to slide, otherwise block_start may become
  82359. * negative and the data will be gone:
  82360. */
  82361. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82362. FLUSH_BLOCK(s, 0);
  82363. }
  82364. }
  82365. FLUSH_BLOCK(s, flush == Z_FINISH);
  82366. return flush == Z_FINISH ? finish_done : block_done;
  82367. }
  82368. /* ===========================================================================
  82369. * Compress as much as possible from the input stream, return the current
  82370. * block state.
  82371. * This function does not perform lazy evaluation of matches and inserts
  82372. * new strings in the dictionary only for unmatched strings or for short
  82373. * matches. It is used only for the fast compression options.
  82374. */
  82375. local block_state deflate_fast(deflate_state *s, int flush)
  82376. {
  82377. IPos hash_head = NIL; /* head of the hash chain */
  82378. int bflush; /* set if current block must be flushed */
  82379. for (;;) {
  82380. /* Make sure that we always have enough lookahead, except
  82381. * at the end of the input file. We need MAX_MATCH bytes
  82382. * for the next match, plus MIN_MATCH bytes to insert the
  82383. * string following the next match.
  82384. */
  82385. if (s->lookahead < MIN_LOOKAHEAD) {
  82386. fill_window(s);
  82387. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82388. return need_more;
  82389. }
  82390. if (s->lookahead == 0) break; /* flush the current block */
  82391. }
  82392. /* Insert the string window[strstart .. strstart+2] in the
  82393. * dictionary, and set hash_head to the head of the hash chain:
  82394. */
  82395. if (s->lookahead >= MIN_MATCH) {
  82396. INSERT_STRING(s, s->strstart, hash_head);
  82397. }
  82398. /* Find the longest match, discarding those <= prev_length.
  82399. * At this point we have always match_length < MIN_MATCH
  82400. */
  82401. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82402. /* To simplify the code, we prevent matches with the string
  82403. * of window index 0 (in particular we have to avoid a match
  82404. * of the string with itself at the start of the input file).
  82405. */
  82406. #ifdef FASTEST
  82407. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82408. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82409. s->match_length = longest_match_fast (s, hash_head);
  82410. }
  82411. #else
  82412. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82413. s->match_length = longest_match (s, hash_head);
  82414. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82415. s->match_length = longest_match_fast (s, hash_head);
  82416. }
  82417. #endif
  82418. /* longest_match() or longest_match_fast() sets match_start */
  82419. }
  82420. if (s->match_length >= MIN_MATCH) {
  82421. check_match(s, s->strstart, s->match_start, s->match_length);
  82422. _tr_tally_dist(s, s->strstart - s->match_start,
  82423. s->match_length - MIN_MATCH, bflush);
  82424. s->lookahead -= s->match_length;
  82425. /* Insert new strings in the hash table only if the match length
  82426. * is not too large. This saves time but degrades compression.
  82427. */
  82428. #ifndef FASTEST
  82429. if (s->match_length <= s->max_insert_length &&
  82430. s->lookahead >= MIN_MATCH) {
  82431. s->match_length--; /* string at strstart already in table */
  82432. do {
  82433. s->strstart++;
  82434. INSERT_STRING(s, s->strstart, hash_head);
  82435. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82436. * always MIN_MATCH bytes ahead.
  82437. */
  82438. } while (--s->match_length != 0);
  82439. s->strstart++;
  82440. } else
  82441. #endif
  82442. {
  82443. s->strstart += s->match_length;
  82444. s->match_length = 0;
  82445. s->ins_h = s->window[s->strstart];
  82446. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82447. #if MIN_MATCH != 3
  82448. Call UPDATE_HASH() MIN_MATCH-3 more times
  82449. #endif
  82450. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82451. * matter since it will be recomputed at next deflate call.
  82452. */
  82453. }
  82454. } else {
  82455. /* No match, output a literal byte */
  82456. Tracevv((stderr,"%c", s->window[s->strstart]));
  82457. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82458. s->lookahead--;
  82459. s->strstart++;
  82460. }
  82461. if (bflush) FLUSH_BLOCK(s, 0);
  82462. }
  82463. FLUSH_BLOCK(s, flush == Z_FINISH);
  82464. return flush == Z_FINISH ? finish_done : block_done;
  82465. }
  82466. #ifndef FASTEST
  82467. /* ===========================================================================
  82468. * Same as above, but achieves better compression. We use a lazy
  82469. * evaluation for matches: a match is finally adopted only if there is
  82470. * no better match at the next window position.
  82471. */
  82472. local block_state deflate_slow(deflate_state *s, int flush)
  82473. {
  82474. IPos hash_head = NIL; /* head of hash chain */
  82475. int bflush; /* set if current block must be flushed */
  82476. /* Process the input block. */
  82477. for (;;) {
  82478. /* Make sure that we always have enough lookahead, except
  82479. * at the end of the input file. We need MAX_MATCH bytes
  82480. * for the next match, plus MIN_MATCH bytes to insert the
  82481. * string following the next match.
  82482. */
  82483. if (s->lookahead < MIN_LOOKAHEAD) {
  82484. fill_window(s);
  82485. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82486. return need_more;
  82487. }
  82488. if (s->lookahead == 0) break; /* flush the current block */
  82489. }
  82490. /* Insert the string window[strstart .. strstart+2] in the
  82491. * dictionary, and set hash_head to the head of the hash chain:
  82492. */
  82493. if (s->lookahead >= MIN_MATCH) {
  82494. INSERT_STRING(s, s->strstart, hash_head);
  82495. }
  82496. /* Find the longest match, discarding those <= prev_length.
  82497. */
  82498. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82499. s->match_length = MIN_MATCH-1;
  82500. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82501. s->strstart - hash_head <= MAX_DIST(s)) {
  82502. /* To simplify the code, we prevent matches with the string
  82503. * of window index 0 (in particular we have to avoid a match
  82504. * of the string with itself at the start of the input file).
  82505. */
  82506. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82507. s->match_length = longest_match (s, hash_head);
  82508. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82509. s->match_length = longest_match_fast (s, hash_head);
  82510. }
  82511. /* longest_match() or longest_match_fast() sets match_start */
  82512. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82513. #if TOO_FAR <= 32767
  82514. || (s->match_length == MIN_MATCH &&
  82515. s->strstart - s->match_start > TOO_FAR)
  82516. #endif
  82517. )) {
  82518. /* If prev_match is also MIN_MATCH, match_start is garbage
  82519. * but we will ignore the current match anyway.
  82520. */
  82521. s->match_length = MIN_MATCH-1;
  82522. }
  82523. }
  82524. /* If there was a match at the previous step and the current
  82525. * match is not better, output the previous match:
  82526. */
  82527. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82528. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82529. /* Do not insert strings in hash table beyond this. */
  82530. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82531. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82532. s->prev_length - MIN_MATCH, bflush);
  82533. /* Insert in hash table all strings up to the end of the match.
  82534. * strstart-1 and strstart are already inserted. If there is not
  82535. * enough lookahead, the last two strings are not inserted in
  82536. * the hash table.
  82537. */
  82538. s->lookahead -= s->prev_length-1;
  82539. s->prev_length -= 2;
  82540. do {
  82541. if (++s->strstart <= max_insert) {
  82542. INSERT_STRING(s, s->strstart, hash_head);
  82543. }
  82544. } while (--s->prev_length != 0);
  82545. s->match_available = 0;
  82546. s->match_length = MIN_MATCH-1;
  82547. s->strstart++;
  82548. if (bflush) FLUSH_BLOCK(s, 0);
  82549. } else if (s->match_available) {
  82550. /* If there was no match at the previous position, output a
  82551. * single literal. If there was a match but the current match
  82552. * is longer, truncate the previous match to a single literal.
  82553. */
  82554. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82555. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82556. if (bflush) {
  82557. FLUSH_BLOCK_ONLY(s, 0);
  82558. }
  82559. s->strstart++;
  82560. s->lookahead--;
  82561. if (s->strm->avail_out == 0) return need_more;
  82562. } else {
  82563. /* There is no previous match to compare with, wait for
  82564. * the next step to decide.
  82565. */
  82566. s->match_available = 1;
  82567. s->strstart++;
  82568. s->lookahead--;
  82569. }
  82570. }
  82571. Assert (flush != Z_NO_FLUSH, "no flush?");
  82572. if (s->match_available) {
  82573. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82574. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82575. s->match_available = 0;
  82576. }
  82577. FLUSH_BLOCK(s, flush == Z_FINISH);
  82578. return flush == Z_FINISH ? finish_done : block_done;
  82579. }
  82580. #endif /* FASTEST */
  82581. #if 0
  82582. /* ===========================================================================
  82583. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82584. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82585. * deflate switches away from Z_RLE.)
  82586. */
  82587. local block_state deflate_rle(s, flush)
  82588. deflate_state *s;
  82589. int flush;
  82590. {
  82591. int bflush; /* set if current block must be flushed */
  82592. uInt run; /* length of run */
  82593. uInt max; /* maximum length of run */
  82594. uInt prev; /* byte at distance one to match */
  82595. Bytef *scan; /* scan for end of run */
  82596. for (;;) {
  82597. /* Make sure that we always have enough lookahead, except
  82598. * at the end of the input file. We need MAX_MATCH bytes
  82599. * for the longest encodable run.
  82600. */
  82601. if (s->lookahead < MAX_MATCH) {
  82602. fill_window(s);
  82603. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82604. return need_more;
  82605. }
  82606. if (s->lookahead == 0) break; /* flush the current block */
  82607. }
  82608. /* See how many times the previous byte repeats */
  82609. run = 0;
  82610. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82611. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82612. scan = s->window + s->strstart - 1;
  82613. prev = *scan++;
  82614. do {
  82615. if (*scan++ != prev)
  82616. break;
  82617. } while (++run < max);
  82618. }
  82619. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82620. if (run >= MIN_MATCH) {
  82621. check_match(s, s->strstart, s->strstart - 1, run);
  82622. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82623. s->lookahead -= run;
  82624. s->strstart += run;
  82625. } else {
  82626. /* No match, output a literal byte */
  82627. Tracevv((stderr,"%c", s->window[s->strstart]));
  82628. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82629. s->lookahead--;
  82630. s->strstart++;
  82631. }
  82632. if (bflush) FLUSH_BLOCK(s, 0);
  82633. }
  82634. FLUSH_BLOCK(s, flush == Z_FINISH);
  82635. return flush == Z_FINISH ? finish_done : block_done;
  82636. }
  82637. #endif
  82638. /*** End of inlined file: deflate.c ***/
  82639. /*** Start of inlined file: inffast.c ***/
  82640. /*** Start of inlined file: inftrees.h ***/
  82641. /* WARNING: this file should *not* be used by applications. It is
  82642. part of the implementation of the compression library and is
  82643. subject to change. Applications should only use zlib.h.
  82644. */
  82645. #ifndef _INFTREES_H_
  82646. #define _INFTREES_H_
  82647. /* Structure for decoding tables. Each entry provides either the
  82648. information needed to do the operation requested by the code that
  82649. indexed that table entry, or it provides a pointer to another
  82650. table that indexes more bits of the code. op indicates whether
  82651. the entry is a pointer to another table, a literal, a length or
  82652. distance, an end-of-block, or an invalid code. For a table
  82653. pointer, the low four bits of op is the number of index bits of
  82654. that table. For a length or distance, the low four bits of op
  82655. is the number of extra bits to get after the code. bits is
  82656. the number of bits in this code or part of the code to drop off
  82657. of the bit buffer. val is the actual byte to output in the case
  82658. of a literal, the base length or distance, or the offset from
  82659. the current table to the next table. Each entry is four bytes. */
  82660. typedef struct {
  82661. unsigned char op; /* operation, extra bits, table bits */
  82662. unsigned char bits; /* bits in this part of the code */
  82663. unsigned short val; /* offset in table or code value */
  82664. } code;
  82665. /* op values as set by inflate_table():
  82666. 00000000 - literal
  82667. 0000tttt - table link, tttt != 0 is the number of table index bits
  82668. 0001eeee - length or distance, eeee is the number of extra bits
  82669. 01100000 - end of block
  82670. 01000000 - invalid code
  82671. */
  82672. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82673. exhaustive search was 1444 code structures (852 for length/literals
  82674. and 592 for distances, the latter actually the result of an
  82675. exhaustive search). The true maximum is not known, but the value
  82676. below is more than safe. */
  82677. #define ENOUGH 2048
  82678. #define MAXD 592
  82679. /* Type of code to build for inftable() */
  82680. typedef enum {
  82681. CODES,
  82682. LENS,
  82683. DISTS
  82684. } codetype;
  82685. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82686. unsigned codes, code FAR * FAR *table,
  82687. unsigned FAR *bits, unsigned short FAR *work));
  82688. #endif
  82689. /*** End of inlined file: inftrees.h ***/
  82690. /*** Start of inlined file: inflate.h ***/
  82691. /* WARNING: this file should *not* be used by applications. It is
  82692. part of the implementation of the compression library and is
  82693. subject to change. Applications should only use zlib.h.
  82694. */
  82695. #ifndef _INFLATE_H_
  82696. #define _INFLATE_H_
  82697. /* define NO_GZIP when compiling if you want to disable gzip header and
  82698. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82699. the crc code when it is not needed. For shared libraries, gzip decoding
  82700. should be left enabled. */
  82701. #ifndef NO_GZIP
  82702. # define GUNZIP
  82703. #endif
  82704. /* Possible inflate modes between inflate() calls */
  82705. typedef enum {
  82706. HEAD, /* i: waiting for magic header */
  82707. FLAGS, /* i: waiting for method and flags (gzip) */
  82708. TIME, /* i: waiting for modification time (gzip) */
  82709. OS, /* i: waiting for extra flags and operating system (gzip) */
  82710. EXLEN, /* i: waiting for extra length (gzip) */
  82711. EXTRA, /* i: waiting for extra bytes (gzip) */
  82712. NAME, /* i: waiting for end of file name (gzip) */
  82713. COMMENT, /* i: waiting for end of comment (gzip) */
  82714. HCRC, /* i: waiting for header crc (gzip) */
  82715. DICTID, /* i: waiting for dictionary check value */
  82716. DICT, /* waiting for inflateSetDictionary() call */
  82717. TYPE, /* i: waiting for type bits, including last-flag bit */
  82718. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82719. STORED, /* i: waiting for stored size (length and complement) */
  82720. COPY, /* i/o: waiting for input or output to copy stored block */
  82721. TABLE, /* i: waiting for dynamic block table lengths */
  82722. LENLENS, /* i: waiting for code length code lengths */
  82723. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82724. LEN, /* i: waiting for length/lit code */
  82725. LENEXT, /* i: waiting for length extra bits */
  82726. DIST, /* i: waiting for distance code */
  82727. DISTEXT, /* i: waiting for distance extra bits */
  82728. MATCH, /* o: waiting for output space to copy string */
  82729. LIT, /* o: waiting for output space to write literal */
  82730. CHECK, /* i: waiting for 32-bit check value */
  82731. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82732. DONE, /* finished check, done -- remain here until reset */
  82733. BAD, /* got a data error -- remain here until reset */
  82734. MEM, /* got an inflate() memory error -- remain here until reset */
  82735. SYNC /* looking for synchronization bytes to restart inflate() */
  82736. } inflate_mode;
  82737. /*
  82738. State transitions between above modes -
  82739. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82740. Process header:
  82741. HEAD -> (gzip) or (zlib)
  82742. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82743. NAME -> COMMENT -> HCRC -> TYPE
  82744. (zlib) -> DICTID or TYPE
  82745. DICTID -> DICT -> TYPE
  82746. Read deflate blocks:
  82747. TYPE -> STORED or TABLE or LEN or CHECK
  82748. STORED -> COPY -> TYPE
  82749. TABLE -> LENLENS -> CODELENS -> LEN
  82750. Read deflate codes:
  82751. LEN -> LENEXT or LIT or TYPE
  82752. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82753. LIT -> LEN
  82754. Process trailer:
  82755. CHECK -> LENGTH -> DONE
  82756. */
  82757. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82758. struct inflate_state {
  82759. inflate_mode mode; /* current inflate mode */
  82760. int last; /* true if processing last block */
  82761. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82762. int havedict; /* true if dictionary provided */
  82763. int flags; /* gzip header method and flags (0 if zlib) */
  82764. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82765. unsigned long check; /* protected copy of check value */
  82766. unsigned long total; /* protected copy of output count */
  82767. gz_headerp head; /* where to save gzip header information */
  82768. /* sliding window */
  82769. unsigned wbits; /* log base 2 of requested window size */
  82770. unsigned wsize; /* window size or zero if not using window */
  82771. unsigned whave; /* valid bytes in the window */
  82772. unsigned write; /* window write index */
  82773. unsigned char FAR *window; /* allocated sliding window, if needed */
  82774. /* bit accumulator */
  82775. unsigned long hold; /* input bit accumulator */
  82776. unsigned bits; /* number of bits in "in" */
  82777. /* for string and stored block copying */
  82778. unsigned length; /* literal or length of data to copy */
  82779. unsigned offset; /* distance back to copy string from */
  82780. /* for table and code decoding */
  82781. unsigned extra; /* extra bits needed */
  82782. /* fixed and dynamic code tables */
  82783. code const FAR *lencode; /* starting table for length/literal codes */
  82784. code const FAR *distcode; /* starting table for distance codes */
  82785. unsigned lenbits; /* index bits for lencode */
  82786. unsigned distbits; /* index bits for distcode */
  82787. /* dynamic table building */
  82788. unsigned ncode; /* number of code length code lengths */
  82789. unsigned nlen; /* number of length code lengths */
  82790. unsigned ndist; /* number of distance code lengths */
  82791. unsigned have; /* number of code lengths in lens[] */
  82792. code FAR *next; /* next available space in codes[] */
  82793. unsigned short lens[320]; /* temporary storage for code lengths */
  82794. unsigned short work[288]; /* work area for code table building */
  82795. code codes[ENOUGH]; /* space for code tables */
  82796. };
  82797. #endif
  82798. /*** End of inlined file: inflate.h ***/
  82799. /*** Start of inlined file: inffast.h ***/
  82800. /* WARNING: this file should *not* be used by applications. It is
  82801. part of the implementation of the compression library and is
  82802. subject to change. Applications should only use zlib.h.
  82803. */
  82804. void inflate_fast OF((z_streamp strm, unsigned start));
  82805. /*** End of inlined file: inffast.h ***/
  82806. #ifndef ASMINF
  82807. /* Allow machine dependent optimization for post-increment or pre-increment.
  82808. Based on testing to date,
  82809. Pre-increment preferred for:
  82810. - PowerPC G3 (Adler)
  82811. - MIPS R5000 (Randers-Pehrson)
  82812. Post-increment preferred for:
  82813. - none
  82814. No measurable difference:
  82815. - Pentium III (Anderson)
  82816. - M68060 (Nikl)
  82817. */
  82818. #ifdef POSTINC
  82819. # define OFF 0
  82820. # define PUP(a) *(a)++
  82821. #else
  82822. # define OFF 1
  82823. # define PUP(a) *++(a)
  82824. #endif
  82825. /*
  82826. Decode literal, length, and distance codes and write out the resulting
  82827. literal and match bytes until either not enough input or output is
  82828. available, an end-of-block is encountered, or a data error is encountered.
  82829. When large enough input and output buffers are supplied to inflate(), for
  82830. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82831. inflate execution time is spent in this routine.
  82832. Entry assumptions:
  82833. state->mode == LEN
  82834. strm->avail_in >= 6
  82835. strm->avail_out >= 258
  82836. start >= strm->avail_out
  82837. state->bits < 8
  82838. On return, state->mode is one of:
  82839. LEN -- ran out of enough output space or enough available input
  82840. TYPE -- reached end of block code, inflate() to interpret next block
  82841. BAD -- error in block data
  82842. Notes:
  82843. - The maximum input bits used by a length/distance pair is 15 bits for the
  82844. length code, 5 bits for the length extra, 15 bits for the distance code,
  82845. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82846. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82847. checking for available input while decoding.
  82848. - The maximum bytes that a single length/distance pair can output is 258
  82849. bytes, which is the maximum length that can be coded. inflate_fast()
  82850. requires strm->avail_out >= 258 for each loop to avoid checking for
  82851. output space.
  82852. */
  82853. void inflate_fast (z_streamp strm, unsigned start)
  82854. {
  82855. struct inflate_state FAR *state;
  82856. unsigned char FAR *in; /* local strm->next_in */
  82857. unsigned char FAR *last; /* while in < last, enough input available */
  82858. unsigned char FAR *out; /* local strm->next_out */
  82859. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82860. unsigned char FAR *end; /* while out < end, enough space available */
  82861. #ifdef INFLATE_STRICT
  82862. unsigned dmax; /* maximum distance from zlib header */
  82863. #endif
  82864. unsigned wsize; /* window size or zero if not using window */
  82865. unsigned whave; /* valid bytes in the window */
  82866. unsigned write; /* window write index */
  82867. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82868. unsigned long hold; /* local strm->hold */
  82869. unsigned bits; /* local strm->bits */
  82870. code const FAR *lcode; /* local strm->lencode */
  82871. code const FAR *dcode; /* local strm->distcode */
  82872. unsigned lmask; /* mask for first level of length codes */
  82873. unsigned dmask; /* mask for first level of distance codes */
  82874. code thisx; /* retrieved table entry */
  82875. unsigned op; /* code bits, operation, extra bits, or */
  82876. /* window position, window bytes to copy */
  82877. unsigned len; /* match length, unused bytes */
  82878. unsigned dist; /* match distance */
  82879. unsigned char FAR *from; /* where to copy match from */
  82880. /* copy state to local variables */
  82881. state = (struct inflate_state FAR *)strm->state;
  82882. in = strm->next_in - OFF;
  82883. last = in + (strm->avail_in - 5);
  82884. out = strm->next_out - OFF;
  82885. beg = out - (start - strm->avail_out);
  82886. end = out + (strm->avail_out - 257);
  82887. #ifdef INFLATE_STRICT
  82888. dmax = state->dmax;
  82889. #endif
  82890. wsize = state->wsize;
  82891. whave = state->whave;
  82892. write = state->write;
  82893. window = state->window;
  82894. hold = state->hold;
  82895. bits = state->bits;
  82896. lcode = state->lencode;
  82897. dcode = state->distcode;
  82898. lmask = (1U << state->lenbits) - 1;
  82899. dmask = (1U << state->distbits) - 1;
  82900. /* decode literals and length/distances until end-of-block or not enough
  82901. input data or output space */
  82902. do {
  82903. if (bits < 15) {
  82904. hold += (unsigned long)(PUP(in)) << bits;
  82905. bits += 8;
  82906. hold += (unsigned long)(PUP(in)) << bits;
  82907. bits += 8;
  82908. }
  82909. thisx = lcode[hold & lmask];
  82910. dolen:
  82911. op = (unsigned)(thisx.bits);
  82912. hold >>= op;
  82913. bits -= op;
  82914. op = (unsigned)(thisx.op);
  82915. if (op == 0) { /* literal */
  82916. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82917. "inflate: literal '%c'\n" :
  82918. "inflate: literal 0x%02x\n", thisx.val));
  82919. PUP(out) = (unsigned char)(thisx.val);
  82920. }
  82921. else if (op & 16) { /* length base */
  82922. len = (unsigned)(thisx.val);
  82923. op &= 15; /* number of extra bits */
  82924. if (op) {
  82925. if (bits < op) {
  82926. hold += (unsigned long)(PUP(in)) << bits;
  82927. bits += 8;
  82928. }
  82929. len += (unsigned)hold & ((1U << op) - 1);
  82930. hold >>= op;
  82931. bits -= op;
  82932. }
  82933. Tracevv((stderr, "inflate: length %u\n", len));
  82934. if (bits < 15) {
  82935. hold += (unsigned long)(PUP(in)) << bits;
  82936. bits += 8;
  82937. hold += (unsigned long)(PUP(in)) << bits;
  82938. bits += 8;
  82939. }
  82940. thisx = dcode[hold & dmask];
  82941. dodist:
  82942. op = (unsigned)(thisx.bits);
  82943. hold >>= op;
  82944. bits -= op;
  82945. op = (unsigned)(thisx.op);
  82946. if (op & 16) { /* distance base */
  82947. dist = (unsigned)(thisx.val);
  82948. op &= 15; /* number of extra bits */
  82949. if (bits < op) {
  82950. hold += (unsigned long)(PUP(in)) << bits;
  82951. bits += 8;
  82952. if (bits < op) {
  82953. hold += (unsigned long)(PUP(in)) << bits;
  82954. bits += 8;
  82955. }
  82956. }
  82957. dist += (unsigned)hold & ((1U << op) - 1);
  82958. #ifdef INFLATE_STRICT
  82959. if (dist > dmax) {
  82960. strm->msg = (char *)"invalid distance too far back";
  82961. state->mode = BAD;
  82962. break;
  82963. }
  82964. #endif
  82965. hold >>= op;
  82966. bits -= op;
  82967. Tracevv((stderr, "inflate: distance %u\n", dist));
  82968. op = (unsigned)(out - beg); /* max distance in output */
  82969. if (dist > op) { /* see if copy from window */
  82970. op = dist - op; /* distance back in window */
  82971. if (op > whave) {
  82972. strm->msg = (char *)"invalid distance too far back";
  82973. state->mode = BAD;
  82974. break;
  82975. }
  82976. from = window - OFF;
  82977. if (write == 0) { /* very common case */
  82978. from += wsize - op;
  82979. if (op < len) { /* some from window */
  82980. len -= op;
  82981. do {
  82982. PUP(out) = PUP(from);
  82983. } while (--op);
  82984. from = out - dist; /* rest from output */
  82985. }
  82986. }
  82987. else if (write < op) { /* wrap around window */
  82988. from += wsize + write - op;
  82989. op -= write;
  82990. if (op < len) { /* some from end of window */
  82991. len -= op;
  82992. do {
  82993. PUP(out) = PUP(from);
  82994. } while (--op);
  82995. from = window - OFF;
  82996. if (write < len) { /* some from start of window */
  82997. op = write;
  82998. len -= op;
  82999. do {
  83000. PUP(out) = PUP(from);
  83001. } while (--op);
  83002. from = out - dist; /* rest from output */
  83003. }
  83004. }
  83005. }
  83006. else { /* contiguous in window */
  83007. from += write - op;
  83008. if (op < len) { /* some from window */
  83009. len -= op;
  83010. do {
  83011. PUP(out) = PUP(from);
  83012. } while (--op);
  83013. from = out - dist; /* rest from output */
  83014. }
  83015. }
  83016. while (len > 2) {
  83017. PUP(out) = PUP(from);
  83018. PUP(out) = PUP(from);
  83019. PUP(out) = PUP(from);
  83020. len -= 3;
  83021. }
  83022. if (len) {
  83023. PUP(out) = PUP(from);
  83024. if (len > 1)
  83025. PUP(out) = PUP(from);
  83026. }
  83027. }
  83028. else {
  83029. from = out - dist; /* copy direct from output */
  83030. do { /* minimum length is three */
  83031. PUP(out) = PUP(from);
  83032. PUP(out) = PUP(from);
  83033. PUP(out) = PUP(from);
  83034. len -= 3;
  83035. } while (len > 2);
  83036. if (len) {
  83037. PUP(out) = PUP(from);
  83038. if (len > 1)
  83039. PUP(out) = PUP(from);
  83040. }
  83041. }
  83042. }
  83043. else if ((op & 64) == 0) { /* 2nd level distance code */
  83044. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  83045. goto dodist;
  83046. }
  83047. else {
  83048. strm->msg = (char *)"invalid distance code";
  83049. state->mode = BAD;
  83050. break;
  83051. }
  83052. }
  83053. else if ((op & 64) == 0) { /* 2nd level length code */
  83054. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  83055. goto dolen;
  83056. }
  83057. else if (op & 32) { /* end-of-block */
  83058. Tracevv((stderr, "inflate: end of block\n"));
  83059. state->mode = TYPE;
  83060. break;
  83061. }
  83062. else {
  83063. strm->msg = (char *)"invalid literal/length code";
  83064. state->mode = BAD;
  83065. break;
  83066. }
  83067. } while (in < last && out < end);
  83068. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83069. len = bits >> 3;
  83070. in -= len;
  83071. bits -= len << 3;
  83072. hold &= (1U << bits) - 1;
  83073. /* update state and return */
  83074. strm->next_in = in + OFF;
  83075. strm->next_out = out + OFF;
  83076. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  83077. strm->avail_out = (unsigned)(out < end ?
  83078. 257 + (end - out) : 257 - (out - end));
  83079. state->hold = hold;
  83080. state->bits = bits;
  83081. return;
  83082. }
  83083. /*
  83084. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83085. - Using bit fields for code structure
  83086. - Different op definition to avoid & for extra bits (do & for table bits)
  83087. - Three separate decoding do-loops for direct, window, and write == 0
  83088. - Special case for distance > 1 copies to do overlapped load and store copy
  83089. - Explicit branch predictions (based on measured branch probabilities)
  83090. - Deferring match copy and interspersed it with decoding subsequent codes
  83091. - Swapping literal/length else
  83092. - Swapping window/direct else
  83093. - Larger unrolled copy loops (three is about right)
  83094. - Moving len -= 3 statement into middle of loop
  83095. */
  83096. #endif /* !ASMINF */
  83097. /*** End of inlined file: inffast.c ***/
  83098. #undef PULLBYTE
  83099. #undef LOAD
  83100. #undef RESTORE
  83101. #undef INITBITS
  83102. #undef NEEDBITS
  83103. #undef DROPBITS
  83104. #undef BYTEBITS
  83105. /*** Start of inlined file: inflate.c ***/
  83106. /*
  83107. * Change history:
  83108. *
  83109. * 1.2.beta0 24 Nov 2002
  83110. * - First version -- complete rewrite of inflate to simplify code, avoid
  83111. * creation of window when not needed, minimize use of window when it is
  83112. * needed, make inffast.c even faster, implement gzip decoding, and to
  83113. * improve code readability and style over the previous zlib inflate code
  83114. *
  83115. * 1.2.beta1 25 Nov 2002
  83116. * - Use pointers for available input and output checking in inffast.c
  83117. * - Remove input and output counters in inffast.c
  83118. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83119. * - Remove unnecessary second byte pull from length extra in inffast.c
  83120. * - Unroll direct copy to three copies per loop in inffast.c
  83121. *
  83122. * 1.2.beta2 4 Dec 2002
  83123. * - Change external routine names to reduce potential conflicts
  83124. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83125. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83126. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83127. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83128. *
  83129. * 1.2.beta3 22 Dec 2002
  83130. * - Add comments on state->bits assertion in inffast.c
  83131. * - Add comments on op field in inftrees.h
  83132. * - Fix bug in reuse of allocated window after inflateReset()
  83133. * - Remove bit fields--back to byte structure for speed
  83134. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83135. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83136. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83137. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83138. * - Use local copies of stream next and avail values, as well as local bit
  83139. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83140. *
  83141. * 1.2.beta4 1 Jan 2003
  83142. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83143. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83144. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83145. * - Rearrange window copies in inflate_fast() for speed and simplification
  83146. * - Unroll last copy for window match in inflate_fast()
  83147. * - Use local copies of window variables in inflate_fast() for speed
  83148. * - Pull out common write == 0 case for speed in inflate_fast()
  83149. * - Make op and len in inflate_fast() unsigned for consistency
  83150. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83151. * - Simplified bad distance check in inflate_fast()
  83152. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83153. * source file infback.c to provide a call-back interface to inflate for
  83154. * programs like gzip and unzip -- uses window as output buffer to avoid
  83155. * window copying
  83156. *
  83157. * 1.2.beta5 1 Jan 2003
  83158. * - Improved inflateBack() interface to allow the caller to provide initial
  83159. * input in strm.
  83160. * - Fixed stored blocks bug in inflateBack()
  83161. *
  83162. * 1.2.beta6 4 Jan 2003
  83163. * - Added comments in inffast.c on effectiveness of POSTINC
  83164. * - Typecasting all around to reduce compiler warnings
  83165. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83166. * make compilers happy
  83167. * - Changed type of window in inflateBackInit() to unsigned char *
  83168. *
  83169. * 1.2.beta7 27 Jan 2003
  83170. * - Changed many types to unsigned or unsigned short to avoid warnings
  83171. * - Added inflateCopy() function
  83172. *
  83173. * 1.2.0 9 Mar 2003
  83174. * - Changed inflateBack() interface to provide separate opaque descriptors
  83175. * for the in() and out() functions
  83176. * - Changed inflateBack() argument and in_func typedef to swap the length
  83177. * and buffer address return values for the input function
  83178. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83179. *
  83180. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83181. */
  83182. /*** Start of inlined file: inffast.h ***/
  83183. /* WARNING: this file should *not* be used by applications. It is
  83184. part of the implementation of the compression library and is
  83185. subject to change. Applications should only use zlib.h.
  83186. */
  83187. void inflate_fast OF((z_streamp strm, unsigned start));
  83188. /*** End of inlined file: inffast.h ***/
  83189. #ifdef MAKEFIXED
  83190. # ifndef BUILDFIXED
  83191. # define BUILDFIXED
  83192. # endif
  83193. #endif
  83194. /* function prototypes */
  83195. local void fixedtables OF((struct inflate_state FAR *state));
  83196. local int updatewindow OF((z_streamp strm, unsigned out));
  83197. #ifdef BUILDFIXED
  83198. void makefixed OF((void));
  83199. #endif
  83200. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83201. unsigned len));
  83202. int ZEXPORT inflateReset (z_streamp strm)
  83203. {
  83204. struct inflate_state FAR *state;
  83205. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83206. state = (struct inflate_state FAR *)strm->state;
  83207. strm->total_in = strm->total_out = state->total = 0;
  83208. strm->msg = Z_NULL;
  83209. strm->adler = 1; /* to support ill-conceived Java test suite */
  83210. state->mode = HEAD;
  83211. state->last = 0;
  83212. state->havedict = 0;
  83213. state->dmax = 32768U;
  83214. state->head = Z_NULL;
  83215. state->wsize = 0;
  83216. state->whave = 0;
  83217. state->write = 0;
  83218. state->hold = 0;
  83219. state->bits = 0;
  83220. state->lencode = state->distcode = state->next = state->codes;
  83221. Tracev((stderr, "inflate: reset\n"));
  83222. return Z_OK;
  83223. }
  83224. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83225. {
  83226. struct inflate_state FAR *state;
  83227. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83228. state = (struct inflate_state FAR *)strm->state;
  83229. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83230. value &= (1L << bits) - 1;
  83231. state->hold += value << state->bits;
  83232. state->bits += bits;
  83233. return Z_OK;
  83234. }
  83235. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83236. {
  83237. struct inflate_state FAR *state;
  83238. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83239. stream_size != (int)(sizeof(z_stream)))
  83240. return Z_VERSION_ERROR;
  83241. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83242. strm->msg = Z_NULL; /* in case we return an error */
  83243. if (strm->zalloc == (alloc_func)0) {
  83244. strm->zalloc = zcalloc;
  83245. strm->opaque = (voidpf)0;
  83246. }
  83247. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83248. state = (struct inflate_state FAR *)
  83249. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83250. if (state == Z_NULL) return Z_MEM_ERROR;
  83251. Tracev((stderr, "inflate: allocated\n"));
  83252. strm->state = (struct internal_state FAR *)state;
  83253. if (windowBits < 0) {
  83254. state->wrap = 0;
  83255. windowBits = -windowBits;
  83256. }
  83257. else {
  83258. state->wrap = (windowBits >> 4) + 1;
  83259. #ifdef GUNZIP
  83260. if (windowBits < 48) windowBits &= 15;
  83261. #endif
  83262. }
  83263. if (windowBits < 8 || windowBits > 15) {
  83264. ZFREE(strm, state);
  83265. strm->state = Z_NULL;
  83266. return Z_STREAM_ERROR;
  83267. }
  83268. state->wbits = (unsigned)windowBits;
  83269. state->window = Z_NULL;
  83270. return inflateReset(strm);
  83271. }
  83272. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83273. {
  83274. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83275. }
  83276. /*
  83277. Return state with length and distance decoding tables and index sizes set to
  83278. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83279. If BUILDFIXED is defined, then instead this routine builds the tables the
  83280. first time it's called, and returns those tables the first time and
  83281. thereafter. This reduces the size of the code by about 2K bytes, in
  83282. exchange for a little execution time. However, BUILDFIXED should not be
  83283. used for threaded applications, since the rewriting of the tables and virgin
  83284. may not be thread-safe.
  83285. */
  83286. local void fixedtables (struct inflate_state FAR *state)
  83287. {
  83288. #ifdef BUILDFIXED
  83289. static int virgin = 1;
  83290. static code *lenfix, *distfix;
  83291. static code fixed[544];
  83292. /* build fixed huffman tables if first call (may not be thread safe) */
  83293. if (virgin) {
  83294. unsigned sym, bits;
  83295. static code *next;
  83296. /* literal/length table */
  83297. sym = 0;
  83298. while (sym < 144) state->lens[sym++] = 8;
  83299. while (sym < 256) state->lens[sym++] = 9;
  83300. while (sym < 280) state->lens[sym++] = 7;
  83301. while (sym < 288) state->lens[sym++] = 8;
  83302. next = fixed;
  83303. lenfix = next;
  83304. bits = 9;
  83305. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83306. /* distance table */
  83307. sym = 0;
  83308. while (sym < 32) state->lens[sym++] = 5;
  83309. distfix = next;
  83310. bits = 5;
  83311. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83312. /* do this just once */
  83313. virgin = 0;
  83314. }
  83315. #else /* !BUILDFIXED */
  83316. /*** Start of inlined file: inffixed.h ***/
  83317. /* WARNING: this file should *not* be used by applications. It
  83318. is part of the implementation of the compression library and
  83319. is subject to change. Applications should only use zlib.h.
  83320. */
  83321. static const code lenfix[512] = {
  83322. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83323. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83324. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83325. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83326. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83327. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83328. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83329. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83330. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83331. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83332. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83333. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83334. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83335. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83336. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83337. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83338. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83339. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83340. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83341. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83342. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83343. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83344. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83345. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83346. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83347. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83348. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83349. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83350. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83351. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83352. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83353. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83354. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83355. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83356. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83357. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83358. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83359. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83360. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83361. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83362. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83363. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83364. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83365. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83366. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83367. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83368. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83369. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83370. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83371. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83372. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83373. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83374. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83375. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83376. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83377. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83378. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83379. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83380. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83381. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83382. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83383. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83384. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83385. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83386. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83387. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83388. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83389. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83390. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83391. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83392. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83393. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83394. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83395. {0,9,255}
  83396. };
  83397. static const code distfix[32] = {
  83398. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83399. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83400. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83401. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83402. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83403. {22,5,193},{64,5,0}
  83404. };
  83405. /*** End of inlined file: inffixed.h ***/
  83406. #endif /* BUILDFIXED */
  83407. state->lencode = lenfix;
  83408. state->lenbits = 9;
  83409. state->distcode = distfix;
  83410. state->distbits = 5;
  83411. }
  83412. #ifdef MAKEFIXED
  83413. #include <stdio.h>
  83414. /*
  83415. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83416. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83417. those tables to stdout, which would be piped to inffixed.h. A small program
  83418. can simply call makefixed to do this:
  83419. void makefixed(void);
  83420. int main(void)
  83421. {
  83422. makefixed();
  83423. return 0;
  83424. }
  83425. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83426. a.out > inffixed.h
  83427. */
  83428. void makefixed()
  83429. {
  83430. unsigned low, size;
  83431. struct inflate_state state;
  83432. fixedtables(&state);
  83433. puts(" /* inffixed.h -- table for decoding fixed codes");
  83434. puts(" * Generated automatically by makefixed().");
  83435. puts(" */");
  83436. puts("");
  83437. puts(" /* WARNING: this file should *not* be used by applications.");
  83438. puts(" It is part of the implementation of this library and is");
  83439. puts(" subject to change. Applications should only use zlib.h.");
  83440. puts(" */");
  83441. puts("");
  83442. size = 1U << 9;
  83443. printf(" static const code lenfix[%u] = {", size);
  83444. low = 0;
  83445. for (;;) {
  83446. if ((low % 7) == 0) printf("\n ");
  83447. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83448. state.lencode[low].val);
  83449. if (++low == size) break;
  83450. putchar(',');
  83451. }
  83452. puts("\n };");
  83453. size = 1U << 5;
  83454. printf("\n static const code distfix[%u] = {", size);
  83455. low = 0;
  83456. for (;;) {
  83457. if ((low % 6) == 0) printf("\n ");
  83458. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83459. state.distcode[low].val);
  83460. if (++low == size) break;
  83461. putchar(',');
  83462. }
  83463. puts("\n };");
  83464. }
  83465. #endif /* MAKEFIXED */
  83466. /*
  83467. Update the window with the last wsize (normally 32K) bytes written before
  83468. returning. If window does not exist yet, create it. This is only called
  83469. when a window is already in use, or when output has been written during this
  83470. inflate call, but the end of the deflate stream has not been reached yet.
  83471. It is also called to create a window for dictionary data when a dictionary
  83472. is loaded.
  83473. Providing output buffers larger than 32K to inflate() should provide a speed
  83474. advantage, since only the last 32K of output is copied to the sliding window
  83475. upon return from inflate(), and since all distances after the first 32K of
  83476. output will fall in the output data, making match copies simpler and faster.
  83477. The advantage may be dependent on the size of the processor's data caches.
  83478. */
  83479. local int updatewindow (z_streamp strm, unsigned out)
  83480. {
  83481. struct inflate_state FAR *state;
  83482. unsigned copy, dist;
  83483. state = (struct inflate_state FAR *)strm->state;
  83484. /* if it hasn't been done already, allocate space for the window */
  83485. if (state->window == Z_NULL) {
  83486. state->window = (unsigned char FAR *)
  83487. ZALLOC(strm, 1U << state->wbits,
  83488. sizeof(unsigned char));
  83489. if (state->window == Z_NULL) return 1;
  83490. }
  83491. /* if window not in use yet, initialize */
  83492. if (state->wsize == 0) {
  83493. state->wsize = 1U << state->wbits;
  83494. state->write = 0;
  83495. state->whave = 0;
  83496. }
  83497. /* copy state->wsize or less output bytes into the circular window */
  83498. copy = out - strm->avail_out;
  83499. if (copy >= state->wsize) {
  83500. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83501. state->write = 0;
  83502. state->whave = state->wsize;
  83503. }
  83504. else {
  83505. dist = state->wsize - state->write;
  83506. if (dist > copy) dist = copy;
  83507. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83508. copy -= dist;
  83509. if (copy) {
  83510. zmemcpy(state->window, strm->next_out - copy, copy);
  83511. state->write = copy;
  83512. state->whave = state->wsize;
  83513. }
  83514. else {
  83515. state->write += dist;
  83516. if (state->write == state->wsize) state->write = 0;
  83517. if (state->whave < state->wsize) state->whave += dist;
  83518. }
  83519. }
  83520. return 0;
  83521. }
  83522. /* Macros for inflate(): */
  83523. /* check function to use adler32() for zlib or crc32() for gzip */
  83524. #ifdef GUNZIP
  83525. # define UPDATE(check, buf, len) \
  83526. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83527. #else
  83528. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83529. #endif
  83530. /* check macros for header crc */
  83531. #ifdef GUNZIP
  83532. # define CRC2(check, word) \
  83533. do { \
  83534. hbuf[0] = (unsigned char)(word); \
  83535. hbuf[1] = (unsigned char)((word) >> 8); \
  83536. check = crc32(check, hbuf, 2); \
  83537. } while (0)
  83538. # define CRC4(check, word) \
  83539. do { \
  83540. hbuf[0] = (unsigned char)(word); \
  83541. hbuf[1] = (unsigned char)((word) >> 8); \
  83542. hbuf[2] = (unsigned char)((word) >> 16); \
  83543. hbuf[3] = (unsigned char)((word) >> 24); \
  83544. check = crc32(check, hbuf, 4); \
  83545. } while (0)
  83546. #endif
  83547. /* Load registers with state in inflate() for speed */
  83548. #define LOAD() \
  83549. do { \
  83550. put = strm->next_out; \
  83551. left = strm->avail_out; \
  83552. next = strm->next_in; \
  83553. have = strm->avail_in; \
  83554. hold = state->hold; \
  83555. bits = state->bits; \
  83556. } while (0)
  83557. /* Restore state from registers in inflate() */
  83558. #define RESTORE() \
  83559. do { \
  83560. strm->next_out = put; \
  83561. strm->avail_out = left; \
  83562. strm->next_in = next; \
  83563. strm->avail_in = have; \
  83564. state->hold = hold; \
  83565. state->bits = bits; \
  83566. } while (0)
  83567. /* Clear the input bit accumulator */
  83568. #define INITBITS() \
  83569. do { \
  83570. hold = 0; \
  83571. bits = 0; \
  83572. } while (0)
  83573. /* Get a byte of input into the bit accumulator, or return from inflate()
  83574. if there is no input available. */
  83575. #define PULLBYTE() \
  83576. do { \
  83577. if (have == 0) goto inf_leave; \
  83578. have--; \
  83579. hold += (unsigned long)(*next++) << bits; \
  83580. bits += 8; \
  83581. } while (0)
  83582. /* Assure that there are at least n bits in the bit accumulator. If there is
  83583. not enough available input to do that, then return from inflate(). */
  83584. #define NEEDBITS(n) \
  83585. do { \
  83586. while (bits < (unsigned)(n)) \
  83587. PULLBYTE(); \
  83588. } while (0)
  83589. /* Return the low n bits of the bit accumulator (n < 16) */
  83590. #define BITS(n) \
  83591. ((unsigned)hold & ((1U << (n)) - 1))
  83592. /* Remove n bits from the bit accumulator */
  83593. #define DROPBITS(n) \
  83594. do { \
  83595. hold >>= (n); \
  83596. bits -= (unsigned)(n); \
  83597. } while (0)
  83598. /* Remove zero to seven bits as needed to go to a byte boundary */
  83599. #define BYTEBITS() \
  83600. do { \
  83601. hold >>= bits & 7; \
  83602. bits -= bits & 7; \
  83603. } while (0)
  83604. /* Reverse the bytes in a 32-bit value */
  83605. #define REVERSE(q) \
  83606. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83607. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83608. /*
  83609. inflate() uses a state machine to process as much input data and generate as
  83610. much output data as possible before returning. The state machine is
  83611. structured roughly as follows:
  83612. for (;;) switch (state) {
  83613. ...
  83614. case STATEn:
  83615. if (not enough input data or output space to make progress)
  83616. return;
  83617. ... make progress ...
  83618. state = STATEm;
  83619. break;
  83620. ...
  83621. }
  83622. so when inflate() is called again, the same case is attempted again, and
  83623. if the appropriate resources are provided, the machine proceeds to the
  83624. next state. The NEEDBITS() macro is usually the way the state evaluates
  83625. whether it can proceed or should return. NEEDBITS() does the return if
  83626. the requested bits are not available. The typical use of the BITS macros
  83627. is:
  83628. NEEDBITS(n);
  83629. ... do something with BITS(n) ...
  83630. DROPBITS(n);
  83631. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83632. input left to load n bits into the accumulator, or it continues. BITS(n)
  83633. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83634. the low n bits off the accumulator. INITBITS() clears the accumulator
  83635. and sets the number of available bits to zero. BYTEBITS() discards just
  83636. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83637. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83638. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83639. if there is no input available. The decoding of variable length codes uses
  83640. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83641. code, and no more.
  83642. Some states loop until they get enough input, making sure that enough
  83643. state information is maintained to continue the loop where it left off
  83644. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83645. would all have to actually be part of the saved state in case NEEDBITS()
  83646. returns:
  83647. case STATEw:
  83648. while (want < need) {
  83649. NEEDBITS(n);
  83650. keep[want++] = BITS(n);
  83651. DROPBITS(n);
  83652. }
  83653. state = STATEx;
  83654. case STATEx:
  83655. As shown above, if the next state is also the next case, then the break
  83656. is omitted.
  83657. A state may also return if there is not enough output space available to
  83658. complete that state. Those states are copying stored data, writing a
  83659. literal byte, and copying a matching string.
  83660. When returning, a "goto inf_leave" is used to update the total counters,
  83661. update the check value, and determine whether any progress has been made
  83662. during that inflate() call in order to return the proper return code.
  83663. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83664. When there is a window, goto inf_leave will update the window with the last
  83665. output written. If a goto inf_leave occurs in the middle of decompression
  83666. and there is no window currently, goto inf_leave will create one and copy
  83667. output to the window for the next call of inflate().
  83668. In this implementation, the flush parameter of inflate() only affects the
  83669. return code (per zlib.h). inflate() always writes as much as possible to
  83670. strm->next_out, given the space available and the provided input--the effect
  83671. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83672. the allocation of and copying into a sliding window until necessary, which
  83673. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83674. stream available. So the only thing the flush parameter actually does is:
  83675. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83676. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83677. */
  83678. int ZEXPORT inflate (z_streamp strm, int flush)
  83679. {
  83680. struct inflate_state FAR *state;
  83681. unsigned char FAR *next; /* next input */
  83682. unsigned char FAR *put; /* next output */
  83683. unsigned have, left; /* available input and output */
  83684. unsigned long hold; /* bit buffer */
  83685. unsigned bits; /* bits in bit buffer */
  83686. unsigned in, out; /* save starting available input and output */
  83687. unsigned copy; /* number of stored or match bytes to copy */
  83688. unsigned char FAR *from; /* where to copy match bytes from */
  83689. code thisx; /* current decoding table entry */
  83690. code last; /* parent table entry */
  83691. unsigned len; /* length to copy for repeats, bits to drop */
  83692. int ret; /* return code */
  83693. #ifdef GUNZIP
  83694. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83695. #endif
  83696. static const unsigned short order[19] = /* permutation of code lengths */
  83697. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83698. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83699. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83700. return Z_STREAM_ERROR;
  83701. state = (struct inflate_state FAR *)strm->state;
  83702. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83703. LOAD();
  83704. in = have;
  83705. out = left;
  83706. ret = Z_OK;
  83707. for (;;)
  83708. switch (state->mode) {
  83709. case HEAD:
  83710. if (state->wrap == 0) {
  83711. state->mode = TYPEDO;
  83712. break;
  83713. }
  83714. NEEDBITS(16);
  83715. #ifdef GUNZIP
  83716. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83717. state->check = crc32(0L, Z_NULL, 0);
  83718. CRC2(state->check, hold);
  83719. INITBITS();
  83720. state->mode = FLAGS;
  83721. break;
  83722. }
  83723. state->flags = 0; /* expect zlib header */
  83724. if (state->head != Z_NULL)
  83725. state->head->done = -1;
  83726. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83727. #else
  83728. if (
  83729. #endif
  83730. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83731. strm->msg = (char *)"incorrect header check";
  83732. state->mode = BAD;
  83733. break;
  83734. }
  83735. if (BITS(4) != Z_DEFLATED) {
  83736. strm->msg = (char *)"unknown compression method";
  83737. state->mode = BAD;
  83738. break;
  83739. }
  83740. DROPBITS(4);
  83741. len = BITS(4) + 8;
  83742. if (len > state->wbits) {
  83743. strm->msg = (char *)"invalid window size";
  83744. state->mode = BAD;
  83745. break;
  83746. }
  83747. state->dmax = 1U << len;
  83748. Tracev((stderr, "inflate: zlib header ok\n"));
  83749. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83750. state->mode = hold & 0x200 ? DICTID : TYPE;
  83751. INITBITS();
  83752. break;
  83753. #ifdef GUNZIP
  83754. case FLAGS:
  83755. NEEDBITS(16);
  83756. state->flags = (int)(hold);
  83757. if ((state->flags & 0xff) != Z_DEFLATED) {
  83758. strm->msg = (char *)"unknown compression method";
  83759. state->mode = BAD;
  83760. break;
  83761. }
  83762. if (state->flags & 0xe000) {
  83763. strm->msg = (char *)"unknown header flags set";
  83764. state->mode = BAD;
  83765. break;
  83766. }
  83767. if (state->head != Z_NULL)
  83768. state->head->text = (int)((hold >> 8) & 1);
  83769. if (state->flags & 0x0200) CRC2(state->check, hold);
  83770. INITBITS();
  83771. state->mode = TIME;
  83772. case TIME:
  83773. NEEDBITS(32);
  83774. if (state->head != Z_NULL)
  83775. state->head->time = hold;
  83776. if (state->flags & 0x0200) CRC4(state->check, hold);
  83777. INITBITS();
  83778. state->mode = OS;
  83779. case OS:
  83780. NEEDBITS(16);
  83781. if (state->head != Z_NULL) {
  83782. state->head->xflags = (int)(hold & 0xff);
  83783. state->head->os = (int)(hold >> 8);
  83784. }
  83785. if (state->flags & 0x0200) CRC2(state->check, hold);
  83786. INITBITS();
  83787. state->mode = EXLEN;
  83788. case EXLEN:
  83789. if (state->flags & 0x0400) {
  83790. NEEDBITS(16);
  83791. state->length = (unsigned)(hold);
  83792. if (state->head != Z_NULL)
  83793. state->head->extra_len = (unsigned)hold;
  83794. if (state->flags & 0x0200) CRC2(state->check, hold);
  83795. INITBITS();
  83796. }
  83797. else if (state->head != Z_NULL)
  83798. state->head->extra = Z_NULL;
  83799. state->mode = EXTRA;
  83800. case EXTRA:
  83801. if (state->flags & 0x0400) {
  83802. copy = state->length;
  83803. if (copy > have) copy = have;
  83804. if (copy) {
  83805. if (state->head != Z_NULL &&
  83806. state->head->extra != Z_NULL) {
  83807. len = state->head->extra_len - state->length;
  83808. zmemcpy(state->head->extra + len, next,
  83809. len + copy > state->head->extra_max ?
  83810. state->head->extra_max - len : copy);
  83811. }
  83812. if (state->flags & 0x0200)
  83813. state->check = crc32(state->check, next, copy);
  83814. have -= copy;
  83815. next += copy;
  83816. state->length -= copy;
  83817. }
  83818. if (state->length) goto inf_leave;
  83819. }
  83820. state->length = 0;
  83821. state->mode = NAME;
  83822. case NAME:
  83823. if (state->flags & 0x0800) {
  83824. if (have == 0) goto inf_leave;
  83825. copy = 0;
  83826. do {
  83827. len = (unsigned)(next[copy++]);
  83828. if (state->head != Z_NULL &&
  83829. state->head->name != Z_NULL &&
  83830. state->length < state->head->name_max)
  83831. state->head->name[state->length++] = len;
  83832. } while (len && copy < have);
  83833. if (state->flags & 0x0200)
  83834. state->check = crc32(state->check, next, copy);
  83835. have -= copy;
  83836. next += copy;
  83837. if (len) goto inf_leave;
  83838. }
  83839. else if (state->head != Z_NULL)
  83840. state->head->name = Z_NULL;
  83841. state->length = 0;
  83842. state->mode = COMMENT;
  83843. case COMMENT:
  83844. if (state->flags & 0x1000) {
  83845. if (have == 0) goto inf_leave;
  83846. copy = 0;
  83847. do {
  83848. len = (unsigned)(next[copy++]);
  83849. if (state->head != Z_NULL &&
  83850. state->head->comment != Z_NULL &&
  83851. state->length < state->head->comm_max)
  83852. state->head->comment[state->length++] = len;
  83853. } while (len && copy < have);
  83854. if (state->flags & 0x0200)
  83855. state->check = crc32(state->check, next, copy);
  83856. have -= copy;
  83857. next += copy;
  83858. if (len) goto inf_leave;
  83859. }
  83860. else if (state->head != Z_NULL)
  83861. state->head->comment = Z_NULL;
  83862. state->mode = HCRC;
  83863. case HCRC:
  83864. if (state->flags & 0x0200) {
  83865. NEEDBITS(16);
  83866. if (hold != (state->check & 0xffff)) {
  83867. strm->msg = (char *)"header crc mismatch";
  83868. state->mode = BAD;
  83869. break;
  83870. }
  83871. INITBITS();
  83872. }
  83873. if (state->head != Z_NULL) {
  83874. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83875. state->head->done = 1;
  83876. }
  83877. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83878. state->mode = TYPE;
  83879. break;
  83880. #endif
  83881. case DICTID:
  83882. NEEDBITS(32);
  83883. strm->adler = state->check = REVERSE(hold);
  83884. INITBITS();
  83885. state->mode = DICT;
  83886. case DICT:
  83887. if (state->havedict == 0) {
  83888. RESTORE();
  83889. return Z_NEED_DICT;
  83890. }
  83891. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83892. state->mode = TYPE;
  83893. case TYPE:
  83894. if (flush == Z_BLOCK) goto inf_leave;
  83895. case TYPEDO:
  83896. if (state->last) {
  83897. BYTEBITS();
  83898. state->mode = CHECK;
  83899. break;
  83900. }
  83901. NEEDBITS(3);
  83902. state->last = BITS(1);
  83903. DROPBITS(1);
  83904. switch (BITS(2)) {
  83905. case 0: /* stored block */
  83906. Tracev((stderr, "inflate: stored block%s\n",
  83907. state->last ? " (last)" : ""));
  83908. state->mode = STORED;
  83909. break;
  83910. case 1: /* fixed block */
  83911. fixedtables(state);
  83912. Tracev((stderr, "inflate: fixed codes block%s\n",
  83913. state->last ? " (last)" : ""));
  83914. state->mode = LEN; /* decode codes */
  83915. break;
  83916. case 2: /* dynamic block */
  83917. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83918. state->last ? " (last)" : ""));
  83919. state->mode = TABLE;
  83920. break;
  83921. case 3:
  83922. strm->msg = (char *)"invalid block type";
  83923. state->mode = BAD;
  83924. }
  83925. DROPBITS(2);
  83926. break;
  83927. case STORED:
  83928. BYTEBITS(); /* go to byte boundary */
  83929. NEEDBITS(32);
  83930. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83931. strm->msg = (char *)"invalid stored block lengths";
  83932. state->mode = BAD;
  83933. break;
  83934. }
  83935. state->length = (unsigned)hold & 0xffff;
  83936. Tracev((stderr, "inflate: stored length %u\n",
  83937. state->length));
  83938. INITBITS();
  83939. state->mode = COPY;
  83940. case COPY:
  83941. copy = state->length;
  83942. if (copy) {
  83943. if (copy > have) copy = have;
  83944. if (copy > left) copy = left;
  83945. if (copy == 0) goto inf_leave;
  83946. zmemcpy(put, next, copy);
  83947. have -= copy;
  83948. next += copy;
  83949. left -= copy;
  83950. put += copy;
  83951. state->length -= copy;
  83952. break;
  83953. }
  83954. Tracev((stderr, "inflate: stored end\n"));
  83955. state->mode = TYPE;
  83956. break;
  83957. case TABLE:
  83958. NEEDBITS(14);
  83959. state->nlen = BITS(5) + 257;
  83960. DROPBITS(5);
  83961. state->ndist = BITS(5) + 1;
  83962. DROPBITS(5);
  83963. state->ncode = BITS(4) + 4;
  83964. DROPBITS(4);
  83965. #ifndef PKZIP_BUG_WORKAROUND
  83966. if (state->nlen > 286 || state->ndist > 30) {
  83967. strm->msg = (char *)"too many length or distance symbols";
  83968. state->mode = BAD;
  83969. break;
  83970. }
  83971. #endif
  83972. Tracev((stderr, "inflate: table sizes ok\n"));
  83973. state->have = 0;
  83974. state->mode = LENLENS;
  83975. case LENLENS:
  83976. while (state->have < state->ncode) {
  83977. NEEDBITS(3);
  83978. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83979. DROPBITS(3);
  83980. }
  83981. while (state->have < 19)
  83982. state->lens[order[state->have++]] = 0;
  83983. state->next = state->codes;
  83984. state->lencode = (code const FAR *)(state->next);
  83985. state->lenbits = 7;
  83986. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83987. &(state->lenbits), state->work);
  83988. if (ret) {
  83989. strm->msg = (char *)"invalid code lengths set";
  83990. state->mode = BAD;
  83991. break;
  83992. }
  83993. Tracev((stderr, "inflate: code lengths ok\n"));
  83994. state->have = 0;
  83995. state->mode = CODELENS;
  83996. case CODELENS:
  83997. while (state->have < state->nlen + state->ndist) {
  83998. for (;;) {
  83999. thisx = state->lencode[BITS(state->lenbits)];
  84000. if ((unsigned)(thisx.bits) <= bits) break;
  84001. PULLBYTE();
  84002. }
  84003. if (thisx.val < 16) {
  84004. NEEDBITS(thisx.bits);
  84005. DROPBITS(thisx.bits);
  84006. state->lens[state->have++] = thisx.val;
  84007. }
  84008. else {
  84009. if (thisx.val == 16) {
  84010. NEEDBITS(thisx.bits + 2);
  84011. DROPBITS(thisx.bits);
  84012. if (state->have == 0) {
  84013. strm->msg = (char *)"invalid bit length repeat";
  84014. state->mode = BAD;
  84015. break;
  84016. }
  84017. len = state->lens[state->have - 1];
  84018. copy = 3 + BITS(2);
  84019. DROPBITS(2);
  84020. }
  84021. else if (thisx.val == 17) {
  84022. NEEDBITS(thisx.bits + 3);
  84023. DROPBITS(thisx.bits);
  84024. len = 0;
  84025. copy = 3 + BITS(3);
  84026. DROPBITS(3);
  84027. }
  84028. else {
  84029. NEEDBITS(thisx.bits + 7);
  84030. DROPBITS(thisx.bits);
  84031. len = 0;
  84032. copy = 11 + BITS(7);
  84033. DROPBITS(7);
  84034. }
  84035. if (state->have + copy > state->nlen + state->ndist) {
  84036. strm->msg = (char *)"invalid bit length repeat";
  84037. state->mode = BAD;
  84038. break;
  84039. }
  84040. while (copy--)
  84041. state->lens[state->have++] = (unsigned short)len;
  84042. }
  84043. }
  84044. /* handle error breaks in while */
  84045. if (state->mode == BAD) break;
  84046. /* build code tables */
  84047. state->next = state->codes;
  84048. state->lencode = (code const FAR *)(state->next);
  84049. state->lenbits = 9;
  84050. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  84051. &(state->lenbits), state->work);
  84052. if (ret) {
  84053. strm->msg = (char *)"invalid literal/lengths set";
  84054. state->mode = BAD;
  84055. break;
  84056. }
  84057. state->distcode = (code const FAR *)(state->next);
  84058. state->distbits = 6;
  84059. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  84060. &(state->next), &(state->distbits), state->work);
  84061. if (ret) {
  84062. strm->msg = (char *)"invalid distances set";
  84063. state->mode = BAD;
  84064. break;
  84065. }
  84066. Tracev((stderr, "inflate: codes ok\n"));
  84067. state->mode = LEN;
  84068. case LEN:
  84069. if (have >= 6 && left >= 258) {
  84070. RESTORE();
  84071. inflate_fast(strm, out);
  84072. LOAD();
  84073. break;
  84074. }
  84075. for (;;) {
  84076. thisx = state->lencode[BITS(state->lenbits)];
  84077. if ((unsigned)(thisx.bits) <= bits) break;
  84078. PULLBYTE();
  84079. }
  84080. if (thisx.op && (thisx.op & 0xf0) == 0) {
  84081. last = thisx;
  84082. for (;;) {
  84083. thisx = state->lencode[last.val +
  84084. (BITS(last.bits + last.op) >> last.bits)];
  84085. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84086. PULLBYTE();
  84087. }
  84088. DROPBITS(last.bits);
  84089. }
  84090. DROPBITS(thisx.bits);
  84091. state->length = (unsigned)thisx.val;
  84092. if ((int)(thisx.op) == 0) {
  84093. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84094. "inflate: literal '%c'\n" :
  84095. "inflate: literal 0x%02x\n", thisx.val));
  84096. state->mode = LIT;
  84097. break;
  84098. }
  84099. if (thisx.op & 32) {
  84100. Tracevv((stderr, "inflate: end of block\n"));
  84101. state->mode = TYPE;
  84102. break;
  84103. }
  84104. if (thisx.op & 64) {
  84105. strm->msg = (char *)"invalid literal/length code";
  84106. state->mode = BAD;
  84107. break;
  84108. }
  84109. state->extra = (unsigned)(thisx.op) & 15;
  84110. state->mode = LENEXT;
  84111. case LENEXT:
  84112. if (state->extra) {
  84113. NEEDBITS(state->extra);
  84114. state->length += BITS(state->extra);
  84115. DROPBITS(state->extra);
  84116. }
  84117. Tracevv((stderr, "inflate: length %u\n", state->length));
  84118. state->mode = DIST;
  84119. case DIST:
  84120. for (;;) {
  84121. thisx = state->distcode[BITS(state->distbits)];
  84122. if ((unsigned)(thisx.bits) <= bits) break;
  84123. PULLBYTE();
  84124. }
  84125. if ((thisx.op & 0xf0) == 0) {
  84126. last = thisx;
  84127. for (;;) {
  84128. thisx = state->distcode[last.val +
  84129. (BITS(last.bits + last.op) >> last.bits)];
  84130. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84131. PULLBYTE();
  84132. }
  84133. DROPBITS(last.bits);
  84134. }
  84135. DROPBITS(thisx.bits);
  84136. if (thisx.op & 64) {
  84137. strm->msg = (char *)"invalid distance code";
  84138. state->mode = BAD;
  84139. break;
  84140. }
  84141. state->offset = (unsigned)thisx.val;
  84142. state->extra = (unsigned)(thisx.op) & 15;
  84143. state->mode = DISTEXT;
  84144. case DISTEXT:
  84145. if (state->extra) {
  84146. NEEDBITS(state->extra);
  84147. state->offset += BITS(state->extra);
  84148. DROPBITS(state->extra);
  84149. }
  84150. #ifdef INFLATE_STRICT
  84151. if (state->offset > state->dmax) {
  84152. strm->msg = (char *)"invalid distance too far back";
  84153. state->mode = BAD;
  84154. break;
  84155. }
  84156. #endif
  84157. if (state->offset > state->whave + out - left) {
  84158. strm->msg = (char *)"invalid distance too far back";
  84159. state->mode = BAD;
  84160. break;
  84161. }
  84162. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84163. state->mode = MATCH;
  84164. case MATCH:
  84165. if (left == 0) goto inf_leave;
  84166. copy = out - left;
  84167. if (state->offset > copy) { /* copy from window */
  84168. copy = state->offset - copy;
  84169. if (copy > state->write) {
  84170. copy -= state->write;
  84171. from = state->window + (state->wsize - copy);
  84172. }
  84173. else
  84174. from = state->window + (state->write - copy);
  84175. if (copy > state->length) copy = state->length;
  84176. }
  84177. else { /* copy from output */
  84178. from = put - state->offset;
  84179. copy = state->length;
  84180. }
  84181. if (copy > left) copy = left;
  84182. left -= copy;
  84183. state->length -= copy;
  84184. do {
  84185. *put++ = *from++;
  84186. } while (--copy);
  84187. if (state->length == 0) state->mode = LEN;
  84188. break;
  84189. case LIT:
  84190. if (left == 0) goto inf_leave;
  84191. *put++ = (unsigned char)(state->length);
  84192. left--;
  84193. state->mode = LEN;
  84194. break;
  84195. case CHECK:
  84196. if (state->wrap) {
  84197. NEEDBITS(32);
  84198. out -= left;
  84199. strm->total_out += out;
  84200. state->total += out;
  84201. if (out)
  84202. strm->adler = state->check =
  84203. UPDATE(state->check, put - out, out);
  84204. out = left;
  84205. if ((
  84206. #ifdef GUNZIP
  84207. state->flags ? hold :
  84208. #endif
  84209. REVERSE(hold)) != state->check) {
  84210. strm->msg = (char *)"incorrect data check";
  84211. state->mode = BAD;
  84212. break;
  84213. }
  84214. INITBITS();
  84215. Tracev((stderr, "inflate: check matches trailer\n"));
  84216. }
  84217. #ifdef GUNZIP
  84218. state->mode = LENGTH;
  84219. case LENGTH:
  84220. if (state->wrap && state->flags) {
  84221. NEEDBITS(32);
  84222. if (hold != (state->total & 0xffffffffUL)) {
  84223. strm->msg = (char *)"incorrect length check";
  84224. state->mode = BAD;
  84225. break;
  84226. }
  84227. INITBITS();
  84228. Tracev((stderr, "inflate: length matches trailer\n"));
  84229. }
  84230. #endif
  84231. state->mode = DONE;
  84232. case DONE:
  84233. ret = Z_STREAM_END;
  84234. goto inf_leave;
  84235. case BAD:
  84236. ret = Z_DATA_ERROR;
  84237. goto inf_leave;
  84238. case MEM:
  84239. return Z_MEM_ERROR;
  84240. case SYNC:
  84241. default:
  84242. return Z_STREAM_ERROR;
  84243. }
  84244. /*
  84245. Return from inflate(), updating the total counts and the check value.
  84246. If there was no progress during the inflate() call, return a buffer
  84247. error. Call updatewindow() to create and/or update the window state.
  84248. Note: a memory error from inflate() is non-recoverable.
  84249. */
  84250. inf_leave:
  84251. RESTORE();
  84252. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84253. if (updatewindow(strm, out)) {
  84254. state->mode = MEM;
  84255. return Z_MEM_ERROR;
  84256. }
  84257. in -= strm->avail_in;
  84258. out -= strm->avail_out;
  84259. strm->total_in += in;
  84260. strm->total_out += out;
  84261. state->total += out;
  84262. if (state->wrap && out)
  84263. strm->adler = state->check =
  84264. UPDATE(state->check, strm->next_out - out, out);
  84265. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84266. (state->mode == TYPE ? 128 : 0);
  84267. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84268. ret = Z_BUF_ERROR;
  84269. return ret;
  84270. }
  84271. int ZEXPORT inflateEnd (z_streamp strm)
  84272. {
  84273. struct inflate_state FAR *state;
  84274. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84275. return Z_STREAM_ERROR;
  84276. state = (struct inflate_state FAR *)strm->state;
  84277. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84278. ZFREE(strm, strm->state);
  84279. strm->state = Z_NULL;
  84280. Tracev((stderr, "inflate: end\n"));
  84281. return Z_OK;
  84282. }
  84283. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84284. {
  84285. struct inflate_state FAR *state;
  84286. unsigned long id_;
  84287. /* check state */
  84288. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84289. state = (struct inflate_state FAR *)strm->state;
  84290. if (state->wrap != 0 && state->mode != DICT)
  84291. return Z_STREAM_ERROR;
  84292. /* check for correct dictionary id */
  84293. if (state->mode == DICT) {
  84294. id_ = adler32(0L, Z_NULL, 0);
  84295. id_ = adler32(id_, dictionary, dictLength);
  84296. if (id_ != state->check)
  84297. return Z_DATA_ERROR;
  84298. }
  84299. /* copy dictionary to window */
  84300. if (updatewindow(strm, strm->avail_out)) {
  84301. state->mode = MEM;
  84302. return Z_MEM_ERROR;
  84303. }
  84304. if (dictLength > state->wsize) {
  84305. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84306. state->wsize);
  84307. state->whave = state->wsize;
  84308. }
  84309. else {
  84310. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84311. dictLength);
  84312. state->whave = dictLength;
  84313. }
  84314. state->havedict = 1;
  84315. Tracev((stderr, "inflate: dictionary set\n"));
  84316. return Z_OK;
  84317. }
  84318. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84319. {
  84320. struct inflate_state FAR *state;
  84321. /* check state */
  84322. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84323. state = (struct inflate_state FAR *)strm->state;
  84324. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84325. /* save header structure */
  84326. state->head = head;
  84327. head->done = 0;
  84328. return Z_OK;
  84329. }
  84330. /*
  84331. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84332. or when out of input. When called, *have is the number of pattern bytes
  84333. found in order so far, in 0..3. On return *have is updated to the new
  84334. state. If on return *have equals four, then the pattern was found and the
  84335. return value is how many bytes were read including the last byte of the
  84336. pattern. If *have is less than four, then the pattern has not been found
  84337. yet and the return value is len. In the latter case, syncsearch() can be
  84338. called again with more data and the *have state. *have is initialized to
  84339. zero for the first call.
  84340. */
  84341. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84342. {
  84343. unsigned got;
  84344. unsigned next;
  84345. got = *have;
  84346. next = 0;
  84347. while (next < len && got < 4) {
  84348. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84349. got++;
  84350. else if (buf[next])
  84351. got = 0;
  84352. else
  84353. got = 4 - got;
  84354. next++;
  84355. }
  84356. *have = got;
  84357. return next;
  84358. }
  84359. int ZEXPORT inflateSync (z_streamp strm)
  84360. {
  84361. unsigned len; /* number of bytes to look at or looked at */
  84362. unsigned long in, out; /* temporary to save total_in and total_out */
  84363. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84364. struct inflate_state FAR *state;
  84365. /* check parameters */
  84366. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84367. state = (struct inflate_state FAR *)strm->state;
  84368. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84369. /* if first time, start search in bit buffer */
  84370. if (state->mode != SYNC) {
  84371. state->mode = SYNC;
  84372. state->hold <<= state->bits & 7;
  84373. state->bits -= state->bits & 7;
  84374. len = 0;
  84375. while (state->bits >= 8) {
  84376. buf[len++] = (unsigned char)(state->hold);
  84377. state->hold >>= 8;
  84378. state->bits -= 8;
  84379. }
  84380. state->have = 0;
  84381. syncsearch(&(state->have), buf, len);
  84382. }
  84383. /* search available input */
  84384. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84385. strm->avail_in -= len;
  84386. strm->next_in += len;
  84387. strm->total_in += len;
  84388. /* return no joy or set up to restart inflate() on a new block */
  84389. if (state->have != 4) return Z_DATA_ERROR;
  84390. in = strm->total_in; out = strm->total_out;
  84391. inflateReset(strm);
  84392. strm->total_in = in; strm->total_out = out;
  84393. state->mode = TYPE;
  84394. return Z_OK;
  84395. }
  84396. /*
  84397. Returns true if inflate is currently at the end of a block generated by
  84398. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84399. implementation to provide an additional safety check. PPP uses
  84400. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84401. block. When decompressing, PPP checks that at the end of input packet,
  84402. inflate is waiting for these length bytes.
  84403. */
  84404. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84405. {
  84406. struct inflate_state FAR *state;
  84407. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84408. state = (struct inflate_state FAR *)strm->state;
  84409. return state->mode == STORED && state->bits == 0;
  84410. }
  84411. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84412. {
  84413. struct inflate_state FAR *state;
  84414. struct inflate_state FAR *copy;
  84415. unsigned char FAR *window;
  84416. unsigned wsize;
  84417. /* check input */
  84418. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84419. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84420. return Z_STREAM_ERROR;
  84421. state = (struct inflate_state FAR *)source->state;
  84422. /* allocate space */
  84423. copy = (struct inflate_state FAR *)
  84424. ZALLOC(source, 1, sizeof(struct inflate_state));
  84425. if (copy == Z_NULL) return Z_MEM_ERROR;
  84426. window = Z_NULL;
  84427. if (state->window != Z_NULL) {
  84428. window = (unsigned char FAR *)
  84429. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84430. if (window == Z_NULL) {
  84431. ZFREE(source, copy);
  84432. return Z_MEM_ERROR;
  84433. }
  84434. }
  84435. /* copy state */
  84436. zmemcpy(dest, source, sizeof(z_stream));
  84437. zmemcpy(copy, state, sizeof(struct inflate_state));
  84438. if (state->lencode >= state->codes &&
  84439. state->lencode <= state->codes + ENOUGH - 1) {
  84440. copy->lencode = copy->codes + (state->lencode - state->codes);
  84441. copy->distcode = copy->codes + (state->distcode - state->codes);
  84442. }
  84443. copy->next = copy->codes + (state->next - state->codes);
  84444. if (window != Z_NULL) {
  84445. wsize = 1U << state->wbits;
  84446. zmemcpy(window, state->window, wsize);
  84447. }
  84448. copy->window = window;
  84449. dest->state = (struct internal_state FAR *)copy;
  84450. return Z_OK;
  84451. }
  84452. /*** End of inlined file: inflate.c ***/
  84453. /*** Start of inlined file: inftrees.c ***/
  84454. #define MAXBITS 15
  84455. const char inflate_copyright[] =
  84456. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84457. /*
  84458. If you use the zlib library in a product, an acknowledgment is welcome
  84459. in the documentation of your product. If for some reason you cannot
  84460. include such an acknowledgment, I would appreciate that you keep this
  84461. copyright string in the executable of your product.
  84462. */
  84463. /*
  84464. Build a set of tables to decode the provided canonical Huffman code.
  84465. The code lengths are lens[0..codes-1]. The result starts at *table,
  84466. whose indices are 0..2^bits-1. work is a writable array of at least
  84467. lens shorts, which is used as a work area. type is the type of code
  84468. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84469. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84470. on return points to the next available entry's address. bits is the
  84471. requested root table index bits, and on return it is the actual root
  84472. table index bits. It will differ if the request is greater than the
  84473. longest code or if it is less than the shortest code.
  84474. */
  84475. int inflate_table (codetype type,
  84476. unsigned short FAR *lens,
  84477. unsigned codes,
  84478. code FAR * FAR *table,
  84479. unsigned FAR *bits,
  84480. unsigned short FAR *work)
  84481. {
  84482. unsigned len; /* a code's length in bits */
  84483. unsigned sym; /* index of code symbols */
  84484. unsigned min, max; /* minimum and maximum code lengths */
  84485. unsigned root; /* number of index bits for root table */
  84486. unsigned curr; /* number of index bits for current table */
  84487. unsigned drop; /* code bits to drop for sub-table */
  84488. int left; /* number of prefix codes available */
  84489. unsigned used; /* code entries in table used */
  84490. unsigned huff; /* Huffman code */
  84491. unsigned incr; /* for incrementing code, index */
  84492. unsigned fill; /* index for replicating entries */
  84493. unsigned low; /* low bits for current root entry */
  84494. unsigned mask; /* mask for low root bits */
  84495. code thisx; /* table entry for duplication */
  84496. code FAR *next; /* next available space in table */
  84497. const unsigned short FAR *base; /* base value table to use */
  84498. const unsigned short FAR *extra; /* extra bits table to use */
  84499. int end; /* use base and extra for symbol > end */
  84500. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84501. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84502. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84503. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84504. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84505. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84506. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84507. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84508. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84509. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84510. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84511. 8193, 12289, 16385, 24577, 0, 0};
  84512. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84513. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84514. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84515. 28, 28, 29, 29, 64, 64};
  84516. /*
  84517. Process a set of code lengths to create a canonical Huffman code. The
  84518. code lengths are lens[0..codes-1]. Each length corresponds to the
  84519. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84520. symbols by length from short to long, and retaining the symbol order
  84521. for codes with equal lengths. Then the code starts with all zero bits
  84522. for the first code of the shortest length, and the codes are integer
  84523. increments for the same length, and zeros are appended as the length
  84524. increases. For the deflate format, these bits are stored backwards
  84525. from their more natural integer increment ordering, and so when the
  84526. decoding tables are built in the large loop below, the integer codes
  84527. are incremented backwards.
  84528. This routine assumes, but does not check, that all of the entries in
  84529. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84530. 1..MAXBITS is interpreted as that code length. zero means that that
  84531. symbol does not occur in this code.
  84532. The codes are sorted by computing a count of codes for each length,
  84533. creating from that a table of starting indices for each length in the
  84534. sorted table, and then entering the symbols in order in the sorted
  84535. table. The sorted table is work[], with that space being provided by
  84536. the caller.
  84537. The length counts are used for other purposes as well, i.e. finding
  84538. the minimum and maximum length codes, determining if there are any
  84539. codes at all, checking for a valid set of lengths, and looking ahead
  84540. at length counts to determine sub-table sizes when building the
  84541. decoding tables.
  84542. */
  84543. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84544. for (len = 0; len <= MAXBITS; len++)
  84545. count[len] = 0;
  84546. for (sym = 0; sym < codes; sym++)
  84547. count[lens[sym]]++;
  84548. /* bound code lengths, force root to be within code lengths */
  84549. root = *bits;
  84550. for (max = MAXBITS; max >= 1; max--)
  84551. if (count[max] != 0) break;
  84552. if (root > max) root = max;
  84553. if (max == 0) { /* no symbols to code at all */
  84554. thisx.op = (unsigned char)64; /* invalid code marker */
  84555. thisx.bits = (unsigned char)1;
  84556. thisx.val = (unsigned short)0;
  84557. *(*table)++ = thisx; /* make a table to force an error */
  84558. *(*table)++ = thisx;
  84559. *bits = 1;
  84560. return 0; /* no symbols, but wait for decoding to report error */
  84561. }
  84562. for (min = 1; min <= MAXBITS; min++)
  84563. if (count[min] != 0) break;
  84564. if (root < min) root = min;
  84565. /* check for an over-subscribed or incomplete set of lengths */
  84566. left = 1;
  84567. for (len = 1; len <= MAXBITS; len++) {
  84568. left <<= 1;
  84569. left -= count[len];
  84570. if (left < 0) return -1; /* over-subscribed */
  84571. }
  84572. if (left > 0 && (type == CODES || max != 1))
  84573. return -1; /* incomplete set */
  84574. /* generate offsets into symbol table for each length for sorting */
  84575. offs[1] = 0;
  84576. for (len = 1; len < MAXBITS; len++)
  84577. offs[len + 1] = offs[len] + count[len];
  84578. /* sort symbols by length, by symbol order within each length */
  84579. for (sym = 0; sym < codes; sym++)
  84580. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84581. /*
  84582. Create and fill in decoding tables. In this loop, the table being
  84583. filled is at next and has curr index bits. The code being used is huff
  84584. with length len. That code is converted to an index by dropping drop
  84585. bits off of the bottom. For codes where len is less than drop + curr,
  84586. those top drop + curr - len bits are incremented through all values to
  84587. fill the table with replicated entries.
  84588. root is the number of index bits for the root table. When len exceeds
  84589. root, sub-tables are created pointed to by the root entry with an index
  84590. of the low root bits of huff. This is saved in low to check for when a
  84591. new sub-table should be started. drop is zero when the root table is
  84592. being filled, and drop is root when sub-tables are being filled.
  84593. When a new sub-table is needed, it is necessary to look ahead in the
  84594. code lengths to determine what size sub-table is needed. The length
  84595. counts are used for this, and so count[] is decremented as codes are
  84596. entered in the tables.
  84597. used keeps track of how many table entries have been allocated from the
  84598. provided *table space. It is checked when a LENS table is being made
  84599. against the space in *table, ENOUGH, minus the maximum space needed by
  84600. the worst case distance code, MAXD. This should never happen, but the
  84601. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84602. This assumes that when type == LENS, bits == 9.
  84603. sym increments through all symbols, and the loop terminates when
  84604. all codes of length max, i.e. all codes, have been processed. This
  84605. routine permits incomplete codes, so another loop after this one fills
  84606. in the rest of the decoding tables with invalid code markers.
  84607. */
  84608. /* set up for code type */
  84609. switch (type) {
  84610. case CODES:
  84611. base = extra = work; /* dummy value--not used */
  84612. end = 19;
  84613. break;
  84614. case LENS:
  84615. base = lbase;
  84616. base -= 257;
  84617. extra = lext;
  84618. extra -= 257;
  84619. end = 256;
  84620. break;
  84621. default: /* DISTS */
  84622. base = dbase;
  84623. extra = dext;
  84624. end = -1;
  84625. }
  84626. /* initialize state for loop */
  84627. huff = 0; /* starting code */
  84628. sym = 0; /* starting code symbol */
  84629. len = min; /* starting code length */
  84630. next = *table; /* current table to fill in */
  84631. curr = root; /* current table index bits */
  84632. drop = 0; /* current bits to drop from code for index */
  84633. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84634. used = 1U << root; /* use root table entries */
  84635. mask = used - 1; /* mask for comparing low */
  84636. /* check available table space */
  84637. if (type == LENS && used >= ENOUGH - MAXD)
  84638. return 1;
  84639. /* process all codes and make table entries */
  84640. for (;;) {
  84641. /* create table entry */
  84642. thisx.bits = (unsigned char)(len - drop);
  84643. if ((int)(work[sym]) < end) {
  84644. thisx.op = (unsigned char)0;
  84645. thisx.val = work[sym];
  84646. }
  84647. else if ((int)(work[sym]) > end) {
  84648. thisx.op = (unsigned char)(extra[work[sym]]);
  84649. thisx.val = base[work[sym]];
  84650. }
  84651. else {
  84652. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84653. thisx.val = 0;
  84654. }
  84655. /* replicate for those indices with low len bits equal to huff */
  84656. incr = 1U << (len - drop);
  84657. fill = 1U << curr;
  84658. min = fill; /* save offset to next table */
  84659. do {
  84660. fill -= incr;
  84661. next[(huff >> drop) + fill] = thisx;
  84662. } while (fill != 0);
  84663. /* backwards increment the len-bit code huff */
  84664. incr = 1U << (len - 1);
  84665. while (huff & incr)
  84666. incr >>= 1;
  84667. if (incr != 0) {
  84668. huff &= incr - 1;
  84669. huff += incr;
  84670. }
  84671. else
  84672. huff = 0;
  84673. /* go to next symbol, update count, len */
  84674. sym++;
  84675. if (--(count[len]) == 0) {
  84676. if (len == max) break;
  84677. len = lens[work[sym]];
  84678. }
  84679. /* create new sub-table if needed */
  84680. if (len > root && (huff & mask) != low) {
  84681. /* if first time, transition to sub-tables */
  84682. if (drop == 0)
  84683. drop = root;
  84684. /* increment past last table */
  84685. next += min; /* here min is 1 << curr */
  84686. /* determine length of next table */
  84687. curr = len - drop;
  84688. left = (int)(1 << curr);
  84689. while (curr + drop < max) {
  84690. left -= count[curr + drop];
  84691. if (left <= 0) break;
  84692. curr++;
  84693. left <<= 1;
  84694. }
  84695. /* check for enough space */
  84696. used += 1U << curr;
  84697. if (type == LENS && used >= ENOUGH - MAXD)
  84698. return 1;
  84699. /* point entry in root table to sub-table */
  84700. low = huff & mask;
  84701. (*table)[low].op = (unsigned char)curr;
  84702. (*table)[low].bits = (unsigned char)root;
  84703. (*table)[low].val = (unsigned short)(next - *table);
  84704. }
  84705. }
  84706. /*
  84707. Fill in rest of table for incomplete codes. This loop is similar to the
  84708. loop above in incrementing huff for table indices. It is assumed that
  84709. len is equal to curr + drop, so there is no loop needed to increment
  84710. through high index bits. When the current sub-table is filled, the loop
  84711. drops back to the root table to fill in any remaining entries there.
  84712. */
  84713. thisx.op = (unsigned char)64; /* invalid code marker */
  84714. thisx.bits = (unsigned char)(len - drop);
  84715. thisx.val = (unsigned short)0;
  84716. while (huff != 0) {
  84717. /* when done with sub-table, drop back to root table */
  84718. if (drop != 0 && (huff & mask) != low) {
  84719. drop = 0;
  84720. len = root;
  84721. next = *table;
  84722. thisx.bits = (unsigned char)len;
  84723. }
  84724. /* put invalid code marker in table */
  84725. next[huff >> drop] = thisx;
  84726. /* backwards increment the len-bit code huff */
  84727. incr = 1U << (len - 1);
  84728. while (huff & incr)
  84729. incr >>= 1;
  84730. if (incr != 0) {
  84731. huff &= incr - 1;
  84732. huff += incr;
  84733. }
  84734. else
  84735. huff = 0;
  84736. }
  84737. /* set return parameters */
  84738. *table += used;
  84739. *bits = root;
  84740. return 0;
  84741. }
  84742. /*** End of inlined file: inftrees.c ***/
  84743. /*** Start of inlined file: trees.c ***/
  84744. /*
  84745. * ALGORITHM
  84746. *
  84747. * The "deflation" process uses several Huffman trees. The more
  84748. * common source values are represented by shorter bit sequences.
  84749. *
  84750. * Each code tree is stored in a compressed form which is itself
  84751. * a Huffman encoding of the lengths of all the code strings (in
  84752. * ascending order by source values). The actual code strings are
  84753. * reconstructed from the lengths in the inflate process, as described
  84754. * in the deflate specification.
  84755. *
  84756. * REFERENCES
  84757. *
  84758. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84759. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84760. *
  84761. * Storer, James A.
  84762. * Data Compression: Methods and Theory, pp. 49-50.
  84763. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84764. *
  84765. * Sedgewick, R.
  84766. * Algorithms, p290.
  84767. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84768. */
  84769. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84770. /* #define GEN_TREES_H */
  84771. #ifdef DEBUG
  84772. # include <ctype.h>
  84773. #endif
  84774. /* ===========================================================================
  84775. * Constants
  84776. */
  84777. #define MAX_BL_BITS 7
  84778. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84779. #define END_BLOCK 256
  84780. /* end of block literal code */
  84781. #define REP_3_6 16
  84782. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84783. #define REPZ_3_10 17
  84784. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84785. #define REPZ_11_138 18
  84786. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84787. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84788. = {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};
  84789. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84790. = {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};
  84791. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84792. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84793. local const uch bl_order[BL_CODES]
  84794. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84795. /* The lengths of the bit length codes are sent in order of decreasing
  84796. * probability, to avoid transmitting the lengths for unused bit length codes.
  84797. */
  84798. #define Buf_size (8 * 2*sizeof(char))
  84799. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84800. * more than 16 bits on some systems.)
  84801. */
  84802. /* ===========================================================================
  84803. * Local data. These are initialized only once.
  84804. */
  84805. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84806. #if defined(GEN_TREES_H) || !defined(STDC)
  84807. /* non ANSI compilers may not accept trees.h */
  84808. local ct_data static_ltree[L_CODES+2];
  84809. /* The static literal tree. Since the bit lengths are imposed, there is no
  84810. * need for the L_CODES extra codes used during heap construction. However
  84811. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84812. * below).
  84813. */
  84814. local ct_data static_dtree[D_CODES];
  84815. /* The static distance tree. (Actually a trivial tree since all codes use
  84816. * 5 bits.)
  84817. */
  84818. uch _dist_code[DIST_CODE_LEN];
  84819. /* Distance codes. The first 256 values correspond to the distances
  84820. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84821. * the 15 bit distances.
  84822. */
  84823. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84824. /* length code for each normalized match length (0 == MIN_MATCH) */
  84825. local int base_length[LENGTH_CODES];
  84826. /* First normalized length for each code (0 = MIN_MATCH) */
  84827. local int base_dist[D_CODES];
  84828. /* First normalized distance for each code (0 = distance of 1) */
  84829. #else
  84830. /*** Start of inlined file: trees.h ***/
  84831. local const ct_data static_ltree[L_CODES+2] = {
  84832. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84833. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84834. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84835. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84836. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84837. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84838. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84839. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84840. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84841. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84842. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84843. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84844. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84845. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84846. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84847. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84848. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84849. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84850. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84851. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84852. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84853. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84854. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84855. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84856. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84857. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84858. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84859. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84860. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84861. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84862. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84863. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84864. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84865. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84866. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84867. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84868. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84869. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84870. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84871. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84872. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84873. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84874. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84875. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84876. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84877. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84878. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84879. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84880. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84881. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84882. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84883. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84884. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84885. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84886. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84887. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84888. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84889. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84890. };
  84891. local const ct_data static_dtree[D_CODES] = {
  84892. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84893. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84894. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84895. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84896. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84897. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84898. };
  84899. const uch _dist_code[DIST_CODE_LEN] = {
  84900. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84901. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84902. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84903. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84904. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84905. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84906. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84907. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84908. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84909. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84910. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84911. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84912. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84913. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84914. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84915. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84916. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84917. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84918. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84919. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84920. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84921. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84922. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84923. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84924. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84925. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84926. };
  84927. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84928. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84929. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84930. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84931. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84932. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84933. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84934. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84935. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84936. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84937. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84938. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84939. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84940. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84941. };
  84942. local const int base_length[LENGTH_CODES] = {
  84943. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84944. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84945. };
  84946. local const int base_dist[D_CODES] = {
  84947. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84948. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84949. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84950. };
  84951. /*** End of inlined file: trees.h ***/
  84952. #endif /* GEN_TREES_H */
  84953. struct static_tree_desc_s {
  84954. const ct_data *static_tree; /* static tree or NULL */
  84955. const intf *extra_bits; /* extra bits for each code or NULL */
  84956. int extra_base; /* base index for extra_bits */
  84957. int elems; /* max number of elements in the tree */
  84958. int max_length; /* max bit length for the codes */
  84959. };
  84960. local static_tree_desc static_l_desc =
  84961. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84962. local static_tree_desc static_d_desc =
  84963. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84964. local static_tree_desc static_bl_desc =
  84965. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84966. /* ===========================================================================
  84967. * Local (static) routines in this file.
  84968. */
  84969. local void tr_static_init OF((void));
  84970. local void init_block OF((deflate_state *s));
  84971. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84972. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84973. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84974. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84975. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84976. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84977. local int build_bl_tree OF((deflate_state *s));
  84978. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84979. int blcodes));
  84980. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84981. ct_data *dtree));
  84982. local void set_data_type OF((deflate_state *s));
  84983. local unsigned bi_reverse OF((unsigned value, int length));
  84984. local void bi_windup OF((deflate_state *s));
  84985. local void bi_flush OF((deflate_state *s));
  84986. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84987. int header));
  84988. #ifdef GEN_TREES_H
  84989. local void gen_trees_header OF((void));
  84990. #endif
  84991. #ifndef DEBUG
  84992. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84993. /* Send a code of the given tree. c and tree must not have side effects */
  84994. #else /* DEBUG */
  84995. # define send_code(s, c, tree) \
  84996. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84997. send_bits(s, tree[c].Code, tree[c].Len); }
  84998. #endif
  84999. /* ===========================================================================
  85000. * Output a short LSB first on the stream.
  85001. * IN assertion: there is enough room in pendingBuf.
  85002. */
  85003. #define put_short(s, w) { \
  85004. put_byte(s, (uch)((w) & 0xff)); \
  85005. put_byte(s, (uch)((ush)(w) >> 8)); \
  85006. }
  85007. /* ===========================================================================
  85008. * Send a value on a given number of bits.
  85009. * IN assertion: length <= 16 and value fits in length bits.
  85010. */
  85011. #ifdef DEBUG
  85012. local void send_bits OF((deflate_state *s, int value, int length));
  85013. local void send_bits (deflate_state *s, int value, int length)
  85014. {
  85015. Tracevv((stderr," l %2d v %4x ", length, value));
  85016. Assert(length > 0 && length <= 15, "invalid length");
  85017. s->bits_sent += (ulg)length;
  85018. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  85019. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  85020. * unused bits in value.
  85021. */
  85022. if (s->bi_valid > (int)Buf_size - length) {
  85023. s->bi_buf |= (value << s->bi_valid);
  85024. put_short(s, s->bi_buf);
  85025. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  85026. s->bi_valid += length - Buf_size;
  85027. } else {
  85028. s->bi_buf |= value << s->bi_valid;
  85029. s->bi_valid += length;
  85030. }
  85031. }
  85032. #else /* !DEBUG */
  85033. #define send_bits(s, value, length) \
  85034. { int len = length;\
  85035. if (s->bi_valid > (int)Buf_size - len) {\
  85036. int val = value;\
  85037. s->bi_buf |= (val << s->bi_valid);\
  85038. put_short(s, s->bi_buf);\
  85039. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  85040. s->bi_valid += len - Buf_size;\
  85041. } else {\
  85042. s->bi_buf |= (value) << s->bi_valid;\
  85043. s->bi_valid += len;\
  85044. }\
  85045. }
  85046. #endif /* DEBUG */
  85047. /* the arguments must not have side effects */
  85048. /* ===========================================================================
  85049. * Initialize the various 'constant' tables.
  85050. */
  85051. local void tr_static_init()
  85052. {
  85053. #if defined(GEN_TREES_H) || !defined(STDC)
  85054. static int static_init_done = 0;
  85055. int n; /* iterates over tree elements */
  85056. int bits; /* bit counter */
  85057. int length; /* length value */
  85058. int code; /* code value */
  85059. int dist; /* distance index */
  85060. ush bl_count[MAX_BITS+1];
  85061. /* number of codes at each bit length for an optimal tree */
  85062. if (static_init_done) return;
  85063. /* For some embedded targets, global variables are not initialized: */
  85064. static_l_desc.static_tree = static_ltree;
  85065. static_l_desc.extra_bits = extra_lbits;
  85066. static_d_desc.static_tree = static_dtree;
  85067. static_d_desc.extra_bits = extra_dbits;
  85068. static_bl_desc.extra_bits = extra_blbits;
  85069. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85070. length = 0;
  85071. for (code = 0; code < LENGTH_CODES-1; code++) {
  85072. base_length[code] = length;
  85073. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  85074. _length_code[length++] = (uch)code;
  85075. }
  85076. }
  85077. Assert (length == 256, "tr_static_init: length != 256");
  85078. /* Note that the length 255 (match length 258) can be represented
  85079. * in two different ways: code 284 + 5 bits or code 285, so we
  85080. * overwrite length_code[255] to use the best encoding:
  85081. */
  85082. _length_code[length-1] = (uch)code;
  85083. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85084. dist = 0;
  85085. for (code = 0 ; code < 16; code++) {
  85086. base_dist[code] = dist;
  85087. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85088. _dist_code[dist++] = (uch)code;
  85089. }
  85090. }
  85091. Assert (dist == 256, "tr_static_init: dist != 256");
  85092. dist >>= 7; /* from now on, all distances are divided by 128 */
  85093. for ( ; code < D_CODES; code++) {
  85094. base_dist[code] = dist << 7;
  85095. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85096. _dist_code[256 + dist++] = (uch)code;
  85097. }
  85098. }
  85099. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85100. /* Construct the codes of the static literal tree */
  85101. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85102. n = 0;
  85103. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85104. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85105. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85106. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85107. /* Codes 286 and 287 do not exist, but we must include them in the
  85108. * tree construction to get a canonical Huffman tree (longest code
  85109. * all ones)
  85110. */
  85111. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85112. /* The static distance tree is trivial: */
  85113. for (n = 0; n < D_CODES; n++) {
  85114. static_dtree[n].Len = 5;
  85115. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85116. }
  85117. static_init_done = 1;
  85118. # ifdef GEN_TREES_H
  85119. gen_trees_header();
  85120. # endif
  85121. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85122. }
  85123. /* ===========================================================================
  85124. * Genererate the file trees.h describing the static trees.
  85125. */
  85126. #ifdef GEN_TREES_H
  85127. # ifndef DEBUG
  85128. # include <stdio.h>
  85129. # endif
  85130. # define SEPARATOR(i, last, width) \
  85131. ((i) == (last)? "\n};\n\n" : \
  85132. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85133. void gen_trees_header()
  85134. {
  85135. FILE *header = fopen("trees.h", "w");
  85136. int i;
  85137. Assert (header != NULL, "Can't open trees.h");
  85138. fprintf(header,
  85139. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85140. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85141. for (i = 0; i < L_CODES+2; i++) {
  85142. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85143. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85144. }
  85145. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85146. for (i = 0; i < D_CODES; i++) {
  85147. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85148. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85149. }
  85150. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85151. for (i = 0; i < DIST_CODE_LEN; i++) {
  85152. fprintf(header, "%2u%s", _dist_code[i],
  85153. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85154. }
  85155. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85156. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85157. fprintf(header, "%2u%s", _length_code[i],
  85158. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85159. }
  85160. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85161. for (i = 0; i < LENGTH_CODES; i++) {
  85162. fprintf(header, "%1u%s", base_length[i],
  85163. SEPARATOR(i, LENGTH_CODES-1, 20));
  85164. }
  85165. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85166. for (i = 0; i < D_CODES; i++) {
  85167. fprintf(header, "%5u%s", base_dist[i],
  85168. SEPARATOR(i, D_CODES-1, 10));
  85169. }
  85170. fclose(header);
  85171. }
  85172. #endif /* GEN_TREES_H */
  85173. /* ===========================================================================
  85174. * Initialize the tree data structures for a new zlib stream.
  85175. */
  85176. void _tr_init(deflate_state *s)
  85177. {
  85178. tr_static_init();
  85179. s->l_desc.dyn_tree = s->dyn_ltree;
  85180. s->l_desc.stat_desc = &static_l_desc;
  85181. s->d_desc.dyn_tree = s->dyn_dtree;
  85182. s->d_desc.stat_desc = &static_d_desc;
  85183. s->bl_desc.dyn_tree = s->bl_tree;
  85184. s->bl_desc.stat_desc = &static_bl_desc;
  85185. s->bi_buf = 0;
  85186. s->bi_valid = 0;
  85187. s->last_eob_len = 8; /* enough lookahead for inflate */
  85188. #ifdef DEBUG
  85189. s->compressed_len = 0L;
  85190. s->bits_sent = 0L;
  85191. #endif
  85192. /* Initialize the first block of the first file: */
  85193. init_block(s);
  85194. }
  85195. /* ===========================================================================
  85196. * Initialize a new block.
  85197. */
  85198. local void init_block (deflate_state *s)
  85199. {
  85200. int n; /* iterates over tree elements */
  85201. /* Initialize the trees. */
  85202. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85203. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85204. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85205. s->dyn_ltree[END_BLOCK].Freq = 1;
  85206. s->opt_len = s->static_len = 0L;
  85207. s->last_lit = s->matches = 0;
  85208. }
  85209. #define SMALLEST 1
  85210. /* Index within the heap array of least frequent node in the Huffman tree */
  85211. /* ===========================================================================
  85212. * Remove the smallest element from the heap and recreate the heap with
  85213. * one less element. Updates heap and heap_len.
  85214. */
  85215. #define pqremove(s, tree, top) \
  85216. {\
  85217. top = s->heap[SMALLEST]; \
  85218. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85219. pqdownheap(s, tree, SMALLEST); \
  85220. }
  85221. /* ===========================================================================
  85222. * Compares to subtrees, using the tree depth as tie breaker when
  85223. * the subtrees have equal frequency. This minimizes the worst case length.
  85224. */
  85225. #define smaller(tree, n, m, depth) \
  85226. (tree[n].Freq < tree[m].Freq || \
  85227. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85228. /* ===========================================================================
  85229. * Restore the heap property by moving down the tree starting at node k,
  85230. * exchanging a node with the smallest of its two sons if necessary, stopping
  85231. * when the heap property is re-established (each father smaller than its
  85232. * two sons).
  85233. */
  85234. local void pqdownheap (deflate_state *s,
  85235. ct_data *tree, /* the tree to restore */
  85236. int k) /* node to move down */
  85237. {
  85238. int v = s->heap[k];
  85239. int j = k << 1; /* left son of k */
  85240. while (j <= s->heap_len) {
  85241. /* Set j to the smallest of the two sons: */
  85242. if (j < s->heap_len &&
  85243. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85244. j++;
  85245. }
  85246. /* Exit if v is smaller than both sons */
  85247. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85248. /* Exchange v with the smallest son */
  85249. s->heap[k] = s->heap[j]; k = j;
  85250. /* And continue down the tree, setting j to the left son of k */
  85251. j <<= 1;
  85252. }
  85253. s->heap[k] = v;
  85254. }
  85255. /* ===========================================================================
  85256. * Compute the optimal bit lengths for a tree and update the total bit length
  85257. * for the current block.
  85258. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85259. * above are the tree nodes sorted by increasing frequency.
  85260. * OUT assertions: the field len is set to the optimal bit length, the
  85261. * array bl_count contains the frequencies for each bit length.
  85262. * The length opt_len is updated; static_len is also updated if stree is
  85263. * not null.
  85264. */
  85265. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85266. {
  85267. ct_data *tree = desc->dyn_tree;
  85268. int max_code = desc->max_code;
  85269. const ct_data *stree = desc->stat_desc->static_tree;
  85270. const intf *extra = desc->stat_desc->extra_bits;
  85271. int base = desc->stat_desc->extra_base;
  85272. int max_length = desc->stat_desc->max_length;
  85273. int h; /* heap index */
  85274. int n, m; /* iterate over the tree elements */
  85275. int bits; /* bit length */
  85276. int xbits; /* extra bits */
  85277. ush f; /* frequency */
  85278. int overflow = 0; /* number of elements with bit length too large */
  85279. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85280. /* In a first pass, compute the optimal bit lengths (which may
  85281. * overflow in the case of the bit length tree).
  85282. */
  85283. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85284. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85285. n = s->heap[h];
  85286. bits = tree[tree[n].Dad].Len + 1;
  85287. if (bits > max_length) bits = max_length, overflow++;
  85288. tree[n].Len = (ush)bits;
  85289. /* We overwrite tree[n].Dad which is no longer needed */
  85290. if (n > max_code) continue; /* not a leaf node */
  85291. s->bl_count[bits]++;
  85292. xbits = 0;
  85293. if (n >= base) xbits = extra[n-base];
  85294. f = tree[n].Freq;
  85295. s->opt_len += (ulg)f * (bits + xbits);
  85296. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85297. }
  85298. if (overflow == 0) return;
  85299. Trace((stderr,"\nbit length overflow\n"));
  85300. /* This happens for example on obj2 and pic of the Calgary corpus */
  85301. /* Find the first bit length which could increase: */
  85302. do {
  85303. bits = max_length-1;
  85304. while (s->bl_count[bits] == 0) bits--;
  85305. s->bl_count[bits]--; /* move one leaf down the tree */
  85306. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85307. s->bl_count[max_length]--;
  85308. /* The brother of the overflow item also moves one step up,
  85309. * but this does not affect bl_count[max_length]
  85310. */
  85311. overflow -= 2;
  85312. } while (overflow > 0);
  85313. /* Now recompute all bit lengths, scanning in increasing frequency.
  85314. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85315. * lengths instead of fixing only the wrong ones. This idea is taken
  85316. * from 'ar' written by Haruhiko Okumura.)
  85317. */
  85318. for (bits = max_length; bits != 0; bits--) {
  85319. n = s->bl_count[bits];
  85320. while (n != 0) {
  85321. m = s->heap[--h];
  85322. if (m > max_code) continue;
  85323. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85324. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85325. s->opt_len += ((long)bits - (long)tree[m].Len)
  85326. *(long)tree[m].Freq;
  85327. tree[m].Len = (ush)bits;
  85328. }
  85329. n--;
  85330. }
  85331. }
  85332. }
  85333. /* ===========================================================================
  85334. * Generate the codes for a given tree and bit counts (which need not be
  85335. * optimal).
  85336. * IN assertion: the array bl_count contains the bit length statistics for
  85337. * the given tree and the field len is set for all tree elements.
  85338. * OUT assertion: the field code is set for all tree elements of non
  85339. * zero code length.
  85340. */
  85341. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85342. int max_code, /* largest code with non zero frequency */
  85343. ushf *bl_count) /* number of codes at each bit length */
  85344. {
  85345. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85346. ush code = 0; /* running code value */
  85347. int bits; /* bit index */
  85348. int n; /* code index */
  85349. /* The distribution counts are first used to generate the code values
  85350. * without bit reversal.
  85351. */
  85352. for (bits = 1; bits <= MAX_BITS; bits++) {
  85353. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85354. }
  85355. /* Check that the bit counts in bl_count are consistent. The last code
  85356. * must be all ones.
  85357. */
  85358. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85359. "inconsistent bit counts");
  85360. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85361. for (n = 0; n <= max_code; n++) {
  85362. int len = tree[n].Len;
  85363. if (len == 0) continue;
  85364. /* Now reverse the bits */
  85365. tree[n].Code = bi_reverse(next_code[len]++, len);
  85366. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85367. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85368. }
  85369. }
  85370. /* ===========================================================================
  85371. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85372. * Update the total bit length for the current block.
  85373. * IN assertion: the field freq is set for all tree elements.
  85374. * OUT assertions: the fields len and code are set to the optimal bit length
  85375. * and corresponding code. The length opt_len is updated; static_len is
  85376. * also updated if stree is not null. The field max_code is set.
  85377. */
  85378. local void build_tree (deflate_state *s,
  85379. tree_desc *desc) /* the tree descriptor */
  85380. {
  85381. ct_data *tree = desc->dyn_tree;
  85382. const ct_data *stree = desc->stat_desc->static_tree;
  85383. int elems = desc->stat_desc->elems;
  85384. int n, m; /* iterate over heap elements */
  85385. int max_code = -1; /* largest code with non zero frequency */
  85386. int node; /* new node being created */
  85387. /* Construct the initial heap, with least frequent element in
  85388. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85389. * heap[0] is not used.
  85390. */
  85391. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85392. for (n = 0; n < elems; n++) {
  85393. if (tree[n].Freq != 0) {
  85394. s->heap[++(s->heap_len)] = max_code = n;
  85395. s->depth[n] = 0;
  85396. } else {
  85397. tree[n].Len = 0;
  85398. }
  85399. }
  85400. /* The pkzip format requires that at least one distance code exists,
  85401. * and that at least one bit should be sent even if there is only one
  85402. * possible code. So to avoid special checks later on we force at least
  85403. * two codes of non zero frequency.
  85404. */
  85405. while (s->heap_len < 2) {
  85406. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85407. tree[node].Freq = 1;
  85408. s->depth[node] = 0;
  85409. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85410. /* node is 0 or 1 so it does not have extra bits */
  85411. }
  85412. desc->max_code = max_code;
  85413. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85414. * establish sub-heaps of increasing lengths:
  85415. */
  85416. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85417. /* Construct the Huffman tree by repeatedly combining the least two
  85418. * frequent nodes.
  85419. */
  85420. node = elems; /* next internal node of the tree */
  85421. do {
  85422. pqremove(s, tree, n); /* n = node of least frequency */
  85423. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85424. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85425. s->heap[--(s->heap_max)] = m;
  85426. /* Create a new node father of n and m */
  85427. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85428. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85429. s->depth[n] : s->depth[m]) + 1);
  85430. tree[n].Dad = tree[m].Dad = (ush)node;
  85431. #ifdef DUMP_BL_TREE
  85432. if (tree == s->bl_tree) {
  85433. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85434. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85435. }
  85436. #endif
  85437. /* and insert the new node in the heap */
  85438. s->heap[SMALLEST] = node++;
  85439. pqdownheap(s, tree, SMALLEST);
  85440. } while (s->heap_len >= 2);
  85441. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85442. /* At this point, the fields freq and dad are set. We can now
  85443. * generate the bit lengths.
  85444. */
  85445. gen_bitlen(s, (tree_desc *)desc);
  85446. /* The field len is now set, we can generate the bit codes */
  85447. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85448. }
  85449. /* ===========================================================================
  85450. * Scan a literal or distance tree to determine the frequencies of the codes
  85451. * in the bit length tree.
  85452. */
  85453. local void scan_tree (deflate_state *s,
  85454. ct_data *tree, /* the tree to be scanned */
  85455. int max_code) /* and its largest code of non zero frequency */
  85456. {
  85457. int n; /* iterates over all tree elements */
  85458. int prevlen = -1; /* last emitted length */
  85459. int curlen; /* length of current code */
  85460. int nextlen = tree[0].Len; /* length of next code */
  85461. int count = 0; /* repeat count of the current code */
  85462. int max_count = 7; /* max repeat count */
  85463. int min_count = 4; /* min repeat count */
  85464. if (nextlen == 0) max_count = 138, min_count = 3;
  85465. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85466. for (n = 0; n <= max_code; n++) {
  85467. curlen = nextlen; nextlen = tree[n+1].Len;
  85468. if (++count < max_count && curlen == nextlen) {
  85469. continue;
  85470. } else if (count < min_count) {
  85471. s->bl_tree[curlen].Freq += count;
  85472. } else if (curlen != 0) {
  85473. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85474. s->bl_tree[REP_3_6].Freq++;
  85475. } else if (count <= 10) {
  85476. s->bl_tree[REPZ_3_10].Freq++;
  85477. } else {
  85478. s->bl_tree[REPZ_11_138].Freq++;
  85479. }
  85480. count = 0; prevlen = curlen;
  85481. if (nextlen == 0) {
  85482. max_count = 138, min_count = 3;
  85483. } else if (curlen == nextlen) {
  85484. max_count = 6, min_count = 3;
  85485. } else {
  85486. max_count = 7, min_count = 4;
  85487. }
  85488. }
  85489. }
  85490. /* ===========================================================================
  85491. * Send a literal or distance tree in compressed form, using the codes in
  85492. * bl_tree.
  85493. */
  85494. local void send_tree (deflate_state *s,
  85495. ct_data *tree, /* the tree to be scanned */
  85496. int max_code) /* and its largest code of non zero frequency */
  85497. {
  85498. int n; /* iterates over all tree elements */
  85499. int prevlen = -1; /* last emitted length */
  85500. int curlen; /* length of current code */
  85501. int nextlen = tree[0].Len; /* length of next code */
  85502. int count = 0; /* repeat count of the current code */
  85503. int max_count = 7; /* max repeat count */
  85504. int min_count = 4; /* min repeat count */
  85505. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85506. if (nextlen == 0) max_count = 138, min_count = 3;
  85507. for (n = 0; n <= max_code; n++) {
  85508. curlen = nextlen; nextlen = tree[n+1].Len;
  85509. if (++count < max_count && curlen == nextlen) {
  85510. continue;
  85511. } else if (count < min_count) {
  85512. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85513. } else if (curlen != 0) {
  85514. if (curlen != prevlen) {
  85515. send_code(s, curlen, s->bl_tree); count--;
  85516. }
  85517. Assert(count >= 3 && count <= 6, " 3_6?");
  85518. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85519. } else if (count <= 10) {
  85520. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85521. } else {
  85522. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85523. }
  85524. count = 0; prevlen = curlen;
  85525. if (nextlen == 0) {
  85526. max_count = 138, min_count = 3;
  85527. } else if (curlen == nextlen) {
  85528. max_count = 6, min_count = 3;
  85529. } else {
  85530. max_count = 7, min_count = 4;
  85531. }
  85532. }
  85533. }
  85534. /* ===========================================================================
  85535. * Construct the Huffman tree for the bit lengths and return the index in
  85536. * bl_order of the last bit length code to send.
  85537. */
  85538. local int build_bl_tree (deflate_state *s)
  85539. {
  85540. int max_blindex; /* index of last bit length code of non zero freq */
  85541. /* Determine the bit length frequencies for literal and distance trees */
  85542. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85543. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85544. /* Build the bit length tree: */
  85545. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85546. /* opt_len now includes the length of the tree representations, except
  85547. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85548. */
  85549. /* Determine the number of bit length codes to send. The pkzip format
  85550. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85551. * 3 but the actual value used is 4.)
  85552. */
  85553. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85554. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85555. }
  85556. /* Update opt_len to include the bit length tree and counts */
  85557. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85558. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85559. s->opt_len, s->static_len));
  85560. return max_blindex;
  85561. }
  85562. /* ===========================================================================
  85563. * Send the header for a block using dynamic Huffman trees: the counts, the
  85564. * lengths of the bit length codes, the literal tree and the distance tree.
  85565. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85566. */
  85567. local void send_all_trees (deflate_state *s,
  85568. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85569. {
  85570. int rank; /* index in bl_order */
  85571. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85572. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85573. "too many codes");
  85574. Tracev((stderr, "\nbl counts: "));
  85575. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85576. send_bits(s, dcodes-1, 5);
  85577. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85578. for (rank = 0; rank < blcodes; rank++) {
  85579. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85580. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85581. }
  85582. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85583. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85584. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85585. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85586. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85587. }
  85588. /* ===========================================================================
  85589. * Send a stored block
  85590. */
  85591. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85592. {
  85593. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85594. #ifdef DEBUG
  85595. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85596. s->compressed_len += (stored_len + 4) << 3;
  85597. #endif
  85598. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85599. }
  85600. /* ===========================================================================
  85601. * Send one empty static block to give enough lookahead for inflate.
  85602. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85603. * The current inflate code requires 9 bits of lookahead. If the
  85604. * last two codes for the previous block (real code plus EOB) were coded
  85605. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85606. * the last real code. In this case we send two empty static blocks instead
  85607. * of one. (There are no problems if the previous block is stored or fixed.)
  85608. * To simplify the code, we assume the worst case of last real code encoded
  85609. * on one bit only.
  85610. */
  85611. void _tr_align (deflate_state *s)
  85612. {
  85613. send_bits(s, STATIC_TREES<<1, 3);
  85614. send_code(s, END_BLOCK, static_ltree);
  85615. #ifdef DEBUG
  85616. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85617. #endif
  85618. bi_flush(s);
  85619. /* Of the 10 bits for the empty block, we have already sent
  85620. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85621. * the EOB of the previous block) was thus at least one plus the length
  85622. * of the EOB plus what we have just sent of the empty static block.
  85623. */
  85624. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85625. send_bits(s, STATIC_TREES<<1, 3);
  85626. send_code(s, END_BLOCK, static_ltree);
  85627. #ifdef DEBUG
  85628. s->compressed_len += 10L;
  85629. #endif
  85630. bi_flush(s);
  85631. }
  85632. s->last_eob_len = 7;
  85633. }
  85634. /* ===========================================================================
  85635. * Determine the best encoding for the current block: dynamic trees, static
  85636. * trees or store, and output the encoded block to the zip file.
  85637. */
  85638. void _tr_flush_block (deflate_state *s,
  85639. charf *buf, /* input block, or NULL if too old */
  85640. ulg stored_len, /* length of input block */
  85641. int eof) /* true if this is the last block for a file */
  85642. {
  85643. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85644. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85645. /* Build the Huffman trees unless a stored block is forced */
  85646. if (s->level > 0) {
  85647. /* Check if the file is binary or text */
  85648. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85649. set_data_type(s);
  85650. /* Construct the literal and distance trees */
  85651. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85652. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85653. s->static_len));
  85654. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85655. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85656. s->static_len));
  85657. /* At this point, opt_len and static_len are the total bit lengths of
  85658. * the compressed block data, excluding the tree representations.
  85659. */
  85660. /* Build the bit length tree for the above two trees, and get the index
  85661. * in bl_order of the last bit length code to send.
  85662. */
  85663. max_blindex = build_bl_tree(s);
  85664. /* Determine the best encoding. Compute the block lengths in bytes. */
  85665. opt_lenb = (s->opt_len+3+7)>>3;
  85666. static_lenb = (s->static_len+3+7)>>3;
  85667. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85668. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85669. s->last_lit));
  85670. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85671. } else {
  85672. Assert(buf != (char*)0, "lost buf");
  85673. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85674. }
  85675. #ifdef FORCE_STORED
  85676. if (buf != (char*)0) { /* force stored block */
  85677. #else
  85678. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85679. /* 4: two words for the lengths */
  85680. #endif
  85681. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85682. * Otherwise we can't have processed more than WSIZE input bytes since
  85683. * the last block flush, because compression would have been
  85684. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85685. * transform a block into a stored block.
  85686. */
  85687. _tr_stored_block(s, buf, stored_len, eof);
  85688. #ifdef FORCE_STATIC
  85689. } else if (static_lenb >= 0) { /* force static trees */
  85690. #else
  85691. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85692. #endif
  85693. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85694. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85695. #ifdef DEBUG
  85696. s->compressed_len += 3 + s->static_len;
  85697. #endif
  85698. } else {
  85699. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85700. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85701. max_blindex+1);
  85702. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85703. #ifdef DEBUG
  85704. s->compressed_len += 3 + s->opt_len;
  85705. #endif
  85706. }
  85707. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85708. /* The above check is made mod 2^32, for files larger than 512 MB
  85709. * and uLong implemented on 32 bits.
  85710. */
  85711. init_block(s);
  85712. if (eof) {
  85713. bi_windup(s);
  85714. #ifdef DEBUG
  85715. s->compressed_len += 7; /* align on byte boundary */
  85716. #endif
  85717. }
  85718. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85719. s->compressed_len-7*eof));
  85720. }
  85721. /* ===========================================================================
  85722. * Save the match info and tally the frequency counts. Return true if
  85723. * the current block must be flushed.
  85724. */
  85725. int _tr_tally (deflate_state *s,
  85726. unsigned dist, /* distance of matched string */
  85727. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85728. {
  85729. s->d_buf[s->last_lit] = (ush)dist;
  85730. s->l_buf[s->last_lit++] = (uch)lc;
  85731. if (dist == 0) {
  85732. /* lc is the unmatched char */
  85733. s->dyn_ltree[lc].Freq++;
  85734. } else {
  85735. s->matches++;
  85736. /* Here, lc is the match length - MIN_MATCH */
  85737. dist--; /* dist = match distance - 1 */
  85738. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85739. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85740. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85741. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85742. s->dyn_dtree[d_code(dist)].Freq++;
  85743. }
  85744. #ifdef TRUNCATE_BLOCK
  85745. /* Try to guess if it is profitable to stop the current block here */
  85746. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85747. /* Compute an upper bound for the compressed length */
  85748. ulg out_length = (ulg)s->last_lit*8L;
  85749. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85750. int dcode;
  85751. for (dcode = 0; dcode < D_CODES; dcode++) {
  85752. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85753. (5L+extra_dbits[dcode]);
  85754. }
  85755. out_length >>= 3;
  85756. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85757. s->last_lit, in_length, out_length,
  85758. 100L - out_length*100L/in_length));
  85759. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85760. }
  85761. #endif
  85762. return (s->last_lit == s->lit_bufsize-1);
  85763. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85764. * on 16 bit machines and because stored blocks are restricted to
  85765. * 64K-1 bytes.
  85766. */
  85767. }
  85768. /* ===========================================================================
  85769. * Send the block data compressed using the given Huffman trees
  85770. */
  85771. local void compress_block (deflate_state *s,
  85772. ct_data *ltree, /* literal tree */
  85773. ct_data *dtree) /* distance tree */
  85774. {
  85775. unsigned dist; /* distance of matched string */
  85776. int lc; /* match length or unmatched char (if dist == 0) */
  85777. unsigned lx = 0; /* running index in l_buf */
  85778. unsigned code; /* the code to send */
  85779. int extra; /* number of extra bits to send */
  85780. if (s->last_lit != 0) do {
  85781. dist = s->d_buf[lx];
  85782. lc = s->l_buf[lx++];
  85783. if (dist == 0) {
  85784. send_code(s, lc, ltree); /* send a literal byte */
  85785. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85786. } else {
  85787. /* Here, lc is the match length - MIN_MATCH */
  85788. code = _length_code[lc];
  85789. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85790. extra = extra_lbits[code];
  85791. if (extra != 0) {
  85792. lc -= base_length[code];
  85793. send_bits(s, lc, extra); /* send the extra length bits */
  85794. }
  85795. dist--; /* dist is now the match distance - 1 */
  85796. code = d_code(dist);
  85797. Assert (code < D_CODES, "bad d_code");
  85798. send_code(s, code, dtree); /* send the distance code */
  85799. extra = extra_dbits[code];
  85800. if (extra != 0) {
  85801. dist -= base_dist[code];
  85802. send_bits(s, dist, extra); /* send the extra distance bits */
  85803. }
  85804. } /* literal or match pair ? */
  85805. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85806. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85807. "pendingBuf overflow");
  85808. } while (lx < s->last_lit);
  85809. send_code(s, END_BLOCK, ltree);
  85810. s->last_eob_len = ltree[END_BLOCK].Len;
  85811. }
  85812. /* ===========================================================================
  85813. * Set the data type to BINARY or TEXT, using a crude approximation:
  85814. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85815. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85816. * IN assertion: the fields Freq of dyn_ltree are set.
  85817. */
  85818. local void set_data_type (deflate_state *s)
  85819. {
  85820. int n;
  85821. for (n = 0; n < 9; n++)
  85822. if (s->dyn_ltree[n].Freq != 0)
  85823. break;
  85824. if (n == 9)
  85825. for (n = 14; n < 32; n++)
  85826. if (s->dyn_ltree[n].Freq != 0)
  85827. break;
  85828. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85829. }
  85830. /* ===========================================================================
  85831. * Reverse the first len bits of a code, using straightforward code (a faster
  85832. * method would use a table)
  85833. * IN assertion: 1 <= len <= 15
  85834. */
  85835. local unsigned bi_reverse (unsigned code, int len)
  85836. {
  85837. register unsigned res = 0;
  85838. do {
  85839. res |= code & 1;
  85840. code >>= 1, res <<= 1;
  85841. } while (--len > 0);
  85842. return res >> 1;
  85843. }
  85844. /* ===========================================================================
  85845. * Flush the bit buffer, keeping at most 7 bits in it.
  85846. */
  85847. local void bi_flush (deflate_state *s)
  85848. {
  85849. if (s->bi_valid == 16) {
  85850. put_short(s, s->bi_buf);
  85851. s->bi_buf = 0;
  85852. s->bi_valid = 0;
  85853. } else if (s->bi_valid >= 8) {
  85854. put_byte(s, (Byte)s->bi_buf);
  85855. s->bi_buf >>= 8;
  85856. s->bi_valid -= 8;
  85857. }
  85858. }
  85859. /* ===========================================================================
  85860. * Flush the bit buffer and align the output on a byte boundary
  85861. */
  85862. local void bi_windup (deflate_state *s)
  85863. {
  85864. if (s->bi_valid > 8) {
  85865. put_short(s, s->bi_buf);
  85866. } else if (s->bi_valid > 0) {
  85867. put_byte(s, (Byte)s->bi_buf);
  85868. }
  85869. s->bi_buf = 0;
  85870. s->bi_valid = 0;
  85871. #ifdef DEBUG
  85872. s->bits_sent = (s->bits_sent+7) & ~7;
  85873. #endif
  85874. }
  85875. /* ===========================================================================
  85876. * Copy a stored block, storing first the length and its
  85877. * one's complement if requested.
  85878. */
  85879. local void copy_block(deflate_state *s,
  85880. charf *buf, /* the input data */
  85881. unsigned len, /* its length */
  85882. int header) /* true if block header must be written */
  85883. {
  85884. bi_windup(s); /* align on byte boundary */
  85885. s->last_eob_len = 8; /* enough lookahead for inflate */
  85886. if (header) {
  85887. put_short(s, (ush)len);
  85888. put_short(s, (ush)~len);
  85889. #ifdef DEBUG
  85890. s->bits_sent += 2*16;
  85891. #endif
  85892. }
  85893. #ifdef DEBUG
  85894. s->bits_sent += (ulg)len<<3;
  85895. #endif
  85896. while (len--) {
  85897. put_byte(s, *buf++);
  85898. }
  85899. }
  85900. /*** End of inlined file: trees.c ***/
  85901. /*** Start of inlined file: zutil.c ***/
  85902. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85903. #ifndef NO_DUMMY_DECL
  85904. struct internal_state {int dummy;}; /* for buggy compilers */
  85905. #endif
  85906. const char * const z_errmsg[10] = {
  85907. "need dictionary", /* Z_NEED_DICT 2 */
  85908. "stream end", /* Z_STREAM_END 1 */
  85909. "", /* Z_OK 0 */
  85910. "file error", /* Z_ERRNO (-1) */
  85911. "stream error", /* Z_STREAM_ERROR (-2) */
  85912. "data error", /* Z_DATA_ERROR (-3) */
  85913. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85914. "buffer error", /* Z_BUF_ERROR (-5) */
  85915. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85916. ""};
  85917. /*const char * ZEXPORT zlibVersion()
  85918. {
  85919. return ZLIB_VERSION;
  85920. }
  85921. uLong ZEXPORT zlibCompileFlags()
  85922. {
  85923. uLong flags;
  85924. flags = 0;
  85925. switch (sizeof(uInt)) {
  85926. case 2: break;
  85927. case 4: flags += 1; break;
  85928. case 8: flags += 2; break;
  85929. default: flags += 3;
  85930. }
  85931. switch (sizeof(uLong)) {
  85932. case 2: break;
  85933. case 4: flags += 1 << 2; break;
  85934. case 8: flags += 2 << 2; break;
  85935. default: flags += 3 << 2;
  85936. }
  85937. switch (sizeof(voidpf)) {
  85938. case 2: break;
  85939. case 4: flags += 1 << 4; break;
  85940. case 8: flags += 2 << 4; break;
  85941. default: flags += 3 << 4;
  85942. }
  85943. switch (sizeof(z_off_t)) {
  85944. case 2: break;
  85945. case 4: flags += 1 << 6; break;
  85946. case 8: flags += 2 << 6; break;
  85947. default: flags += 3 << 6;
  85948. }
  85949. #ifdef DEBUG
  85950. flags += 1 << 8;
  85951. #endif
  85952. #if defined(ASMV) || defined(ASMINF)
  85953. flags += 1 << 9;
  85954. #endif
  85955. #ifdef ZLIB_WINAPI
  85956. flags += 1 << 10;
  85957. #endif
  85958. #ifdef BUILDFIXED
  85959. flags += 1 << 12;
  85960. #endif
  85961. #ifdef DYNAMIC_CRC_TABLE
  85962. flags += 1 << 13;
  85963. #endif
  85964. #ifdef NO_GZCOMPRESS
  85965. flags += 1L << 16;
  85966. #endif
  85967. #ifdef NO_GZIP
  85968. flags += 1L << 17;
  85969. #endif
  85970. #ifdef PKZIP_BUG_WORKAROUND
  85971. flags += 1L << 20;
  85972. #endif
  85973. #ifdef FASTEST
  85974. flags += 1L << 21;
  85975. #endif
  85976. #ifdef STDC
  85977. # ifdef NO_vsnprintf
  85978. flags += 1L << 25;
  85979. # ifdef HAS_vsprintf_void
  85980. flags += 1L << 26;
  85981. # endif
  85982. # else
  85983. # ifdef HAS_vsnprintf_void
  85984. flags += 1L << 26;
  85985. # endif
  85986. # endif
  85987. #else
  85988. flags += 1L << 24;
  85989. # ifdef NO_snprintf
  85990. flags += 1L << 25;
  85991. # ifdef HAS_sprintf_void
  85992. flags += 1L << 26;
  85993. # endif
  85994. # else
  85995. # ifdef HAS_snprintf_void
  85996. flags += 1L << 26;
  85997. # endif
  85998. # endif
  85999. #endif
  86000. return flags;
  86001. }*/
  86002. #ifdef DEBUG
  86003. # ifndef verbose
  86004. # define verbose 0
  86005. # endif
  86006. int z_verbose = verbose;
  86007. void z_error (const char *m)
  86008. {
  86009. fprintf(stderr, "%s\n", m);
  86010. exit(1);
  86011. }
  86012. #endif
  86013. /* exported to allow conversion of error code to string for compress() and
  86014. * uncompress()
  86015. */
  86016. const char * ZEXPORT zError(int err)
  86017. {
  86018. return ERR_MSG(err);
  86019. }
  86020. #if defined(_WIN32_WCE)
  86021. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  86022. * errno. We define it as a global variable to simplify porting.
  86023. * Its value is always 0 and should not be used.
  86024. */
  86025. int errno = 0;
  86026. #endif
  86027. #ifndef HAVE_MEMCPY
  86028. void zmemcpy(dest, source, len)
  86029. Bytef* dest;
  86030. const Bytef* source;
  86031. uInt len;
  86032. {
  86033. if (len == 0) return;
  86034. do {
  86035. *dest++ = *source++; /* ??? to be unrolled */
  86036. } while (--len != 0);
  86037. }
  86038. int zmemcmp(s1, s2, len)
  86039. const Bytef* s1;
  86040. const Bytef* s2;
  86041. uInt len;
  86042. {
  86043. uInt j;
  86044. for (j = 0; j < len; j++) {
  86045. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  86046. }
  86047. return 0;
  86048. }
  86049. void zmemzero(dest, len)
  86050. Bytef* dest;
  86051. uInt len;
  86052. {
  86053. if (len == 0) return;
  86054. do {
  86055. *dest++ = 0; /* ??? to be unrolled */
  86056. } while (--len != 0);
  86057. }
  86058. #endif
  86059. #ifdef SYS16BIT
  86060. #ifdef __TURBOC__
  86061. /* Turbo C in 16-bit mode */
  86062. # define MY_ZCALLOC
  86063. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  86064. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  86065. * must fix the pointer. Warning: the pointer must be put back to its
  86066. * original form in order to free it, use zcfree().
  86067. */
  86068. #define MAX_PTR 10
  86069. /* 10*64K = 640K */
  86070. local int next_ptr = 0;
  86071. typedef struct ptr_table_s {
  86072. voidpf org_ptr;
  86073. voidpf new_ptr;
  86074. } ptr_table;
  86075. local ptr_table table[MAX_PTR];
  86076. /* This table is used to remember the original form of pointers
  86077. * to large buffers (64K). Such pointers are normalized with a zero offset.
  86078. * Since MSDOS is not a preemptive multitasking OS, this table is not
  86079. * protected from concurrent access. This hack doesn't work anyway on
  86080. * a protected system like OS/2. Use Microsoft C instead.
  86081. */
  86082. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86083. {
  86084. voidpf buf = opaque; /* just to make some compilers happy */
  86085. ulg bsize = (ulg)items*size;
  86086. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86087. * will return a usable pointer which doesn't have to be normalized.
  86088. */
  86089. if (bsize < 65520L) {
  86090. buf = farmalloc(bsize);
  86091. if (*(ush*)&buf != 0) return buf;
  86092. } else {
  86093. buf = farmalloc(bsize + 16L);
  86094. }
  86095. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86096. table[next_ptr].org_ptr = buf;
  86097. /* Normalize the pointer to seg:0 */
  86098. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86099. *(ush*)&buf = 0;
  86100. table[next_ptr++].new_ptr = buf;
  86101. return buf;
  86102. }
  86103. void zcfree (voidpf opaque, voidpf ptr)
  86104. {
  86105. int n;
  86106. if (*(ush*)&ptr != 0) { /* object < 64K */
  86107. farfree(ptr);
  86108. return;
  86109. }
  86110. /* Find the original pointer */
  86111. for (n = 0; n < next_ptr; n++) {
  86112. if (ptr != table[n].new_ptr) continue;
  86113. farfree(table[n].org_ptr);
  86114. while (++n < next_ptr) {
  86115. table[n-1] = table[n];
  86116. }
  86117. next_ptr--;
  86118. return;
  86119. }
  86120. ptr = opaque; /* just to make some compilers happy */
  86121. Assert(0, "zcfree: ptr not found");
  86122. }
  86123. #endif /* __TURBOC__ */
  86124. #ifdef M_I86
  86125. /* Microsoft C in 16-bit mode */
  86126. # define MY_ZCALLOC
  86127. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86128. # define _halloc halloc
  86129. # define _hfree hfree
  86130. #endif
  86131. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86132. {
  86133. if (opaque) opaque = 0; /* to make compiler happy */
  86134. return _halloc((long)items, size);
  86135. }
  86136. void zcfree (voidpf opaque, voidpf ptr)
  86137. {
  86138. if (opaque) opaque = 0; /* to make compiler happy */
  86139. _hfree(ptr);
  86140. }
  86141. #endif /* M_I86 */
  86142. #endif /* SYS16BIT */
  86143. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86144. #ifndef STDC
  86145. extern voidp malloc OF((uInt size));
  86146. extern voidp calloc OF((uInt items, uInt size));
  86147. extern void free OF((voidpf ptr));
  86148. #endif
  86149. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86150. {
  86151. if (opaque) items += size - size; /* make compiler happy */
  86152. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86153. (voidpf)calloc(items, size);
  86154. }
  86155. void zcfree (voidpf opaque, voidpf ptr)
  86156. {
  86157. free(ptr);
  86158. if (opaque) return; /* make compiler happy */
  86159. }
  86160. #endif /* MY_ZCALLOC */
  86161. /*** End of inlined file: zutil.c ***/
  86162. #undef Byte
  86163. #else
  86164. #include <zlib.h>
  86165. #endif
  86166. }
  86167. #if JUCE_MSVC
  86168. #pragma warning (pop)
  86169. #endif
  86170. BEGIN_JUCE_NAMESPACE
  86171. // internal helper object that holds the zlib structures so they don't have to be
  86172. // included publicly.
  86173. class GZIPDecompressHelper
  86174. {
  86175. public:
  86176. GZIPDecompressHelper (const bool noWrap)
  86177. : finished (true),
  86178. needsDictionary (false),
  86179. error (true),
  86180. streamIsValid (false),
  86181. data (0),
  86182. dataSize (0)
  86183. {
  86184. using namespace zlibNamespace;
  86185. zerostruct (stream);
  86186. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86187. finished = error = ! streamIsValid;
  86188. }
  86189. ~GZIPDecompressHelper()
  86190. {
  86191. using namespace zlibNamespace;
  86192. if (streamIsValid)
  86193. inflateEnd (&stream);
  86194. }
  86195. bool needsInput() const throw() { return dataSize <= 0; }
  86196. void setInput (uint8* const data_, const int size) throw()
  86197. {
  86198. data = data_;
  86199. dataSize = size;
  86200. }
  86201. int doNextBlock (uint8* const dest, const int destSize)
  86202. {
  86203. using namespace zlibNamespace;
  86204. if (streamIsValid && data != 0 && ! finished)
  86205. {
  86206. stream.next_in = data;
  86207. stream.next_out = dest;
  86208. stream.avail_in = dataSize;
  86209. stream.avail_out = destSize;
  86210. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86211. {
  86212. case Z_STREAM_END:
  86213. finished = true;
  86214. // deliberate fall-through
  86215. case Z_OK:
  86216. data += dataSize - stream.avail_in;
  86217. dataSize = stream.avail_in;
  86218. return destSize - stream.avail_out;
  86219. case Z_NEED_DICT:
  86220. needsDictionary = true;
  86221. data += dataSize - stream.avail_in;
  86222. dataSize = stream.avail_in;
  86223. break;
  86224. case Z_DATA_ERROR:
  86225. case Z_MEM_ERROR:
  86226. error = true;
  86227. default:
  86228. break;
  86229. }
  86230. }
  86231. return 0;
  86232. }
  86233. bool finished, needsDictionary, error, streamIsValid;
  86234. private:
  86235. zlibNamespace::z_stream stream;
  86236. uint8* data;
  86237. int dataSize;
  86238. GZIPDecompressHelper (const GZIPDecompressHelper&);
  86239. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  86240. };
  86241. const int gzipDecompBufferSize = 32768;
  86242. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86243. const bool deleteSourceWhenDestroyed,
  86244. const bool noWrap_,
  86245. const int64 uncompressedStreamLength_)
  86246. : sourceStream (sourceStream_),
  86247. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86248. uncompressedStreamLength (uncompressedStreamLength_),
  86249. noWrap (noWrap_),
  86250. isEof (false),
  86251. activeBufferSize (0),
  86252. originalSourcePos (sourceStream_->getPosition()),
  86253. currentPos (0),
  86254. buffer (gzipDecompBufferSize),
  86255. helper (new GZIPDecompressHelper (noWrap_))
  86256. {
  86257. }
  86258. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86259. {
  86260. }
  86261. int64 GZIPDecompressorInputStream::getTotalLength()
  86262. {
  86263. return uncompressedStreamLength;
  86264. }
  86265. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86266. {
  86267. if ((howMany > 0) && ! isEof)
  86268. {
  86269. jassert (destBuffer != 0);
  86270. if (destBuffer != 0)
  86271. {
  86272. int numRead = 0;
  86273. uint8* d = static_cast <uint8*> (destBuffer);
  86274. while (! helper->error)
  86275. {
  86276. const int n = helper->doNextBlock (d, howMany);
  86277. currentPos += n;
  86278. if (n == 0)
  86279. {
  86280. if (helper->finished || helper->needsDictionary)
  86281. {
  86282. isEof = true;
  86283. return numRead;
  86284. }
  86285. if (helper->needsInput())
  86286. {
  86287. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  86288. if (activeBufferSize > 0)
  86289. {
  86290. helper->setInput (buffer, activeBufferSize);
  86291. }
  86292. else
  86293. {
  86294. isEof = true;
  86295. return numRead;
  86296. }
  86297. }
  86298. }
  86299. else
  86300. {
  86301. numRead += n;
  86302. howMany -= n;
  86303. d += n;
  86304. if (howMany <= 0)
  86305. return numRead;
  86306. }
  86307. }
  86308. }
  86309. }
  86310. return 0;
  86311. }
  86312. bool GZIPDecompressorInputStream::isExhausted()
  86313. {
  86314. return helper->error || isEof;
  86315. }
  86316. int64 GZIPDecompressorInputStream::getPosition()
  86317. {
  86318. return currentPos;
  86319. }
  86320. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86321. {
  86322. if (newPos < currentPos)
  86323. {
  86324. // to go backwards, reset the stream and start again..
  86325. isEof = false;
  86326. activeBufferSize = 0;
  86327. currentPos = 0;
  86328. helper = new GZIPDecompressHelper (noWrap);
  86329. sourceStream->setPosition (originalSourcePos);
  86330. }
  86331. skipNextBytes (newPos - currentPos);
  86332. return true;
  86333. }
  86334. END_JUCE_NAMESPACE
  86335. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86336. #endif
  86337. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86338. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86339. #if JUCE_USE_FLAC
  86340. #if JUCE_WINDOWS
  86341. #include <windows.h>
  86342. #endif
  86343. namespace FlacNamespace
  86344. {
  86345. #if JUCE_INCLUDE_FLAC_CODE
  86346. #if JUCE_MSVC
  86347. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86348. #endif
  86349. #define FLAC__NO_DLL 1
  86350. #if ! defined (SIZE_MAX)
  86351. #define SIZE_MAX 0xffffffff
  86352. #endif
  86353. #define __STDC_LIMIT_MACROS 1
  86354. /*** Start of inlined file: all.h ***/
  86355. #ifndef FLAC__ALL_H
  86356. #define FLAC__ALL_H
  86357. /*** Start of inlined file: export.h ***/
  86358. #ifndef FLAC__EXPORT_H
  86359. #define FLAC__EXPORT_H
  86360. /** \file include/FLAC/export.h
  86361. *
  86362. * \brief
  86363. * This module contains #defines and symbols for exporting function
  86364. * calls, and providing version information and compiled-in features.
  86365. *
  86366. * See the \link flac_export export \endlink module.
  86367. */
  86368. /** \defgroup flac_export FLAC/export.h: export symbols
  86369. * \ingroup flac
  86370. *
  86371. * \brief
  86372. * This module contains #defines and symbols for exporting function
  86373. * calls, and providing version information and compiled-in features.
  86374. *
  86375. * If you are compiling with MSVC and will link to the static library
  86376. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86377. * make sure the symbols are exported properly.
  86378. *
  86379. * \{
  86380. */
  86381. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86382. #define FLAC_API
  86383. #else
  86384. #ifdef FLAC_API_EXPORTS
  86385. #define FLAC_API _declspec(dllexport)
  86386. #else
  86387. #define FLAC_API _declspec(dllimport)
  86388. #endif
  86389. #endif
  86390. /** These #defines will mirror the libtool-based library version number, see
  86391. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86392. */
  86393. #define FLAC_API_VERSION_CURRENT 10
  86394. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86395. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86396. #ifdef __cplusplus
  86397. extern "C" {
  86398. #endif
  86399. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86400. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86401. #ifdef __cplusplus
  86402. }
  86403. #endif
  86404. /* \} */
  86405. #endif
  86406. /*** End of inlined file: export.h ***/
  86407. /*** Start of inlined file: assert.h ***/
  86408. #ifndef FLAC__ASSERT_H
  86409. #define FLAC__ASSERT_H
  86410. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86411. #ifdef DEBUG
  86412. #include <assert.h>
  86413. #define FLAC__ASSERT(x) assert(x)
  86414. #define FLAC__ASSERT_DECLARATION(x) x
  86415. #else
  86416. #define FLAC__ASSERT(x)
  86417. #define FLAC__ASSERT_DECLARATION(x)
  86418. #endif
  86419. #endif
  86420. /*** End of inlined file: assert.h ***/
  86421. /*** Start of inlined file: callback.h ***/
  86422. #ifndef FLAC__CALLBACK_H
  86423. #define FLAC__CALLBACK_H
  86424. /*** Start of inlined file: ordinals.h ***/
  86425. #ifndef FLAC__ORDINALS_H
  86426. #define FLAC__ORDINALS_H
  86427. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86428. #include <inttypes.h>
  86429. #endif
  86430. typedef signed char FLAC__int8;
  86431. typedef unsigned char FLAC__uint8;
  86432. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86433. typedef __int16 FLAC__int16;
  86434. typedef __int32 FLAC__int32;
  86435. typedef __int64 FLAC__int64;
  86436. typedef unsigned __int16 FLAC__uint16;
  86437. typedef unsigned __int32 FLAC__uint32;
  86438. typedef unsigned __int64 FLAC__uint64;
  86439. #elif defined(__EMX__)
  86440. typedef short FLAC__int16;
  86441. typedef long FLAC__int32;
  86442. typedef long long FLAC__int64;
  86443. typedef unsigned short FLAC__uint16;
  86444. typedef unsigned long FLAC__uint32;
  86445. typedef unsigned long long FLAC__uint64;
  86446. #else
  86447. typedef int16_t FLAC__int16;
  86448. typedef int32_t FLAC__int32;
  86449. typedef int64_t FLAC__int64;
  86450. typedef uint16_t FLAC__uint16;
  86451. typedef uint32_t FLAC__uint32;
  86452. typedef uint64_t FLAC__uint64;
  86453. #endif
  86454. typedef int FLAC__bool;
  86455. typedef FLAC__uint8 FLAC__byte;
  86456. #ifdef true
  86457. #undef true
  86458. #endif
  86459. #ifdef false
  86460. #undef false
  86461. #endif
  86462. #ifndef __cplusplus
  86463. #define true 1
  86464. #define false 0
  86465. #endif
  86466. #endif
  86467. /*** End of inlined file: ordinals.h ***/
  86468. #include <stdlib.h> /* for size_t */
  86469. /** \file include/FLAC/callback.h
  86470. *
  86471. * \brief
  86472. * This module defines the structures for describing I/O callbacks
  86473. * to the other FLAC interfaces.
  86474. *
  86475. * See the detailed documentation for callbacks in the
  86476. * \link flac_callbacks callbacks \endlink module.
  86477. */
  86478. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86479. * \ingroup flac
  86480. *
  86481. * \brief
  86482. * This module defines the structures for describing I/O callbacks
  86483. * to the other FLAC interfaces.
  86484. *
  86485. * The purpose of the I/O callback functions is to create a common way
  86486. * for the metadata interfaces to handle I/O.
  86487. *
  86488. * Originally the metadata interfaces required filenames as the way of
  86489. * specifying FLAC files to operate on. This is problematic in some
  86490. * environments so there is an additional option to specify a set of
  86491. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86492. *
  86493. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86494. * opaque structure for a data source.
  86495. *
  86496. * The callback function prototypes are similar (but not identical) to the
  86497. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86498. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86499. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86500. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86501. * is required. \warning You generally CANNOT directly use fseek or ftell
  86502. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86503. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86504. * large files. You will have to find an equivalent function (e.g. ftello),
  86505. * or write a wrapper. The same is true for feof() since this is usually
  86506. * implemented as a macro, not as a function whose address can be taken.
  86507. *
  86508. * \{
  86509. */
  86510. #ifdef __cplusplus
  86511. extern "C" {
  86512. #endif
  86513. /** This is the opaque handle type used by the callbacks. Typically
  86514. * this is a \c FILE* or address of a file descriptor.
  86515. */
  86516. typedef void* FLAC__IOHandle;
  86517. /** Signature for the read callback.
  86518. * The signature and semantics match POSIX fread() implementations
  86519. * and can generally be used interchangeably.
  86520. *
  86521. * \param ptr The address of the read buffer.
  86522. * \param size The size of the records to be read.
  86523. * \param nmemb The number of records to be read.
  86524. * \param handle The handle to the data source.
  86525. * \retval size_t
  86526. * The number of records read.
  86527. */
  86528. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86529. /** Signature for the write callback.
  86530. * The signature and semantics match POSIX fwrite() implementations
  86531. * and can generally be used interchangeably.
  86532. *
  86533. * \param ptr The address of the write buffer.
  86534. * \param size The size of the records to be written.
  86535. * \param nmemb The number of records to be written.
  86536. * \param handle The handle to the data source.
  86537. * \retval size_t
  86538. * The number of records written.
  86539. */
  86540. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86541. /** Signature for the seek callback.
  86542. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86543. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86544. * and 32-bits wide.
  86545. *
  86546. * \param handle The handle to the data source.
  86547. * \param offset The new position, relative to \a whence
  86548. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86549. * \retval int
  86550. * \c 0 on success, \c -1 on error.
  86551. */
  86552. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86553. /** Signature for the tell callback.
  86554. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86555. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86556. * and 32-bits wide.
  86557. *
  86558. * \param handle The handle to the data source.
  86559. * \retval FLAC__int64
  86560. * The current position on success, \c -1 on error.
  86561. */
  86562. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86563. /** Signature for the EOF callback.
  86564. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86565. * on many systems, feof() is a macro, so in this case a wrapper function
  86566. * must be provided instead.
  86567. *
  86568. * \param handle The handle to the data source.
  86569. * \retval int
  86570. * \c 0 if not at end of file, nonzero if at end of file.
  86571. */
  86572. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86573. /** Signature for the close callback.
  86574. * The signature and semantics match POSIX fclose() implementations
  86575. * and can generally be used interchangeably.
  86576. *
  86577. * \param handle The handle to the data source.
  86578. * \retval int
  86579. * \c 0 on success, \c EOF on error.
  86580. */
  86581. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86582. /** A structure for holding a set of callbacks.
  86583. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86584. * describe which of the callbacks are required. The ones that are not
  86585. * required may be set to NULL.
  86586. *
  86587. * If the seek requirement for an interface is optional, you can signify that
  86588. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86589. */
  86590. typedef struct {
  86591. FLAC__IOCallback_Read read;
  86592. FLAC__IOCallback_Write write;
  86593. FLAC__IOCallback_Seek seek;
  86594. FLAC__IOCallback_Tell tell;
  86595. FLAC__IOCallback_Eof eof;
  86596. FLAC__IOCallback_Close close;
  86597. } FLAC__IOCallbacks;
  86598. /* \} */
  86599. #ifdef __cplusplus
  86600. }
  86601. #endif
  86602. #endif
  86603. /*** End of inlined file: callback.h ***/
  86604. /*** Start of inlined file: format.h ***/
  86605. #ifndef FLAC__FORMAT_H
  86606. #define FLAC__FORMAT_H
  86607. #ifdef __cplusplus
  86608. extern "C" {
  86609. #endif
  86610. /** \file include/FLAC/format.h
  86611. *
  86612. * \brief
  86613. * This module contains structure definitions for the representation
  86614. * of FLAC format components in memory. These are the basic
  86615. * structures used by the rest of the interfaces.
  86616. *
  86617. * See the detailed documentation in the
  86618. * \link flac_format format \endlink module.
  86619. */
  86620. /** \defgroup flac_format FLAC/format.h: format components
  86621. * \ingroup flac
  86622. *
  86623. * \brief
  86624. * This module contains structure definitions for the representation
  86625. * of FLAC format components in memory. These are the basic
  86626. * structures used by the rest of the interfaces.
  86627. *
  86628. * First, you should be familiar with the
  86629. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86630. * follow directly from the specification. As a user of libFLAC, the
  86631. * interesting parts really are the structures that describe the frame
  86632. * header and metadata blocks.
  86633. *
  86634. * The format structures here are very primitive, designed to store
  86635. * information in an efficient way. Reading information from the
  86636. * structures is easy but creating or modifying them directly is
  86637. * more complex. For the most part, as a user of a library, editing
  86638. * is not necessary; however, for metadata blocks it is, so there are
  86639. * convenience functions provided in the \link flac_metadata metadata
  86640. * module \endlink to simplify the manipulation of metadata blocks.
  86641. *
  86642. * \note
  86643. * It's not the best convention, but symbols ending in _LEN are in bits
  86644. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86645. * global variables because they are usually used when declaring byte
  86646. * arrays and some compilers require compile-time knowledge of array
  86647. * sizes when declared on the stack.
  86648. *
  86649. * \{
  86650. */
  86651. /*
  86652. Most of the values described in this file are defined by the FLAC
  86653. format specification. There is nothing to tune here.
  86654. */
  86655. /** The largest legal metadata type code. */
  86656. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86657. /** The minimum block size, in samples, permitted by the format. */
  86658. #define FLAC__MIN_BLOCK_SIZE (16u)
  86659. /** The maximum block size, in samples, permitted by the format. */
  86660. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86661. /** The maximum block size, in samples, permitted by the FLAC subset for
  86662. * sample rates up to 48kHz. */
  86663. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86664. /** The maximum number of channels permitted by the format. */
  86665. #define FLAC__MAX_CHANNELS (8u)
  86666. /** The minimum sample resolution permitted by the format. */
  86667. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86668. /** The maximum sample resolution permitted by the format. */
  86669. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86670. /** The maximum sample resolution permitted by libFLAC.
  86671. *
  86672. * \warning
  86673. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86674. * the reference encoder/decoder is currently limited to 24 bits because
  86675. * of prevalent 32-bit math, so make sure and use this value when
  86676. * appropriate.
  86677. */
  86678. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86679. /** The maximum sample rate permitted by the format. The value is
  86680. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86681. * as to why.
  86682. */
  86683. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86684. /** The maximum LPC order permitted by the format. */
  86685. #define FLAC__MAX_LPC_ORDER (32u)
  86686. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86687. * up to 48kHz. */
  86688. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86689. /** The minimum quantized linear predictor coefficient precision
  86690. * permitted by the format.
  86691. */
  86692. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86693. /** The maximum quantized linear predictor coefficient precision
  86694. * permitted by the format.
  86695. */
  86696. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86697. /** The maximum order of the fixed predictors permitted by the format. */
  86698. #define FLAC__MAX_FIXED_ORDER (4u)
  86699. /** The maximum Rice partition order permitted by the format. */
  86700. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86701. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86702. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86703. /** The version string of the release, stamped onto the libraries and binaries.
  86704. *
  86705. * \note
  86706. * This does not correspond to the shared library version number, which
  86707. * is used to determine binary compatibility.
  86708. */
  86709. extern FLAC_API const char *FLAC__VERSION_STRING;
  86710. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86711. * This is a NUL-terminated ASCII string; when inserted into the
  86712. * VORBIS_COMMENT the trailing null is stripped.
  86713. */
  86714. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86715. /** The byte string representation of the beginning of a FLAC stream. */
  86716. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86717. /** The 32-bit integer big-endian representation of the beginning of
  86718. * a FLAC stream.
  86719. */
  86720. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86721. /** The length of the FLAC signature in bits. */
  86722. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86723. /** The length of the FLAC signature in bytes. */
  86724. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86725. /*****************************************************************************
  86726. *
  86727. * Subframe structures
  86728. *
  86729. *****************************************************************************/
  86730. /*****************************************************************************/
  86731. /** An enumeration of the available entropy coding methods. */
  86732. typedef enum {
  86733. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86734. /**< Residual is coded by partitioning into contexts, each with it's own
  86735. * 4-bit Rice parameter. */
  86736. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86737. /**< Residual is coded by partitioning into contexts, each with it's own
  86738. * 5-bit Rice parameter. */
  86739. } FLAC__EntropyCodingMethodType;
  86740. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86741. *
  86742. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86743. * give the string equivalent. The contents should not be modified.
  86744. */
  86745. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86746. /** Contents of a Rice partitioned residual
  86747. */
  86748. typedef struct {
  86749. unsigned *parameters;
  86750. /**< The Rice parameters for each context. */
  86751. unsigned *raw_bits;
  86752. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86753. * partitions and zero for unescaped partitions.
  86754. */
  86755. unsigned capacity_by_order;
  86756. /**< The capacity of the \a parameters and \a raw_bits arrays
  86757. * specified as an order, i.e. the number of array elements
  86758. * allocated is 2 ^ \a capacity_by_order.
  86759. */
  86760. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86761. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86762. */
  86763. typedef struct {
  86764. unsigned order;
  86765. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86766. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86767. /**< The context's Rice parameters and/or raw bits. */
  86768. } FLAC__EntropyCodingMethod_PartitionedRice;
  86769. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86770. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86771. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86772. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86773. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86774. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86775. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86776. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86777. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86778. */
  86779. typedef struct {
  86780. FLAC__EntropyCodingMethodType type;
  86781. union {
  86782. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86783. } data;
  86784. } FLAC__EntropyCodingMethod;
  86785. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86786. /*****************************************************************************/
  86787. /** An enumeration of the available subframe types. */
  86788. typedef enum {
  86789. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86790. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86791. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86792. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86793. } FLAC__SubframeType;
  86794. /** Maps a FLAC__SubframeType to a C string.
  86795. *
  86796. * Using a FLAC__SubframeType as the index to this array will
  86797. * give the string equivalent. The contents should not be modified.
  86798. */
  86799. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86800. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86801. */
  86802. typedef struct {
  86803. FLAC__int32 value; /**< The constant signal value. */
  86804. } FLAC__Subframe_Constant;
  86805. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86806. */
  86807. typedef struct {
  86808. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86809. } FLAC__Subframe_Verbatim;
  86810. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86811. */
  86812. typedef struct {
  86813. FLAC__EntropyCodingMethod entropy_coding_method;
  86814. /**< The residual coding method. */
  86815. unsigned order;
  86816. /**< The polynomial order. */
  86817. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86818. /**< Warmup samples to prime the predictor, length == order. */
  86819. const FLAC__int32 *residual;
  86820. /**< The residual signal, length == (blocksize minus order) samples. */
  86821. } FLAC__Subframe_Fixed;
  86822. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86823. */
  86824. typedef struct {
  86825. FLAC__EntropyCodingMethod entropy_coding_method;
  86826. /**< The residual coding method. */
  86827. unsigned order;
  86828. /**< The FIR order. */
  86829. unsigned qlp_coeff_precision;
  86830. /**< Quantized FIR filter coefficient precision in bits. */
  86831. int quantization_level;
  86832. /**< The qlp coeff shift needed. */
  86833. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86834. /**< FIR filter coefficients. */
  86835. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86836. /**< Warmup samples to prime the predictor, length == order. */
  86837. const FLAC__int32 *residual;
  86838. /**< The residual signal, length == (blocksize minus order) samples. */
  86839. } FLAC__Subframe_LPC;
  86840. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86841. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86842. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86843. */
  86844. typedef struct {
  86845. FLAC__SubframeType type;
  86846. union {
  86847. FLAC__Subframe_Constant constant;
  86848. FLAC__Subframe_Fixed fixed;
  86849. FLAC__Subframe_LPC lpc;
  86850. FLAC__Subframe_Verbatim verbatim;
  86851. } data;
  86852. unsigned wasted_bits;
  86853. } FLAC__Subframe;
  86854. /** == 1 (bit)
  86855. *
  86856. * This used to be a zero-padding bit (hence the name
  86857. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86858. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86859. * to mean something else.
  86860. */
  86861. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86862. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86863. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86864. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86865. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86866. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86867. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86868. /*****************************************************************************/
  86869. /*****************************************************************************
  86870. *
  86871. * Frame structures
  86872. *
  86873. *****************************************************************************/
  86874. /** An enumeration of the available channel assignments. */
  86875. typedef enum {
  86876. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86877. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86878. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86879. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86880. } FLAC__ChannelAssignment;
  86881. /** Maps a FLAC__ChannelAssignment to a C string.
  86882. *
  86883. * Using a FLAC__ChannelAssignment as the index to this array will
  86884. * give the string equivalent. The contents should not be modified.
  86885. */
  86886. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86887. /** An enumeration of the possible frame numbering methods. */
  86888. typedef enum {
  86889. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86890. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86891. } FLAC__FrameNumberType;
  86892. /** Maps a FLAC__FrameNumberType to a C string.
  86893. *
  86894. * Using a FLAC__FrameNumberType as the index to this array will
  86895. * give the string equivalent. The contents should not be modified.
  86896. */
  86897. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86898. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86899. */
  86900. typedef struct {
  86901. unsigned blocksize;
  86902. /**< The number of samples per subframe. */
  86903. unsigned sample_rate;
  86904. /**< The sample rate in Hz. */
  86905. unsigned channels;
  86906. /**< The number of channels (== number of subframes). */
  86907. FLAC__ChannelAssignment channel_assignment;
  86908. /**< The channel assignment for the frame. */
  86909. unsigned bits_per_sample;
  86910. /**< The sample resolution. */
  86911. FLAC__FrameNumberType number_type;
  86912. /**< The numbering scheme used for the frame. As a convenience, the
  86913. * decoder will always convert a frame number to a sample number because
  86914. * the rules are complex. */
  86915. union {
  86916. FLAC__uint32 frame_number;
  86917. FLAC__uint64 sample_number;
  86918. } number;
  86919. /**< The frame number or sample number of first sample in frame;
  86920. * use the \a number_type value to determine which to use. */
  86921. FLAC__uint8 crc;
  86922. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86923. * of the raw frame header bytes, meaning everything before the CRC byte
  86924. * including the sync code.
  86925. */
  86926. } FLAC__FrameHeader;
  86927. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86928. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86929. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86930. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86931. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86932. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86933. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86934. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86935. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86936. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86937. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86938. */
  86939. typedef struct {
  86940. FLAC__uint16 crc;
  86941. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86942. * 0) of the bytes before the crc, back to and including the frame header
  86943. * sync code.
  86944. */
  86945. } FLAC__FrameFooter;
  86946. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86947. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86948. */
  86949. typedef struct {
  86950. FLAC__FrameHeader header;
  86951. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86952. FLAC__FrameFooter footer;
  86953. } FLAC__Frame;
  86954. /*****************************************************************************/
  86955. /*****************************************************************************
  86956. *
  86957. * Meta-data structures
  86958. *
  86959. *****************************************************************************/
  86960. /** An enumeration of the available metadata block types. */
  86961. typedef enum {
  86962. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86963. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86964. FLAC__METADATA_TYPE_PADDING = 1,
  86965. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86966. FLAC__METADATA_TYPE_APPLICATION = 2,
  86967. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86968. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86969. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86970. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86971. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86972. FLAC__METADATA_TYPE_CUESHEET = 5,
  86973. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86974. FLAC__METADATA_TYPE_PICTURE = 6,
  86975. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86976. FLAC__METADATA_TYPE_UNDEFINED = 7
  86977. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86978. } FLAC__MetadataType;
  86979. /** Maps a FLAC__MetadataType to a C string.
  86980. *
  86981. * Using a FLAC__MetadataType as the index to this array will
  86982. * give the string equivalent. The contents should not be modified.
  86983. */
  86984. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86985. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86986. */
  86987. typedef struct {
  86988. unsigned min_blocksize, max_blocksize;
  86989. unsigned min_framesize, max_framesize;
  86990. unsigned sample_rate;
  86991. unsigned channels;
  86992. unsigned bits_per_sample;
  86993. FLAC__uint64 total_samples;
  86994. FLAC__byte md5sum[16];
  86995. } FLAC__StreamMetadata_StreamInfo;
  86996. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86997. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86998. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86999. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87000. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  87001. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  87002. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  87003. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  87004. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  87005. /** The total stream length of the STREAMINFO block in bytes. */
  87006. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  87007. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  87008. */
  87009. typedef struct {
  87010. int dummy;
  87011. /**< Conceptually this is an empty struct since we don't store the
  87012. * padding bytes. Empty structs are not allowed by some C compilers,
  87013. * hence the dummy.
  87014. */
  87015. } FLAC__StreamMetadata_Padding;
  87016. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  87017. */
  87018. typedef struct {
  87019. FLAC__byte id[4];
  87020. FLAC__byte *data;
  87021. } FLAC__StreamMetadata_Application;
  87022. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  87023. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  87024. */
  87025. typedef struct {
  87026. FLAC__uint64 sample_number;
  87027. /**< The sample number of the target frame. */
  87028. FLAC__uint64 stream_offset;
  87029. /**< The offset, in bytes, of the target frame with respect to
  87030. * beginning of the first frame. */
  87031. unsigned frame_samples;
  87032. /**< The number of samples in the target frame. */
  87033. } FLAC__StreamMetadata_SeekPoint;
  87034. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  87035. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  87036. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  87037. /** The total stream length of a seek point in bytes. */
  87038. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  87039. /** The value used in the \a sample_number field of
  87040. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  87041. * point (== 0xffffffffffffffff).
  87042. */
  87043. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  87044. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  87045. *
  87046. * \note From the format specification:
  87047. * - The seek points must be sorted by ascending sample number.
  87048. * - Each seek point's sample number must be the first sample of the
  87049. * target frame.
  87050. * - Each seek point's sample number must be unique within the table.
  87051. * - Existence of a SEEKTABLE block implies a correct setting of
  87052. * total_samples in the stream_info block.
  87053. * - Behavior is undefined when more than one SEEKTABLE block is
  87054. * present in a stream.
  87055. */
  87056. typedef struct {
  87057. unsigned num_points;
  87058. FLAC__StreamMetadata_SeekPoint *points;
  87059. } FLAC__StreamMetadata_SeekTable;
  87060. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87061. *
  87062. * For convenience, the APIs maintain a trailing NUL character at the end of
  87063. * \a entry which is not counted toward \a length, i.e.
  87064. * \code strlen(entry) == length \endcode
  87065. */
  87066. typedef struct {
  87067. FLAC__uint32 length;
  87068. FLAC__byte *entry;
  87069. } FLAC__StreamMetadata_VorbisComment_Entry;
  87070. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  87071. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87072. */
  87073. typedef struct {
  87074. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  87075. FLAC__uint32 num_comments;
  87076. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  87077. } FLAC__StreamMetadata_VorbisComment;
  87078. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  87079. /** FLAC CUESHEET track index structure. (See the
  87080. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  87081. * the full description of each field.)
  87082. */
  87083. typedef struct {
  87084. FLAC__uint64 offset;
  87085. /**< Offset in samples, relative to the track offset, of the index
  87086. * point.
  87087. */
  87088. FLAC__byte number;
  87089. /**< The index point number. */
  87090. } FLAC__StreamMetadata_CueSheet_Index;
  87091. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87092. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87093. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87094. /** FLAC CUESHEET track structure. (See the
  87095. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87096. * the full description of each field.)
  87097. */
  87098. typedef struct {
  87099. FLAC__uint64 offset;
  87100. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87101. FLAC__byte number;
  87102. /**< The track number. */
  87103. char isrc[13];
  87104. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87105. unsigned type:1;
  87106. /**< The track type: 0 for audio, 1 for non-audio. */
  87107. unsigned pre_emphasis:1;
  87108. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87109. FLAC__byte num_indices;
  87110. /**< The number of track index points. */
  87111. FLAC__StreamMetadata_CueSheet_Index *indices;
  87112. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87113. } FLAC__StreamMetadata_CueSheet_Track;
  87114. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87115. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87116. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87117. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87118. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87119. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87120. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87121. /** FLAC CUESHEET structure. (See the
  87122. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87123. * for the full description of each field.)
  87124. */
  87125. typedef struct {
  87126. char media_catalog_number[129];
  87127. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87128. * general, the media catalog number may be 0 to 128 bytes long; any
  87129. * unused characters should be right-padded with NUL characters.
  87130. */
  87131. FLAC__uint64 lead_in;
  87132. /**< The number of lead-in samples. */
  87133. FLAC__bool is_cd;
  87134. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87135. unsigned num_tracks;
  87136. /**< The number of tracks. */
  87137. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87138. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87139. } FLAC__StreamMetadata_CueSheet;
  87140. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87141. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87142. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87143. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87144. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87145. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87146. typedef enum {
  87147. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87148. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87149. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87150. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87151. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87152. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87153. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87154. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87155. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87156. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87157. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87158. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87159. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87160. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87161. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87162. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87163. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87164. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87165. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87166. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87167. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87168. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87169. } FLAC__StreamMetadata_Picture_Type;
  87170. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87171. *
  87172. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87173. * will give the string equivalent. The contents should not be
  87174. * modified.
  87175. */
  87176. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87177. /** FLAC PICTURE structure. (See the
  87178. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87179. * for the full description of each field.)
  87180. */
  87181. typedef struct {
  87182. FLAC__StreamMetadata_Picture_Type type;
  87183. /**< The kind of picture stored. */
  87184. char *mime_type;
  87185. /**< Picture data's MIME type, in ASCII printable characters
  87186. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87187. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87188. * MIME type of '-->' is also allowed, in which case the picture
  87189. * data should be a complete URL. In file storage, the MIME type is
  87190. * stored as a 32-bit length followed by the ASCII string with no NUL
  87191. * terminator, but is converted to a plain C string in this structure
  87192. * for convenience.
  87193. */
  87194. FLAC__byte *description;
  87195. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87196. * the description is stored as a 32-bit length followed by the UTF-8
  87197. * string with no NUL terminator, but is converted to a plain C string
  87198. * in this structure for convenience.
  87199. */
  87200. FLAC__uint32 width;
  87201. /**< Picture's width in pixels. */
  87202. FLAC__uint32 height;
  87203. /**< Picture's height in pixels. */
  87204. FLAC__uint32 depth;
  87205. /**< Picture's color depth in bits-per-pixel. */
  87206. FLAC__uint32 colors;
  87207. /**< For indexed palettes (like GIF), picture's number of colors (the
  87208. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87209. */
  87210. FLAC__uint32 data_length;
  87211. /**< Length of binary picture data in bytes. */
  87212. FLAC__byte *data;
  87213. /**< Binary picture data. */
  87214. } FLAC__StreamMetadata_Picture;
  87215. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87216. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87217. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87218. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87219. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87220. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87221. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87222. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87223. /** Structure that is used when a metadata block of unknown type is loaded.
  87224. * The contents are opaque. The structure is used only internally to
  87225. * correctly handle unknown metadata.
  87226. */
  87227. typedef struct {
  87228. FLAC__byte *data;
  87229. } FLAC__StreamMetadata_Unknown;
  87230. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87231. */
  87232. typedef struct {
  87233. FLAC__MetadataType type;
  87234. /**< The type of the metadata block; used determine which member of the
  87235. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87236. * then \a data.unknown must be used. */
  87237. FLAC__bool is_last;
  87238. /**< \c true if this metadata block is the last, else \a false */
  87239. unsigned length;
  87240. /**< Length, in bytes, of the block data as it appears in the stream. */
  87241. union {
  87242. FLAC__StreamMetadata_StreamInfo stream_info;
  87243. FLAC__StreamMetadata_Padding padding;
  87244. FLAC__StreamMetadata_Application application;
  87245. FLAC__StreamMetadata_SeekTable seek_table;
  87246. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87247. FLAC__StreamMetadata_CueSheet cue_sheet;
  87248. FLAC__StreamMetadata_Picture picture;
  87249. FLAC__StreamMetadata_Unknown unknown;
  87250. } data;
  87251. /**< Polymorphic block data; use the \a type value to determine which
  87252. * to use. */
  87253. } FLAC__StreamMetadata;
  87254. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87255. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87256. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87257. /** The total stream length of a metadata block header in bytes. */
  87258. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87259. /*****************************************************************************/
  87260. /*****************************************************************************
  87261. *
  87262. * Utility functions
  87263. *
  87264. *****************************************************************************/
  87265. /** Tests that a sample rate is valid for FLAC.
  87266. *
  87267. * \param sample_rate The sample rate to test for compliance.
  87268. * \retval FLAC__bool
  87269. * \c true if the given sample rate conforms to the specification, else
  87270. * \c false.
  87271. */
  87272. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87273. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87274. * for valid sample rates are slightly more complex since the rate has to
  87275. * be expressible completely in the frame header.
  87276. *
  87277. * \param sample_rate The sample rate to test for compliance.
  87278. * \retval FLAC__bool
  87279. * \c true if the given sample rate conforms to the specification for the
  87280. * subset, else \c false.
  87281. */
  87282. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87283. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87284. * comment specification.
  87285. *
  87286. * Vorbis comment names must be composed only of characters from
  87287. * [0x20-0x3C,0x3E-0x7D].
  87288. *
  87289. * \param name A NUL-terminated string to be checked.
  87290. * \assert
  87291. * \code name != NULL \endcode
  87292. * \retval FLAC__bool
  87293. * \c false if entry name is illegal, else \c true.
  87294. */
  87295. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87296. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87297. * comment specification.
  87298. *
  87299. * Vorbis comment values must be valid UTF-8 sequences.
  87300. *
  87301. * \param value A string to be checked.
  87302. * \param length A the length of \a value in bytes. May be
  87303. * \c (unsigned)(-1) to indicate that \a value is a plain
  87304. * UTF-8 NUL-terminated string.
  87305. * \assert
  87306. * \code value != NULL \endcode
  87307. * \retval FLAC__bool
  87308. * \c false if entry name is illegal, else \c true.
  87309. */
  87310. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87311. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87312. * comment specification.
  87313. *
  87314. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87315. * 'value' must be legal according to
  87316. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87317. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87318. *
  87319. * \param entry An entry to be checked.
  87320. * \param length The length of \a entry in bytes.
  87321. * \assert
  87322. * \code value != NULL \endcode
  87323. * \retval FLAC__bool
  87324. * \c false if entry name is illegal, else \c true.
  87325. */
  87326. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87327. /** Check a seek table to see if it conforms to the FLAC specification.
  87328. * See the format specification for limits on the contents of the
  87329. * seek table.
  87330. *
  87331. * \param seek_table A pointer to a seek table to be checked.
  87332. * \assert
  87333. * \code seek_table != NULL \endcode
  87334. * \retval FLAC__bool
  87335. * \c false if seek table is illegal, else \c true.
  87336. */
  87337. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87338. /** Sort a seek table's seek points according to the format specification.
  87339. * This includes a "unique-ification" step to remove duplicates, i.e.
  87340. * seek points with identical \a sample_number values. Duplicate seek
  87341. * points are converted into placeholder points and sorted to the end of
  87342. * the table.
  87343. *
  87344. * \param seek_table A pointer to a seek table to be sorted.
  87345. * \assert
  87346. * \code seek_table != NULL \endcode
  87347. * \retval unsigned
  87348. * The number of duplicate seek points converted into placeholders.
  87349. */
  87350. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87351. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87352. * See the format specification for limits on the contents of the
  87353. * cue sheet.
  87354. *
  87355. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87356. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87357. * stringent requirements for a CD-DA (audio) disc.
  87358. * \param violation Address of a pointer to a string. If there is a
  87359. * violation, a pointer to a string explanation of the
  87360. * violation will be returned here. \a violation may be
  87361. * \c NULL if you don't need the returned string. Do not
  87362. * free the returned string; it will always point to static
  87363. * data.
  87364. * \assert
  87365. * \code cue_sheet != NULL \endcode
  87366. * \retval FLAC__bool
  87367. * \c false if cue sheet is illegal, else \c true.
  87368. */
  87369. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87370. /** Check picture data to see if it conforms to the FLAC specification.
  87371. * See the format specification for limits on the contents of the
  87372. * PICTURE block.
  87373. *
  87374. * \param picture A pointer to existing picture data to be checked.
  87375. * \param violation Address of a pointer to a string. If there is a
  87376. * violation, a pointer to a string explanation of the
  87377. * violation will be returned here. \a violation may be
  87378. * \c NULL if you don't need the returned string. Do not
  87379. * free the returned string; it will always point to static
  87380. * data.
  87381. * \assert
  87382. * \code picture != NULL \endcode
  87383. * \retval FLAC__bool
  87384. * \c false if picture data is illegal, else \c true.
  87385. */
  87386. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87387. /* \} */
  87388. #ifdef __cplusplus
  87389. }
  87390. #endif
  87391. #endif
  87392. /*** End of inlined file: format.h ***/
  87393. /*** Start of inlined file: metadata.h ***/
  87394. #ifndef FLAC__METADATA_H
  87395. #define FLAC__METADATA_H
  87396. #include <sys/types.h> /* for off_t */
  87397. /* --------------------------------------------------------------------
  87398. (For an example of how all these routines are used, see the source
  87399. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87400. metaflac in src/metaflac/)
  87401. ------------------------------------------------------------------*/
  87402. /** \file include/FLAC/metadata.h
  87403. *
  87404. * \brief
  87405. * This module provides functions for creating and manipulating FLAC
  87406. * metadata blocks in memory, and three progressively more powerful
  87407. * interfaces for traversing and editing metadata in FLAC files.
  87408. *
  87409. * See the detailed documentation for each interface in the
  87410. * \link flac_metadata metadata \endlink module.
  87411. */
  87412. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87413. * \ingroup flac
  87414. *
  87415. * \brief
  87416. * This module provides functions for creating and manipulating FLAC
  87417. * metadata blocks in memory, and three progressively more powerful
  87418. * interfaces for traversing and editing metadata in native FLAC files.
  87419. * Note that currently only the Chain interface (level 2) supports Ogg
  87420. * FLAC files, and it is read-only i.e. no writing back changed
  87421. * metadata to file.
  87422. *
  87423. * There are three metadata interfaces of increasing complexity:
  87424. *
  87425. * Level 0:
  87426. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87427. * PICTURE blocks.
  87428. *
  87429. * Level 1:
  87430. * Read-write access to all metadata blocks. This level is write-
  87431. * efficient in most cases (more on this below), and uses less memory
  87432. * than level 2.
  87433. *
  87434. * Level 2:
  87435. * Read-write access to all metadata blocks. This level is write-
  87436. * efficient in all cases, but uses more memory since all metadata for
  87437. * the whole file is read into memory and manipulated before writing
  87438. * out again.
  87439. *
  87440. * What do we mean by efficient? Since FLAC metadata appears at the
  87441. * beginning of the file, when writing metadata back to a FLAC file
  87442. * it is possible to grow or shrink the metadata such that the entire
  87443. * file must be rewritten. However, if the size remains the same during
  87444. * changes or PADDING blocks are utilized, only the metadata needs to be
  87445. * overwritten, which is much faster.
  87446. *
  87447. * Efficient means the whole file is rewritten at most one time, and only
  87448. * when necessary. Level 1 is not efficient only in the case that you
  87449. * cause more than one metadata block to grow or shrink beyond what can
  87450. * be accomodated by padding. In this case you should probably use level
  87451. * 2, which allows you to edit all the metadata for a file in memory and
  87452. * write it out all at once.
  87453. *
  87454. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87455. * front of the file.
  87456. *
  87457. * All levels access files via their filenames. In addition, level 2
  87458. * has additional alternative read and write functions that take an I/O
  87459. * handle and callbacks, for situations where access by filename is not
  87460. * possible.
  87461. *
  87462. * In addition to the three interfaces, this module defines functions for
  87463. * creating and manipulating various metadata objects in memory. As we see
  87464. * from the Format module, FLAC metadata blocks in memory are very primitive
  87465. * structures for storing information in an efficient way. Reading
  87466. * information from the structures is easy but creating or modifying them
  87467. * directly is more complex. The metadata object routines here facilitate
  87468. * this by taking care of the consistency and memory management drudgery.
  87469. *
  87470. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87471. * metadata however, you will not probably not need these.
  87472. *
  87473. * From a dependency standpoint, none of the encoders or decoders require
  87474. * the metadata module. This is so that embedded users can strip out the
  87475. * metadata module from libFLAC to reduce the size and complexity.
  87476. */
  87477. #ifdef __cplusplus
  87478. extern "C" {
  87479. #endif
  87480. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87481. * \ingroup flac_metadata
  87482. *
  87483. * \brief
  87484. * The level 0 interface consists of individual routines to read the
  87485. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87486. * only a filename.
  87487. *
  87488. * They try to skip any ID3v2 tag at the head of the file.
  87489. *
  87490. * \{
  87491. */
  87492. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87493. * will try to skip any ID3v2 tag at the head of the file.
  87494. *
  87495. * \param filename The path to the FLAC file to read.
  87496. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87497. * FLAC__StreamMetadata is a simple structure with no
  87498. * memory allocation involved, you pass the address of
  87499. * an existing structure. It need not be initialized.
  87500. * \assert
  87501. * \code filename != NULL \endcode
  87502. * \code streaminfo != NULL \endcode
  87503. * \retval FLAC__bool
  87504. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87505. * \c false if there was a memory allocation error, a file decoder error,
  87506. * or the file contained no STREAMINFO block. (A memory allocation error
  87507. * is possible because this function must set up a file decoder.)
  87508. */
  87509. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87510. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87511. * function will try to skip any ID3v2 tag at the head of the file.
  87512. *
  87513. * \param filename The path to the FLAC file to read.
  87514. * \param tags The address where the returned pointer will be
  87515. * stored. The \a tags object must be deleted by
  87516. * the caller using FLAC__metadata_object_delete().
  87517. * \assert
  87518. * \code filename != NULL \endcode
  87519. * \code tags != NULL \endcode
  87520. * \retval FLAC__bool
  87521. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87522. * and \a *tags will be set to the address of the metadata structure.
  87523. * Returns \c false if there was a memory allocation error, a file
  87524. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87525. * \a *tags will be set to \c NULL.
  87526. */
  87527. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87528. /** Read the CUESHEET metadata block of the given FLAC file. This
  87529. * function will try to skip any ID3v2 tag at the head of the file.
  87530. *
  87531. * \param filename The path to the FLAC file to read.
  87532. * \param cuesheet The address where the returned pointer will be
  87533. * stored. The \a cuesheet object must be deleted by
  87534. * the caller using FLAC__metadata_object_delete().
  87535. * \assert
  87536. * \code filename != NULL \endcode
  87537. * \code cuesheet != NULL \endcode
  87538. * \retval FLAC__bool
  87539. * \c true if a valid CUESHEET block was read from \a filename,
  87540. * and \a *cuesheet will be set to the address of the metadata
  87541. * structure. Returns \c false if there was a memory allocation
  87542. * error, a file decoder error, or the file contained no CUESHEET
  87543. * block, and \a *cuesheet will be set to \c NULL.
  87544. */
  87545. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87546. /** Read a PICTURE metadata block of the given FLAC file. This
  87547. * function will try to skip any ID3v2 tag at the head of the file.
  87548. * Since there can be more than one PICTURE block in a file, this
  87549. * function takes a number of parameters that act as constraints to
  87550. * the search. The PICTURE block with the largest area matching all
  87551. * the constraints will be returned, or \a *picture will be set to
  87552. * \c NULL if there was no such block.
  87553. *
  87554. * \param filename The path to the FLAC file to read.
  87555. * \param picture The address where the returned pointer will be
  87556. * stored. The \a picture object must be deleted by
  87557. * the caller using FLAC__metadata_object_delete().
  87558. * \param type The desired picture type. Use \c -1 to mean
  87559. * "any type".
  87560. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87561. * string will be matched exactly. Use \c NULL to
  87562. * mean "any MIME type".
  87563. * \param description The desired description. The string will be
  87564. * matched exactly. Use \c NULL to mean "any
  87565. * description".
  87566. * \param max_width The maximum width in pixels desired. Use
  87567. * \c (unsigned)(-1) to mean "any width".
  87568. * \param max_height The maximum height in pixels desired. Use
  87569. * \c (unsigned)(-1) to mean "any height".
  87570. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87571. * Use \c (unsigned)(-1) to mean "any depth".
  87572. * \param max_colors The maximum number of colors desired. Use
  87573. * \c (unsigned)(-1) to mean "any number of colors".
  87574. * \assert
  87575. * \code filename != NULL \endcode
  87576. * \code picture != NULL \endcode
  87577. * \retval FLAC__bool
  87578. * \c true if a valid PICTURE block was read from \a filename,
  87579. * and \a *picture will be set to the address of the metadata
  87580. * structure. Returns \c false if there was a memory allocation
  87581. * error, a file decoder error, or the file contained no PICTURE
  87582. * block, and \a *picture will be set to \c NULL.
  87583. */
  87584. 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);
  87585. /* \} */
  87586. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87587. * \ingroup flac_metadata
  87588. *
  87589. * \brief
  87590. * The level 1 interface provides read-write access to FLAC file metadata and
  87591. * operates directly on the FLAC file.
  87592. *
  87593. * The general usage of this interface is:
  87594. *
  87595. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87596. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87597. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87598. * see if the file is writable, or only read access is allowed.
  87599. * - Use FLAC__metadata_simple_iterator_next() and
  87600. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87601. * This is does not read the actual blocks themselves.
  87602. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87603. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87604. * forward from the front of the file.
  87605. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87606. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87607. * the current iterator position. The returned object is yours to modify
  87608. * and free.
  87609. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87610. * back. You must have write permission to the original file. Make sure to
  87611. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87612. * below.
  87613. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87614. * Use the object creation functions from
  87615. * \link flac_metadata_object here \endlink to generate new objects.
  87616. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87617. * currently referred to by the iterator, or replace it with padding.
  87618. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87619. * finished.
  87620. *
  87621. * \note
  87622. * The FLAC file remains open the whole time between
  87623. * FLAC__metadata_simple_iterator_init() and
  87624. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87625. * the file during this time.
  87626. *
  87627. * \note
  87628. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87629. * FLAC__StreamMetadata objects. These are managed automatically.
  87630. *
  87631. * \note
  87632. * If any of the modification functions
  87633. * (FLAC__metadata_simple_iterator_set_block(),
  87634. * FLAC__metadata_simple_iterator_delete_block(),
  87635. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87636. * you should delete the iterator as it may no longer be valid.
  87637. *
  87638. * \{
  87639. */
  87640. struct FLAC__Metadata_SimpleIterator;
  87641. /** The opaque structure definition for the level 1 iterator type.
  87642. * See the
  87643. * \link flac_metadata_level1 metadata level 1 module \endlink
  87644. * for a detailed description.
  87645. */
  87646. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87647. /** Status type for FLAC__Metadata_SimpleIterator.
  87648. *
  87649. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87650. */
  87651. typedef enum {
  87652. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87653. /**< The iterator is in the normal OK state */
  87654. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87655. /**< The data passed into a function violated the function's usage criteria */
  87656. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87657. /**< The iterator could not open the target file */
  87658. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87659. /**< The iterator could not find the FLAC signature at the start of the file */
  87660. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87661. /**< The iterator tried to write to a file that was not writable */
  87662. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87663. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87664. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87665. /**< The iterator encountered an error while reading the FLAC file */
  87666. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87667. /**< The iterator encountered an error while seeking in the FLAC file */
  87668. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87669. /**< The iterator encountered an error while writing the FLAC file */
  87670. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87671. /**< The iterator encountered an error renaming the FLAC file */
  87672. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87673. /**< The iterator encountered an error removing the temporary file */
  87674. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87675. /**< Memory allocation failed */
  87676. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87677. /**< The caller violated an assertion or an unexpected error occurred */
  87678. } FLAC__Metadata_SimpleIteratorStatus;
  87679. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87680. *
  87681. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87682. * will give the string equivalent. The contents should not be modified.
  87683. */
  87684. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87685. /** Create a new iterator instance.
  87686. *
  87687. * \retval FLAC__Metadata_SimpleIterator*
  87688. * \c NULL if there was an error allocating memory, else the new instance.
  87689. */
  87690. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87691. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87692. *
  87693. * \param iterator A pointer to an existing iterator.
  87694. * \assert
  87695. * \code iterator != NULL \endcode
  87696. */
  87697. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87698. /** Get the current status of the iterator. Call this after a function
  87699. * returns \c false to get the reason for the error. Also resets the status
  87700. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87701. *
  87702. * \param iterator A pointer to an existing iterator.
  87703. * \assert
  87704. * \code iterator != NULL \endcode
  87705. * \retval FLAC__Metadata_SimpleIteratorStatus
  87706. * The current status of the iterator.
  87707. */
  87708. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87709. /** Initialize the iterator to point to the first metadata block in the
  87710. * given FLAC file.
  87711. *
  87712. * \param iterator A pointer to an existing iterator.
  87713. * \param filename The path to the FLAC file.
  87714. * \param read_only If \c true, the FLAC file will be opened
  87715. * in read-only mode; if \c false, the FLAC
  87716. * file will be opened for edit even if no
  87717. * edits are performed.
  87718. * \param preserve_file_stats If \c true, the owner and modification
  87719. * time will be preserved even if the FLAC
  87720. * file is written to.
  87721. * \assert
  87722. * \code iterator != NULL \endcode
  87723. * \code filename != NULL \endcode
  87724. * \retval FLAC__bool
  87725. * \c false if a memory allocation error occurs, the file can't be
  87726. * opened, or another error occurs, else \c true.
  87727. */
  87728. 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);
  87729. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87730. * FLAC__metadata_simple_iterator_set_block() and
  87731. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87732. *
  87733. * \param iterator A pointer to an existing iterator.
  87734. * \assert
  87735. * \code iterator != NULL \endcode
  87736. * \retval FLAC__bool
  87737. * See above.
  87738. */
  87739. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87740. /** Moves the iterator forward one metadata block, returning \c false if
  87741. * already at the end.
  87742. *
  87743. * \param iterator A pointer to an existing initialized iterator.
  87744. * \assert
  87745. * \code iterator != NULL \endcode
  87746. * \a iterator has been successfully initialized with
  87747. * FLAC__metadata_simple_iterator_init()
  87748. * \retval FLAC__bool
  87749. * \c false if already at the last metadata block of the chain, else
  87750. * \c true.
  87751. */
  87752. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87753. /** Moves the iterator backward one metadata block, returning \c false if
  87754. * already at the beginning.
  87755. *
  87756. * \param iterator A pointer to an existing initialized iterator.
  87757. * \assert
  87758. * \code iterator != NULL \endcode
  87759. * \a iterator has been successfully initialized with
  87760. * FLAC__metadata_simple_iterator_init()
  87761. * \retval FLAC__bool
  87762. * \c false if already at the first metadata block of the chain, else
  87763. * \c true.
  87764. */
  87765. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87766. /** Returns a flag telling if the current metadata block is the last.
  87767. *
  87768. * \param iterator A pointer to an existing initialized iterator.
  87769. * \assert
  87770. * \code iterator != NULL \endcode
  87771. * \a iterator has been successfully initialized with
  87772. * FLAC__metadata_simple_iterator_init()
  87773. * \retval FLAC__bool
  87774. * \c true if the current metadata block is the last in the file,
  87775. * else \c false.
  87776. */
  87777. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87778. /** Get the offset of the metadata block at the current position. This
  87779. * avoids reading the actual block data which can save time for large
  87780. * blocks.
  87781. *
  87782. * \param iterator A pointer to an existing initialized iterator.
  87783. * \assert
  87784. * \code iterator != NULL \endcode
  87785. * \a iterator has been successfully initialized with
  87786. * FLAC__metadata_simple_iterator_init()
  87787. * \retval off_t
  87788. * The offset of the metadata block at the current iterator position.
  87789. * This is the byte offset relative to the beginning of the file of
  87790. * the current metadata block's header.
  87791. */
  87792. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87793. /** Get the type of the metadata block at the current position. This
  87794. * avoids reading the actual block data which can save time for large
  87795. * blocks.
  87796. *
  87797. * \param iterator A pointer to an existing initialized iterator.
  87798. * \assert
  87799. * \code iterator != NULL \endcode
  87800. * \a iterator has been successfully initialized with
  87801. * FLAC__metadata_simple_iterator_init()
  87802. * \retval FLAC__MetadataType
  87803. * The type of the metadata block at the current iterator position.
  87804. */
  87805. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87806. /** Get the length of the metadata block at the current position. This
  87807. * avoids reading the actual block data which can save time for large
  87808. * blocks.
  87809. *
  87810. * \param iterator A pointer to an existing initialized iterator.
  87811. * \assert
  87812. * \code iterator != NULL \endcode
  87813. * \a iterator has been successfully initialized with
  87814. * FLAC__metadata_simple_iterator_init()
  87815. * \retval unsigned
  87816. * The length of the metadata block at the current iterator position.
  87817. * The is same length as that in the
  87818. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87819. * i.e. the length of the metadata body that follows the header.
  87820. */
  87821. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87822. /** Get the application ID of the \c APPLICATION block at the current
  87823. * position. This avoids reading the actual block data which can save
  87824. * time for large blocks.
  87825. *
  87826. * \param iterator A pointer to an existing initialized iterator.
  87827. * \param id A pointer to a buffer of at least \c 4 bytes where
  87828. * the ID will be stored.
  87829. * \assert
  87830. * \code iterator != NULL \endcode
  87831. * \code id != NULL \endcode
  87832. * \a iterator has been successfully initialized with
  87833. * FLAC__metadata_simple_iterator_init()
  87834. * \retval FLAC__bool
  87835. * \c true if the ID was successfully read, else \c false, in which
  87836. * case you should check FLAC__metadata_simple_iterator_status() to
  87837. * find out why. If the status is
  87838. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87839. * current metadata block is not an \c APPLICATION block. Otherwise
  87840. * if the status is
  87841. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87842. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87843. * occurred and the iterator can no longer be used.
  87844. */
  87845. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87846. /** Get the metadata block at the current position. You can modify the
  87847. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87848. * write it back to the FLAC file.
  87849. *
  87850. * You must call FLAC__metadata_object_delete() on the returned object
  87851. * when you are finished with it.
  87852. *
  87853. * \param iterator A pointer to an existing initialized iterator.
  87854. * \assert
  87855. * \code iterator != NULL \endcode
  87856. * \a iterator has been successfully initialized with
  87857. * FLAC__metadata_simple_iterator_init()
  87858. * \retval FLAC__StreamMetadata*
  87859. * The current metadata block, or \c NULL if there was a memory
  87860. * allocation error.
  87861. */
  87862. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87863. /** Write a block back to the FLAC file. This function tries to be
  87864. * as efficient as possible; how the block is actually written is
  87865. * shown by the following:
  87866. *
  87867. * Existing block is a STREAMINFO block and the new block is a
  87868. * STREAMINFO block: the new block is written in place. Make sure
  87869. * you know what you're doing when changing the values of a
  87870. * STREAMINFO block.
  87871. *
  87872. * Existing block is a STREAMINFO block and the new block is a
  87873. * not a STREAMINFO block: this is an error since the first block
  87874. * must be a STREAMINFO block. Returns \c false without altering the
  87875. * file.
  87876. *
  87877. * Existing block is not a STREAMINFO block and the new block is a
  87878. * STREAMINFO block: this is an error since there may be only one
  87879. * STREAMINFO block. Returns \c false without altering the file.
  87880. *
  87881. * Existing block and new block are the same length: the existing
  87882. * block will be replaced by the new block, written in place.
  87883. *
  87884. * Existing block is longer than new block: if use_padding is \c true,
  87885. * the existing block will be overwritten in place with the new
  87886. * block followed by a PADDING block, if possible, to make the total
  87887. * size the same as the existing block. Remember that a padding
  87888. * block requires at least four bytes so if the difference in size
  87889. * between the new block and existing block is less than that, the
  87890. * entire file will have to be rewritten, using the new block's
  87891. * exact size. If use_padding is \c false, the entire file will be
  87892. * rewritten, replacing the existing block by the new block.
  87893. *
  87894. * Existing block is shorter than new block: if use_padding is \c true,
  87895. * the function will try and expand the new block into the following
  87896. * PADDING block, if it exists and doing so won't shrink the PADDING
  87897. * block to less than 4 bytes. If there is no following PADDING
  87898. * block, or it will shrink to less than 4 bytes, or use_padding is
  87899. * \c false, the entire file is rewritten, replacing the existing block
  87900. * with the new block. Note that in this case any following PADDING
  87901. * block is preserved as is.
  87902. *
  87903. * After writing the block, the iterator will remain in the same
  87904. * place, i.e. pointing to the new block.
  87905. *
  87906. * \param iterator A pointer to an existing initialized iterator.
  87907. * \param block The block to set.
  87908. * \param use_padding See above.
  87909. * \assert
  87910. * \code iterator != NULL \endcode
  87911. * \a iterator has been successfully initialized with
  87912. * FLAC__metadata_simple_iterator_init()
  87913. * \code block != NULL \endcode
  87914. * \retval FLAC__bool
  87915. * \c true if successful, else \c false.
  87916. */
  87917. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87918. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87919. * except that instead of writing over an existing block, it appends
  87920. * a block after the existing block. \a use_padding is again used to
  87921. * tell the function to try an expand into following padding in an
  87922. * attempt to avoid rewriting the entire file.
  87923. *
  87924. * This function will fail and return \c false if given a STREAMINFO
  87925. * block.
  87926. *
  87927. * After writing the block, the iterator will be pointing to the
  87928. * new block.
  87929. *
  87930. * \param iterator A pointer to an existing initialized iterator.
  87931. * \param block The block to set.
  87932. * \param use_padding See above.
  87933. * \assert
  87934. * \code iterator != NULL \endcode
  87935. * \a iterator has been successfully initialized with
  87936. * FLAC__metadata_simple_iterator_init()
  87937. * \code block != NULL \endcode
  87938. * \retval FLAC__bool
  87939. * \c true if successful, else \c false.
  87940. */
  87941. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87942. /** Deletes the block at the current position. This will cause the
  87943. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87944. * in which case the block will be replaced by an equal-sized PADDING
  87945. * block. The iterator will be left pointing to the block before the
  87946. * one just deleted.
  87947. *
  87948. * You may not delete the STREAMINFO block.
  87949. *
  87950. * \param iterator A pointer to an existing initialized iterator.
  87951. * \param use_padding See above.
  87952. * \assert
  87953. * \code iterator != NULL \endcode
  87954. * \a iterator has been successfully initialized with
  87955. * FLAC__metadata_simple_iterator_init()
  87956. * \retval FLAC__bool
  87957. * \c true if successful, else \c false.
  87958. */
  87959. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87960. /* \} */
  87961. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87962. * \ingroup flac_metadata
  87963. *
  87964. * \brief
  87965. * The level 2 interface provides read-write access to FLAC file metadata;
  87966. * all metadata is read into memory, operated on in memory, and then written
  87967. * to file, which is more efficient than level 1 when editing multiple blocks.
  87968. *
  87969. * Currently Ogg FLAC is supported for read only, via
  87970. * FLAC__metadata_chain_read_ogg() but a subsequent
  87971. * FLAC__metadata_chain_write() will fail.
  87972. *
  87973. * The general usage of this interface is:
  87974. *
  87975. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87976. * linked list of FLAC metadata blocks.
  87977. * - Read all metadata into the the chain from a FLAC file using
  87978. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87979. * check the status.
  87980. * - Optionally, consolidate the padding using
  87981. * FLAC__metadata_chain_merge_padding() or
  87982. * FLAC__metadata_chain_sort_padding().
  87983. * - Create a new iterator using FLAC__metadata_iterator_new()
  87984. * - Initialize the iterator to point to the first element in the chain
  87985. * using FLAC__metadata_iterator_init()
  87986. * - Traverse the chain using FLAC__metadata_iterator_next and
  87987. * FLAC__metadata_iterator_prev().
  87988. * - Get a block for reading or modification using
  87989. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87990. * inside the chain is returned, so the block is yours to modify.
  87991. * Changes will be reflected in the FLAC file when you write the
  87992. * chain. You can also add and delete blocks (see functions below).
  87993. * - When done, write out the chain using FLAC__metadata_chain_write().
  87994. * Make sure to read the whole comment to the function below.
  87995. * - Delete the chain using FLAC__metadata_chain_delete().
  87996. *
  87997. * \note
  87998. * Even though the FLAC file is not open while the chain is being
  87999. * manipulated, you must not alter the file externally during
  88000. * this time. The chain assumes the FLAC file will not change
  88001. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  88002. * and FLAC__metadata_chain_write().
  88003. *
  88004. * \note
  88005. * Do not modify the is_last, length, or type fields of returned
  88006. * FLAC__StreamMetadata objects. These are managed automatically.
  88007. *
  88008. * \note
  88009. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  88010. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  88011. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  88012. * become owned by the chain and they will be deleted when the chain is
  88013. * deleted.
  88014. *
  88015. * \{
  88016. */
  88017. struct FLAC__Metadata_Chain;
  88018. /** The opaque structure definition for the level 2 chain type.
  88019. */
  88020. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  88021. struct FLAC__Metadata_Iterator;
  88022. /** The opaque structure definition for the level 2 iterator type.
  88023. */
  88024. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  88025. typedef enum {
  88026. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  88027. /**< The chain is in the normal OK state */
  88028. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  88029. /**< The data passed into a function violated the function's usage criteria */
  88030. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  88031. /**< The chain could not open the target file */
  88032. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  88033. /**< The chain could not find the FLAC signature at the start of the file */
  88034. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  88035. /**< The chain tried to write to a file that was not writable */
  88036. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  88037. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  88038. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  88039. /**< The chain encountered an error while reading the FLAC file */
  88040. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  88041. /**< The chain encountered an error while seeking in the FLAC file */
  88042. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  88043. /**< The chain encountered an error while writing the FLAC file */
  88044. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  88045. /**< The chain encountered an error renaming the FLAC file */
  88046. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  88047. /**< The chain encountered an error removing the temporary file */
  88048. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  88049. /**< Memory allocation failed */
  88050. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  88051. /**< The caller violated an assertion or an unexpected error occurred */
  88052. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  88053. /**< One or more of the required callbacks was NULL */
  88054. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  88055. /**< FLAC__metadata_chain_write() was called on a chain read by
  88056. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88057. * or
  88058. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  88059. * was called on a chain read by
  88060. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88061. * Matching read/write methods must always be used. */
  88062. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  88063. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  88064. * chain write requires a tempfile; use
  88065. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  88066. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  88067. * called when the chain write does not require a tempfile; use
  88068. * FLAC__metadata_chain_write_with_callbacks() instead.
  88069. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  88070. * before writing via callbacks. */
  88071. } FLAC__Metadata_ChainStatus;
  88072. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  88073. *
  88074. * Using a FLAC__Metadata_ChainStatus as the index to this array
  88075. * will give the string equivalent. The contents should not be modified.
  88076. */
  88077. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  88078. /*********** FLAC__Metadata_Chain ***********/
  88079. /** Create a new chain instance.
  88080. *
  88081. * \retval FLAC__Metadata_Chain*
  88082. * \c NULL if there was an error allocating memory, else the new instance.
  88083. */
  88084. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88085. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88086. *
  88087. * \param chain A pointer to an existing chain.
  88088. * \assert
  88089. * \code chain != NULL \endcode
  88090. */
  88091. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88092. /** Get the current status of the chain. Call this after a function
  88093. * returns \c false to get the reason for the error. Also resets the
  88094. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88095. *
  88096. * \param chain A pointer to an existing chain.
  88097. * \assert
  88098. * \code chain != NULL \endcode
  88099. * \retval FLAC__Metadata_ChainStatus
  88100. * The current status of the chain.
  88101. */
  88102. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88103. /** Read all metadata from a FLAC file into the chain.
  88104. *
  88105. * \param chain A pointer to an existing chain.
  88106. * \param filename The path to the FLAC file to read.
  88107. * \assert
  88108. * \code chain != NULL \endcode
  88109. * \code filename != NULL \endcode
  88110. * \retval FLAC__bool
  88111. * \c true if a valid list of metadata blocks was read from
  88112. * \a filename, else \c false. On failure, check the status with
  88113. * FLAC__metadata_chain_status().
  88114. */
  88115. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88116. /** Read all metadata from an Ogg FLAC file into the chain.
  88117. *
  88118. * \note Ogg FLAC metadata data writing is not supported yet and
  88119. * FLAC__metadata_chain_write() will fail.
  88120. *
  88121. * \param chain A pointer to an existing chain.
  88122. * \param filename The path to the Ogg FLAC file to read.
  88123. * \assert
  88124. * \code chain != NULL \endcode
  88125. * \code filename != NULL \endcode
  88126. * \retval FLAC__bool
  88127. * \c true if a valid list of metadata blocks was read from
  88128. * \a filename, else \c false. On failure, check the status with
  88129. * FLAC__metadata_chain_status().
  88130. */
  88131. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88132. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88133. *
  88134. * The \a handle need only be open for reading, but must be seekable.
  88135. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88136. * for Windows).
  88137. *
  88138. * \param chain A pointer to an existing chain.
  88139. * \param handle The I/O handle of the FLAC stream to read. The
  88140. * handle will NOT be closed after the metadata is read;
  88141. * that is the duty of the caller.
  88142. * \param callbacks
  88143. * A set of callbacks to use for I/O. The mandatory
  88144. * callbacks are \a read, \a seek, and \a tell.
  88145. * \assert
  88146. * \code chain != NULL \endcode
  88147. * \retval FLAC__bool
  88148. * \c true if a valid list of metadata blocks was read from
  88149. * \a handle, else \c false. On failure, check the status with
  88150. * FLAC__metadata_chain_status().
  88151. */
  88152. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88153. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88154. *
  88155. * The \a handle need only be open for reading, but must be seekable.
  88156. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88157. * for Windows).
  88158. *
  88159. * \note Ogg FLAC metadata data writing is not supported yet and
  88160. * FLAC__metadata_chain_write() will fail.
  88161. *
  88162. * \param chain A pointer to an existing chain.
  88163. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88164. * handle will NOT be closed after the metadata is read;
  88165. * that is the duty of the caller.
  88166. * \param callbacks
  88167. * A set of callbacks to use for I/O. The mandatory
  88168. * callbacks are \a read, \a seek, and \a tell.
  88169. * \assert
  88170. * \code chain != NULL \endcode
  88171. * \retval FLAC__bool
  88172. * \c true if a valid list of metadata blocks was read from
  88173. * \a handle, else \c false. On failure, check the status with
  88174. * FLAC__metadata_chain_status().
  88175. */
  88176. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88177. /** Checks if writing the given chain would require the use of a
  88178. * temporary file, or if it could be written in place.
  88179. *
  88180. * Under certain conditions, padding can be utilized so that writing
  88181. * edited metadata back to the FLAC file does not require rewriting the
  88182. * entire file. If rewriting is required, then a temporary workfile is
  88183. * required. When writing metadata using callbacks, you must check
  88184. * this function to know whether to call
  88185. * FLAC__metadata_chain_write_with_callbacks() or
  88186. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88187. * writing with FLAC__metadata_chain_write(), the temporary file is
  88188. * handled internally.
  88189. *
  88190. * \param chain A pointer to an existing chain.
  88191. * \param use_padding
  88192. * Whether or not padding will be allowed to be used
  88193. * during the write. The value of \a use_padding given
  88194. * here must match the value later passed to
  88195. * FLAC__metadata_chain_write_with_callbacks() or
  88196. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88197. * \assert
  88198. * \code chain != NULL \endcode
  88199. * \retval FLAC__bool
  88200. * \c true if writing the current chain would require a tempfile, or
  88201. * \c false if metadata can be written in place.
  88202. */
  88203. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88204. /** Write all metadata out to the FLAC file. This function tries to be as
  88205. * efficient as possible; how the metadata is actually written is shown by
  88206. * the following:
  88207. *
  88208. * If the current chain is the same size as the existing metadata, the new
  88209. * data is written in place.
  88210. *
  88211. * If the current chain is longer than the existing metadata, and
  88212. * \a use_padding is \c true, and the last block is a PADDING block of
  88213. * sufficient length, the function will truncate the final padding block
  88214. * so that the overall size of the metadata is the same as the existing
  88215. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88216. * the above conditions are met, the entire FLAC file must be rewritten.
  88217. * If you want to use padding this way it is a good idea to call
  88218. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88219. * amount of padding to work with, unless you need to preserve ordering
  88220. * of the PADDING blocks for some reason.
  88221. *
  88222. * If the current chain is shorter than the existing metadata, and
  88223. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88224. * is extended to make the overall size the same as the existing data. If
  88225. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88226. * PADDING block is added to the end of the new data to make it the same
  88227. * size as the existing data (if possible, see the note to
  88228. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88229. * and the new data is written in place. If none of the above apply or
  88230. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88231. *
  88232. * If \a preserve_file_stats is \c true, the owner and modification time will
  88233. * be preserved even if the FLAC file is written.
  88234. *
  88235. * For this write function to be used, the chain must have been read with
  88236. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88237. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88238. *
  88239. * \param chain A pointer to an existing chain.
  88240. * \param use_padding See above.
  88241. * \param preserve_file_stats See above.
  88242. * \assert
  88243. * \code chain != NULL \endcode
  88244. * \retval FLAC__bool
  88245. * \c true if the write succeeded, else \c false. On failure,
  88246. * check the status with FLAC__metadata_chain_status().
  88247. */
  88248. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88249. /** Write all metadata out to a FLAC stream via callbacks.
  88250. *
  88251. * (See FLAC__metadata_chain_write() for the details on how padding is
  88252. * used to write metadata in place if possible.)
  88253. *
  88254. * The \a handle must be open for updating and be seekable. The
  88255. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88256. * for Windows).
  88257. *
  88258. * For this write function to be used, the chain must have been read with
  88259. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88260. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88261. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88262. * \c false.
  88263. *
  88264. * \param chain A pointer to an existing chain.
  88265. * \param use_padding See FLAC__metadata_chain_write()
  88266. * \param handle The I/O handle of the FLAC stream to write. The
  88267. * handle will NOT be closed after the metadata is
  88268. * written; that is the duty of the caller.
  88269. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88270. * callbacks are \a write and \a seek.
  88271. * \assert
  88272. * \code chain != NULL \endcode
  88273. * \retval FLAC__bool
  88274. * \c true if the write succeeded, else \c false. On failure,
  88275. * check the status with FLAC__metadata_chain_status().
  88276. */
  88277. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88278. /** Write all metadata out to a FLAC stream via callbacks.
  88279. *
  88280. * (See FLAC__metadata_chain_write() for the details on how padding is
  88281. * used to write metadata in place if possible.)
  88282. *
  88283. * This version of the write-with-callbacks function must be used when
  88284. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88285. * this function, you must supply an I/O handle corresponding to the
  88286. * FLAC file to edit, and a temporary handle to which the new FLAC
  88287. * file will be written. It is the caller's job to move this temporary
  88288. * FLAC file on top of the original FLAC file to complete the metadata
  88289. * edit.
  88290. *
  88291. * The \a handle must be open for reading and be seekable. The
  88292. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88293. * for Windows).
  88294. *
  88295. * The \a temp_handle must be open for writing. The
  88296. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88297. * for Windows). It should be an empty stream, or at least positioned
  88298. * at the start-of-file (in which case it is the caller's duty to
  88299. * truncate it on return).
  88300. *
  88301. * For this write function to be used, the chain must have been read with
  88302. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88303. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88304. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88305. * \c true.
  88306. *
  88307. * \param chain A pointer to an existing chain.
  88308. * \param use_padding See FLAC__metadata_chain_write()
  88309. * \param handle The I/O handle of the original FLAC stream to read.
  88310. * The handle will NOT be closed after the metadata is
  88311. * written; that is the duty of the caller.
  88312. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88313. * The mandatory callbacks are \a read, \a seek, and
  88314. * \a eof.
  88315. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88316. * handle will NOT be closed after the metadata is
  88317. * written; that is the duty of the caller.
  88318. * \param temp_callbacks
  88319. * A set of callbacks to use for I/O on temp_handle.
  88320. * The only mandatory callback is \a write.
  88321. * \assert
  88322. * \code chain != NULL \endcode
  88323. * \retval FLAC__bool
  88324. * \c true if the write succeeded, else \c false. On failure,
  88325. * check the status with FLAC__metadata_chain_status().
  88326. */
  88327. 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);
  88328. /** Merge adjacent PADDING blocks into a single block.
  88329. *
  88330. * \note This function does not write to the FLAC file, it only
  88331. * modifies the chain.
  88332. *
  88333. * \warning Any iterator on the current chain will become invalid after this
  88334. * call. You should delete the iterator and get a new one.
  88335. *
  88336. * \param chain A pointer to an existing chain.
  88337. * \assert
  88338. * \code chain != NULL \endcode
  88339. */
  88340. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88341. /** This function will move all PADDING blocks to the end on the metadata,
  88342. * then merge them into a single block.
  88343. *
  88344. * \note This function does not write to the FLAC file, it only
  88345. * modifies the chain.
  88346. *
  88347. * \warning Any iterator on the current chain will become invalid after this
  88348. * call. You should delete the iterator and get a new one.
  88349. *
  88350. * \param chain A pointer to an existing chain.
  88351. * \assert
  88352. * \code chain != NULL \endcode
  88353. */
  88354. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88355. /*********** FLAC__Metadata_Iterator ***********/
  88356. /** Create a new iterator instance.
  88357. *
  88358. * \retval FLAC__Metadata_Iterator*
  88359. * \c NULL if there was an error allocating memory, else the new instance.
  88360. */
  88361. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88362. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88363. *
  88364. * \param iterator A pointer to an existing iterator.
  88365. * \assert
  88366. * \code iterator != NULL \endcode
  88367. */
  88368. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88369. /** Initialize the iterator to point to the first metadata block in the
  88370. * given chain.
  88371. *
  88372. * \param iterator A pointer to an existing iterator.
  88373. * \param chain A pointer to an existing and initialized (read) chain.
  88374. * \assert
  88375. * \code iterator != NULL \endcode
  88376. * \code chain != NULL \endcode
  88377. */
  88378. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88379. /** Moves the iterator forward one metadata block, returning \c false if
  88380. * already at the end.
  88381. *
  88382. * \param iterator A pointer to an existing initialized iterator.
  88383. * \assert
  88384. * \code iterator != NULL \endcode
  88385. * \a iterator has been successfully initialized with
  88386. * FLAC__metadata_iterator_init()
  88387. * \retval FLAC__bool
  88388. * \c false if already at the last metadata block of the chain, else
  88389. * \c true.
  88390. */
  88391. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88392. /** Moves the iterator backward one metadata block, returning \c false if
  88393. * already at the beginning.
  88394. *
  88395. * \param iterator A pointer to an existing initialized iterator.
  88396. * \assert
  88397. * \code iterator != NULL \endcode
  88398. * \a iterator has been successfully initialized with
  88399. * FLAC__metadata_iterator_init()
  88400. * \retval FLAC__bool
  88401. * \c false if already at the first metadata block of the chain, else
  88402. * \c true.
  88403. */
  88404. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88405. /** Get the type of the metadata block at the current position.
  88406. *
  88407. * \param iterator A pointer to an existing initialized iterator.
  88408. * \assert
  88409. * \code iterator != NULL \endcode
  88410. * \a iterator has been successfully initialized with
  88411. * FLAC__metadata_iterator_init()
  88412. * \retval FLAC__MetadataType
  88413. * The type of the metadata block at the current iterator position.
  88414. */
  88415. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88416. /** Get the metadata block at the current position. You can modify
  88417. * the block in place but must write the chain before the changes
  88418. * are reflected to the FLAC file. You do not need to call
  88419. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88420. * the pointer returned by FLAC__metadata_iterator_get_block()
  88421. * points directly into the chain.
  88422. *
  88423. * \warning
  88424. * Do not call FLAC__metadata_object_delete() on the returned object;
  88425. * to delete a block use FLAC__metadata_iterator_delete_block().
  88426. *
  88427. * \param iterator A pointer to an existing initialized iterator.
  88428. * \assert
  88429. * \code iterator != NULL \endcode
  88430. * \a iterator has been successfully initialized with
  88431. * FLAC__metadata_iterator_init()
  88432. * \retval FLAC__StreamMetadata*
  88433. * The current metadata block.
  88434. */
  88435. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88436. /** Set the metadata block at the current position, replacing the existing
  88437. * block. The new block passed in becomes owned by the chain and it will be
  88438. * deleted when the chain is deleted.
  88439. *
  88440. * \param iterator A pointer to an existing initialized iterator.
  88441. * \param block A pointer to a metadata block.
  88442. * \assert
  88443. * \code iterator != NULL \endcode
  88444. * \a iterator has been successfully initialized with
  88445. * FLAC__metadata_iterator_init()
  88446. * \code block != NULL \endcode
  88447. * \retval FLAC__bool
  88448. * \c false if the conditions in the above description are not met, or
  88449. * a memory allocation error occurs, otherwise \c true.
  88450. */
  88451. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88452. /** Removes the current block from the chain. If \a replace_with_padding is
  88453. * \c true, the block will instead be replaced with a padding block of equal
  88454. * size. You can not delete the STREAMINFO block. The iterator will be
  88455. * left pointing to the block before the one just "deleted", even if
  88456. * \a replace_with_padding is \c true.
  88457. *
  88458. * \param iterator A pointer to an existing initialized iterator.
  88459. * \param replace_with_padding See above.
  88460. * \assert
  88461. * \code iterator != NULL \endcode
  88462. * \a iterator has been successfully initialized with
  88463. * FLAC__metadata_iterator_init()
  88464. * \retval FLAC__bool
  88465. * \c false if the conditions in the above description are not met,
  88466. * otherwise \c true.
  88467. */
  88468. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88469. /** Insert a new block before the current block. You cannot insert a block
  88470. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88471. * as there can be only one, the one that already exists at the head when you
  88472. * read in a chain. The chain takes ownership of the new block and it will be
  88473. * deleted when the chain is deleted. The iterator will be left pointing to
  88474. * the new block.
  88475. *
  88476. * \param iterator A pointer to an existing initialized iterator.
  88477. * \param block A pointer to a metadata block to insert.
  88478. * \assert
  88479. * \code iterator != NULL \endcode
  88480. * \a iterator has been successfully initialized with
  88481. * FLAC__metadata_iterator_init()
  88482. * \retval FLAC__bool
  88483. * \c false if the conditions in the above description are not met, or
  88484. * a memory allocation error occurs, otherwise \c true.
  88485. */
  88486. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88487. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88488. * block as there can be only one, the one that already exists at the head when
  88489. * you read in a chain. The chain takes ownership of the new block and it will
  88490. * be deleted when the chain is deleted. The iterator will be left pointing to
  88491. * the new block.
  88492. *
  88493. * \param iterator A pointer to an existing initialized iterator.
  88494. * \param block A pointer to a metadata block to insert.
  88495. * \assert
  88496. * \code iterator != NULL \endcode
  88497. * \a iterator has been successfully initialized with
  88498. * FLAC__metadata_iterator_init()
  88499. * \retval FLAC__bool
  88500. * \c false if the conditions in the above description are not met, or
  88501. * a memory allocation error occurs, otherwise \c true.
  88502. */
  88503. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88504. /* \} */
  88505. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88506. * \ingroup flac_metadata
  88507. *
  88508. * \brief
  88509. * This module contains methods for manipulating FLAC metadata objects.
  88510. *
  88511. * Since many are variable length we have to be careful about the memory
  88512. * management. We decree that all pointers to data in the object are
  88513. * owned by the object and memory-managed by the object.
  88514. *
  88515. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88516. * functions to create all instances. When using the
  88517. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88518. * \a copy to \c true to have the function make it's own copy of the data, or
  88519. * to \c false to give the object ownership of your data. In the latter case
  88520. * your pointer must be freeable by free() and will be free()d when the object
  88521. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88522. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88523. * the length argument is 0 and the \a copy argument is \c false.
  88524. *
  88525. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88526. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88527. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88528. * case of a memory allocation error.
  88529. *
  88530. * We don't have the convenience of C++ here, so note that the library relies
  88531. * on you to keep the types straight. In other words, if you pass, for
  88532. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88533. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88534. * failure.
  88535. *
  88536. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88537. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88538. * toward the length or stored in the stream, but it can make working with plain
  88539. * comments (those that don't contain embedded-NULs in the value) easier.
  88540. * Entries passed into these functions have trailing NULs added if missing, and
  88541. * returned entries are guaranteed to have a trailing NUL.
  88542. *
  88543. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88544. * comment entry/name/value will first validate that it complies with the Vorbis
  88545. * comment specification and return false if it does not.
  88546. *
  88547. * There is no need to recalculate the length field on metadata blocks you
  88548. * have modified. They will be calculated automatically before they are
  88549. * written back to a file.
  88550. *
  88551. * \{
  88552. */
  88553. /** Create a new metadata object instance of the given type.
  88554. *
  88555. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88556. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88557. * the vendor string set (but zero comments).
  88558. *
  88559. * Do not pass in a value greater than or equal to
  88560. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88561. * doing.
  88562. *
  88563. * \param type Type of object to create
  88564. * \retval FLAC__StreamMetadata*
  88565. * \c NULL if there was an error allocating memory or the type code is
  88566. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88567. */
  88568. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88569. /** Create a copy of an existing metadata object.
  88570. *
  88571. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88572. * object is also copied. The caller takes ownership of the new block and
  88573. * is responsible for freeing it with FLAC__metadata_object_delete().
  88574. *
  88575. * \param object Pointer to object to copy.
  88576. * \assert
  88577. * \code object != NULL \endcode
  88578. * \retval FLAC__StreamMetadata*
  88579. * \c NULL if there was an error allocating memory, else the new instance.
  88580. */
  88581. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88582. /** Free a metadata object. Deletes the object pointed to by \a object.
  88583. *
  88584. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88585. * object is also deleted.
  88586. *
  88587. * \param object A pointer to an existing object.
  88588. * \assert
  88589. * \code object != NULL \endcode
  88590. */
  88591. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88592. /** Compares two metadata objects.
  88593. *
  88594. * The compare is "deep", i.e. dynamically allocated data within the
  88595. * object is also compared.
  88596. *
  88597. * \param block1 A pointer to an existing object.
  88598. * \param block2 A pointer to an existing object.
  88599. * \assert
  88600. * \code block1 != NULL \endcode
  88601. * \code block2 != NULL \endcode
  88602. * \retval FLAC__bool
  88603. * \c true if objects are identical, else \c false.
  88604. */
  88605. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88606. /** Sets the application data of an APPLICATION block.
  88607. *
  88608. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88609. * takes ownership of the pointer. The existing data will be freed if this
  88610. * function is successful, otherwise the original data will remain if \a copy
  88611. * is \c true and malloc() fails.
  88612. *
  88613. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88614. *
  88615. * \param object A pointer to an existing APPLICATION object.
  88616. * \param data A pointer to the data to set.
  88617. * \param length The length of \a data in bytes.
  88618. * \param copy See above.
  88619. * \assert
  88620. * \code object != NULL \endcode
  88621. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88622. * \code (data != NULL && length > 0) ||
  88623. * (data == NULL && length == 0 && copy == false) \endcode
  88624. * \retval FLAC__bool
  88625. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88626. */
  88627. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88628. /** Resize the seekpoint array.
  88629. *
  88630. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88631. * points will be added to the end.
  88632. *
  88633. * \param object A pointer to an existing SEEKTABLE object.
  88634. * \param new_num_points The desired length of the array; may be \c 0.
  88635. * \assert
  88636. * \code object != NULL \endcode
  88637. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88638. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88639. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88640. * \retval FLAC__bool
  88641. * \c false if memory allocation error, else \c true.
  88642. */
  88643. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88644. /** Set a seekpoint in a seektable.
  88645. *
  88646. * \param object A pointer to an existing SEEKTABLE object.
  88647. * \param point_num Index into seekpoint array to set.
  88648. * \param point The point to set.
  88649. * \assert
  88650. * \code object != NULL \endcode
  88651. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88652. * \code object->data.seek_table.num_points > point_num \endcode
  88653. */
  88654. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88655. /** Insert a seekpoint into a seektable.
  88656. *
  88657. * \param object A pointer to an existing SEEKTABLE object.
  88658. * \param point_num Index into seekpoint array to set.
  88659. * \param point The point to set.
  88660. * \assert
  88661. * \code object != NULL \endcode
  88662. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88663. * \code object->data.seek_table.num_points >= point_num \endcode
  88664. * \retval FLAC__bool
  88665. * \c false if memory allocation error, else \c true.
  88666. */
  88667. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88668. /** Delete a seekpoint from a seektable.
  88669. *
  88670. * \param object A pointer to an existing SEEKTABLE object.
  88671. * \param point_num Index into seekpoint array to set.
  88672. * \assert
  88673. * \code object != NULL \endcode
  88674. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88675. * \code object->data.seek_table.num_points > point_num \endcode
  88676. * \retval FLAC__bool
  88677. * \c false if memory allocation error, else \c true.
  88678. */
  88679. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88680. /** Check a seektable to see if it conforms to the FLAC specification.
  88681. * See the format specification for limits on the contents of the
  88682. * seektable.
  88683. *
  88684. * \param object A pointer to an existing SEEKTABLE object.
  88685. * \assert
  88686. * \code object != NULL \endcode
  88687. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88688. * \retval FLAC__bool
  88689. * \c false if seek table is illegal, else \c true.
  88690. */
  88691. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88692. /** Append a number of placeholder points to the end of a seek table.
  88693. *
  88694. * \note
  88695. * As with the other ..._seektable_template_... functions, you should
  88696. * call FLAC__metadata_object_seektable_template_sort() when finished
  88697. * to make the seek table legal.
  88698. *
  88699. * \param object A pointer to an existing SEEKTABLE object.
  88700. * \param num The number of placeholder points to append.
  88701. * \assert
  88702. * \code object != NULL \endcode
  88703. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88704. * \retval FLAC__bool
  88705. * \c false if memory allocation fails, else \c true.
  88706. */
  88707. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88708. /** Append a specific seek point template to the end of a seek table.
  88709. *
  88710. * \note
  88711. * As with the other ..._seektable_template_... functions, you should
  88712. * call FLAC__metadata_object_seektable_template_sort() when finished
  88713. * to make the seek table legal.
  88714. *
  88715. * \param object A pointer to an existing SEEKTABLE object.
  88716. * \param sample_number The sample number of the seek point template.
  88717. * \assert
  88718. * \code object != NULL \endcode
  88719. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88720. * \retval FLAC__bool
  88721. * \c false if memory allocation fails, else \c true.
  88722. */
  88723. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88724. /** Append specific seek point templates to the end of a seek table.
  88725. *
  88726. * \note
  88727. * As with the other ..._seektable_template_... functions, you should
  88728. * call FLAC__metadata_object_seektable_template_sort() when finished
  88729. * to make the seek table legal.
  88730. *
  88731. * \param object A pointer to an existing SEEKTABLE object.
  88732. * \param sample_numbers An array of sample numbers for the seek points.
  88733. * \param num The number of seek point templates to append.
  88734. * \assert
  88735. * \code object != NULL \endcode
  88736. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88737. * \retval FLAC__bool
  88738. * \c false if memory allocation fails, else \c true.
  88739. */
  88740. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88741. /** Append a set of evenly-spaced seek point templates to the end of a
  88742. * seek table.
  88743. *
  88744. * \note
  88745. * As with the other ..._seektable_template_... functions, you should
  88746. * call FLAC__metadata_object_seektable_template_sort() when finished
  88747. * to make the seek table legal.
  88748. *
  88749. * \param object A pointer to an existing SEEKTABLE object.
  88750. * \param num The number of placeholder points to append.
  88751. * \param total_samples The total number of samples to be encoded;
  88752. * the seekpoints will be spaced approximately
  88753. * \a total_samples / \a num samples apart.
  88754. * \assert
  88755. * \code object != NULL \endcode
  88756. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88757. * \code total_samples > 0 \endcode
  88758. * \retval FLAC__bool
  88759. * \c false if memory allocation fails, else \c true.
  88760. */
  88761. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88762. /** Append a set of evenly-spaced seek point templates to the end of a
  88763. * seek table.
  88764. *
  88765. * \note
  88766. * As with the other ..._seektable_template_... functions, you should
  88767. * call FLAC__metadata_object_seektable_template_sort() when finished
  88768. * to make the seek table legal.
  88769. *
  88770. * \param object A pointer to an existing SEEKTABLE object.
  88771. * \param samples The number of samples apart to space the placeholder
  88772. * points. The first point will be at sample \c 0, the
  88773. * second at sample \a samples, then 2*\a samples, and
  88774. * so on. As long as \a samples and \a total_samples
  88775. * are greater than \c 0, there will always be at least
  88776. * one seekpoint at sample \c 0.
  88777. * \param total_samples The total number of samples to be encoded;
  88778. * the seekpoints will be spaced
  88779. * \a samples samples apart.
  88780. * \assert
  88781. * \code object != NULL \endcode
  88782. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88783. * \code samples > 0 \endcode
  88784. * \code total_samples > 0 \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_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88789. /** Sort a seek table's seek points according to the format specification,
  88790. * removing duplicates.
  88791. *
  88792. * \param object A pointer to a seek table to be sorted.
  88793. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88794. * If \c true, duplicates are deleted and the seek table is
  88795. * shrunk appropriately; the number of placeholder points
  88796. * present in the seek table will be the same after the call
  88797. * as before.
  88798. * \assert
  88799. * \code object != NULL \endcode
  88800. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88801. * \retval FLAC__bool
  88802. * \c false if realloc() fails, else \c true.
  88803. */
  88804. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88805. /** Sets the vendor string in a VORBIS_COMMENT block.
  88806. *
  88807. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88808. * one already.
  88809. *
  88810. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88811. * takes ownership of the \c entry.entry pointer.
  88812. *
  88813. * \note If this function returns \c false, the caller still owns the
  88814. * pointer.
  88815. *
  88816. * \param object A pointer to an existing VORBIS_COMMENT object.
  88817. * \param entry The entry to set the vendor string to.
  88818. * \param copy See above.
  88819. * \assert
  88820. * \code object != NULL \endcode
  88821. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88822. * \code (entry.entry != NULL && entry.length > 0) ||
  88823. * (entry.entry == NULL && entry.length == 0) \endcode
  88824. * \retval FLAC__bool
  88825. * \c false if memory allocation fails or \a entry does not comply with the
  88826. * Vorbis comment specification, else \c true.
  88827. */
  88828. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88829. /** Resize the comment array.
  88830. *
  88831. * If the size shrinks, elements will truncated; if it grows, new empty
  88832. * fields will be added to the end.
  88833. *
  88834. * \param object A pointer to an existing VORBIS_COMMENT object.
  88835. * \param new_num_comments The desired length of the array; may be \c 0.
  88836. * \assert
  88837. * \code object != NULL \endcode
  88838. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88839. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88840. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88841. * \retval FLAC__bool
  88842. * \c false if memory allocation fails, else \c true.
  88843. */
  88844. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88845. /** Sets a comment in a VORBIS_COMMENT block.
  88846. *
  88847. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88848. * one already.
  88849. *
  88850. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88851. * takes ownership of the \c entry.entry pointer.
  88852. *
  88853. * \note If this function returns \c false, the caller still owns the
  88854. * pointer.
  88855. *
  88856. * \param object A pointer to an existing VORBIS_COMMENT object.
  88857. * \param comment_num Index into comment array to set.
  88858. * \param entry The entry to set the comment to.
  88859. * \param copy See above.
  88860. * \assert
  88861. * \code object != NULL \endcode
  88862. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88863. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88864. * \code (entry.entry != NULL && entry.length > 0) ||
  88865. * (entry.entry == NULL && entry.length == 0) \endcode
  88866. * \retval FLAC__bool
  88867. * \c false if memory allocation fails or \a entry does not comply with the
  88868. * Vorbis comment specification, else \c true.
  88869. */
  88870. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88871. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88872. *
  88873. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88874. * one already.
  88875. *
  88876. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88877. * takes ownership of the \c entry.entry pointer.
  88878. *
  88879. * \note If this function returns \c false, the caller still owns the
  88880. * pointer.
  88881. *
  88882. * \param object A pointer to an existing VORBIS_COMMENT object.
  88883. * \param comment_num The index at which to insert the comment. The comments
  88884. * at and after \a comment_num move right one position.
  88885. * To append a comment to the end, set \a comment_num to
  88886. * \c object->data.vorbis_comment.num_comments .
  88887. * \param entry The comment to insert.
  88888. * \param copy See above.
  88889. * \assert
  88890. * \code object != NULL \endcode
  88891. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88892. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88893. * \code (entry.entry != NULL && entry.length > 0) ||
  88894. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88895. * \retval FLAC__bool
  88896. * \c false if memory allocation fails or \a entry does not comply with the
  88897. * Vorbis comment specification, else \c true.
  88898. */
  88899. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88900. /** Appends a comment to a VORBIS_COMMENT block.
  88901. *
  88902. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88903. * one already.
  88904. *
  88905. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88906. * takes ownership of the \c entry.entry pointer.
  88907. *
  88908. * \note If this function returns \c false, the caller still owns the
  88909. * pointer.
  88910. *
  88911. * \param object A pointer to an existing VORBIS_COMMENT object.
  88912. * \param entry The comment to insert.
  88913. * \param copy See above.
  88914. * \assert
  88915. * \code object != NULL \endcode
  88916. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88917. * \code (entry.entry != NULL && entry.length > 0) ||
  88918. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88919. * \retval FLAC__bool
  88920. * \c false if memory allocation fails or \a entry does not comply with the
  88921. * Vorbis comment specification, else \c true.
  88922. */
  88923. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88924. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88925. *
  88926. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88927. * one already.
  88928. *
  88929. * Depending on the the value of \a all, either all or just the first comment
  88930. * whose field name(s) match the given entry's name will be replaced by the
  88931. * given entry. If no comments match, \a entry will simply be appended.
  88932. *
  88933. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88934. * takes ownership of the \c entry.entry pointer.
  88935. *
  88936. * \note If this function returns \c false, the caller still owns the
  88937. * pointer.
  88938. *
  88939. * \param object A pointer to an existing VORBIS_COMMENT object.
  88940. * \param entry The comment to insert.
  88941. * \param all If \c true, all comments whose field name matches
  88942. * \a entry's field name will be removed, and \a entry will
  88943. * be inserted at the position of the first matching
  88944. * comment. If \c false, only the first comment whose
  88945. * field name matches \a entry's field name will be
  88946. * replaced with \a entry.
  88947. * \param copy See above.
  88948. * \assert
  88949. * \code object != NULL \endcode
  88950. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88951. * \code (entry.entry != NULL && entry.length > 0) ||
  88952. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88953. * \retval FLAC__bool
  88954. * \c false if memory allocation fails or \a entry does not comply with the
  88955. * Vorbis comment specification, else \c true.
  88956. */
  88957. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88958. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88959. *
  88960. * \param object A pointer to an existing VORBIS_COMMENT object.
  88961. * \param comment_num The index of the comment to delete.
  88962. * \assert
  88963. * \code object != NULL \endcode
  88964. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88965. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88966. * \retval FLAC__bool
  88967. * \c false if realloc() fails, else \c true.
  88968. */
  88969. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88970. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88971. *
  88972. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88973. * memory and shall be owned by the caller. For convenience the entry will
  88974. * have a terminating NUL.
  88975. *
  88976. * \param entry A pointer to a Vorbis comment entry. The entry's
  88977. * \c entry pointer should not point to allocated
  88978. * memory as it will be overwritten.
  88979. * \param field_name The field name in ASCII, \c NUL terminated.
  88980. * \param field_value The field value in UTF-8, \c NUL terminated.
  88981. * \assert
  88982. * \code entry != NULL \endcode
  88983. * \code field_name != NULL \endcode
  88984. * \code field_value != NULL \endcode
  88985. * \retval FLAC__bool
  88986. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88987. * not comply with the Vorbis comment specification, else \c true.
  88988. */
  88989. 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);
  88990. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88991. *
  88992. * The returned pointers to name and value will be allocated by malloc()
  88993. * and shall be owned by the caller.
  88994. *
  88995. * \param entry An existing Vorbis comment entry.
  88996. * \param field_name The address of where the returned pointer to the
  88997. * field name will be stored.
  88998. * \param field_value The address of where the returned pointer to the
  88999. * field value will be stored.
  89000. * \assert
  89001. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89002. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  89003. * \code field_name != NULL \endcode
  89004. * \code field_value != NULL \endcode
  89005. * \retval FLAC__bool
  89006. * \c false if memory allocation fails or \a entry does not comply with the
  89007. * Vorbis comment specification, else \c true.
  89008. */
  89009. 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);
  89010. /** Check if the given Vorbis comment entry's field name matches the given
  89011. * field name.
  89012. *
  89013. * \param entry An existing Vorbis comment entry.
  89014. * \param field_name The field name to check.
  89015. * \param field_name_length The length of \a field_name, not including the
  89016. * terminating \c NUL.
  89017. * \assert
  89018. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89019. * \retval FLAC__bool
  89020. * \c true if the field names match, else \c false
  89021. */
  89022. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  89023. /** Find a Vorbis comment with the given field name.
  89024. *
  89025. * The search begins at entry number \a offset; use an offset of 0 to
  89026. * search from the beginning of the comment array.
  89027. *
  89028. * \param object A pointer to an existing VORBIS_COMMENT object.
  89029. * \param offset The offset into the comment array from where to start
  89030. * the search.
  89031. * \param field_name The field name of the comment to find.
  89032. * \assert
  89033. * \code object != NULL \endcode
  89034. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89035. * \code field_name != NULL \endcode
  89036. * \retval int
  89037. * The offset in the comment array of the first comment whose field
  89038. * name matches \a field_name, or \c -1 if no match was found.
  89039. */
  89040. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  89041. /** Remove first Vorbis comment matching the given field name.
  89042. *
  89043. * \param object A pointer to an existing VORBIS_COMMENT object.
  89044. * \param field_name The field name of comment to delete.
  89045. * \assert
  89046. * \code object != NULL \endcode
  89047. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89048. * \retval int
  89049. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89050. * \c 1 for one matching entry deleted.
  89051. */
  89052. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  89053. /** Remove all Vorbis comments matching the given field name.
  89054. *
  89055. * \param object A pointer to an existing VORBIS_COMMENT object.
  89056. * \param field_name The field name of comments to delete.
  89057. * \assert
  89058. * \code object != NULL \endcode
  89059. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89060. * \retval int
  89061. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89062. * else the number of matching entries deleted.
  89063. */
  89064. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  89065. /** Create a new CUESHEET track instance.
  89066. *
  89067. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  89068. *
  89069. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89070. * \c NULL if there was an error allocating memory, else the new instance.
  89071. */
  89072. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  89073. /** Create a copy of an existing CUESHEET track object.
  89074. *
  89075. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  89076. * object is also copied. The caller takes ownership of the new object and
  89077. * is responsible for freeing it with
  89078. * FLAC__metadata_object_cuesheet_track_delete().
  89079. *
  89080. * \param object Pointer to object to copy.
  89081. * \assert
  89082. * \code object != NULL \endcode
  89083. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89084. * \c NULL if there was an error allocating memory, else the new instance.
  89085. */
  89086. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89087. /** Delete a CUESHEET track object
  89088. *
  89089. * \param object A pointer to an existing CUESHEET track object.
  89090. * \assert
  89091. * \code object != NULL \endcode
  89092. */
  89093. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89094. /** Resize a track's index point array.
  89095. *
  89096. * If the size shrinks, elements will truncated; if it grows, new blank
  89097. * indices will be added to the end.
  89098. *
  89099. * \param object A pointer to an existing CUESHEET object.
  89100. * \param track_num The index of the track to modify. NOTE: this is not
  89101. * necessarily the same as the track's \a number field.
  89102. * \param new_num_indices The desired length of the array; may be \c 0.
  89103. * \assert
  89104. * \code object != NULL \endcode
  89105. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89106. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89107. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89108. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89109. * \retval FLAC__bool
  89110. * \c false if memory allocation error, else \c true.
  89111. */
  89112. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89113. /** Insert an index point in a CUESHEET track at the given index.
  89114. *
  89115. * \param object A pointer to an existing CUESHEET object.
  89116. * \param track_num The index of the track to modify. NOTE: this is not
  89117. * necessarily the same as the track's \a number field.
  89118. * \param index_num The index into the track's index array at which to
  89119. * insert the index point. NOTE: this is not necessarily
  89120. * the same as the index point's \a number field. The
  89121. * indices at and after \a index_num move right one
  89122. * position. To append an index point to the end, set
  89123. * \a index_num to
  89124. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89125. * \param index The index point to insert.
  89126. * \assert
  89127. * \code object != NULL \endcode
  89128. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89129. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89130. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89131. * \retval FLAC__bool
  89132. * \c false if realloc() fails, else \c true.
  89133. */
  89134. 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);
  89135. /** Insert a blank index point in a CUESHEET track at the given index.
  89136. *
  89137. * A blank index point is one in which all field values are zero.
  89138. *
  89139. * \param object A pointer to an existing CUESHEET object.
  89140. * \param track_num The index of the track to modify. NOTE: this is not
  89141. * necessarily the same as the track's \a number field.
  89142. * \param index_num The index into the track's index array at which to
  89143. * insert the index point. NOTE: this is not necessarily
  89144. * the same as the index point's \a number field. The
  89145. * indices at and after \a index_num move right one
  89146. * position. To append an index point to the end, set
  89147. * \a index_num to
  89148. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89149. * \assert
  89150. * \code object != NULL \endcode
  89151. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89152. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89153. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89154. * \retval FLAC__bool
  89155. * \c false if realloc() fails, else \c true.
  89156. */
  89157. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89158. /** Delete an index point in a CUESHEET track at the given index.
  89159. *
  89160. * \param object A pointer to an existing CUESHEET object.
  89161. * \param track_num The index into the track array of the track to
  89162. * modify. NOTE: this is not necessarily the same
  89163. * as the track's \a number field.
  89164. * \param index_num The index into the track's index array of the index
  89165. * to delete. NOTE: this is not necessarily the same
  89166. * as the index's \a number field.
  89167. * \assert
  89168. * \code object != NULL \endcode
  89169. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89170. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89171. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89172. * \retval FLAC__bool
  89173. * \c false if realloc() fails, else \c true.
  89174. */
  89175. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89176. /** Resize the track array.
  89177. *
  89178. * If the size shrinks, elements will truncated; if it grows, new blank
  89179. * tracks will be added to the end.
  89180. *
  89181. * \param object A pointer to an existing CUESHEET object.
  89182. * \param new_num_tracks The desired length of the array; may be \c 0.
  89183. * \assert
  89184. * \code object != NULL \endcode
  89185. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89186. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89187. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89188. * \retval FLAC__bool
  89189. * \c false if memory allocation error, else \c true.
  89190. */
  89191. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89192. /** Sets a track in a CUESHEET block.
  89193. *
  89194. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89195. * takes ownership of the \a track pointer.
  89196. *
  89197. * \param object A pointer to an existing CUESHEET object.
  89198. * \param track_num Index into track array to set. NOTE: this is not
  89199. * necessarily the same as the track's \a number field.
  89200. * \param track The track to set the track to. You may safely pass in
  89201. * a const pointer if \a copy is \c true.
  89202. * \param copy See above.
  89203. * \assert
  89204. * \code object != NULL \endcode
  89205. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89206. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89207. * \code (track->indices != NULL && track->num_indices > 0) ||
  89208. * (track->indices == NULL && track->num_indices == 0)
  89209. * \retval FLAC__bool
  89210. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89211. */
  89212. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89213. /** Insert a track in a CUESHEET block at the given index.
  89214. *
  89215. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89216. * takes ownership of the \a track pointer.
  89217. *
  89218. * \param object A pointer to an existing CUESHEET object.
  89219. * \param track_num The index at which to insert the track. NOTE: this
  89220. * is not necessarily the same as the track's \a number
  89221. * field. The tracks at and after \a track_num move right
  89222. * one position. To append a track to the end, set
  89223. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89224. * \param track The track to insert. You may safely pass in a const
  89225. * pointer if \a copy is \c true.
  89226. * \param copy See above.
  89227. * \assert
  89228. * \code object != NULL \endcode
  89229. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89230. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89231. * \retval FLAC__bool
  89232. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89233. */
  89234. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89235. /** Insert a blank track in a CUESHEET block at the given index.
  89236. *
  89237. * A blank track is one in which all field values are zero.
  89238. *
  89239. * \param object A pointer to an existing CUESHEET object.
  89240. * \param track_num The index at which to insert the track. NOTE: this
  89241. * is not necessarily the same as the track's \a number
  89242. * field. The tracks at and after \a track_num move right
  89243. * one position. To append a track to the end, set
  89244. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89245. * \assert
  89246. * \code object != NULL \endcode
  89247. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89248. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89249. * \retval FLAC__bool
  89250. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89251. */
  89252. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89253. /** Delete a track in a CUESHEET block at the given index.
  89254. *
  89255. * \param object A pointer to an existing CUESHEET object.
  89256. * \param track_num The index into the track array of the track to
  89257. * delete. NOTE: this is not necessarily the same
  89258. * as the track's \a number field.
  89259. * \assert
  89260. * \code object != NULL \endcode
  89261. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89262. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89263. * \retval FLAC__bool
  89264. * \c false if realloc() fails, else \c true.
  89265. */
  89266. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89267. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89268. * See the format specification for limits on the contents of the
  89269. * cue sheet.
  89270. *
  89271. * \param object A pointer to an existing CUESHEET object.
  89272. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89273. * stringent requirements for a CD-DA (audio) disc.
  89274. * \param violation Address of a pointer to a string. If there is a
  89275. * violation, a pointer to a string explanation of the
  89276. * violation will be returned here. \a violation may be
  89277. * \c NULL if you don't need the returned string. Do not
  89278. * free the returned string; it will always point to static
  89279. * data.
  89280. * \assert
  89281. * \code object != NULL \endcode
  89282. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89283. * \retval FLAC__bool
  89284. * \c false if cue sheet is illegal, else \c true.
  89285. */
  89286. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89287. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89288. * assumes the cue sheet corresponds to a CD; the result is undefined
  89289. * if the cuesheet's is_cd bit is not set.
  89290. *
  89291. * \param object A pointer to an existing CUESHEET object.
  89292. * \assert
  89293. * \code object != NULL \endcode
  89294. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89295. * \retval FLAC__uint32
  89296. * The unsigned integer representation of the CDDB/freedb ID
  89297. */
  89298. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89299. /** Sets the MIME type of a PICTURE block.
  89300. *
  89301. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89302. * takes ownership of the pointer. The existing string will be freed if this
  89303. * function is successful, otherwise the original string will remain if \a copy
  89304. * is \c true and malloc() fails.
  89305. *
  89306. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89307. *
  89308. * \param object A pointer to an existing PICTURE object.
  89309. * \param mime_type A pointer to the MIME type string. The string must be
  89310. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89311. * is done.
  89312. * \param copy See above.
  89313. * \assert
  89314. * \code object != NULL \endcode
  89315. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89316. * \code (mime_type != NULL) \endcode
  89317. * \retval FLAC__bool
  89318. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89319. */
  89320. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89321. /** Sets the description of a PICTURE block.
  89322. *
  89323. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89324. * takes ownership of the pointer. The existing string will be freed if this
  89325. * function is successful, otherwise the original string will remain if \a copy
  89326. * is \c true and malloc() fails.
  89327. *
  89328. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89329. *
  89330. * \param object A pointer to an existing PICTURE object.
  89331. * \param description A pointer to the description string. The string must be
  89332. * valid UTF-8, NUL-terminated. No validation is done.
  89333. * \param copy See above.
  89334. * \assert
  89335. * \code object != NULL \endcode
  89336. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89337. * \code (description != NULL) \endcode
  89338. * \retval FLAC__bool
  89339. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89340. */
  89341. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89342. /** Sets the picture data of a PICTURE block.
  89343. *
  89344. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89345. * takes ownership of the pointer. Also sets the \a data_length field of the
  89346. * metadata object to what is passed in as the \a length parameter. The
  89347. * existing data will be freed if this function is successful, otherwise the
  89348. * original data and data_length will remain if \a copy is \c true and
  89349. * malloc() fails.
  89350. *
  89351. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89352. *
  89353. * \param object A pointer to an existing PICTURE object.
  89354. * \param data A pointer to the data to set.
  89355. * \param length The length of \a data in bytes.
  89356. * \param copy See above.
  89357. * \assert
  89358. * \code object != NULL \endcode
  89359. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89360. * \code (data != NULL && length > 0) ||
  89361. * (data == NULL && length == 0 && copy == false) \endcode
  89362. * \retval FLAC__bool
  89363. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89364. */
  89365. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89366. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89367. * See the format specification for limits on the contents of the
  89368. * PICTURE block.
  89369. *
  89370. * \param object A pointer to existing PICTURE block to be checked.
  89371. * \param violation Address of a pointer to a string. If there is a
  89372. * violation, a pointer to a string explanation of the
  89373. * violation will be returned here. \a violation may be
  89374. * \c NULL if you don't need the returned string. Do not
  89375. * free the returned string; it will always point to static
  89376. * data.
  89377. * \assert
  89378. * \code object != NULL \endcode
  89379. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89380. * \retval FLAC__bool
  89381. * \c false if PICTURE block is illegal, else \c true.
  89382. */
  89383. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89384. /* \} */
  89385. #ifdef __cplusplus
  89386. }
  89387. #endif
  89388. #endif
  89389. /*** End of inlined file: metadata.h ***/
  89390. /*** Start of inlined file: stream_decoder.h ***/
  89391. #ifndef FLAC__STREAM_DECODER_H
  89392. #define FLAC__STREAM_DECODER_H
  89393. #include <stdio.h> /* for FILE */
  89394. #ifdef __cplusplus
  89395. extern "C" {
  89396. #endif
  89397. /** \file include/FLAC/stream_decoder.h
  89398. *
  89399. * \brief
  89400. * This module contains the functions which implement the stream
  89401. * decoder.
  89402. *
  89403. * See the detailed documentation in the
  89404. * \link flac_stream_decoder stream decoder \endlink module.
  89405. */
  89406. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89407. * \ingroup flac
  89408. *
  89409. * \brief
  89410. * This module describes the decoder layers provided by libFLAC.
  89411. *
  89412. * The stream decoder can be used to decode complete streams either from
  89413. * the client via callbacks, or directly from a file, depending on how
  89414. * it is initialized. When decoding via callbacks, the client provides
  89415. * callbacks for reading FLAC data and writing decoded samples, and
  89416. * handling metadata and errors. If the client also supplies seek-related
  89417. * callback, the decoder function for sample-accurate seeking within the
  89418. * FLAC input is also available. When decoding from a file, the client
  89419. * needs only supply a filename or open \c FILE* and write/metadata/error
  89420. * callbacks; the rest of the callbacks are supplied internally. For more
  89421. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89422. */
  89423. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89424. * \ingroup flac_decoder
  89425. *
  89426. * \brief
  89427. * This module contains the functions which implement the stream
  89428. * decoder.
  89429. *
  89430. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89431. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89432. *
  89433. * The basic usage of this decoder is as follows:
  89434. * - The program creates an instance of a decoder using
  89435. * FLAC__stream_decoder_new().
  89436. * - The program overrides the default settings using
  89437. * FLAC__stream_decoder_set_*() functions.
  89438. * - The program initializes the instance to validate the settings and
  89439. * prepare for decoding using
  89440. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89441. * or FLAC__stream_decoder_init_file() for native FLAC,
  89442. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89443. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89444. * - The program calls the FLAC__stream_decoder_process_*() functions
  89445. * to decode data, which subsequently calls the callbacks.
  89446. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89447. * which flushes the input and output and resets the decoder to the
  89448. * uninitialized state.
  89449. * - The instance may be used again or deleted with
  89450. * FLAC__stream_decoder_delete().
  89451. *
  89452. * In more detail, the program will create a new instance by calling
  89453. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89454. * functions to override the default decoder options, and call
  89455. * one of the FLAC__stream_decoder_init_*() functions.
  89456. *
  89457. * There are three initialization functions for native FLAC, one for
  89458. * setting up the decoder to decode FLAC data from the client via
  89459. * callbacks, and two for decoding directly from a FLAC file.
  89460. *
  89461. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89462. * You must also supply several callbacks for handling I/O. Some (like
  89463. * seeking) are optional, depending on the capabilities of the input.
  89464. *
  89465. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89466. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89467. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89468. * the other callbacks internally.
  89469. *
  89470. * There are three similarly-named init functions for decoding from Ogg
  89471. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89472. * library has been built with Ogg support.
  89473. *
  89474. * Once the decoder is initialized, your program will call one of several
  89475. * functions to start the decoding process:
  89476. *
  89477. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89478. * most one metadata block or audio frame and return, calling either the
  89479. * metadata callback or write callback, respectively, once. If the decoder
  89480. * loses sync it will return with only the error callback being called.
  89481. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89482. * to process the stream from the current location and stop upon reaching
  89483. * the first audio frame. The client will get one metadata, write, or error
  89484. * callback per metadata block, audio frame, or sync error, respectively.
  89485. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89486. * to process the stream from the current location until the read callback
  89487. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89488. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89489. * write, or error callback per metadata block, audio frame, or sync error,
  89490. * respectively.
  89491. *
  89492. * When the decoder has finished decoding (normally or through an abort),
  89493. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89494. * ensures the decoder is in the correct state and frees memory. Then the
  89495. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89496. * again to decode another stream.
  89497. *
  89498. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89499. * At any point after the stream decoder has been initialized, the client can
  89500. * call this function to seek to an exact sample within the stream.
  89501. * Subsequently, the first time the write callback is called it will be
  89502. * passed a (possibly partial) block starting at that sample.
  89503. *
  89504. * If the client cannot seek via the callback interface provided, but still
  89505. * has another way of seeking, it can flush the decoder using
  89506. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89507. * through the read callback.
  89508. *
  89509. * The stream decoder also provides MD5 signature checking. If this is
  89510. * turned on before initialization, FLAC__stream_decoder_finish() will
  89511. * report when the decoded MD5 signature does not match the one stored
  89512. * in the STREAMINFO block. MD5 checking is automatically turned off
  89513. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89514. * in the STREAMINFO block or when a seek is attempted.
  89515. *
  89516. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89517. * attention. By default, the decoder only calls the metadata_callback for
  89518. * the STREAMINFO block. These functions allow you to tell the decoder
  89519. * explicitly which blocks to parse and return via the metadata_callback
  89520. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89521. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89522. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89523. * which blocks to return. Remember that metadata blocks can potentially
  89524. * be big (for example, cover art) so filtering out the ones you don't
  89525. * use can reduce the memory requirements of the decoder. Also note the
  89526. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89527. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89528. * filtering APPLICATION blocks based on the application ID.
  89529. *
  89530. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89531. * they still can legally be filtered from the metadata_callback.
  89532. *
  89533. * \note
  89534. * The "set" functions may only be called when the decoder is in the
  89535. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89536. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89537. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89538. * return \c true, otherwise \c false.
  89539. *
  89540. * \note
  89541. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89542. * defaults, including the callbacks.
  89543. *
  89544. * \{
  89545. */
  89546. /** State values for a FLAC__StreamDecoder
  89547. *
  89548. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89549. */
  89550. typedef enum {
  89551. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89552. /**< The decoder is ready to search for metadata. */
  89553. FLAC__STREAM_DECODER_READ_METADATA,
  89554. /**< The decoder is ready to or is in the process of reading metadata. */
  89555. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89556. /**< The decoder is ready to or is in the process of searching for the
  89557. * frame sync code.
  89558. */
  89559. FLAC__STREAM_DECODER_READ_FRAME,
  89560. /**< The decoder is ready to or is in the process of reading a frame. */
  89561. FLAC__STREAM_DECODER_END_OF_STREAM,
  89562. /**< The decoder has reached the end of the stream. */
  89563. FLAC__STREAM_DECODER_OGG_ERROR,
  89564. /**< An error occurred in the underlying Ogg layer. */
  89565. FLAC__STREAM_DECODER_SEEK_ERROR,
  89566. /**< An error occurred while seeking. The decoder must be flushed
  89567. * with FLAC__stream_decoder_flush() or reset with
  89568. * FLAC__stream_decoder_reset() before decoding can continue.
  89569. */
  89570. FLAC__STREAM_DECODER_ABORTED,
  89571. /**< The decoder was aborted by the read callback. */
  89572. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89573. /**< An error occurred allocating memory. The decoder is in an invalid
  89574. * state and can no longer be used.
  89575. */
  89576. FLAC__STREAM_DECODER_UNINITIALIZED
  89577. /**< The decoder is in the uninitialized state; one of the
  89578. * FLAC__stream_decoder_init_*() functions must be called before samples
  89579. * can be processed.
  89580. */
  89581. } FLAC__StreamDecoderState;
  89582. /** Maps a FLAC__StreamDecoderState to a C string.
  89583. *
  89584. * Using a FLAC__StreamDecoderState as the index to this array
  89585. * will give the string equivalent. The contents should not be modified.
  89586. */
  89587. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89588. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89589. */
  89590. typedef enum {
  89591. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89592. /**< Initialization was successful. */
  89593. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89594. /**< The library was not compiled with support for the given container
  89595. * format.
  89596. */
  89597. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89598. /**< A required callback was not supplied. */
  89599. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89600. /**< An error occurred allocating memory. */
  89601. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89602. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89603. * FLAC__stream_decoder_init_ogg_file(). */
  89604. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89605. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89606. * already initialized, usually because
  89607. * FLAC__stream_decoder_finish() was not called.
  89608. */
  89609. } FLAC__StreamDecoderInitStatus;
  89610. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89611. *
  89612. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89613. * will give the string equivalent. The contents should not be modified.
  89614. */
  89615. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89616. /** Return values for the FLAC__StreamDecoder read callback.
  89617. */
  89618. typedef enum {
  89619. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89620. /**< The read was OK and decoding can continue. */
  89621. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89622. /**< The read was attempted while at the end of the stream. Note that
  89623. * the client must only return this value when the read callback was
  89624. * called when already at the end of the stream. Otherwise, if the read
  89625. * itself moves to the end of the stream, the client should still return
  89626. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89627. * the next read callback it should return
  89628. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89629. * of \c 0.
  89630. */
  89631. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89632. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89633. } FLAC__StreamDecoderReadStatus;
  89634. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89635. *
  89636. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89637. * will give the string equivalent. The contents should not be modified.
  89638. */
  89639. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89640. /** Return values for the FLAC__StreamDecoder seek callback.
  89641. */
  89642. typedef enum {
  89643. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89644. /**< The seek was OK and decoding can continue. */
  89645. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89646. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89647. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89648. /**< Client does not support seeking. */
  89649. } FLAC__StreamDecoderSeekStatus;
  89650. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89651. *
  89652. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89653. * will give the string equivalent. The contents should not be modified.
  89654. */
  89655. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89656. /** Return values for the FLAC__StreamDecoder tell callback.
  89657. */
  89658. typedef enum {
  89659. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89660. /**< The tell was OK and decoding can continue. */
  89661. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89662. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89663. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89664. /**< Client does not support telling the position. */
  89665. } FLAC__StreamDecoderTellStatus;
  89666. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89667. *
  89668. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89669. * will give the string equivalent. The contents should not be modified.
  89670. */
  89671. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89672. /** Return values for the FLAC__StreamDecoder length callback.
  89673. */
  89674. typedef enum {
  89675. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89676. /**< The length call was OK and decoding can continue. */
  89677. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89678. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89679. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89680. /**< Client does not support reporting the length. */
  89681. } FLAC__StreamDecoderLengthStatus;
  89682. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89683. *
  89684. * Using a FLAC__StreamDecoderLengthStatus 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__StreamDecoderLengthStatusString[];
  89688. /** Return values for the FLAC__StreamDecoder write callback.
  89689. */
  89690. typedef enum {
  89691. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89692. /**< The write was OK and decoding can continue. */
  89693. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89694. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89695. } FLAC__StreamDecoderWriteStatus;
  89696. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89697. *
  89698. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89699. * will give the string equivalent. The contents should not be modified.
  89700. */
  89701. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89702. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89703. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89704. * all. The rest could be caused by bad sync (false synchronization on
  89705. * data that is not the start of a frame) or corrupted data. The error
  89706. * itself is the decoder's best guess at what happened assuming a correct
  89707. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89708. * could be caused by a correct sync on the start of a frame, but some
  89709. * data in the frame header was corrupted. Or it could be the result of
  89710. * syncing on a point the stream that looked like the starting of a frame
  89711. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89712. * could be because the decoder encountered a valid frame made by a future
  89713. * version of the encoder which it cannot parse, or because of a false
  89714. * sync making it appear as though an encountered frame was generated by
  89715. * a future encoder.
  89716. */
  89717. typedef enum {
  89718. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89719. /**< An error in the stream caused the decoder to lose synchronization. */
  89720. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89721. /**< The decoder encountered a corrupted frame header. */
  89722. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89723. /**< The frame's data did not match the CRC in the footer. */
  89724. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89725. /**< The decoder encountered reserved fields in use in the stream. */
  89726. } FLAC__StreamDecoderErrorStatus;
  89727. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89728. *
  89729. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89730. * will give the string equivalent. The contents should not be modified.
  89731. */
  89732. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89733. /***********************************************************************
  89734. *
  89735. * class FLAC__StreamDecoder
  89736. *
  89737. ***********************************************************************/
  89738. struct FLAC__StreamDecoderProtected;
  89739. struct FLAC__StreamDecoderPrivate;
  89740. /** The opaque structure definition for the stream decoder type.
  89741. * See the \link flac_stream_decoder stream decoder module \endlink
  89742. * for a detailed description.
  89743. */
  89744. typedef struct {
  89745. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89746. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89747. } FLAC__StreamDecoder;
  89748. /** Signature for the read callback.
  89749. *
  89750. * A function pointer matching this signature must be passed to
  89751. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89752. * called when the decoder needs more input data. The address of the
  89753. * buffer to be filled is supplied, along with the number of bytes the
  89754. * buffer can hold. The callback may choose to supply less data and
  89755. * modify the byte count but must be careful not to overflow the buffer.
  89756. * The callback then returns a status code chosen from
  89757. * FLAC__StreamDecoderReadStatus.
  89758. *
  89759. * Here is an example of a read callback for stdio streams:
  89760. * \code
  89761. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89762. * {
  89763. * FILE *file = ((MyClientData*)client_data)->file;
  89764. * if(*bytes > 0) {
  89765. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89766. * if(ferror(file))
  89767. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89768. * else if(*bytes == 0)
  89769. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89770. * else
  89771. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89772. * }
  89773. * else
  89774. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89775. * }
  89776. * \endcode
  89777. *
  89778. * \note In general, FLAC__StreamDecoder functions which change the
  89779. * state should not be called on the \a decoder while in the callback.
  89780. *
  89781. * \param decoder The decoder instance calling the callback.
  89782. * \param buffer A pointer to a location for the callee to store
  89783. * data to be decoded.
  89784. * \param bytes A pointer to the size of the buffer. On entry
  89785. * to the callback, it contains the maximum number
  89786. * of bytes that may be stored in \a buffer. The
  89787. * callee must set it to the actual number of bytes
  89788. * stored (0 in case of error or end-of-stream) before
  89789. * returning.
  89790. * \param client_data The callee's client data set through
  89791. * FLAC__stream_decoder_init_*().
  89792. * \retval FLAC__StreamDecoderReadStatus
  89793. * The callee's return status. Note that the callback should return
  89794. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89795. * zero bytes were read and there is no more data to be read.
  89796. */
  89797. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89798. /** Signature for the seek callback.
  89799. *
  89800. * A function pointer matching this signature may be passed to
  89801. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89802. * called when the decoder needs to seek the input stream. The decoder
  89803. * will pass the absolute byte offset to seek to, 0 meaning the
  89804. * beginning of the stream.
  89805. *
  89806. * Here is an example of a seek callback for stdio streams:
  89807. * \code
  89808. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89809. * {
  89810. * FILE *file = ((MyClientData*)client_data)->file;
  89811. * if(file == stdin)
  89812. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89813. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89814. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89815. * else
  89816. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89817. * }
  89818. * \endcode
  89819. *
  89820. * \note In general, FLAC__StreamDecoder functions which change the
  89821. * state should not be called on the \a decoder while in the callback.
  89822. *
  89823. * \param decoder The decoder instance calling the callback.
  89824. * \param absolute_byte_offset The offset from the beginning of the stream
  89825. * to seek to.
  89826. * \param client_data The callee's client data set through
  89827. * FLAC__stream_decoder_init_*().
  89828. * \retval FLAC__StreamDecoderSeekStatus
  89829. * The callee's return status.
  89830. */
  89831. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89832. /** Signature for the tell callback.
  89833. *
  89834. * A function pointer matching this signature may be passed to
  89835. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89836. * called when the decoder wants to know the current position of the
  89837. * stream. The callback should return the byte offset from the
  89838. * beginning of the stream.
  89839. *
  89840. * Here is an example of a tell callback for stdio streams:
  89841. * \code
  89842. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89843. * {
  89844. * FILE *file = ((MyClientData*)client_data)->file;
  89845. * off_t pos;
  89846. * if(file == stdin)
  89847. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89848. * else if((pos = ftello(file)) < 0)
  89849. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89850. * else {
  89851. * *absolute_byte_offset = (FLAC__uint64)pos;
  89852. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89853. * }
  89854. * }
  89855. * \endcode
  89856. *
  89857. * \note In general, FLAC__StreamDecoder functions which change the
  89858. * state should not be called on the \a decoder while in the callback.
  89859. *
  89860. * \param decoder The decoder instance calling the callback.
  89861. * \param absolute_byte_offset A pointer to storage for the current offset
  89862. * from the beginning of the stream.
  89863. * \param client_data The callee's client data set through
  89864. * FLAC__stream_decoder_init_*().
  89865. * \retval FLAC__StreamDecoderTellStatus
  89866. * The callee's return status.
  89867. */
  89868. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89869. /** Signature for the length callback.
  89870. *
  89871. * A function pointer matching this signature may be passed to
  89872. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89873. * called when the decoder wants to know the total length of the stream
  89874. * in bytes.
  89875. *
  89876. * Here is an example of a length callback for stdio streams:
  89877. * \code
  89878. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89879. * {
  89880. * FILE *file = ((MyClientData*)client_data)->file;
  89881. * struct stat filestats;
  89882. *
  89883. * if(file == stdin)
  89884. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89885. * else if(fstat(fileno(file), &filestats) != 0)
  89886. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89887. * else {
  89888. * *stream_length = (FLAC__uint64)filestats.st_size;
  89889. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89890. * }
  89891. * }
  89892. * \endcode
  89893. *
  89894. * \note In general, FLAC__StreamDecoder functions which change the
  89895. * state should not be called on the \a decoder while in the callback.
  89896. *
  89897. * \param decoder The decoder instance calling the callback.
  89898. * \param stream_length A pointer to storage for the length of the stream
  89899. * in bytes.
  89900. * \param client_data The callee's client data set through
  89901. * FLAC__stream_decoder_init_*().
  89902. * \retval FLAC__StreamDecoderLengthStatus
  89903. * The callee's return status.
  89904. */
  89905. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89906. /** Signature for the EOF callback.
  89907. *
  89908. * A function pointer matching this signature may be passed to
  89909. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89910. * called when the decoder needs to know if the end of the stream has
  89911. * been reached.
  89912. *
  89913. * Here is an example of a EOF callback for stdio streams:
  89914. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89915. * \code
  89916. * {
  89917. * FILE *file = ((MyClientData*)client_data)->file;
  89918. * return feof(file)? true : false;
  89919. * }
  89920. * \endcode
  89921. *
  89922. * \note In general, FLAC__StreamDecoder functions which change the
  89923. * state should not be called on the \a decoder while in the callback.
  89924. *
  89925. * \param decoder The decoder instance calling the callback.
  89926. * \param client_data The callee's client data set through
  89927. * FLAC__stream_decoder_init_*().
  89928. * \retval FLAC__bool
  89929. * \c true if the currently at the end of the stream, else \c false.
  89930. */
  89931. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89932. /** Signature for the write callback.
  89933. *
  89934. * A function pointer matching this signature must be passed to one of
  89935. * the FLAC__stream_decoder_init_*() functions.
  89936. * The supplied function will be called when the decoder has decoded a
  89937. * single audio frame. The decoder will pass the frame metadata as well
  89938. * as an array of pointers (one for each channel) pointing to the
  89939. * decoded audio.
  89940. *
  89941. * \note In general, FLAC__StreamDecoder functions which change the
  89942. * state should not be called on the \a decoder while in the callback.
  89943. *
  89944. * \param decoder The decoder instance calling the callback.
  89945. * \param frame The description of the decoded frame. See
  89946. * FLAC__Frame.
  89947. * \param buffer An array of pointers to decoded channels of data.
  89948. * Each pointer will point to an array of signed
  89949. * samples of length \a frame->header.blocksize.
  89950. * Channels will be ordered according to the FLAC
  89951. * specification; see the documentation for the
  89952. * <A HREF="../format.html#frame_header">frame header</A>.
  89953. * \param client_data The callee's client data set through
  89954. * FLAC__stream_decoder_init_*().
  89955. * \retval FLAC__StreamDecoderWriteStatus
  89956. * The callee's return status.
  89957. */
  89958. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89959. /** Signature for the metadata callback.
  89960. *
  89961. * A function pointer matching this signature must be passed to one of
  89962. * the FLAC__stream_decoder_init_*() functions.
  89963. * The supplied function will be called when the decoder has decoded a
  89964. * metadata block. In a valid FLAC file there will always be one
  89965. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89966. * These will be supplied by the decoder in the same order as they
  89967. * appear in the stream and always before the first audio frame (i.e.
  89968. * write callback). The metadata block that is passed in must not be
  89969. * modified, and it doesn't live beyond the callback, so you should make
  89970. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89971. * elsewhere. Since metadata blocks can potentially be large, by
  89972. * default the decoder only calls the metadata callback for the
  89973. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89974. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89975. *
  89976. * \note In general, FLAC__StreamDecoder functions which change the
  89977. * state should not be called on the \a decoder while in the callback.
  89978. *
  89979. * \param decoder The decoder instance calling the callback.
  89980. * \param metadata The decoded metadata block.
  89981. * \param client_data The callee's client data set through
  89982. * FLAC__stream_decoder_init_*().
  89983. */
  89984. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89985. /** Signature for the error callback.
  89986. *
  89987. * A function pointer matching this signature must be passed to one of
  89988. * the FLAC__stream_decoder_init_*() functions.
  89989. * The supplied function will be called whenever an error occurs during
  89990. * decoding.
  89991. *
  89992. * \note In general, FLAC__StreamDecoder functions which change the
  89993. * state should not be called on the \a decoder while in the callback.
  89994. *
  89995. * \param decoder The decoder instance calling the callback.
  89996. * \param status The error encountered by the decoder.
  89997. * \param client_data The callee's client data set through
  89998. * FLAC__stream_decoder_init_*().
  89999. */
  90000. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  90001. /***********************************************************************
  90002. *
  90003. * Class constructor/destructor
  90004. *
  90005. ***********************************************************************/
  90006. /** Create a new stream decoder instance. The instance is created with
  90007. * default settings; see the individual FLAC__stream_decoder_set_*()
  90008. * functions for each setting's default.
  90009. *
  90010. * \retval FLAC__StreamDecoder*
  90011. * \c NULL if there was an error allocating memory, else the new instance.
  90012. */
  90013. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  90014. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  90015. *
  90016. * \param decoder A pointer to an existing decoder.
  90017. * \assert
  90018. * \code decoder != NULL \endcode
  90019. */
  90020. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  90021. /***********************************************************************
  90022. *
  90023. * Public class method prototypes
  90024. *
  90025. ***********************************************************************/
  90026. /** Set the serial number for the FLAC stream within the Ogg container.
  90027. * The default behavior is to use the serial number of the first Ogg
  90028. * page. Setting a serial number here will explicitly specify which
  90029. * stream is to be decoded.
  90030. *
  90031. * \note
  90032. * This does not need to be set for native FLAC decoding.
  90033. *
  90034. * \default \c use serial number of first page
  90035. * \param decoder A decoder instance to set.
  90036. * \param serial_number See above.
  90037. * \assert
  90038. * \code decoder != NULL \endcode
  90039. * \retval FLAC__bool
  90040. * \c false if the decoder is already initialized, else \c true.
  90041. */
  90042. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  90043. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  90044. * compute the MD5 signature of the unencoded audio data while decoding
  90045. * and compare it to the signature from the STREAMINFO block, if it
  90046. * exists, during FLAC__stream_decoder_finish().
  90047. *
  90048. * MD5 signature checking will be turned off (until the next
  90049. * FLAC__stream_decoder_reset()) if there is no signature in the
  90050. * STREAMINFO block or when a seek is attempted.
  90051. *
  90052. * Clients that do not use the MD5 check should leave this off to speed
  90053. * up decoding.
  90054. *
  90055. * \default \c false
  90056. * \param decoder A decoder instance to set.
  90057. * \param value Flag value (see above).
  90058. * \assert
  90059. * \code decoder != NULL \endcode
  90060. * \retval FLAC__bool
  90061. * \c false if the decoder is already initialized, else \c true.
  90062. */
  90063. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  90064. /** Direct the decoder to pass on all metadata blocks of type \a type.
  90065. *
  90066. * \default By default, only the \c STREAMINFO block is returned via the
  90067. * metadata callback.
  90068. * \param decoder A decoder instance to set.
  90069. * \param type See above.
  90070. * \assert
  90071. * \code decoder != NULL \endcode
  90072. * \a type is valid
  90073. * \retval FLAC__bool
  90074. * \c false if the decoder is already initialized, else \c true.
  90075. */
  90076. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90077. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  90078. * given \a id.
  90079. *
  90080. * \default By default, only the \c STREAMINFO block is returned via the
  90081. * metadata callback.
  90082. * \param decoder A decoder instance to set.
  90083. * \param id See above.
  90084. * \assert
  90085. * \code decoder != NULL \endcode
  90086. * \code id != 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_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90091. /** Direct the decoder to pass on all metadata blocks of any type.
  90092. *
  90093. * \default By default, only the \c STREAMINFO block is returned via the
  90094. * metadata callback.
  90095. * \param decoder A decoder instance to set.
  90096. * \assert
  90097. * \code decoder != NULL \endcode
  90098. * \retval FLAC__bool
  90099. * \c false if the decoder is already initialized, else \c true.
  90100. */
  90101. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90102. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90103. *
  90104. * \default By default, only the \c STREAMINFO block is returned via the
  90105. * metadata callback.
  90106. * \param decoder A decoder instance to set.
  90107. * \param type See above.
  90108. * \assert
  90109. * \code decoder != NULL \endcode
  90110. * \a type is valid
  90111. * \retval FLAC__bool
  90112. * \c false if the decoder is already initialized, else \c true.
  90113. */
  90114. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90115. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90116. * the given \a id.
  90117. *
  90118. * \default By default, only the \c STREAMINFO block is returned via the
  90119. * metadata callback.
  90120. * \param decoder A decoder instance to set.
  90121. * \param id See above.
  90122. * \assert
  90123. * \code decoder != NULL \endcode
  90124. * \code id != NULL \endcode
  90125. * \retval FLAC__bool
  90126. * \c false if the decoder is already initialized, else \c true.
  90127. */
  90128. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90129. /** Direct the decoder to filter out all metadata blocks of any type.
  90130. *
  90131. * \default By default, only the \c STREAMINFO block is returned via the
  90132. * metadata callback.
  90133. * \param decoder A decoder instance to set.
  90134. * \assert
  90135. * \code decoder != NULL \endcode
  90136. * \retval FLAC__bool
  90137. * \c false if the decoder is already initialized, else \c true.
  90138. */
  90139. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90140. /** Get the current decoder state.
  90141. *
  90142. * \param decoder A decoder instance to query.
  90143. * \assert
  90144. * \code decoder != NULL \endcode
  90145. * \retval FLAC__StreamDecoderState
  90146. * The current decoder state.
  90147. */
  90148. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90149. /** Get the current decoder state as a C string.
  90150. *
  90151. * \param decoder A decoder instance to query.
  90152. * \assert
  90153. * \code decoder != NULL \endcode
  90154. * \retval const char *
  90155. * The decoder state as a C string. Do not modify the contents.
  90156. */
  90157. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90158. /** Get the "MD5 signature checking" flag.
  90159. * This is the value of the setting, not whether or not the decoder is
  90160. * currently checking the MD5 (remember, it can be turned off automatically
  90161. * by a seek). When the decoder is reset the flag will be restored to the
  90162. * value returned by this function.
  90163. *
  90164. * \param decoder A decoder instance to query.
  90165. * \assert
  90166. * \code decoder != NULL \endcode
  90167. * \retval FLAC__bool
  90168. * See above.
  90169. */
  90170. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90171. /** Get the total number of samples in the stream being decoded.
  90172. * Will only be valid after decoding has started and will contain the
  90173. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90174. *
  90175. * \param decoder A decoder instance to query.
  90176. * \assert
  90177. * \code decoder != NULL \endcode
  90178. * \retval unsigned
  90179. * See above.
  90180. */
  90181. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90182. /** Get the current number of channels in the stream being decoded.
  90183. * Will only be valid after decoding has started and will contain the
  90184. * value from the most recently decoded frame header.
  90185. *
  90186. * \param decoder A decoder instance to query.
  90187. * \assert
  90188. * \code decoder != NULL \endcode
  90189. * \retval unsigned
  90190. * See above.
  90191. */
  90192. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90193. /** Get the current channel assignment in the stream being decoded.
  90194. * Will only be valid after decoding has started and will contain the
  90195. * value from the most recently decoded frame header.
  90196. *
  90197. * \param decoder A decoder instance to query.
  90198. * \assert
  90199. * \code decoder != NULL \endcode
  90200. * \retval FLAC__ChannelAssignment
  90201. * See above.
  90202. */
  90203. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90204. /** Get the current sample resolution in the stream being decoded.
  90205. * Will only be valid after decoding has started and will contain the
  90206. * value from the most recently decoded frame header.
  90207. *
  90208. * \param decoder A decoder instance to query.
  90209. * \assert
  90210. * \code decoder != NULL \endcode
  90211. * \retval unsigned
  90212. * See above.
  90213. */
  90214. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90215. /** Get the current sample rate in Hz of the stream being decoded.
  90216. * Will only be valid after decoding has started and will contain the
  90217. * value from the most recently decoded frame header.
  90218. *
  90219. * \param decoder A decoder instance to query.
  90220. * \assert
  90221. * \code decoder != NULL \endcode
  90222. * \retval unsigned
  90223. * See above.
  90224. */
  90225. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90226. /** Get the current blocksize of the stream being decoded.
  90227. * Will only be valid after decoding has started and will contain the
  90228. * value from the most recently decoded frame header.
  90229. *
  90230. * \param decoder A decoder instance to query.
  90231. * \assert
  90232. * \code decoder != NULL \endcode
  90233. * \retval unsigned
  90234. * See above.
  90235. */
  90236. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90237. /** Returns the decoder's current read position within the stream.
  90238. * The position is the byte offset from the start of the stream.
  90239. * Bytes before this position have been fully decoded. Note that
  90240. * there may still be undecoded bytes in the decoder's read FIFO.
  90241. * The returned position is correct even after a seek.
  90242. *
  90243. * \warning This function currently only works for native FLAC,
  90244. * not Ogg FLAC streams.
  90245. *
  90246. * \param decoder A decoder instance to query.
  90247. * \param position Address at which to return the desired position.
  90248. * \assert
  90249. * \code decoder != NULL \endcode
  90250. * \code position != NULL \endcode
  90251. * \retval FLAC__bool
  90252. * \c true if successful, \c false if the stream is not native FLAC,
  90253. * or there was an error from the 'tell' callback or it returned
  90254. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90255. */
  90256. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90257. /** Initialize the decoder instance to decode native FLAC streams.
  90258. *
  90259. * This flavor of initialization sets up the decoder to decode from a
  90260. * native FLAC stream. I/O is performed via callbacks to the client.
  90261. * For decoding from a plain file via filename or open FILE*,
  90262. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90263. * provide a simpler interface.
  90264. *
  90265. * This function should be called after FLAC__stream_decoder_new() and
  90266. * FLAC__stream_decoder_set_*() but before any of the
  90267. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90268. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90269. * if initialization succeeded.
  90270. *
  90271. * \param decoder An uninitialized decoder instance.
  90272. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90273. * pointer must not be \c NULL.
  90274. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90275. * pointer may be \c NULL if seeking is not
  90276. * supported. If \a seek_callback is not \c NULL then a
  90277. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90278. * Alternatively, a dummy seek callback that just
  90279. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90280. * may also be supplied, all though this is slightly
  90281. * less efficient for the decoder.
  90282. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90283. * pointer may be \c NULL if not supported by the client. If
  90284. * \a seek_callback is not \c NULL then a
  90285. * \a tell_callback must also be supplied.
  90286. * Alternatively, a dummy tell callback that just
  90287. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90288. * may also be supplied, all though this is slightly
  90289. * less efficient for the decoder.
  90290. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90291. * pointer may be \c NULL if not supported by the client. If
  90292. * \a seek_callback is not \c NULL then a
  90293. * \a length_callback must also be supplied.
  90294. * Alternatively, a dummy length callback that just
  90295. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90296. * may also be supplied, all though this is slightly
  90297. * less efficient for the decoder.
  90298. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90299. * pointer may be \c NULL if not supported by the client. If
  90300. * \a seek_callback is not \c NULL then a
  90301. * \a eof_callback must also be supplied.
  90302. * Alternatively, a dummy length callback that just
  90303. * returns \c false
  90304. * may also be supplied, all though this is slightly
  90305. * less efficient for the decoder.
  90306. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90307. * pointer must not be \c NULL.
  90308. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90309. * pointer may be \c NULL if the callback is not
  90310. * desired.
  90311. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90312. * pointer must not be \c NULL.
  90313. * \param client_data This value will be supplied to callbacks in their
  90314. * \a client_data argument.
  90315. * \assert
  90316. * \code decoder != NULL \endcode
  90317. * \retval FLAC__StreamDecoderInitStatus
  90318. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90319. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90320. */
  90321. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90322. FLAC__StreamDecoder *decoder,
  90323. FLAC__StreamDecoderReadCallback read_callback,
  90324. FLAC__StreamDecoderSeekCallback seek_callback,
  90325. FLAC__StreamDecoderTellCallback tell_callback,
  90326. FLAC__StreamDecoderLengthCallback length_callback,
  90327. FLAC__StreamDecoderEofCallback eof_callback,
  90328. FLAC__StreamDecoderWriteCallback write_callback,
  90329. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90330. FLAC__StreamDecoderErrorCallback error_callback,
  90331. void *client_data
  90332. );
  90333. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90334. *
  90335. * This flavor of initialization sets up the decoder to decode from a
  90336. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90337. * client. For decoding from a plain file via filename or open FILE*,
  90338. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90339. * provide a simpler interface.
  90340. *
  90341. * This function should be called after FLAC__stream_decoder_new() and
  90342. * FLAC__stream_decoder_set_*() but before any of the
  90343. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90344. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90345. * if initialization succeeded.
  90346. *
  90347. * \note Support for Ogg FLAC in the library is optional. If this
  90348. * library has been built without support for Ogg FLAC, this function
  90349. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90350. *
  90351. * \param decoder An uninitialized decoder instance.
  90352. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90353. * pointer must not be \c NULL.
  90354. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90355. * pointer may be \c NULL if seeking is not
  90356. * supported. If \a seek_callback is not \c NULL then a
  90357. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90358. * Alternatively, a dummy seek callback that just
  90359. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90360. * may also be supplied, all though this is slightly
  90361. * less efficient for the decoder.
  90362. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90363. * pointer may be \c NULL if not supported by the client. If
  90364. * \a seek_callback is not \c NULL then a
  90365. * \a tell_callback must also be supplied.
  90366. * Alternatively, a dummy tell callback that just
  90367. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90368. * may also be supplied, all though this is slightly
  90369. * less efficient for the decoder.
  90370. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90371. * pointer may be \c NULL if not supported by the client. If
  90372. * \a seek_callback is not \c NULL then a
  90373. * \a length_callback must also be supplied.
  90374. * Alternatively, a dummy length callback that just
  90375. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90376. * may also be supplied, all though this is slightly
  90377. * less efficient for the decoder.
  90378. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90379. * pointer may be \c NULL if not supported by the client. If
  90380. * \a seek_callback is not \c NULL then a
  90381. * \a eof_callback must also be supplied.
  90382. * Alternatively, a dummy length callback that just
  90383. * returns \c false
  90384. * may also be supplied, all though this is slightly
  90385. * less efficient for the decoder.
  90386. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90387. * pointer must not be \c NULL.
  90388. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90389. * pointer may be \c NULL if the callback is not
  90390. * desired.
  90391. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90392. * pointer must not be \c NULL.
  90393. * \param client_data This value will be supplied to callbacks in their
  90394. * \a client_data argument.
  90395. * \assert
  90396. * \code decoder != NULL \endcode
  90397. * \retval FLAC__StreamDecoderInitStatus
  90398. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90399. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90400. */
  90401. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90402. FLAC__StreamDecoder *decoder,
  90403. FLAC__StreamDecoderReadCallback read_callback,
  90404. FLAC__StreamDecoderSeekCallback seek_callback,
  90405. FLAC__StreamDecoderTellCallback tell_callback,
  90406. FLAC__StreamDecoderLengthCallback length_callback,
  90407. FLAC__StreamDecoderEofCallback eof_callback,
  90408. FLAC__StreamDecoderWriteCallback write_callback,
  90409. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90410. FLAC__StreamDecoderErrorCallback error_callback,
  90411. void *client_data
  90412. );
  90413. /** Initialize the decoder instance to decode native FLAC files.
  90414. *
  90415. * This flavor of initialization sets up the decoder to decode from a
  90416. * plain native FLAC file. For non-stdio streams, you must use
  90417. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90418. *
  90419. * This function should be called after FLAC__stream_decoder_new() and
  90420. * FLAC__stream_decoder_set_*() but before any of the
  90421. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90422. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90423. * if initialization succeeded.
  90424. *
  90425. * \param decoder An uninitialized decoder instance.
  90426. * \param file An open FLAC file. The file should have been
  90427. * opened with mode \c "rb" and rewound. The file
  90428. * becomes owned by the decoder and should not be
  90429. * manipulated by the client while decoding.
  90430. * Unless \a file is \c stdin, it will be closed
  90431. * when FLAC__stream_decoder_finish() is called.
  90432. * Note however that seeking will not work when
  90433. * decoding from \c stdout since it is not seekable.
  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. * \code file != NULL \endcode
  90446. * \retval FLAC__StreamDecoderInitStatus
  90447. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90448. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90449. */
  90450. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90451. FLAC__StreamDecoder *decoder,
  90452. FILE *file,
  90453. FLAC__StreamDecoderWriteCallback write_callback,
  90454. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90455. FLAC__StreamDecoderErrorCallback error_callback,
  90456. void *client_data
  90457. );
  90458. /** Initialize the decoder instance to decode Ogg FLAC files.
  90459. *
  90460. * This flavor of initialization sets up the decoder to decode from a
  90461. * plain Ogg FLAC file. For non-stdio streams, you must use
  90462. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90463. *
  90464. * This function should be called after FLAC__stream_decoder_new() and
  90465. * FLAC__stream_decoder_set_*() but before any of the
  90466. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90467. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90468. * if initialization succeeded.
  90469. *
  90470. * \note Support for Ogg FLAC in the library is optional. If this
  90471. * library has been built without support for Ogg FLAC, this function
  90472. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90473. *
  90474. * \param decoder An uninitialized decoder instance.
  90475. * \param file An open FLAC file. The file should have been
  90476. * opened with mode \c "rb" and rewound. The file
  90477. * becomes owned by the decoder and should not be
  90478. * manipulated by the client while decoding.
  90479. * Unless \a file is \c stdin, it will be closed
  90480. * when FLAC__stream_decoder_finish() is called.
  90481. * Note however that seeking will not work when
  90482. * decoding from \c stdout since it is not seekable.
  90483. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90484. * pointer must not be \c NULL.
  90485. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90486. * pointer may be \c NULL if the callback is not
  90487. * desired.
  90488. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90489. * pointer must not be \c NULL.
  90490. * \param client_data This value will be supplied to callbacks in their
  90491. * \a client_data argument.
  90492. * \assert
  90493. * \code decoder != NULL \endcode
  90494. * \code file != NULL \endcode
  90495. * \retval FLAC__StreamDecoderInitStatus
  90496. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90497. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90498. */
  90499. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90500. FLAC__StreamDecoder *decoder,
  90501. FILE *file,
  90502. FLAC__StreamDecoderWriteCallback write_callback,
  90503. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90504. FLAC__StreamDecoderErrorCallback error_callback,
  90505. void *client_data
  90506. );
  90507. /** Initialize the decoder instance to decode native FLAC files.
  90508. *
  90509. * This flavor of initialization sets up the decoder to decode from a plain
  90510. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90511. * example, with Unicode filenames on Windows), you must use
  90512. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90513. * and provide callbacks for the I/O.
  90514. *
  90515. * This function should be called after FLAC__stream_decoder_new() and
  90516. * FLAC__stream_decoder_set_*() but before any of the
  90517. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90518. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90519. * if initialization succeeded.
  90520. *
  90521. * \param decoder An uninitialized decoder instance.
  90522. * \param filename The name of the file to decode from. The file will
  90523. * be opened with fopen(). Use \c NULL to decode from
  90524. * \c stdin. Note that \c stdin is not seekable.
  90525. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90526. * pointer must not be \c NULL.
  90527. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90528. * pointer may be \c NULL if the callback is not
  90529. * desired.
  90530. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90531. * pointer must not be \c NULL.
  90532. * \param client_data This value will be supplied to callbacks in their
  90533. * \a client_data argument.
  90534. * \assert
  90535. * \code decoder != NULL \endcode
  90536. * \retval FLAC__StreamDecoderInitStatus
  90537. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90538. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90539. */
  90540. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90541. FLAC__StreamDecoder *decoder,
  90542. const char *filename,
  90543. FLAC__StreamDecoderWriteCallback write_callback,
  90544. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90545. FLAC__StreamDecoderErrorCallback error_callback,
  90546. void *client_data
  90547. );
  90548. /** Initialize the decoder instance to decode Ogg FLAC files.
  90549. *
  90550. * This flavor of initialization sets up the decoder to decode from a plain
  90551. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90552. * example, with Unicode filenames on Windows), you must use
  90553. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90554. * and provide callbacks for the I/O.
  90555. *
  90556. * This function should be called after FLAC__stream_decoder_new() and
  90557. * FLAC__stream_decoder_set_*() but before any of the
  90558. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90559. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90560. * if initialization succeeded.
  90561. *
  90562. * \note Support for Ogg FLAC in the library is optional. If this
  90563. * library has been built without support for Ogg FLAC, this function
  90564. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90565. *
  90566. * \param decoder An uninitialized decoder instance.
  90567. * \param filename The name of the file to decode from. The file will
  90568. * be opened with fopen(). Use \c NULL to decode from
  90569. * \c stdin. Note that \c stdin is not seekable.
  90570. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90571. * pointer must not be \c NULL.
  90572. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90573. * pointer may be \c NULL if the callback is not
  90574. * desired.
  90575. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90576. * pointer must not be \c NULL.
  90577. * \param client_data This value will be supplied to callbacks in their
  90578. * \a client_data argument.
  90579. * \assert
  90580. * \code decoder != NULL \endcode
  90581. * \retval FLAC__StreamDecoderInitStatus
  90582. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90583. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90584. */
  90585. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90586. FLAC__StreamDecoder *decoder,
  90587. const char *filename,
  90588. FLAC__StreamDecoderWriteCallback write_callback,
  90589. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90590. FLAC__StreamDecoderErrorCallback error_callback,
  90591. void *client_data
  90592. );
  90593. /** Finish the decoding process.
  90594. * Flushes the decoding buffer, releases resources, resets the decoder
  90595. * settings to their defaults, and returns the decoder state to
  90596. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90597. *
  90598. * In the event of a prematurely-terminated decode, it is not strictly
  90599. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90600. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90601. * with a FLAC__stream_decoder_finish().
  90602. *
  90603. * \param decoder An uninitialized decoder instance.
  90604. * \assert
  90605. * \code decoder != NULL \endcode
  90606. * \retval FLAC__bool
  90607. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90608. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90609. * signature does not match the one computed by the decoder; else
  90610. * \c true.
  90611. */
  90612. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90613. /** Flush the stream input.
  90614. * The decoder's input buffer will be cleared and the state set to
  90615. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90616. * off MD5 checking.
  90617. *
  90618. * \param decoder A decoder instance.
  90619. * \assert
  90620. * \code decoder != NULL \endcode
  90621. * \retval FLAC__bool
  90622. * \c true if successful, else \c false if a memory allocation
  90623. * error occurs (in which case the state will be set to
  90624. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90625. */
  90626. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90627. /** Reset the decoding process.
  90628. * The decoder's input buffer will be cleared and the state set to
  90629. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90630. * FLAC__stream_decoder_finish() except that the settings are
  90631. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90632. * before decoding again. MD5 checking will be restored to its original
  90633. * setting.
  90634. *
  90635. * If the decoder is seekable, or was initialized with
  90636. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90637. * the decoder will also attempt to seek to the beginning of the file.
  90638. * If this rewind fails, this function will return \c false. It follows
  90639. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90640. * \c stdin.
  90641. *
  90642. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90643. * and is not seekable (i.e. no seek callback was provided or the seek
  90644. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90645. * is the duty of the client to start feeding data from the beginning of
  90646. * the stream on the next FLAC__stream_decoder_process() or
  90647. * FLAC__stream_decoder_process_interleaved() call.
  90648. *
  90649. * \param decoder A decoder instance.
  90650. * \assert
  90651. * \code decoder != NULL \endcode
  90652. * \retval FLAC__bool
  90653. * \c true if successful, else \c false if a memory allocation occurs
  90654. * (in which case the state will be set to
  90655. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90656. * occurs (the state will be unchanged).
  90657. */
  90658. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90659. /** Decode one metadata block or audio frame.
  90660. * This version instructs the decoder to decode a either a single metadata
  90661. * block or a single frame and stop, unless the callbacks return a fatal
  90662. * error or the read callback returns
  90663. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90664. *
  90665. * As the decoder needs more input it will call the read callback.
  90666. * Depending on what was decoded, the metadata or write callback will be
  90667. * called with the decoded metadata block or audio frame.
  90668. *
  90669. * Unless there is a fatal read error or end of stream, this function
  90670. * will return once one whole frame is decoded. In other words, if the
  90671. * stream is not synchronized or points to a corrupt frame header, the
  90672. * decoder will continue to try and resync until it gets to a valid
  90673. * frame, then decode one frame, then return. If the decoder points to
  90674. * a frame whose frame CRC in the frame footer does not match the
  90675. * computed frame CRC, this function will issue a
  90676. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90677. * error callback, and return, having decoded one complete, although
  90678. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90679. * correct length to the write callback.)
  90680. *
  90681. * \param decoder An initialized decoder instance.
  90682. * \assert
  90683. * \code decoder != NULL \endcode
  90684. * \retval FLAC__bool
  90685. * \c false if any fatal read, write, or memory allocation error
  90686. * occurred (meaning decoding must stop), else \c true; for more
  90687. * information about the decoder, check the decoder state with
  90688. * FLAC__stream_decoder_get_state().
  90689. */
  90690. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90691. /** Decode until the end of the metadata.
  90692. * This version instructs the decoder to decode from the current position
  90693. * and continue until all the metadata has been read, or until the
  90694. * callbacks return a fatal error or the read callback returns
  90695. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90696. *
  90697. * As the decoder needs more input it will call the read callback.
  90698. * As each metadata block is decoded, the metadata callback will be called
  90699. * with the decoded metadata.
  90700. *
  90701. * \param decoder An initialized decoder instance.
  90702. * \assert
  90703. * \code decoder != NULL \endcode
  90704. * \retval FLAC__bool
  90705. * \c false if any fatal read, write, or memory allocation error
  90706. * occurred (meaning decoding must stop), else \c true; for more
  90707. * information about the decoder, check the decoder state with
  90708. * FLAC__stream_decoder_get_state().
  90709. */
  90710. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90711. /** Decode until the end of the stream.
  90712. * This version instructs the decoder to decode from the current position
  90713. * and continue until the end of stream (the read callback returns
  90714. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90715. * callbacks return a fatal error.
  90716. *
  90717. * As the decoder needs more input it will call the read callback.
  90718. * As each metadata block and frame is decoded, the metadata or write
  90719. * callback will be called with the decoded metadata or frame.
  90720. *
  90721. * \param decoder An initialized decoder instance.
  90722. * \assert
  90723. * \code decoder != NULL \endcode
  90724. * \retval FLAC__bool
  90725. * \c false if any fatal read, write, or memory allocation error
  90726. * occurred (meaning decoding must stop), else \c true; for more
  90727. * information about the decoder, check the decoder state with
  90728. * FLAC__stream_decoder_get_state().
  90729. */
  90730. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90731. /** Skip one audio frame.
  90732. * This version instructs the decoder to 'skip' a single frame and stop,
  90733. * unless the callbacks return a fatal error or the read callback returns
  90734. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90735. *
  90736. * The decoding flow is the same as what occurs when
  90737. * FLAC__stream_decoder_process_single() is called to process an audio
  90738. * frame, except that this function does not decode the parsed data into
  90739. * PCM or call the write callback. The integrity of the frame is still
  90740. * checked the same way as in the other process functions.
  90741. *
  90742. * This function will return once one whole frame is skipped, in the
  90743. * same way that FLAC__stream_decoder_process_single() will return once
  90744. * one whole frame is decoded.
  90745. *
  90746. * This function can be used in more quickly determining FLAC frame
  90747. * boundaries when decoding of the actual data is not needed, for
  90748. * example when an application is separating a FLAC stream into frames
  90749. * for editing or storing in a container. To do this, the application
  90750. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90751. * to the next frame, then use
  90752. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90753. * boundary.
  90754. *
  90755. * This function should only be called when the stream has advanced
  90756. * past all the metadata, otherwise it will return \c false.
  90757. *
  90758. * \param decoder An initialized decoder instance not in a metadata
  90759. * state.
  90760. * \assert
  90761. * \code decoder != NULL \endcode
  90762. * \retval FLAC__bool
  90763. * \c false if any fatal read, write, or memory allocation error
  90764. * occurred (meaning decoding must stop), or if the decoder
  90765. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90766. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90767. * information about the decoder, check the decoder state with
  90768. * FLAC__stream_decoder_get_state().
  90769. */
  90770. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90771. /** Flush the input and seek to an absolute sample.
  90772. * Decoding will resume at the given sample. Note that because of
  90773. * this, the next write callback may contain a partial block. The
  90774. * client must support seeking the input or this function will fail
  90775. * and return \c false. Furthermore, if the decoder state is
  90776. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90777. * with FLAC__stream_decoder_flush() or reset with
  90778. * FLAC__stream_decoder_reset() before decoding can continue.
  90779. *
  90780. * \param decoder A decoder instance.
  90781. * \param sample The target sample number to seek to.
  90782. * \assert
  90783. * \code decoder != NULL \endcode
  90784. * \retval FLAC__bool
  90785. * \c true if successful, else \c false.
  90786. */
  90787. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90788. /* \} */
  90789. #ifdef __cplusplus
  90790. }
  90791. #endif
  90792. #endif
  90793. /*** End of inlined file: stream_decoder.h ***/
  90794. /*** Start of inlined file: stream_encoder.h ***/
  90795. #ifndef FLAC__STREAM_ENCODER_H
  90796. #define FLAC__STREAM_ENCODER_H
  90797. #include <stdio.h> /* for FILE */
  90798. #ifdef __cplusplus
  90799. extern "C" {
  90800. #endif
  90801. /** \file include/FLAC/stream_encoder.h
  90802. *
  90803. * \brief
  90804. * This module contains the functions which implement the stream
  90805. * encoder.
  90806. *
  90807. * See the detailed documentation in the
  90808. * \link flac_stream_encoder stream encoder \endlink module.
  90809. */
  90810. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90811. * \ingroup flac
  90812. *
  90813. * \brief
  90814. * This module describes the encoder layers provided by libFLAC.
  90815. *
  90816. * The stream encoder can be used to encode complete streams either to the
  90817. * client via callbacks, or directly to a file, depending on how it is
  90818. * initialized. When encoding via callbacks, the client provides a write
  90819. * callback which will be called whenever FLAC data is ready to be written.
  90820. * If the client also supplies a seek callback, the encoder will also
  90821. * automatically handle the writing back of metadata discovered while
  90822. * encoding, like stream info, seek points offsets, etc. When encoding to
  90823. * a file, the client needs only supply a filename or open \c FILE* and an
  90824. * optional progress callback for periodic notification of progress; the
  90825. * write and seek callbacks are supplied internally. For more info see the
  90826. * \link flac_stream_encoder stream encoder \endlink module.
  90827. */
  90828. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90829. * \ingroup flac_encoder
  90830. *
  90831. * \brief
  90832. * This module contains the functions which implement the stream
  90833. * encoder.
  90834. *
  90835. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90836. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90837. *
  90838. * The basic usage of this encoder is as follows:
  90839. * - The program creates an instance of an encoder using
  90840. * FLAC__stream_encoder_new().
  90841. * - The program overrides the default settings using
  90842. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90843. * functions should be called:
  90844. * - FLAC__stream_encoder_set_channels()
  90845. * - FLAC__stream_encoder_set_bits_per_sample()
  90846. * - FLAC__stream_encoder_set_sample_rate()
  90847. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90848. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90849. * - If the application wants to control the compression level or set its own
  90850. * metadata, then the following should also be called:
  90851. * - FLAC__stream_encoder_set_compression_level()
  90852. * - FLAC__stream_encoder_set_verify()
  90853. * - FLAC__stream_encoder_set_metadata()
  90854. * - The rest of the set functions should only be called if the client needs
  90855. * exact control over how the audio is compressed; thorough understanding
  90856. * of the FLAC format is necessary to achieve good results.
  90857. * - The program initializes the instance to validate the settings and
  90858. * prepare for encoding using
  90859. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90860. * or FLAC__stream_encoder_init_file() for native FLAC
  90861. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90862. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90863. * - The program calls FLAC__stream_encoder_process() or
  90864. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90865. * subsequently calls the callbacks when there is encoder data ready
  90866. * to be written.
  90867. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90868. * which causes the encoder to encode any data still in its input pipe,
  90869. * update the metadata with the final encoding statistics if output
  90870. * seeking is possible, and finally reset the encoder to the
  90871. * uninitialized state.
  90872. * - The instance may be used again or deleted with
  90873. * FLAC__stream_encoder_delete().
  90874. *
  90875. * In more detail, the stream encoder functions similarly to the
  90876. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90877. * callbacks and more options. Typically the client will create a new
  90878. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90879. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90880. * calling one of the FLAC__stream_encoder_init_*() functions.
  90881. *
  90882. * Unlike the decoders, the stream encoder has many options that can
  90883. * affect the speed and compression ratio. When setting these parameters
  90884. * you should have some basic knowledge of the format (see the
  90885. * <A HREF="../documentation.html#format">user-level documentation</A>
  90886. * or the <A HREF="../format.html">formal description</A>). The
  90887. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90888. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90889. * functions will do this, so make sure to pay attention to the state
  90890. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90891. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90892. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90893. * the constructor.
  90894. *
  90895. * There are three initialization functions for native FLAC, one for
  90896. * setting up the encoder to encode FLAC data to the client via
  90897. * callbacks, and two for encoding directly to a file.
  90898. *
  90899. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90900. * You must also supply a write callback which will be called anytime
  90901. * there is raw encoded data to write. If the client can seek the output
  90902. * it is best to also supply seek and tell callbacks, as this allows the
  90903. * encoder to go back after encoding is finished to write back
  90904. * information that was collected while encoding, like seek point offsets,
  90905. * frame sizes, etc.
  90906. *
  90907. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90908. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90909. * filename or open \c FILE*; the encoder will handle all the callbacks
  90910. * internally. You may also supply a progress callback for periodic
  90911. * notification of the encoding progress.
  90912. *
  90913. * There are three similarly-named init functions for encoding to Ogg
  90914. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90915. * library has been built with Ogg support.
  90916. *
  90917. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90918. * call the write callback several times, once with the \c fLaC signature,
  90919. * and once for each encoded metadata block. Note that for Ogg FLAC
  90920. * encoding you will usually get at least twice the number of callbacks than
  90921. * with native FLAC, one for the Ogg page header and one for the page body.
  90922. *
  90923. * After initializing the instance, the client may feed audio data to the
  90924. * encoder in one of two ways:
  90925. *
  90926. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90927. * will pass an array of pointers to buffers, one for each channel, to
  90928. * the encoder, each of the same length. The samples need not be
  90929. * block-aligned, but each channel should have the same number of samples.
  90930. * - Channel interleaved, through
  90931. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90932. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90933. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90934. * Again, the samples need not be block-aligned but they must be
  90935. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90936. * the last value channelN_sampleM.
  90937. *
  90938. * Note that for either process call, each sample in the buffers should be a
  90939. * signed integer, right-justified to the resolution set by
  90940. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90941. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90942. *
  90943. * When the client is finished encoding data, it calls
  90944. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90945. * data still in its input pipe, and call the metadata callback with the
  90946. * final encoding statistics. Then the instance may be deleted with
  90947. * FLAC__stream_encoder_delete() or initialized again to encode another
  90948. * stream.
  90949. *
  90950. * For programs that write their own metadata, but that do not know the
  90951. * actual metadata until after encoding, it is advantageous to instruct
  90952. * the encoder to write a PADDING block of the correct size, so that
  90953. * instead of rewriting the whole stream after encoding, the program can
  90954. * just overwrite the PADDING block. If only the maximum size of the
  90955. * metadata is known, the program can write a slightly larger padding
  90956. * block, then split it after encoding.
  90957. *
  90958. * Make sure you understand how lengths are calculated. All FLAC metadata
  90959. * blocks have a 4 byte header which contains the type and length. This
  90960. * length does not include the 4 bytes of the header. See the format page
  90961. * for the specification of metadata blocks and their lengths.
  90962. *
  90963. * \note
  90964. * If you are writing the FLAC data to a file via callbacks, make sure it
  90965. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90966. * after the first encoding pass, the encoder will try to seek back to the
  90967. * beginning of the stream, to the STREAMINFO block, to write some data
  90968. * there. (If using FLAC__stream_encoder_init*_file() or
  90969. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90970. *
  90971. * \note
  90972. * The "set" functions may only be called when the encoder is in the
  90973. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90974. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90975. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90976. * return \c true, otherwise \c false.
  90977. *
  90978. * \note
  90979. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90980. * defaults.
  90981. *
  90982. * \{
  90983. */
  90984. /** State values for a FLAC__StreamEncoder.
  90985. *
  90986. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90987. *
  90988. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90989. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90990. * must be deleted with FLAC__stream_encoder_delete().
  90991. */
  90992. typedef enum {
  90993. FLAC__STREAM_ENCODER_OK = 0,
  90994. /**< The encoder is in the normal OK state and samples can be processed. */
  90995. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90996. /**< The encoder is in the uninitialized state; one of the
  90997. * FLAC__stream_encoder_init_*() functions must be called before samples
  90998. * can be processed.
  90999. */
  91000. FLAC__STREAM_ENCODER_OGG_ERROR,
  91001. /**< An error occurred in the underlying Ogg layer. */
  91002. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  91003. /**< An error occurred in the underlying verify stream decoder;
  91004. * check FLAC__stream_encoder_get_verify_decoder_state().
  91005. */
  91006. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  91007. /**< The verify decoder detected a mismatch between the original
  91008. * audio signal and the decoded audio signal.
  91009. */
  91010. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  91011. /**< One of the callbacks returned a fatal error. */
  91012. FLAC__STREAM_ENCODER_IO_ERROR,
  91013. /**< An I/O error occurred while opening/reading/writing a file.
  91014. * Check \c errno.
  91015. */
  91016. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  91017. /**< An error occurred while writing the stream; usually, the
  91018. * write_callback returned an error.
  91019. */
  91020. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  91021. /**< Memory allocation failed. */
  91022. } FLAC__StreamEncoderState;
  91023. /** Maps a FLAC__StreamEncoderState to a C string.
  91024. *
  91025. * Using a FLAC__StreamEncoderState as the index to this array
  91026. * will give the string equivalent. The contents should not be modified.
  91027. */
  91028. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  91029. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  91030. */
  91031. typedef enum {
  91032. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  91033. /**< Initialization was successful. */
  91034. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  91035. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  91036. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  91037. /**< The library was not compiled with support for the given container
  91038. * format.
  91039. */
  91040. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  91041. /**< A required callback was not supplied. */
  91042. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  91043. /**< The encoder has an invalid setting for number of channels. */
  91044. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  91045. /**< The encoder has an invalid setting for bits-per-sample.
  91046. * FLAC supports 4-32 bps but the reference encoder currently supports
  91047. * only up to 24 bps.
  91048. */
  91049. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  91050. /**< The encoder has an invalid setting for the input sample rate. */
  91051. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  91052. /**< The encoder has an invalid setting for the block size. */
  91053. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  91054. /**< The encoder has an invalid setting for the maximum LPC order. */
  91055. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  91056. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  91057. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  91058. /**< The specified block size is less than the maximum LPC order. */
  91059. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  91060. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  91061. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  91062. /**< The metadata input to the encoder is invalid, in one of the following ways:
  91063. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  91064. * - One of the metadata blocks contains an undefined type
  91065. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  91066. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  91067. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  91068. */
  91069. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  91070. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  91071. * already initialized, usually because
  91072. * FLAC__stream_encoder_finish() was not called.
  91073. */
  91074. } FLAC__StreamEncoderInitStatus;
  91075. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  91076. *
  91077. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  91078. * will give the string equivalent. The contents should not be modified.
  91079. */
  91080. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  91081. /** Return values for the FLAC__StreamEncoder read callback.
  91082. */
  91083. typedef enum {
  91084. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91085. /**< The read was OK and decoding can continue. */
  91086. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91087. /**< The read was attempted at the end of the stream. */
  91088. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91089. /**< An unrecoverable error occurred. */
  91090. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91091. /**< Client does not support reading back from the output. */
  91092. } FLAC__StreamEncoderReadStatus;
  91093. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91094. *
  91095. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91096. * will give the string equivalent. The contents should not be modified.
  91097. */
  91098. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91099. /** Return values for the FLAC__StreamEncoder write callback.
  91100. */
  91101. typedef enum {
  91102. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91103. /**< The write was OK and encoding can continue. */
  91104. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91105. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91106. } FLAC__StreamEncoderWriteStatus;
  91107. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91108. *
  91109. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91110. * will give the string equivalent. The contents should not be modified.
  91111. */
  91112. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91113. /** Return values for the FLAC__StreamEncoder seek callback.
  91114. */
  91115. typedef enum {
  91116. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91117. /**< The seek was OK and encoding can continue. */
  91118. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91119. /**< An unrecoverable error occurred. */
  91120. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91121. /**< Client does not support seeking. */
  91122. } FLAC__StreamEncoderSeekStatus;
  91123. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91124. *
  91125. * Using a FLAC__StreamEncoderSeekStatus 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__StreamEncoderSeekStatusString[];
  91129. /** Return values for the FLAC__StreamEncoder tell callback.
  91130. */
  91131. typedef enum {
  91132. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91133. /**< The tell was OK and encoding can continue. */
  91134. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91135. /**< An unrecoverable error occurred. */
  91136. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91137. /**< Client does not support seeking. */
  91138. } FLAC__StreamEncoderTellStatus;
  91139. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91140. *
  91141. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91142. * will give the string equivalent. The contents should not be modified.
  91143. */
  91144. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91145. /***********************************************************************
  91146. *
  91147. * class FLAC__StreamEncoder
  91148. *
  91149. ***********************************************************************/
  91150. struct FLAC__StreamEncoderProtected;
  91151. struct FLAC__StreamEncoderPrivate;
  91152. /** The opaque structure definition for the stream encoder type.
  91153. * See the \link flac_stream_encoder stream encoder module \endlink
  91154. * for a detailed description.
  91155. */
  91156. typedef struct {
  91157. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91158. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91159. } FLAC__StreamEncoder;
  91160. /** Signature for the read callback.
  91161. *
  91162. * A function pointer matching this signature must be passed to
  91163. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91164. * The supplied function will be called when the encoder needs to read back
  91165. * encoded data. This happens during the metadata callback, when the encoder
  91166. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91167. * while encoding. The address of the buffer to be filled is supplied, along
  91168. * with the number of bytes the buffer can hold. The callback may choose to
  91169. * supply less data and modify the byte count but must be careful not to
  91170. * overflow the buffer. The callback then returns a status code chosen from
  91171. * FLAC__StreamEncoderReadStatus.
  91172. *
  91173. * Here is an example of a read callback for stdio streams:
  91174. * \code
  91175. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91176. * {
  91177. * FILE *file = ((MyClientData*)client_data)->file;
  91178. * if(*bytes > 0) {
  91179. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91180. * if(ferror(file))
  91181. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91182. * else if(*bytes == 0)
  91183. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91184. * else
  91185. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91186. * }
  91187. * else
  91188. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91189. * }
  91190. * \endcode
  91191. *
  91192. * \note In general, FLAC__StreamEncoder functions which change the
  91193. * state should not be called on the \a encoder while in the callback.
  91194. *
  91195. * \param encoder The encoder instance calling the callback.
  91196. * \param buffer A pointer to a location for the callee to store
  91197. * data to be encoded.
  91198. * \param bytes A pointer to the size of the buffer. On entry
  91199. * to the callback, it contains the maximum number
  91200. * of bytes that may be stored in \a buffer. The
  91201. * callee must set it to the actual number of bytes
  91202. * stored (0 in case of error or end-of-stream) before
  91203. * returning.
  91204. * \param client_data The callee's client data set through
  91205. * FLAC__stream_encoder_set_client_data().
  91206. * \retval FLAC__StreamEncoderReadStatus
  91207. * The callee's return status.
  91208. */
  91209. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91210. /** Signature for the write callback.
  91211. *
  91212. * A function pointer matching this signature must be passed to
  91213. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91214. * by the encoder anytime there is raw encoded data ready to write. It may
  91215. * include metadata mixed with encoded audio frames and the data is not
  91216. * guaranteed to be aligned on frame or metadata block boundaries.
  91217. *
  91218. * The only duty of the callback is to write out the \a bytes worth of data
  91219. * in \a buffer to the current position in the output stream. The arguments
  91220. * \a samples and \a current_frame are purely informational. If \a samples
  91221. * is greater than \c 0, then \a current_frame will hold the current frame
  91222. * number that is being written; otherwise it indicates that the write
  91223. * callback is being called to write metadata.
  91224. *
  91225. * \note
  91226. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91227. * write callback will be called twice when writing each audio
  91228. * frame; once for the page header, and once for the page body.
  91229. * When writing the page header, the \a samples argument to the
  91230. * write callback will be \c 0.
  91231. *
  91232. * \note In general, FLAC__StreamEncoder functions which change the
  91233. * state should not be called on the \a encoder while in the callback.
  91234. *
  91235. * \param encoder The encoder instance calling the callback.
  91236. * \param buffer An array of encoded data of length \a bytes.
  91237. * \param bytes The byte length of \a buffer.
  91238. * \param samples The number of samples encoded by \a buffer.
  91239. * \c 0 has a special meaning; see above.
  91240. * \param current_frame The number of the current frame being encoded.
  91241. * \param client_data The callee's client data set through
  91242. * FLAC__stream_encoder_init_*().
  91243. * \retval FLAC__StreamEncoderWriteStatus
  91244. * The callee's return status.
  91245. */
  91246. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91247. /** Signature for the seek callback.
  91248. *
  91249. * A function pointer matching this signature may be passed to
  91250. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91251. * when the encoder needs to seek the output stream. The encoder will pass
  91252. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91253. *
  91254. * Here is an example of a seek callback for stdio streams:
  91255. * \code
  91256. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91257. * {
  91258. * FILE *file = ((MyClientData*)client_data)->file;
  91259. * if(file == stdin)
  91260. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91261. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91262. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91263. * else
  91264. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91265. * }
  91266. * \endcode
  91267. *
  91268. * \note In general, FLAC__StreamEncoder functions which change the
  91269. * state should not be called on the \a encoder while in the callback.
  91270. *
  91271. * \param encoder The encoder instance calling the callback.
  91272. * \param absolute_byte_offset The offset from the beginning of the stream
  91273. * to seek to.
  91274. * \param client_data The callee's client data set through
  91275. * FLAC__stream_encoder_init_*().
  91276. * \retval FLAC__StreamEncoderSeekStatus
  91277. * The callee's return status.
  91278. */
  91279. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91280. /** Signature for the tell callback.
  91281. *
  91282. * A function pointer matching this signature may be passed to
  91283. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91284. * when the encoder needs to know the current position of the output stream.
  91285. *
  91286. * \warning
  91287. * The callback must return the true current byte offset of the output to
  91288. * which the encoder is writing. If you are buffering the output, make
  91289. * sure and take this into account. If you are writing directly to a
  91290. * FILE* from your write callback, ftell() is sufficient. If you are
  91291. * writing directly to a file descriptor from your write callback, you
  91292. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91293. * these points to rewrite metadata after encoding.
  91294. *
  91295. * Here is an example of a tell callback for stdio streams:
  91296. * \code
  91297. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91298. * {
  91299. * FILE *file = ((MyClientData*)client_data)->file;
  91300. * off_t pos;
  91301. * if(file == stdin)
  91302. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91303. * else if((pos = ftello(file)) < 0)
  91304. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91305. * else {
  91306. * *absolute_byte_offset = (FLAC__uint64)pos;
  91307. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91308. * }
  91309. * }
  91310. * \endcode
  91311. *
  91312. * \note In general, FLAC__StreamEncoder functions which change the
  91313. * state should not be called on the \a encoder while in the callback.
  91314. *
  91315. * \param encoder The encoder instance calling the callback.
  91316. * \param absolute_byte_offset The address at which to store the current
  91317. * position of the output.
  91318. * \param client_data The callee's client data set through
  91319. * FLAC__stream_encoder_init_*().
  91320. * \retval FLAC__StreamEncoderTellStatus
  91321. * The callee's return status.
  91322. */
  91323. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91324. /** Signature for the metadata callback.
  91325. *
  91326. * A function pointer matching this signature may be passed to
  91327. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91328. * once at the end of encoding with the populated STREAMINFO structure. This
  91329. * is so the client can seek back to the beginning of the file and write the
  91330. * STREAMINFO block with the correct statistics after encoding (like
  91331. * minimum/maximum frame size and total samples).
  91332. *
  91333. * \note In general, FLAC__StreamEncoder functions which change the
  91334. * state should not be called on the \a encoder while in the callback.
  91335. *
  91336. * \param encoder The encoder instance calling the callback.
  91337. * \param metadata The final populated STREAMINFO block.
  91338. * \param client_data The callee's client data set through
  91339. * FLAC__stream_encoder_init_*().
  91340. */
  91341. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91342. /** Signature for the progress callback.
  91343. *
  91344. * A function pointer matching this signature may be passed to
  91345. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91346. * The supplied function will be called when the encoder has finished
  91347. * writing a frame. The \c total_frames_estimate argument to the
  91348. * callback will be based on the value from
  91349. * FLAC__stream_encoder_set_total_samples_estimate().
  91350. *
  91351. * \note In general, FLAC__StreamEncoder functions which change the
  91352. * state should not be called on the \a encoder while in the callback.
  91353. *
  91354. * \param encoder The encoder instance calling the callback.
  91355. * \param bytes_written Bytes written so far.
  91356. * \param samples_written Samples written so far.
  91357. * \param frames_written Frames written so far.
  91358. * \param total_frames_estimate The estimate of the total number of
  91359. * frames to be written.
  91360. * \param client_data The callee's client data set through
  91361. * FLAC__stream_encoder_init_*().
  91362. */
  91363. 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);
  91364. /***********************************************************************
  91365. *
  91366. * Class constructor/destructor
  91367. *
  91368. ***********************************************************************/
  91369. /** Create a new stream encoder instance. The instance is created with
  91370. * default settings; see the individual FLAC__stream_encoder_set_*()
  91371. * functions for each setting's default.
  91372. *
  91373. * \retval FLAC__StreamEncoder*
  91374. * \c NULL if there was an error allocating memory, else the new instance.
  91375. */
  91376. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91377. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91378. *
  91379. * \param encoder A pointer to an existing encoder.
  91380. * \assert
  91381. * \code encoder != NULL \endcode
  91382. */
  91383. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91384. /***********************************************************************
  91385. *
  91386. * Public class method prototypes
  91387. *
  91388. ***********************************************************************/
  91389. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91390. *
  91391. * \note
  91392. * This does not need to be set for native FLAC encoding.
  91393. *
  91394. * \note
  91395. * It is recommended to set a serial number explicitly as the default of '0'
  91396. * may collide with other streams.
  91397. *
  91398. * \default \c 0
  91399. * \param encoder An encoder instance to set.
  91400. * \param serial_number See above.
  91401. * \assert
  91402. * \code encoder != NULL \endcode
  91403. * \retval FLAC__bool
  91404. * \c false if the encoder is already initialized, else \c true.
  91405. */
  91406. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91407. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91408. * encoded output by feeding it through an internal decoder and comparing
  91409. * the original signal against the decoded signal. If a mismatch occurs,
  91410. * the process call will return \c false. Note that this will slow the
  91411. * encoding process by the extra time required for decoding and comparison.
  91412. *
  91413. * \default \c false
  91414. * \param encoder An encoder instance to set.
  91415. * \param value Flag value (see above).
  91416. * \assert
  91417. * \code encoder != NULL \endcode
  91418. * \retval FLAC__bool
  91419. * \c false if the encoder is already initialized, else \c true.
  91420. */
  91421. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91422. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91423. * the encoder will comply with the Subset and will check the
  91424. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91425. * comply. If \c false, the settings may take advantage of the full
  91426. * range that the format allows.
  91427. *
  91428. * Make sure you know what it entails before setting this to \c false.
  91429. *
  91430. * \default \c true
  91431. * \param encoder An encoder instance to set.
  91432. * \param value Flag value (see above).
  91433. * \assert
  91434. * \code encoder != NULL \endcode
  91435. * \retval FLAC__bool
  91436. * \c false if the encoder is already initialized, else \c true.
  91437. */
  91438. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91439. /** Set the number of channels to be encoded.
  91440. *
  91441. * \default \c 2
  91442. * \param encoder An encoder instance to set.
  91443. * \param value See above.
  91444. * \assert
  91445. * \code encoder != NULL \endcode
  91446. * \retval FLAC__bool
  91447. * \c false if the encoder is already initialized, else \c true.
  91448. */
  91449. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91450. /** Set the sample resolution of the input to be encoded.
  91451. *
  91452. * \warning
  91453. * Do not feed the encoder data that is wider than the value you
  91454. * set here or you will generate an invalid stream.
  91455. *
  91456. * \default \c 16
  91457. * \param encoder An encoder instance to set.
  91458. * \param value See above.
  91459. * \assert
  91460. * \code encoder != NULL \endcode
  91461. * \retval FLAC__bool
  91462. * \c false if the encoder is already initialized, else \c true.
  91463. */
  91464. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91465. /** Set the sample rate (in Hz) of the input to be encoded.
  91466. *
  91467. * \default \c 44100
  91468. * \param encoder An encoder instance to set.
  91469. * \param value See above.
  91470. * \assert
  91471. * \code encoder != NULL \endcode
  91472. * \retval FLAC__bool
  91473. * \c false if the encoder is already initialized, else \c true.
  91474. */
  91475. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91476. /** Set the compression level
  91477. *
  91478. * The compression level is roughly proportional to the amount of effort
  91479. * the encoder expends to compress the file. A higher level usually
  91480. * means more computation but higher compression. The default level is
  91481. * suitable for most applications.
  91482. *
  91483. * Currently the levels range from \c 0 (fastest, least compression) to
  91484. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91485. * treated as \c 8.
  91486. *
  91487. * This function automatically calls the following other \c _set_
  91488. * functions with appropriate values, so the client does not need to
  91489. * unless it specifically wants to override them:
  91490. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91491. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91492. * - FLAC__stream_encoder_set_apodization()
  91493. * - FLAC__stream_encoder_set_max_lpc_order()
  91494. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91495. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91496. * - FLAC__stream_encoder_set_do_escape_coding()
  91497. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91498. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91499. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91500. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91501. *
  91502. * The actual values set for each level are:
  91503. * <table>
  91504. * <tr>
  91505. * <td><b>level</b><td>
  91506. * <td>do mid-side stereo<td>
  91507. * <td>loose mid-side stereo<td>
  91508. * <td>apodization<td>
  91509. * <td>max lpc order<td>
  91510. * <td>qlp coeff precision<td>
  91511. * <td>qlp coeff prec search<td>
  91512. * <td>escape coding<td>
  91513. * <td>exhaustive model search<td>
  91514. * <td>min residual partition order<td>
  91515. * <td>max residual partition order<td>
  91516. * <td>rice parameter search dist<td>
  91517. * </tr>
  91518. * <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>
  91519. * <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>
  91520. * <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>
  91521. * <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>
  91522. * <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>
  91523. * <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>
  91524. * <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>
  91525. * <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>
  91526. * <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>
  91527. * </table>
  91528. *
  91529. * \default \c 5
  91530. * \param encoder An encoder instance to set.
  91531. * \param value See above.
  91532. * \assert
  91533. * \code encoder != NULL \endcode
  91534. * \retval FLAC__bool
  91535. * \c false if the encoder is already initialized, else \c true.
  91536. */
  91537. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91538. /** Set the blocksize to use while encoding.
  91539. *
  91540. * The number of samples to use per frame. Use \c 0 to let the encoder
  91541. * estimate a blocksize; this is usually best.
  91542. *
  91543. * \default \c 0
  91544. * \param encoder An encoder instance to set.
  91545. * \param value See above.
  91546. * \assert
  91547. * \code encoder != NULL \endcode
  91548. * \retval FLAC__bool
  91549. * \c false if the encoder is already initialized, else \c true.
  91550. */
  91551. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91552. /** Set to \c true to enable mid-side encoding on stereo input. The
  91553. * number of channels must be 2 for this to have any effect. Set to
  91554. * \c false to use only independent channel coding.
  91555. *
  91556. * \default \c false
  91557. * \param encoder An encoder instance to set.
  91558. * \param value Flag value (see above).
  91559. * \assert
  91560. * \code encoder != NULL \endcode
  91561. * \retval FLAC__bool
  91562. * \c false if the encoder is already initialized, else \c true.
  91563. */
  91564. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91565. /** Set to \c true to enable adaptive switching between mid-side and
  91566. * left-right encoding on stereo input. Set to \c false to use
  91567. * exhaustive searching. Setting this to \c true requires
  91568. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91569. * \c true in order to have any effect.
  91570. *
  91571. * \default \c false
  91572. * \param encoder An encoder instance to set.
  91573. * \param value Flag value (see above).
  91574. * \assert
  91575. * \code encoder != NULL \endcode
  91576. * \retval FLAC__bool
  91577. * \c false if the encoder is already initialized, else \c true.
  91578. */
  91579. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91580. /** Sets the apodization function(s) the encoder will use when windowing
  91581. * audio data for LPC analysis.
  91582. *
  91583. * The \a specification is a plain ASCII string which specifies exactly
  91584. * which functions to use. There may be more than one (up to 32),
  91585. * separated by \c ';' characters. Some functions take one or more
  91586. * comma-separated arguments in parentheses.
  91587. *
  91588. * The available functions are \c bartlett, \c bartlett_hann,
  91589. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91590. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91591. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91592. *
  91593. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91594. * (0<STDDEV<=0.5).
  91595. *
  91596. * For \c tukey(P), P specifies the fraction of the window that is
  91597. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91598. * corresponds to \c hann.
  91599. *
  91600. * Example specifications are \c "blackman" or
  91601. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91602. *
  91603. * Any function that is specified erroneously is silently dropped. Up
  91604. * to 32 functions are kept, the rest are dropped. If the specification
  91605. * is empty the encoder defaults to \c "tukey(0.5)".
  91606. *
  91607. * When more than one function is specified, then for every subframe the
  91608. * encoder will try each of them separately and choose the window that
  91609. * results in the smallest compressed subframe.
  91610. *
  91611. * Note that each function specified causes the encoder to occupy a
  91612. * floating point array in which to store the window.
  91613. *
  91614. * \default \c "tukey(0.5)"
  91615. * \param encoder An encoder instance to set.
  91616. * \param specification See above.
  91617. * \assert
  91618. * \code encoder != NULL \endcode
  91619. * \code specification != NULL \endcode
  91620. * \retval FLAC__bool
  91621. * \c false if the encoder is already initialized, else \c true.
  91622. */
  91623. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91624. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91625. *
  91626. * \default \c 0
  91627. * \param encoder An encoder instance to set.
  91628. * \param value See above.
  91629. * \assert
  91630. * \code encoder != NULL \endcode
  91631. * \retval FLAC__bool
  91632. * \c false if the encoder is already initialized, else \c true.
  91633. */
  91634. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91635. /** Set the precision, in bits, of the quantized linear predictor
  91636. * coefficients, or \c 0 to let the encoder select it based on the
  91637. * blocksize.
  91638. *
  91639. * \note
  91640. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91641. * be less than 32.
  91642. *
  91643. * \default \c 0
  91644. * \param encoder An encoder instance to set.
  91645. * \param value See above.
  91646. * \assert
  91647. * \code encoder != NULL \endcode
  91648. * \retval FLAC__bool
  91649. * \c false if the encoder is already initialized, else \c true.
  91650. */
  91651. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91652. /** Set to \c false to use only the specified quantized linear predictor
  91653. * coefficient precision, or \c true to search neighboring precision
  91654. * values and use the best one.
  91655. *
  91656. * \default \c false
  91657. * \param encoder An encoder instance to set.
  91658. * \param value See above.
  91659. * \assert
  91660. * \code encoder != NULL \endcode
  91661. * \retval FLAC__bool
  91662. * \c false if the encoder is already initialized, else \c true.
  91663. */
  91664. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91665. /** Deprecated. Setting this value has no effect.
  91666. *
  91667. * \default \c false
  91668. * \param encoder An encoder instance to set.
  91669. * \param value See above.
  91670. * \assert
  91671. * \code encoder != NULL \endcode
  91672. * \retval FLAC__bool
  91673. * \c false if the encoder is already initialized, else \c true.
  91674. */
  91675. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91676. /** Set to \c false to let the encoder estimate the best model order
  91677. * based on the residual signal energy, or \c true to force the
  91678. * encoder to evaluate all order models and select the best.
  91679. *
  91680. * \default \c false
  91681. * \param encoder An encoder instance to set.
  91682. * \param value See above.
  91683. * \assert
  91684. * \code encoder != NULL \endcode
  91685. * \retval FLAC__bool
  91686. * \c false if the encoder is already initialized, else \c true.
  91687. */
  91688. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91689. /** Set the minimum partition order to search when coding the residual.
  91690. * This is used in tandem with
  91691. * FLAC__stream_encoder_set_max_residual_partition_order().
  91692. *
  91693. * The partition order determines the context size in the residual.
  91694. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91695. *
  91696. * Set both min and max values to \c 0 to force a single context,
  91697. * whose Rice parameter is based on the residual signal variance.
  91698. * Otherwise, set a min and max order, and the encoder will search
  91699. * all orders, using the mean of each context for its Rice parameter,
  91700. * and use the best.
  91701. *
  91702. * \default \c 0
  91703. * \param encoder An encoder instance to set.
  91704. * \param value See above.
  91705. * \assert
  91706. * \code encoder != NULL \endcode
  91707. * \retval FLAC__bool
  91708. * \c false if the encoder is already initialized, else \c true.
  91709. */
  91710. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91711. /** Set the maximum partition order to search when coding the residual.
  91712. * This is used in tandem with
  91713. * FLAC__stream_encoder_set_min_residual_partition_order().
  91714. *
  91715. * The partition order determines the context size in the residual.
  91716. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91717. *
  91718. * Set both min and max values to \c 0 to force a single context,
  91719. * whose Rice parameter is based on the residual signal variance.
  91720. * Otherwise, set a min and max order, and the encoder will search
  91721. * all orders, using the mean of each context for its Rice parameter,
  91722. * and use the best.
  91723. *
  91724. * \default \c 0
  91725. * \param encoder An encoder instance to set.
  91726. * \param value See above.
  91727. * \assert
  91728. * \code encoder != NULL \endcode
  91729. * \retval FLAC__bool
  91730. * \c false if the encoder is already initialized, else \c true.
  91731. */
  91732. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91733. /** Deprecated. Setting this value has no effect.
  91734. *
  91735. * \default \c 0
  91736. * \param encoder An encoder instance to set.
  91737. * \param value See above.
  91738. * \assert
  91739. * \code encoder != NULL \endcode
  91740. * \retval FLAC__bool
  91741. * \c false if the encoder is already initialized, else \c true.
  91742. */
  91743. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91744. /** Set an estimate of the total samples that will be encoded.
  91745. * This is merely an estimate and may be set to \c 0 if unknown.
  91746. * This value will be written to the STREAMINFO block before encoding,
  91747. * and can remove the need for the caller to rewrite the value later
  91748. * if the value is known before encoding.
  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_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91759. /** Set the metadata blocks to be emitted to the stream before encoding.
  91760. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91761. * array of pointers to metadata blocks. The array is non-const since
  91762. * the encoder may need to change the \a is_last flag inside them, and
  91763. * in some cases update seek point offsets. Otherwise, the encoder will
  91764. * not modify or free the blocks. It is up to the caller to free the
  91765. * metadata blocks after encoding finishes.
  91766. *
  91767. * \note
  91768. * The encoder stores only copies of the pointers in the \a metadata array;
  91769. * the metadata blocks themselves must survive at least until after
  91770. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91771. *
  91772. * \note
  91773. * The STREAMINFO block is always written and no STREAMINFO block may
  91774. * occur in the supplied array.
  91775. *
  91776. * \note
  91777. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91778. * in the \a metadata array, but the client has specified that it does not
  91779. * support seeking, then the SEEKTABLE will be written verbatim. However
  91780. * by itself this is not very useful as the client will not know the stream
  91781. * offsets for the seekpoints ahead of time. In order to get a proper
  91782. * seektable the client must support seeking. See next note.
  91783. *
  91784. * \note
  91785. * SEEKTABLE blocks are handled specially. Since you will not know
  91786. * the values for the seek point stream offsets, you should pass in
  91787. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91788. * required sample numbers (or placeholder points), with \c 0 for the
  91789. * \a frame_samples and \a stream_offset fields for each point. If the
  91790. * client has specified that it supports seeking by providing a seek
  91791. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91792. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91793. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91794. * then while it is encoding the encoder will fill the stream offsets in
  91795. * for you and when encoding is finished, it will seek back and write the
  91796. * real values into the SEEKTABLE block in the stream. There are helper
  91797. * routines for manipulating seektable template blocks; see metadata.h:
  91798. * FLAC__metadata_object_seektable_template_*(). If the client does
  91799. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91800. * will slow down or remove the ability to seek in the FLAC stream.
  91801. *
  91802. * \note
  91803. * The encoder instance \b will modify the first \c SEEKTABLE block
  91804. * as it transforms the template to a valid seektable while encoding,
  91805. * but it is still up to the caller to free all metadata blocks after
  91806. * encoding.
  91807. *
  91808. * \note
  91809. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91810. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91811. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91812. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91813. * block is present in the \a metadata array, libFLAC will write an
  91814. * empty one, containing only the vendor string.
  91815. *
  91816. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91817. * the second metadata block of the stream. The encoder already supplies
  91818. * the STREAMINFO block automatically. If \a metadata does not contain a
  91819. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91820. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91821. * first, the init function will reorder \a metadata by moving the
  91822. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91823. * blocks will remain as they were.
  91824. *
  91825. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91826. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91827. * return \c false.
  91828. *
  91829. * \default \c NULL, 0
  91830. * \param encoder An encoder instance to set.
  91831. * \param metadata See above.
  91832. * \param num_blocks See above.
  91833. * \assert
  91834. * \code encoder != NULL \endcode
  91835. * \retval FLAC__bool
  91836. * \c false if the encoder is already initialized, else \c true.
  91837. * \c false if the encoder is already initialized, or if
  91838. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91839. */
  91840. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91841. /** Get the current encoder state.
  91842. *
  91843. * \param encoder An encoder instance to query.
  91844. * \assert
  91845. * \code encoder != NULL \endcode
  91846. * \retval FLAC__StreamEncoderState
  91847. * The current encoder state.
  91848. */
  91849. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91850. /** Get the state of the verify stream decoder.
  91851. * Useful when the stream encoder state is
  91852. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91853. *
  91854. * \param encoder An encoder instance to query.
  91855. * \assert
  91856. * \code encoder != NULL \endcode
  91857. * \retval FLAC__StreamDecoderState
  91858. * The verify stream decoder state.
  91859. */
  91860. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91861. /** Get the current encoder state as a C string.
  91862. * This version automatically resolves
  91863. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91864. * verify decoder's state.
  91865. *
  91866. * \param encoder A encoder instance to query.
  91867. * \assert
  91868. * \code encoder != NULL \endcode
  91869. * \retval const char *
  91870. * The encoder state as a C string. Do not modify the contents.
  91871. */
  91872. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91873. /** Get relevant values about the nature of a verify decoder error.
  91874. * Useful when the stream encoder state is
  91875. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91876. * be addresses in which the stats will be returned, or NULL if value
  91877. * is not desired.
  91878. *
  91879. * \param encoder An encoder instance to query.
  91880. * \param absolute_sample The absolute sample number of the mismatch.
  91881. * \param frame_number The number of the frame in which the mismatch occurred.
  91882. * \param channel The channel in which the mismatch occurred.
  91883. * \param sample The number of the sample (relative to the frame) in
  91884. * which the mismatch occurred.
  91885. * \param expected The expected value for the sample in question.
  91886. * \param got The actual value returned by the decoder.
  91887. * \assert
  91888. * \code encoder != NULL \endcode
  91889. */
  91890. 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);
  91891. /** Get the "verify" flag.
  91892. *
  91893. * \param encoder An encoder instance to query.
  91894. * \assert
  91895. * \code encoder != NULL \endcode
  91896. * \retval FLAC__bool
  91897. * See FLAC__stream_encoder_set_verify().
  91898. */
  91899. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91900. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91901. *
  91902. * \param encoder An encoder instance to query.
  91903. * \assert
  91904. * \code encoder != NULL \endcode
  91905. * \retval FLAC__bool
  91906. * See FLAC__stream_encoder_set_streamable_subset().
  91907. */
  91908. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91909. /** Get the number of input channels being processed.
  91910. *
  91911. * \param encoder An encoder instance to query.
  91912. * \assert
  91913. * \code encoder != NULL \endcode
  91914. * \retval unsigned
  91915. * See FLAC__stream_encoder_set_channels().
  91916. */
  91917. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91918. /** Get the input sample resolution setting.
  91919. *
  91920. * \param encoder An encoder instance to query.
  91921. * \assert
  91922. * \code encoder != NULL \endcode
  91923. * \retval unsigned
  91924. * See FLAC__stream_encoder_set_bits_per_sample().
  91925. */
  91926. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91927. /** Get the input sample rate setting.
  91928. *
  91929. * \param encoder An encoder instance to query.
  91930. * \assert
  91931. * \code encoder != NULL \endcode
  91932. * \retval unsigned
  91933. * See FLAC__stream_encoder_set_sample_rate().
  91934. */
  91935. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91936. /** Get the blocksize setting.
  91937. *
  91938. * \param encoder An encoder instance to query.
  91939. * \assert
  91940. * \code encoder != NULL \endcode
  91941. * \retval unsigned
  91942. * See FLAC__stream_encoder_set_blocksize().
  91943. */
  91944. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91945. /** Get the "mid/side stereo coding" flag.
  91946. *
  91947. * \param encoder An encoder instance to query.
  91948. * \assert
  91949. * \code encoder != NULL \endcode
  91950. * \retval FLAC__bool
  91951. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91952. */
  91953. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91954. /** Get the "adaptive mid/side switching" flag.
  91955. *
  91956. * \param encoder An encoder instance to query.
  91957. * \assert
  91958. * \code encoder != NULL \endcode
  91959. * \retval FLAC__bool
  91960. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91961. */
  91962. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91963. /** Get the maximum LPC order setting.
  91964. *
  91965. * \param encoder An encoder instance to query.
  91966. * \assert
  91967. * \code encoder != NULL \endcode
  91968. * \retval unsigned
  91969. * See FLAC__stream_encoder_set_max_lpc_order().
  91970. */
  91971. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91972. /** Get the quantized linear predictor coefficient precision setting.
  91973. *
  91974. * \param encoder An encoder instance to query.
  91975. * \assert
  91976. * \code encoder != NULL \endcode
  91977. * \retval unsigned
  91978. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91979. */
  91980. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91981. /** Get the qlp coefficient precision search flag.
  91982. *
  91983. * \param encoder An encoder instance to query.
  91984. * \assert
  91985. * \code encoder != NULL \endcode
  91986. * \retval FLAC__bool
  91987. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91988. */
  91989. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91990. /** Get the "escape coding" flag.
  91991. *
  91992. * \param encoder An encoder instance to query.
  91993. * \assert
  91994. * \code encoder != NULL \endcode
  91995. * \retval FLAC__bool
  91996. * See FLAC__stream_encoder_set_do_escape_coding().
  91997. */
  91998. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91999. /** Get the exhaustive model search flag.
  92000. *
  92001. * \param encoder An encoder instance to query.
  92002. * \assert
  92003. * \code encoder != NULL \endcode
  92004. * \retval FLAC__bool
  92005. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  92006. */
  92007. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  92008. /** Get the minimum residual partition order setting.
  92009. *
  92010. * \param encoder An encoder instance to query.
  92011. * \assert
  92012. * \code encoder != NULL \endcode
  92013. * \retval unsigned
  92014. * See FLAC__stream_encoder_set_min_residual_partition_order().
  92015. */
  92016. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92017. /** Get maximum residual partition order setting.
  92018. *
  92019. * \param encoder An encoder instance to query.
  92020. * \assert
  92021. * \code encoder != NULL \endcode
  92022. * \retval unsigned
  92023. * See FLAC__stream_encoder_set_max_residual_partition_order().
  92024. */
  92025. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92026. /** Get the Rice parameter search distance setting.
  92027. *
  92028. * \param encoder An encoder instance to query.
  92029. * \assert
  92030. * \code encoder != NULL \endcode
  92031. * \retval unsigned
  92032. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  92033. */
  92034. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  92035. /** Get the previously set estimate of the total samples to be encoded.
  92036. * The encoder merely mimics back the value given to
  92037. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  92038. * other way of knowing how many samples the client will encode.
  92039. *
  92040. * \param encoder An encoder instance to set.
  92041. * \assert
  92042. * \code encoder != NULL \endcode
  92043. * \retval FLAC__uint64
  92044. * See FLAC__stream_encoder_get_total_samples_estimate().
  92045. */
  92046. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  92047. /** Initialize the encoder instance to encode native FLAC streams.
  92048. *
  92049. * This flavor of initialization sets up the encoder to encode to a
  92050. * native FLAC stream. I/O is performed via callbacks to the client.
  92051. * For encoding to a plain file via filename or open \c FILE*,
  92052. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  92053. * provide a simpler interface.
  92054. *
  92055. * This function should be called after FLAC__stream_encoder_new() and
  92056. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92057. * or FLAC__stream_encoder_process_interleaved().
  92058. * initialization succeeded.
  92059. *
  92060. * The call to FLAC__stream_encoder_init_stream() currently will also
  92061. * immediately call the write callback several times, once with the \c fLaC
  92062. * signature, and once for each encoded metadata block.
  92063. *
  92064. * \param encoder An uninitialized encoder instance.
  92065. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92066. * pointer must not be \c NULL.
  92067. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92068. * pointer may be \c NULL if seeking is not
  92069. * supported. The encoder uses seeking to go back
  92070. * and write some some stream statistics to the
  92071. * STREAMINFO block; this is recommended but not
  92072. * necessary to create a valid FLAC stream. If
  92073. * \a seek_callback is not \c NULL then a
  92074. * \a tell_callback must also be supplied.
  92075. * Alternatively, a dummy seek callback that just
  92076. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92077. * may also be supplied, all though this is slightly
  92078. * less efficient for the encoder.
  92079. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92080. * pointer may be \c NULL if seeking is not
  92081. * supported. If \a seek_callback is \c NULL then
  92082. * this argument will be ignored. If
  92083. * \a seek_callback is not \c NULL then a
  92084. * \a tell_callback must also be supplied.
  92085. * Alternatively, a dummy tell callback that just
  92086. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92087. * may also be supplied, all though this is slightly
  92088. * less efficient for the encoder.
  92089. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92090. * pointer may be \c NULL if the callback is not
  92091. * desired. If the client provides a seek callback,
  92092. * this function is not necessary as the encoder
  92093. * will automatically seek back and update the
  92094. * STREAMINFO block. It may also be \c NULL if the
  92095. * client does not support seeking, since it will
  92096. * have no way of going back to update the
  92097. * STREAMINFO. However the client can still supply
  92098. * a callback if it would like to know the details
  92099. * from the STREAMINFO.
  92100. * \param client_data This value will be supplied to callbacks in their
  92101. * \a client_data argument.
  92102. * \assert
  92103. * \code encoder != NULL \endcode
  92104. * \retval FLAC__StreamEncoderInitStatus
  92105. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92106. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92107. */
  92108. 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);
  92109. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92110. *
  92111. * This flavor of initialization sets up the encoder to encode to a FLAC
  92112. * stream in an Ogg container. I/O is performed via callbacks to the
  92113. * client. For encoding to a plain file via filename or open \c FILE*,
  92114. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92115. * provide a simpler interface.
  92116. *
  92117. * This function should be called after FLAC__stream_encoder_new() and
  92118. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92119. * or FLAC__stream_encoder_process_interleaved().
  92120. * initialization succeeded.
  92121. *
  92122. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92123. * immediately call the write callback several times to write the metadata
  92124. * packets.
  92125. *
  92126. * \param encoder An uninitialized encoder instance.
  92127. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92128. * pointer must not be \c NULL if \a seek_callback
  92129. * is non-NULL since they are both needed to be
  92130. * able to write data back to the Ogg FLAC stream
  92131. * in the post-encode phase.
  92132. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92133. * pointer must not be \c NULL.
  92134. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92135. * pointer may be \c NULL if seeking is not
  92136. * supported. The encoder uses seeking to go back
  92137. * and write some some stream statistics to the
  92138. * STREAMINFO block; this is recommended but not
  92139. * necessary to create a valid FLAC stream. If
  92140. * \a seek_callback is not \c NULL then a
  92141. * \a tell_callback must also be supplied.
  92142. * Alternatively, a dummy seek callback that just
  92143. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92144. * may also be supplied, all though this is slightly
  92145. * less efficient for the encoder.
  92146. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92147. * pointer may be \c NULL if seeking is not
  92148. * supported. If \a seek_callback is \c NULL then
  92149. * this argument will be ignored. If
  92150. * \a seek_callback is not \c NULL then a
  92151. * \a tell_callback must also be supplied.
  92152. * Alternatively, a dummy tell callback that just
  92153. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92154. * may also be supplied, all though this is slightly
  92155. * less efficient for the encoder.
  92156. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92157. * pointer may be \c NULL if the callback is not
  92158. * desired. If the client provides a seek callback,
  92159. * this function is not necessary as the encoder
  92160. * will automatically seek back and update the
  92161. * STREAMINFO block. It may also be \c NULL if the
  92162. * client does not support seeking, since it will
  92163. * have no way of going back to update the
  92164. * STREAMINFO. However the client can still supply
  92165. * a callback if it would like to know the details
  92166. * from the STREAMINFO.
  92167. * \param client_data This value will be supplied to callbacks in their
  92168. * \a client_data argument.
  92169. * \assert
  92170. * \code encoder != NULL \endcode
  92171. * \retval FLAC__StreamEncoderInitStatus
  92172. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92173. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92174. */
  92175. 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);
  92176. /** Initialize the encoder instance to encode native FLAC files.
  92177. *
  92178. * This flavor of initialization sets up the encoder to encode to a
  92179. * plain native FLAC file. For non-stdio streams, you must use
  92180. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92181. *
  92182. * This function should be called after FLAC__stream_encoder_new() and
  92183. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92184. * or FLAC__stream_encoder_process_interleaved().
  92185. * initialization succeeded.
  92186. *
  92187. * \param encoder An uninitialized encoder instance.
  92188. * \param file An open file. The file should have been opened
  92189. * with mode \c "w+b" and rewound. The file
  92190. * becomes owned by the encoder and should not be
  92191. * manipulated by the client while encoding.
  92192. * Unless \a file is \c stdout, it will be closed
  92193. * when FLAC__stream_encoder_finish() is called.
  92194. * Note however that a proper SEEKTABLE cannot be
  92195. * created when encoding to \c stdout since it is
  92196. * not seekable.
  92197. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92198. * pointer may be \c NULL if the callback is not
  92199. * desired.
  92200. * \param client_data This value will be supplied to callbacks in their
  92201. * \a client_data argument.
  92202. * \assert
  92203. * \code encoder != NULL \endcode
  92204. * \code file != NULL \endcode
  92205. * \retval FLAC__StreamEncoderInitStatus
  92206. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92207. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92208. */
  92209. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92210. /** Initialize the encoder instance to encode Ogg FLAC files.
  92211. *
  92212. * This flavor of initialization sets up the encoder to encode to a
  92213. * plain Ogg FLAC file. For non-stdio streams, you must use
  92214. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92215. *
  92216. * This function should be called after FLAC__stream_encoder_new() and
  92217. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92218. * or FLAC__stream_encoder_process_interleaved().
  92219. * initialization succeeded.
  92220. *
  92221. * \param encoder An uninitialized encoder instance.
  92222. * \param file An open file. The file should have been opened
  92223. * with mode \c "w+b" and rewound. The file
  92224. * becomes owned by the encoder and should not be
  92225. * manipulated by the client while encoding.
  92226. * Unless \a file is \c stdout, it will be closed
  92227. * when FLAC__stream_encoder_finish() is called.
  92228. * Note however that a proper SEEKTABLE cannot be
  92229. * created when encoding to \c stdout since it is
  92230. * not seekable.
  92231. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92232. * pointer may be \c NULL if the callback is not
  92233. * desired.
  92234. * \param client_data This value will be supplied to callbacks in their
  92235. * \a client_data argument.
  92236. * \assert
  92237. * \code encoder != NULL \endcode
  92238. * \code file != NULL \endcode
  92239. * \retval FLAC__StreamEncoderInitStatus
  92240. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92241. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92242. */
  92243. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92244. /** Initialize the encoder instance to encode native FLAC files.
  92245. *
  92246. * This flavor of initialization sets up the encoder to encode to a plain
  92247. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92248. * with Unicode filenames on Windows), you must use
  92249. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92250. * and provide callbacks for the I/O.
  92251. *
  92252. * This function should be called after FLAC__stream_encoder_new() and
  92253. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92254. * or FLAC__stream_encoder_process_interleaved().
  92255. * initialization succeeded.
  92256. *
  92257. * \param encoder An uninitialized encoder instance.
  92258. * \param filename The name of the file to encode to. The file will
  92259. * be opened with fopen(). Use \c NULL to encode to
  92260. * \c stdout. Note however that a proper SEEKTABLE
  92261. * cannot be created when encoding to \c stdout since
  92262. * it is not seekable.
  92263. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92264. * pointer may be \c NULL if the callback is not
  92265. * desired.
  92266. * \param client_data This value will be supplied to callbacks in their
  92267. * \a client_data argument.
  92268. * \assert
  92269. * \code encoder != NULL \endcode
  92270. * \retval FLAC__StreamEncoderInitStatus
  92271. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92272. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92273. */
  92274. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92275. /** Initialize the encoder instance to encode Ogg FLAC files.
  92276. *
  92277. * This flavor of initialization sets up the encoder to encode to a plain
  92278. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92279. * with Unicode filenames on Windows), you must use
  92280. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92281. * and provide callbacks for the I/O.
  92282. *
  92283. * This function should be called after FLAC__stream_encoder_new() and
  92284. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92285. * or FLAC__stream_encoder_process_interleaved().
  92286. * initialization succeeded.
  92287. *
  92288. * \param encoder An uninitialized encoder instance.
  92289. * \param filename The name of the file to encode to. The file will
  92290. * be opened with fopen(). Use \c NULL to encode to
  92291. * \c stdout. Note however that a proper SEEKTABLE
  92292. * cannot be created when encoding to \c stdout since
  92293. * it is not seekable.
  92294. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92295. * pointer may be \c NULL if the callback is not
  92296. * desired.
  92297. * \param client_data This value will be supplied to callbacks in their
  92298. * \a client_data argument.
  92299. * \assert
  92300. * \code encoder != NULL \endcode
  92301. * \retval FLAC__StreamEncoderInitStatus
  92302. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92303. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92304. */
  92305. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92306. /** Finish the encoding process.
  92307. * Flushes the encoding buffer, releases resources, resets the encoder
  92308. * settings to their defaults, and returns the encoder state to
  92309. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92310. * one or more write callbacks before returning, and will generate
  92311. * a metadata callback.
  92312. *
  92313. * Note that in the course of processing the last frame, errors can
  92314. * occur, so the caller should be sure to check the return value to
  92315. * ensure the file was encoded properly.
  92316. *
  92317. * In the event of a prematurely-terminated encode, it is not strictly
  92318. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92319. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92320. * with a FLAC__stream_encoder_finish().
  92321. *
  92322. * \param encoder An uninitialized encoder instance.
  92323. * \assert
  92324. * \code encoder != NULL \endcode
  92325. * \retval FLAC__bool
  92326. * \c false if an error occurred processing the last frame; or if verify
  92327. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92328. * verify mismatch; else \c true. If \c false, caller should check the
  92329. * state with FLAC__stream_encoder_get_state() for more information
  92330. * about the error.
  92331. */
  92332. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92333. /** Submit data for encoding.
  92334. * This version allows you to supply the input data via an array of
  92335. * pointers, each pointer pointing to an array of \a samples samples
  92336. * representing one channel. The samples need not be block-aligned,
  92337. * but each channel should have the same number of samples. Each sample
  92338. * should be a signed integer, right-justified to the resolution set by
  92339. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92340. * resolution is 16 bits per sample, the samples should all be in the
  92341. * range [-32768,32767].
  92342. *
  92343. * For applications where channel order is important, channels must
  92344. * follow the order as described in the
  92345. * <A HREF="../format.html#frame_header">frame header</A>.
  92346. *
  92347. * \param encoder An initialized encoder instance in the OK state.
  92348. * \param buffer An array of pointers to each channel's signal.
  92349. * \param samples The number of samples in one channel.
  92350. * \assert
  92351. * \code encoder != NULL \endcode
  92352. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92353. * \retval FLAC__bool
  92354. * \c true if successful, else \c false; in this case, check the
  92355. * encoder state with FLAC__stream_encoder_get_state() to see what
  92356. * went wrong.
  92357. */
  92358. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92359. /** Submit data for encoding.
  92360. * This version allows you to supply the input data where the channels
  92361. * are interleaved into a single array (i.e. channel0_sample0,
  92362. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92363. * The samples need not be block-aligned but they must be
  92364. * sample-aligned, i.e. the first value should be channel0_sample0
  92365. * and the last value channelN_sampleM. Each sample should be a signed
  92366. * integer, right-justified to the resolution set by
  92367. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92368. * resolution is 16 bits per sample, the samples should all be in the
  92369. * range [-32768,32767].
  92370. *
  92371. * For applications where channel order is important, channels must
  92372. * follow the order as described in the
  92373. * <A HREF="../format.html#frame_header">frame header</A>.
  92374. *
  92375. * \param encoder An initialized encoder instance in the OK state.
  92376. * \param buffer An array of channel-interleaved data (see above).
  92377. * \param samples The number of samples in one channel, the same as for
  92378. * FLAC__stream_encoder_process(). For example, if
  92379. * encoding two channels, \c 1000 \a samples corresponds
  92380. * to a \a buffer of 2000 values.
  92381. * \assert
  92382. * \code encoder != NULL \endcode
  92383. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92384. * \retval FLAC__bool
  92385. * \c true if successful, else \c false; in this case, check the
  92386. * encoder state with FLAC__stream_encoder_get_state() to see what
  92387. * went wrong.
  92388. */
  92389. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92390. /* \} */
  92391. #ifdef __cplusplus
  92392. }
  92393. #endif
  92394. #endif
  92395. /*** End of inlined file: stream_encoder.h ***/
  92396. #ifdef _MSC_VER
  92397. /* OPT: an MSVC built-in would be better */
  92398. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92399. {
  92400. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92401. return (x>>16) | (x<<16);
  92402. }
  92403. #endif
  92404. #if defined(_MSC_VER) && defined(_X86_)
  92405. /* OPT: an MSVC built-in would be better */
  92406. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92407. {
  92408. __asm {
  92409. mov edx, start
  92410. mov ecx, len
  92411. test ecx, ecx
  92412. loop1:
  92413. jz done1
  92414. mov eax, [edx]
  92415. bswap eax
  92416. mov [edx], eax
  92417. add edx, 4
  92418. dec ecx
  92419. jmp short loop1
  92420. done1:
  92421. }
  92422. }
  92423. #endif
  92424. /** \mainpage
  92425. *
  92426. * \section intro Introduction
  92427. *
  92428. * This is the documentation for the FLAC C and C++ APIs. It is
  92429. * highly interconnected; this introduction should give you a top
  92430. * level idea of the structure and how to find the information you
  92431. * need. As a prerequisite you should have at least a basic
  92432. * knowledge of the FLAC format, documented
  92433. * <A HREF="../format.html">here</A>.
  92434. *
  92435. * \section c_api FLAC C API
  92436. *
  92437. * The FLAC C API is the interface to libFLAC, a set of structures
  92438. * describing the components of FLAC streams, and functions for
  92439. * encoding and decoding streams, as well as manipulating FLAC
  92440. * metadata in files. The public include files will be installed
  92441. * in your include area (for example /usr/include/FLAC/...).
  92442. *
  92443. * By writing a little code and linking against libFLAC, it is
  92444. * relatively easy to add FLAC support to another program. The
  92445. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92446. * Complete source code of libFLAC as well as the command-line
  92447. * encoder and plugins is available and is a useful source of
  92448. * examples.
  92449. *
  92450. * Aside from encoders and decoders, libFLAC provides a powerful
  92451. * metadata interface for manipulating metadata in FLAC files. It
  92452. * allows the user to add, delete, and modify FLAC metadata blocks
  92453. * and it can automatically take advantage of PADDING blocks to avoid
  92454. * rewriting the entire FLAC file when changing the size of the
  92455. * metadata.
  92456. *
  92457. * libFLAC usually only requires the standard C library and C math
  92458. * library. In particular, threading is not used so there is no
  92459. * dependency on a thread library. However, libFLAC does not use
  92460. * global variables and should be thread-safe.
  92461. *
  92462. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92463. * However the metadata editing interfaces currently have limited
  92464. * read-only support for Ogg FLAC files.
  92465. *
  92466. * \section cpp_api FLAC C++ API
  92467. *
  92468. * The FLAC C++ API is a set of classes that encapsulate the
  92469. * structures and functions in libFLAC. They provide slightly more
  92470. * functionality with respect to metadata but are otherwise
  92471. * equivalent. For the most part, they share the same usage as
  92472. * their counterparts in libFLAC, and the FLAC C API documentation
  92473. * can be used as a supplement. The public include files
  92474. * for the C++ API will be installed in your include area (for
  92475. * example /usr/include/FLAC++/...).
  92476. *
  92477. * libFLAC++ is also licensed under
  92478. * <A HREF="../license.html">Xiph's BSD license</A>.
  92479. *
  92480. * \section getting_started Getting Started
  92481. *
  92482. * A good starting point for learning the API is to browse through
  92483. * the <A HREF="modules.html">modules</A>. Modules are logical
  92484. * groupings of related functions or classes, which correspond roughly
  92485. * to header files or sections of header files. Each module includes a
  92486. * detailed description of the general usage of its functions or
  92487. * classes.
  92488. *
  92489. * From there you can go on to look at the documentation of
  92490. * individual functions. You can see different views of the individual
  92491. * functions through the links in top bar across this page.
  92492. *
  92493. * If you prefer a more hands-on approach, you can jump right to some
  92494. * <A HREF="../documentation_example_code.html">example code</A>.
  92495. *
  92496. * \section porting_guide Porting Guide
  92497. *
  92498. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92499. * has been introduced which gives detailed instructions on how to
  92500. * port your code to newer versions of FLAC.
  92501. *
  92502. * \section embedded_developers Embedded Developers
  92503. *
  92504. * libFLAC has grown larger over time as more functionality has been
  92505. * included, but much of it may be unnecessary for a particular embedded
  92506. * implementation. Unused parts may be pruned by some simple editing of
  92507. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92508. * metadata interface are all independent from each other.
  92509. *
  92510. * It is easiest to just describe the dependencies:
  92511. *
  92512. * - All modules depend on the \link flac_format Format \endlink module.
  92513. * - The decoders and encoders depend on the bitbuffer.
  92514. * - The decoder is independent of the encoder. The encoder uses the
  92515. * decoder because of the verify feature, but this can be removed if
  92516. * not needed.
  92517. * - Parts of the metadata interface require the stream decoder (but not
  92518. * the encoder).
  92519. * - Ogg support is selectable through the compile time macro
  92520. * \c FLAC__HAS_OGG.
  92521. *
  92522. * For example, if your application only requires the stream decoder, no
  92523. * encoder, and no metadata interface, you can remove the stream encoder
  92524. * and the metadata interface, which will greatly reduce the size of the
  92525. * library.
  92526. *
  92527. * Also, there are several places in the libFLAC code with comments marked
  92528. * with "OPT:" where a #define can be changed to enable code that might be
  92529. * faster on a specific platform. Experimenting with these can yield faster
  92530. * binaries.
  92531. */
  92532. /** \defgroup porting Porting Guide for New Versions
  92533. *
  92534. * This module describes differences in the library interfaces from
  92535. * version to version. It assists in the porting of code that uses
  92536. * the libraries to newer versions of FLAC.
  92537. *
  92538. * One simple facility for making porting easier that has been added
  92539. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92540. * library's includes (e.g. \c include/FLAC/export.h). The
  92541. * \c #defines mirror the libraries'
  92542. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92543. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92544. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92545. * These can be used to support multiple versions of an API during the
  92546. * transition phase, e.g.
  92547. *
  92548. * \code
  92549. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92550. * legacy code
  92551. * #else
  92552. * new code
  92553. * #endif
  92554. * \endcode
  92555. *
  92556. * The the source will work for multiple versions and the legacy code can
  92557. * easily be removed when the transition is complete.
  92558. *
  92559. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92560. * include/FLAC/export.h), which can be used to determine whether or not
  92561. * the library has been compiled with support for Ogg FLAC. This is
  92562. * simpler than trying to call an Ogg init function and catching the
  92563. * error.
  92564. */
  92565. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92566. * \ingroup porting
  92567. *
  92568. * \brief
  92569. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92570. *
  92571. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92572. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92573. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92574. * decoding layers and three encoding layers have been merged into a
  92575. * single stream decoder and stream encoder. That is, the functionality
  92576. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92577. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92578. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92579. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92580. * is there is now a single API that can be used to encode or decode
  92581. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92582. * on both seekable and non-seekable streams.
  92583. *
  92584. * Instead of creating an encoder or decoder of a certain layer, now the
  92585. * client will always create a FLAC__StreamEncoder or
  92586. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92587. * initialization function. For example, for the decoder,
  92588. * FLAC__stream_decoder_init() has been replaced by
  92589. * FLAC__stream_decoder_init_stream(). This init function takes
  92590. * callbacks for the I/O, and the seeking callbacks are optional. This
  92591. * allows the client to use the same object for seekable and
  92592. * non-seekable streams. For decoding a FLAC file directly, the client
  92593. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92594. * and fewer callbacks; most of the other callbacks are supplied
  92595. * internally. For situations where fopen()ing by filename is not
  92596. * possible (e.g. Unicode filenames on Windows) the client can instead
  92597. * open the file itself and supply the FILE* to
  92598. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92599. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92600. * Since the callbacks and client data are now passed to the init
  92601. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92602. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92603. * rest of the calls to the decoder are the same as before.
  92604. *
  92605. * There are counterpart init functions for Ogg FLAC, e.g.
  92606. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92607. * and callbacks are the same as for native FLAC.
  92608. *
  92609. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92610. * been set up like so:
  92611. *
  92612. * \code
  92613. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92614. * if(decoder == NULL) do_something;
  92615. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92616. * [... other settings ...]
  92617. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92618. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92619. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92620. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92621. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92622. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92623. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92624. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92625. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92626. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92627. * \endcode
  92628. *
  92629. * In FLAC 1.1.3 it is like this:
  92630. *
  92631. * \code
  92632. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92633. * if(decoder == NULL) do_something;
  92634. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92635. * [... other settings ...]
  92636. * if(FLAC__stream_decoder_init_stream(
  92637. * decoder,
  92638. * my_read_callback,
  92639. * my_seek_callback, // or NULL
  92640. * my_tell_callback, // or NULL
  92641. * my_length_callback, // or NULL
  92642. * my_eof_callback, // or NULL
  92643. * my_write_callback,
  92644. * my_metadata_callback, // or NULL
  92645. * my_error_callback,
  92646. * my_client_data
  92647. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92648. * \endcode
  92649. *
  92650. * or you could do;
  92651. *
  92652. * \code
  92653. * [...]
  92654. * FILE *file = fopen("somefile.flac","rb");
  92655. * if(file == NULL) do_somthing;
  92656. * if(FLAC__stream_decoder_init_FILE(
  92657. * decoder,
  92658. * file,
  92659. * my_write_callback,
  92660. * my_metadata_callback, // or NULL
  92661. * my_error_callback,
  92662. * my_client_data
  92663. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92664. * \endcode
  92665. *
  92666. * or just:
  92667. *
  92668. * \code
  92669. * [...]
  92670. * if(FLAC__stream_decoder_init_file(
  92671. * decoder,
  92672. * "somefile.flac",
  92673. * my_write_callback,
  92674. * my_metadata_callback, // or NULL
  92675. * my_error_callback,
  92676. * my_client_data
  92677. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92678. * \endcode
  92679. *
  92680. * Another small change to the decoder is in how it handles unparseable
  92681. * streams. Before, when the decoder found an unparseable stream
  92682. * (reserved for when the decoder encounters a stream from a future
  92683. * encoder that it can't parse), it changed the state to
  92684. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92685. * drops sync and calls the error callback with a new error code
  92686. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92687. * more robust. If your error callback does not discriminate on the the
  92688. * error state, your code does not need to be changed.
  92689. *
  92690. * The encoder now has a new setting:
  92691. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92692. * method used to window the data before LPC analysis. You only need to
  92693. * add a call to this function if the default is not suitable. There
  92694. * are also two new convenience functions that may be useful:
  92695. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92696. * FLAC__metadata_get_cuesheet().
  92697. *
  92698. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92699. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92700. * is now \c size_t instead of \c unsigned.
  92701. */
  92702. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92703. * \ingroup porting
  92704. *
  92705. * \brief
  92706. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92707. *
  92708. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92709. * There was a slight change in the implementation of
  92710. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92711. * of the \a metadata array of pointers so the client no longer needs
  92712. * to maintain it after the call. The objects themselves that are
  92713. * pointed to by the array are still not copied though and must be
  92714. * maintained until the call to FLAC__stream_encoder_finish().
  92715. */
  92716. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92717. * \ingroup porting
  92718. *
  92719. * \brief
  92720. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92721. *
  92722. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92723. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92724. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92725. *
  92726. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92727. * has changed to reflect the conversion of one of the reserved bits
  92728. * into active use. It used to be \c 2 and now is \c 1. However the
  92729. * FLAC frame header length has not changed, so to skip the proper
  92730. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92731. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92732. */
  92733. /** \defgroup flac FLAC C API
  92734. *
  92735. * The FLAC C API is the interface to libFLAC, a set of structures
  92736. * describing the components of FLAC streams, and functions for
  92737. * encoding and decoding streams, as well as manipulating FLAC
  92738. * metadata in files.
  92739. *
  92740. * You should start with the format components as all other modules
  92741. * are dependent on it.
  92742. */
  92743. #endif
  92744. /*** End of inlined file: all.h ***/
  92745. /*** Start of inlined file: bitmath.c ***/
  92746. /*** Start of inlined file: juce_FlacHeader.h ***/
  92747. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92748. // tasks..
  92749. #define VERSION "1.2.1"
  92750. #define FLAC__NO_DLL 1
  92751. #if JUCE_MSVC
  92752. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92753. #endif
  92754. #if JUCE_MAC
  92755. #define FLAC__SYS_DARWIN 1
  92756. #endif
  92757. /*** End of inlined file: juce_FlacHeader.h ***/
  92758. #if JUCE_USE_FLAC
  92759. #if HAVE_CONFIG_H
  92760. # include <config.h>
  92761. #endif
  92762. /*** Start of inlined file: bitmath.h ***/
  92763. #ifndef FLAC__PRIVATE__BITMATH_H
  92764. #define FLAC__PRIVATE__BITMATH_H
  92765. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92766. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92767. unsigned FLAC__bitmath_silog2(int v);
  92768. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92769. #endif
  92770. /*** End of inlined file: bitmath.h ***/
  92771. /* An example of what FLAC__bitmath_ilog2() computes:
  92772. *
  92773. * ilog2( 0) = assertion failure
  92774. * ilog2( 1) = 0
  92775. * ilog2( 2) = 1
  92776. * ilog2( 3) = 1
  92777. * ilog2( 4) = 2
  92778. * ilog2( 5) = 2
  92779. * ilog2( 6) = 2
  92780. * ilog2( 7) = 2
  92781. * ilog2( 8) = 3
  92782. * ilog2( 9) = 3
  92783. * ilog2(10) = 3
  92784. * ilog2(11) = 3
  92785. * ilog2(12) = 3
  92786. * ilog2(13) = 3
  92787. * ilog2(14) = 3
  92788. * ilog2(15) = 3
  92789. * ilog2(16) = 4
  92790. * ilog2(17) = 4
  92791. * ilog2(18) = 4
  92792. */
  92793. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92794. {
  92795. unsigned l = 0;
  92796. FLAC__ASSERT(v > 0);
  92797. while(v >>= 1)
  92798. l++;
  92799. return l;
  92800. }
  92801. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92802. {
  92803. unsigned l = 0;
  92804. FLAC__ASSERT(v > 0);
  92805. while(v >>= 1)
  92806. l++;
  92807. return l;
  92808. }
  92809. /* An example of what FLAC__bitmath_silog2() computes:
  92810. *
  92811. * silog2(-10) = 5
  92812. * silog2(- 9) = 5
  92813. * silog2(- 8) = 4
  92814. * silog2(- 7) = 4
  92815. * silog2(- 6) = 4
  92816. * silog2(- 5) = 4
  92817. * silog2(- 4) = 3
  92818. * silog2(- 3) = 3
  92819. * silog2(- 2) = 2
  92820. * silog2(- 1) = 2
  92821. * silog2( 0) = 0
  92822. * silog2( 1) = 2
  92823. * silog2( 2) = 3
  92824. * silog2( 3) = 3
  92825. * silog2( 4) = 4
  92826. * silog2( 5) = 4
  92827. * silog2( 6) = 4
  92828. * silog2( 7) = 4
  92829. * silog2( 8) = 5
  92830. * silog2( 9) = 5
  92831. * silog2( 10) = 5
  92832. */
  92833. unsigned FLAC__bitmath_silog2(int v)
  92834. {
  92835. while(1) {
  92836. if(v == 0) {
  92837. return 0;
  92838. }
  92839. else if(v > 0) {
  92840. unsigned l = 0;
  92841. while(v) {
  92842. l++;
  92843. v >>= 1;
  92844. }
  92845. return l+1;
  92846. }
  92847. else if(v == -1) {
  92848. return 2;
  92849. }
  92850. else {
  92851. v++;
  92852. v = -v;
  92853. }
  92854. }
  92855. }
  92856. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92857. {
  92858. while(1) {
  92859. if(v == 0) {
  92860. return 0;
  92861. }
  92862. else if(v > 0) {
  92863. unsigned l = 0;
  92864. while(v) {
  92865. l++;
  92866. v >>= 1;
  92867. }
  92868. return l+1;
  92869. }
  92870. else if(v == -1) {
  92871. return 2;
  92872. }
  92873. else {
  92874. v++;
  92875. v = -v;
  92876. }
  92877. }
  92878. }
  92879. #endif
  92880. /*** End of inlined file: bitmath.c ***/
  92881. /*** Start of inlined file: bitreader.c ***/
  92882. /*** Start of inlined file: juce_FlacHeader.h ***/
  92883. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92884. // tasks..
  92885. #define VERSION "1.2.1"
  92886. #define FLAC__NO_DLL 1
  92887. #if JUCE_MSVC
  92888. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92889. #endif
  92890. #if JUCE_MAC
  92891. #define FLAC__SYS_DARWIN 1
  92892. #endif
  92893. /*** End of inlined file: juce_FlacHeader.h ***/
  92894. #if JUCE_USE_FLAC
  92895. #if HAVE_CONFIG_H
  92896. # include <config.h>
  92897. #endif
  92898. #include <stdlib.h> /* for malloc() */
  92899. #include <string.h> /* for memcpy(), memset() */
  92900. #ifdef _MSC_VER
  92901. #include <winsock.h> /* for ntohl() */
  92902. #elif defined FLAC__SYS_DARWIN
  92903. #include <machine/endian.h> /* for ntohl() */
  92904. #elif defined __MINGW32__
  92905. #include <winsock.h> /* for ntohl() */
  92906. #else
  92907. #include <netinet/in.h> /* for ntohl() */
  92908. #endif
  92909. /*** Start of inlined file: bitreader.h ***/
  92910. #ifndef FLAC__PRIVATE__BITREADER_H
  92911. #define FLAC__PRIVATE__BITREADER_H
  92912. #include <stdio.h> /* for FILE */
  92913. /*** Start of inlined file: cpu.h ***/
  92914. #ifndef FLAC__PRIVATE__CPU_H
  92915. #define FLAC__PRIVATE__CPU_H
  92916. #ifdef HAVE_CONFIG_H
  92917. #include <config.h>
  92918. #endif
  92919. typedef enum {
  92920. FLAC__CPUINFO_TYPE_IA32,
  92921. FLAC__CPUINFO_TYPE_PPC,
  92922. FLAC__CPUINFO_TYPE_UNKNOWN
  92923. } FLAC__CPUInfo_Type;
  92924. typedef struct {
  92925. FLAC__bool cpuid;
  92926. FLAC__bool bswap;
  92927. FLAC__bool cmov;
  92928. FLAC__bool mmx;
  92929. FLAC__bool fxsr;
  92930. FLAC__bool sse;
  92931. FLAC__bool sse2;
  92932. FLAC__bool sse3;
  92933. FLAC__bool ssse3;
  92934. FLAC__bool _3dnow;
  92935. FLAC__bool ext3dnow;
  92936. FLAC__bool extmmx;
  92937. } FLAC__CPUInfo_IA32;
  92938. typedef struct {
  92939. FLAC__bool altivec;
  92940. FLAC__bool ppc64;
  92941. } FLAC__CPUInfo_PPC;
  92942. typedef struct {
  92943. FLAC__bool use_asm;
  92944. FLAC__CPUInfo_Type type;
  92945. union {
  92946. FLAC__CPUInfo_IA32 ia32;
  92947. FLAC__CPUInfo_PPC ppc;
  92948. } data;
  92949. } FLAC__CPUInfo;
  92950. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92951. #ifndef FLAC__NO_ASM
  92952. #ifdef FLAC__CPU_IA32
  92953. #ifdef FLAC__HAS_NASM
  92954. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92955. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92956. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92957. #endif
  92958. #endif
  92959. #endif
  92960. #endif
  92961. /*** End of inlined file: cpu.h ***/
  92962. /*
  92963. * opaque structure definition
  92964. */
  92965. struct FLAC__BitReader;
  92966. typedef struct FLAC__BitReader FLAC__BitReader;
  92967. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92968. /*
  92969. * construction, deletion, initialization, etc functions
  92970. */
  92971. FLAC__BitReader *FLAC__bitreader_new(void);
  92972. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92973. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92974. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92975. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92976. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92977. /*
  92978. * CRC functions
  92979. */
  92980. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92981. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92982. /*
  92983. * info functions
  92984. */
  92985. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92986. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92987. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92988. /*
  92989. * read functions
  92990. */
  92991. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92992. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92993. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92994. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92995. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92996. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92997. 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! */
  92998. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92999. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93000. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93001. #ifndef FLAC__NO_ASM
  93002. # ifdef FLAC__CPU_IA32
  93003. # ifdef FLAC__HAS_NASM
  93004. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93005. # endif
  93006. # endif
  93007. #endif
  93008. #if 0 /* UNUSED */
  93009. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93010. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  93011. #endif
  93012. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  93013. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  93014. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  93015. #endif
  93016. /*** End of inlined file: bitreader.h ***/
  93017. /*** Start of inlined file: crc.h ***/
  93018. #ifndef FLAC__PRIVATE__CRC_H
  93019. #define FLAC__PRIVATE__CRC_H
  93020. /* 8 bit CRC generator, MSB shifted first
  93021. ** polynomial = x^8 + x^2 + x^1 + x^0
  93022. ** init = 0
  93023. */
  93024. extern FLAC__byte const FLAC__crc8_table[256];
  93025. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  93026. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  93027. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  93028. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  93029. /* 16 bit CRC generator, MSB shifted first
  93030. ** polynomial = x^16 + x^15 + x^2 + x^0
  93031. ** init = 0
  93032. */
  93033. extern unsigned FLAC__crc16_table[256];
  93034. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  93035. /* this alternate may be faster on some systems/compilers */
  93036. #if 0
  93037. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  93038. #endif
  93039. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  93040. #endif
  93041. /*** End of inlined file: crc.h ***/
  93042. /* Things should be fastest when this matches the machine word size */
  93043. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  93044. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  93045. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  93046. typedef FLAC__uint32 brword;
  93047. #define FLAC__BYTES_PER_WORD 4
  93048. #define FLAC__BITS_PER_WORD 32
  93049. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93050. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  93051. #if WORDS_BIGENDIAN
  93052. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93053. #else
  93054. #if defined (_MSC_VER) && defined (_X86_)
  93055. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93056. #else
  93057. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93058. #endif
  93059. #endif
  93060. /* counts the # of zero MSBs in a word */
  93061. #define COUNT_ZERO_MSBS(word) ( \
  93062. (word) <= 0xffff ? \
  93063. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  93064. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  93065. )
  93066. /* this alternate might be slightly faster on some systems/compilers: */
  93067. #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])) )
  93068. /*
  93069. * This should be at least twice as large as the largest number of words
  93070. * required to represent any 'number' (in any encoding) you are going to
  93071. * read. With FLAC this is on the order of maybe a few hundred bits.
  93072. * If the buffer is smaller than that, the decoder won't be able to read
  93073. * in a whole number that is in a variable length encoding (e.g. Rice).
  93074. * But to be practical it should be at least 1K bytes.
  93075. *
  93076. * Increase this number to decrease the number of read callbacks, at the
  93077. * expense of using more memory. Or decrease for the reverse effect,
  93078. * keeping in mind the limit from the first paragraph. The optimal size
  93079. * also depends on the CPU cache size and other factors; some twiddling
  93080. * may be necessary to squeeze out the best performance.
  93081. */
  93082. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  93083. static const unsigned char byte_to_unary_table[] = {
  93084. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93085. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93086. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93087. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93088. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93089. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93090. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93091. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93100. };
  93101. #ifdef min
  93102. #undef min
  93103. #endif
  93104. #define min(x,y) ((x)<(y)?(x):(y))
  93105. #ifdef max
  93106. #undef max
  93107. #endif
  93108. #define max(x,y) ((x)>(y)?(x):(y))
  93109. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93110. #ifdef _MSC_VER
  93111. #define FLAC__U64L(x) x
  93112. #else
  93113. #define FLAC__U64L(x) x##LLU
  93114. #endif
  93115. #ifndef FLaC__INLINE
  93116. #define FLaC__INLINE
  93117. #endif
  93118. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93119. struct FLAC__BitReader {
  93120. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93121. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93122. brword *buffer;
  93123. unsigned capacity; /* in words */
  93124. unsigned words; /* # of completed words in buffer */
  93125. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93126. unsigned consumed_words; /* #words ... */
  93127. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93128. unsigned read_crc16; /* the running frame CRC */
  93129. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93130. FLAC__BitReaderReadCallback read_callback;
  93131. void *client_data;
  93132. FLAC__CPUInfo cpu_info;
  93133. };
  93134. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93135. {
  93136. register unsigned crc = br->read_crc16;
  93137. #if FLAC__BYTES_PER_WORD == 4
  93138. switch(br->crc16_align) {
  93139. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93140. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93141. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93142. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93143. }
  93144. #elif FLAC__BYTES_PER_WORD == 8
  93145. switch(br->crc16_align) {
  93146. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93147. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93148. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93149. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93150. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93151. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93152. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93153. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93154. }
  93155. #else
  93156. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93157. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93158. br->read_crc16 = crc;
  93159. #endif
  93160. br->crc16_align = 0;
  93161. }
  93162. /* would be static except it needs to be called by asm routines */
  93163. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93164. {
  93165. unsigned start, end;
  93166. size_t bytes;
  93167. FLAC__byte *target;
  93168. /* first shift the unconsumed buffer data toward the front as much as possible */
  93169. if(br->consumed_words > 0) {
  93170. start = br->consumed_words;
  93171. end = br->words + (br->bytes? 1:0);
  93172. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93173. br->words -= start;
  93174. br->consumed_words = 0;
  93175. }
  93176. /*
  93177. * set the target for reading, taking into account word alignment and endianness
  93178. */
  93179. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93180. if(bytes == 0)
  93181. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93182. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93183. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93184. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93185. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93186. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93187. * ^^-------target, bytes=3
  93188. * on LE machines, have to byteswap the odd tail word so nothing is
  93189. * overwritten:
  93190. */
  93191. #if WORDS_BIGENDIAN
  93192. #else
  93193. if(br->bytes)
  93194. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93195. #endif
  93196. /* now it looks like:
  93197. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93198. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93199. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93200. * ^^-------target, bytes=3
  93201. */
  93202. /* read in the data; note that the callback may return a smaller number of bytes */
  93203. if(!br->read_callback(target, &bytes, br->client_data))
  93204. return false;
  93205. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93206. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93207. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93208. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93209. * now have to byteswap on LE machines:
  93210. */
  93211. #if WORDS_BIGENDIAN
  93212. #else
  93213. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93214. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93215. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93216. start = br->words;
  93217. local_swap32_block_(br->buffer + start, end - start);
  93218. }
  93219. else
  93220. # endif
  93221. for(start = br->words; start < end; start++)
  93222. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93223. #endif
  93224. /* now it looks like:
  93225. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93226. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93227. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93228. * finally we'll update the reader values:
  93229. */
  93230. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93231. br->words = end / FLAC__BYTES_PER_WORD;
  93232. br->bytes = end % FLAC__BYTES_PER_WORD;
  93233. return true;
  93234. }
  93235. /***********************************************************************
  93236. *
  93237. * Class constructor/destructor
  93238. *
  93239. ***********************************************************************/
  93240. FLAC__BitReader *FLAC__bitreader_new(void)
  93241. {
  93242. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93243. /* calloc() implies:
  93244. memset(br, 0, sizeof(FLAC__BitReader));
  93245. br->buffer = 0;
  93246. br->capacity = 0;
  93247. br->words = br->bytes = 0;
  93248. br->consumed_words = br->consumed_bits = 0;
  93249. br->read_callback = 0;
  93250. br->client_data = 0;
  93251. */
  93252. return br;
  93253. }
  93254. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93255. {
  93256. FLAC__ASSERT(0 != br);
  93257. FLAC__bitreader_free(br);
  93258. free(br);
  93259. }
  93260. /***********************************************************************
  93261. *
  93262. * Public class methods
  93263. *
  93264. ***********************************************************************/
  93265. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93266. {
  93267. FLAC__ASSERT(0 != br);
  93268. br->words = br->bytes = 0;
  93269. br->consumed_words = br->consumed_bits = 0;
  93270. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93271. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93272. if(br->buffer == 0)
  93273. return false;
  93274. br->read_callback = rcb;
  93275. br->client_data = cd;
  93276. br->cpu_info = cpu;
  93277. return true;
  93278. }
  93279. void FLAC__bitreader_free(FLAC__BitReader *br)
  93280. {
  93281. FLAC__ASSERT(0 != br);
  93282. if(0 != br->buffer)
  93283. free(br->buffer);
  93284. br->buffer = 0;
  93285. br->capacity = 0;
  93286. br->words = br->bytes = 0;
  93287. br->consumed_words = br->consumed_bits = 0;
  93288. br->read_callback = 0;
  93289. br->client_data = 0;
  93290. }
  93291. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93292. {
  93293. br->words = br->bytes = 0;
  93294. br->consumed_words = br->consumed_bits = 0;
  93295. return true;
  93296. }
  93297. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93298. {
  93299. unsigned i, j;
  93300. if(br == 0) {
  93301. fprintf(out, "bitreader is NULL\n");
  93302. }
  93303. else {
  93304. 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);
  93305. for(i = 0; i < br->words; i++) {
  93306. fprintf(out, "%08X: ", i);
  93307. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93308. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93309. fprintf(out, ".");
  93310. else
  93311. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93312. fprintf(out, "\n");
  93313. }
  93314. if(br->bytes > 0) {
  93315. fprintf(out, "%08X: ", i);
  93316. for(j = 0; j < br->bytes*8; j++)
  93317. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93318. fprintf(out, ".");
  93319. else
  93320. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93321. fprintf(out, "\n");
  93322. }
  93323. }
  93324. }
  93325. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93326. {
  93327. FLAC__ASSERT(0 != br);
  93328. FLAC__ASSERT(0 != br->buffer);
  93329. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93330. br->read_crc16 = (unsigned)seed;
  93331. br->crc16_align = br->consumed_bits;
  93332. }
  93333. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93334. {
  93335. FLAC__ASSERT(0 != br);
  93336. FLAC__ASSERT(0 != br->buffer);
  93337. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93338. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93339. /* CRC any tail bytes in a partially-consumed word */
  93340. if(br->consumed_bits) {
  93341. const brword tail = br->buffer[br->consumed_words];
  93342. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93343. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93344. }
  93345. return br->read_crc16;
  93346. }
  93347. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93348. {
  93349. return ((br->consumed_bits & 7) == 0);
  93350. }
  93351. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93352. {
  93353. return 8 - (br->consumed_bits & 7);
  93354. }
  93355. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93356. {
  93357. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93358. }
  93359. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93360. {
  93361. FLAC__ASSERT(0 != br);
  93362. FLAC__ASSERT(0 != br->buffer);
  93363. FLAC__ASSERT(bits <= 32);
  93364. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93365. FLAC__ASSERT(br->consumed_words <= br->words);
  93366. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93367. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93368. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93369. *val = 0;
  93370. return true;
  93371. }
  93372. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93373. if(!bitreader_read_from_client_(br))
  93374. return false;
  93375. }
  93376. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93377. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93378. if(br->consumed_bits) {
  93379. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93380. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93381. const brword word = br->buffer[br->consumed_words];
  93382. if(bits < n) {
  93383. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93384. br->consumed_bits += bits;
  93385. return true;
  93386. }
  93387. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93388. bits -= n;
  93389. crc16_update_word_(br, word);
  93390. br->consumed_words++;
  93391. br->consumed_bits = 0;
  93392. 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 */
  93393. *val <<= bits;
  93394. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93395. br->consumed_bits = bits;
  93396. }
  93397. return true;
  93398. }
  93399. else {
  93400. const brword word = br->buffer[br->consumed_words];
  93401. if(bits < FLAC__BITS_PER_WORD) {
  93402. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93403. br->consumed_bits = bits;
  93404. return true;
  93405. }
  93406. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93407. *val = word;
  93408. crc16_update_word_(br, word);
  93409. br->consumed_words++;
  93410. return true;
  93411. }
  93412. }
  93413. else {
  93414. /* in this case we're starting our read at a partial tail word;
  93415. * the reader has guaranteed that we have at least 'bits' bits
  93416. * available to read, which makes this case simpler.
  93417. */
  93418. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93419. if(br->consumed_bits) {
  93420. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93421. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93422. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93423. br->consumed_bits += bits;
  93424. return true;
  93425. }
  93426. else {
  93427. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93428. br->consumed_bits += bits;
  93429. return true;
  93430. }
  93431. }
  93432. }
  93433. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93434. {
  93435. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93436. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93437. return false;
  93438. /* sign-extend: */
  93439. *val <<= (32-bits);
  93440. *val >>= (32-bits);
  93441. return true;
  93442. }
  93443. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93444. {
  93445. FLAC__uint32 hi, lo;
  93446. if(bits > 32) {
  93447. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93448. return false;
  93449. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93450. return false;
  93451. *val = hi;
  93452. *val <<= 32;
  93453. *val |= lo;
  93454. }
  93455. else {
  93456. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93457. return false;
  93458. *val = lo;
  93459. }
  93460. return true;
  93461. }
  93462. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93463. {
  93464. FLAC__uint32 x8, x32 = 0;
  93465. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93466. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93467. return false;
  93468. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93469. return false;
  93470. x32 |= (x8 << 8);
  93471. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93472. return false;
  93473. x32 |= (x8 << 16);
  93474. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93475. return false;
  93476. x32 |= (x8 << 24);
  93477. *val = x32;
  93478. return true;
  93479. }
  93480. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93481. {
  93482. /*
  93483. * OPT: a faster implementation is possible but probably not that useful
  93484. * since this is only called a couple of times in the metadata readers.
  93485. */
  93486. FLAC__ASSERT(0 != br);
  93487. FLAC__ASSERT(0 != br->buffer);
  93488. if(bits > 0) {
  93489. const unsigned n = br->consumed_bits & 7;
  93490. unsigned m;
  93491. FLAC__uint32 x;
  93492. if(n != 0) {
  93493. m = min(8-n, bits);
  93494. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93495. return false;
  93496. bits -= m;
  93497. }
  93498. m = bits / 8;
  93499. if(m > 0) {
  93500. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93501. return false;
  93502. bits %= 8;
  93503. }
  93504. if(bits > 0) {
  93505. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93506. return false;
  93507. }
  93508. }
  93509. return true;
  93510. }
  93511. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93512. {
  93513. FLAC__uint32 x;
  93514. FLAC__ASSERT(0 != br);
  93515. FLAC__ASSERT(0 != br->buffer);
  93516. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93517. /* step 1: skip over partial head word to get word aligned */
  93518. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93519. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93520. return false;
  93521. nvals--;
  93522. }
  93523. if(0 == nvals)
  93524. return true;
  93525. /* step 2: skip whole words in chunks */
  93526. while(nvals >= FLAC__BYTES_PER_WORD) {
  93527. if(br->consumed_words < br->words) {
  93528. br->consumed_words++;
  93529. nvals -= FLAC__BYTES_PER_WORD;
  93530. }
  93531. else if(!bitreader_read_from_client_(br))
  93532. return false;
  93533. }
  93534. /* step 3: skip any remainder from partial tail bytes */
  93535. while(nvals) {
  93536. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93537. return false;
  93538. nvals--;
  93539. }
  93540. return true;
  93541. }
  93542. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93543. {
  93544. FLAC__uint32 x;
  93545. FLAC__ASSERT(0 != br);
  93546. FLAC__ASSERT(0 != br->buffer);
  93547. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93548. /* step 1: read from partial head word to get word aligned */
  93549. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93550. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93551. return false;
  93552. *val++ = (FLAC__byte)x;
  93553. nvals--;
  93554. }
  93555. if(0 == nvals)
  93556. return true;
  93557. /* step 2: read whole words in chunks */
  93558. while(nvals >= FLAC__BYTES_PER_WORD) {
  93559. if(br->consumed_words < br->words) {
  93560. const brword word = br->buffer[br->consumed_words++];
  93561. #if FLAC__BYTES_PER_WORD == 4
  93562. val[0] = (FLAC__byte)(word >> 24);
  93563. val[1] = (FLAC__byte)(word >> 16);
  93564. val[2] = (FLAC__byte)(word >> 8);
  93565. val[3] = (FLAC__byte)word;
  93566. #elif FLAC__BYTES_PER_WORD == 8
  93567. val[0] = (FLAC__byte)(word >> 56);
  93568. val[1] = (FLAC__byte)(word >> 48);
  93569. val[2] = (FLAC__byte)(word >> 40);
  93570. val[3] = (FLAC__byte)(word >> 32);
  93571. val[4] = (FLAC__byte)(word >> 24);
  93572. val[5] = (FLAC__byte)(word >> 16);
  93573. val[6] = (FLAC__byte)(word >> 8);
  93574. val[7] = (FLAC__byte)word;
  93575. #else
  93576. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93577. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93578. #endif
  93579. val += FLAC__BYTES_PER_WORD;
  93580. nvals -= FLAC__BYTES_PER_WORD;
  93581. }
  93582. else if(!bitreader_read_from_client_(br))
  93583. return false;
  93584. }
  93585. /* step 3: read any remainder from partial tail bytes */
  93586. while(nvals) {
  93587. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93588. return false;
  93589. *val++ = (FLAC__byte)x;
  93590. nvals--;
  93591. }
  93592. return true;
  93593. }
  93594. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93595. #if 0 /* slow but readable version */
  93596. {
  93597. unsigned bit;
  93598. FLAC__ASSERT(0 != br);
  93599. FLAC__ASSERT(0 != br->buffer);
  93600. *val = 0;
  93601. while(1) {
  93602. if(!FLAC__bitreader_read_bit(br, &bit))
  93603. return false;
  93604. if(bit)
  93605. break;
  93606. else
  93607. *val++;
  93608. }
  93609. return true;
  93610. }
  93611. #else
  93612. {
  93613. unsigned i;
  93614. FLAC__ASSERT(0 != br);
  93615. FLAC__ASSERT(0 != br->buffer);
  93616. *val = 0;
  93617. while(1) {
  93618. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93619. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93620. if(b) {
  93621. i = COUNT_ZERO_MSBS(b);
  93622. *val += i;
  93623. i++;
  93624. br->consumed_bits += i;
  93625. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93626. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93627. br->consumed_words++;
  93628. br->consumed_bits = 0;
  93629. }
  93630. return true;
  93631. }
  93632. else {
  93633. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93634. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93635. br->consumed_words++;
  93636. br->consumed_bits = 0;
  93637. /* didn't find stop bit yet, have to keep going... */
  93638. }
  93639. }
  93640. /* at this point we've eaten up all the whole words; have to try
  93641. * reading through any tail bytes before calling the read callback.
  93642. * this is a repeat of the above logic adjusted for the fact we
  93643. * don't have a whole word. note though if the client is feeding
  93644. * us data a byte at a time (unlikely), br->consumed_bits may not
  93645. * be zero.
  93646. */
  93647. if(br->bytes) {
  93648. const unsigned end = br->bytes * 8;
  93649. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93650. if(b) {
  93651. i = COUNT_ZERO_MSBS(b);
  93652. *val += i;
  93653. i++;
  93654. br->consumed_bits += i;
  93655. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93656. return true;
  93657. }
  93658. else {
  93659. *val += end - br->consumed_bits;
  93660. br->consumed_bits += end;
  93661. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93662. /* didn't find stop bit yet, have to keep going... */
  93663. }
  93664. }
  93665. if(!bitreader_read_from_client_(br))
  93666. return false;
  93667. }
  93668. }
  93669. #endif
  93670. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93671. {
  93672. FLAC__uint32 lsbs = 0, msbs = 0;
  93673. unsigned uval;
  93674. FLAC__ASSERT(0 != br);
  93675. FLAC__ASSERT(0 != br->buffer);
  93676. FLAC__ASSERT(parameter <= 31);
  93677. /* read the unary MSBs and end bit */
  93678. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93679. return false;
  93680. /* read the binary LSBs */
  93681. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93682. return false;
  93683. /* compose the value */
  93684. uval = (msbs << parameter) | lsbs;
  93685. if(uval & 1)
  93686. *val = -((int)(uval >> 1)) - 1;
  93687. else
  93688. *val = (int)(uval >> 1);
  93689. return true;
  93690. }
  93691. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93692. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93693. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93694. /* OPT: possibly faster version for use with MSVC */
  93695. #ifdef _MSC_VER
  93696. {
  93697. unsigned i;
  93698. unsigned uval = 0;
  93699. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93700. /* try and get br->consumed_words and br->consumed_bits into register;
  93701. * must remember to flush them back to *br before calling other
  93702. * bitwriter functions that use them, and before returning */
  93703. register unsigned cwords;
  93704. register unsigned cbits;
  93705. FLAC__ASSERT(0 != br);
  93706. FLAC__ASSERT(0 != br->buffer);
  93707. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93708. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93709. FLAC__ASSERT(parameter < 32);
  93710. /* 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 */
  93711. if(nvals == 0)
  93712. return true;
  93713. cbits = br->consumed_bits;
  93714. cwords = br->consumed_words;
  93715. while(1) {
  93716. /* read unary part */
  93717. while(1) {
  93718. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93719. brword b = br->buffer[cwords] << cbits;
  93720. if(b) {
  93721. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93722. __asm {
  93723. bsr eax, b
  93724. not eax
  93725. and eax, 31
  93726. mov i, eax
  93727. }
  93728. #else
  93729. i = COUNT_ZERO_MSBS(b);
  93730. #endif
  93731. uval += i;
  93732. bits = parameter;
  93733. i++;
  93734. cbits += i;
  93735. if(cbits == FLAC__BITS_PER_WORD) {
  93736. crc16_update_word_(br, br->buffer[cwords]);
  93737. cwords++;
  93738. cbits = 0;
  93739. }
  93740. goto break1;
  93741. }
  93742. else {
  93743. uval += FLAC__BITS_PER_WORD - cbits;
  93744. crc16_update_word_(br, br->buffer[cwords]);
  93745. cwords++;
  93746. cbits = 0;
  93747. /* didn't find stop bit yet, have to keep going... */
  93748. }
  93749. }
  93750. /* at this point we've eaten up all the whole words; have to try
  93751. * reading through any tail bytes before calling the read callback.
  93752. * this is a repeat of the above logic adjusted for the fact we
  93753. * don't have a whole word. note though if the client is feeding
  93754. * us data a byte at a time (unlikely), br->consumed_bits may not
  93755. * be zero.
  93756. */
  93757. if(br->bytes) {
  93758. const unsigned end = br->bytes * 8;
  93759. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93760. if(b) {
  93761. i = COUNT_ZERO_MSBS(b);
  93762. uval += i;
  93763. bits = parameter;
  93764. i++;
  93765. cbits += i;
  93766. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93767. goto break1;
  93768. }
  93769. else {
  93770. uval += end - cbits;
  93771. cbits += end;
  93772. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93773. /* didn't find stop bit yet, have to keep going... */
  93774. }
  93775. }
  93776. /* flush registers and read; bitreader_read_from_client_() does
  93777. * not touch br->consumed_bits at all but we still need to set
  93778. * it in case it fails and we have to return false.
  93779. */
  93780. br->consumed_bits = cbits;
  93781. br->consumed_words = cwords;
  93782. if(!bitreader_read_from_client_(br))
  93783. return false;
  93784. cwords = br->consumed_words;
  93785. }
  93786. break1:
  93787. /* read binary part */
  93788. FLAC__ASSERT(cwords <= br->words);
  93789. if(bits) {
  93790. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93791. /* flush registers and read; bitreader_read_from_client_() does
  93792. * not touch br->consumed_bits at all but we still need to set
  93793. * it in case it fails and we have to return false.
  93794. */
  93795. br->consumed_bits = cbits;
  93796. br->consumed_words = cwords;
  93797. if(!bitreader_read_from_client_(br))
  93798. return false;
  93799. cwords = br->consumed_words;
  93800. }
  93801. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93802. if(cbits) {
  93803. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93804. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93805. const brword word = br->buffer[cwords];
  93806. if(bits < n) {
  93807. uval <<= bits;
  93808. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93809. cbits += bits;
  93810. goto break2;
  93811. }
  93812. uval <<= n;
  93813. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93814. bits -= n;
  93815. crc16_update_word_(br, word);
  93816. cwords++;
  93817. cbits = 0;
  93818. 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 */
  93819. uval <<= bits;
  93820. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93821. cbits = bits;
  93822. }
  93823. goto break2;
  93824. }
  93825. else {
  93826. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93827. uval <<= bits;
  93828. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93829. cbits = bits;
  93830. goto break2;
  93831. }
  93832. }
  93833. else {
  93834. /* in this case we're starting our read at a partial tail word;
  93835. * the reader has guaranteed that we have at least 'bits' bits
  93836. * available to read, which makes this case simpler.
  93837. */
  93838. uval <<= bits;
  93839. if(cbits) {
  93840. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93841. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93842. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93843. cbits += bits;
  93844. goto break2;
  93845. }
  93846. else {
  93847. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93848. cbits += bits;
  93849. goto break2;
  93850. }
  93851. }
  93852. }
  93853. break2:
  93854. /* compose the value */
  93855. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93856. /* are we done? */
  93857. --nvals;
  93858. if(nvals == 0) {
  93859. br->consumed_bits = cbits;
  93860. br->consumed_words = cwords;
  93861. return true;
  93862. }
  93863. uval = 0;
  93864. ++vals;
  93865. }
  93866. }
  93867. #else
  93868. {
  93869. unsigned i;
  93870. unsigned uval = 0;
  93871. /* try and get br->consumed_words and br->consumed_bits into register;
  93872. * must remember to flush them back to *br before calling other
  93873. * bitwriter functions that use them, and before returning */
  93874. register unsigned cwords;
  93875. register unsigned cbits;
  93876. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93877. FLAC__ASSERT(0 != br);
  93878. FLAC__ASSERT(0 != br->buffer);
  93879. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93880. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93881. FLAC__ASSERT(parameter < 32);
  93882. /* 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 */
  93883. if(nvals == 0)
  93884. return true;
  93885. cbits = br->consumed_bits;
  93886. cwords = br->consumed_words;
  93887. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93888. while(1) {
  93889. /* read unary part */
  93890. while(1) {
  93891. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93892. brword b = br->buffer[cwords] << cbits;
  93893. if(b) {
  93894. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93895. asm volatile (
  93896. "bsrl %1, %0;"
  93897. "notl %0;"
  93898. "andl $31, %0;"
  93899. : "=r"(i)
  93900. : "r"(b)
  93901. );
  93902. #else
  93903. i = COUNT_ZERO_MSBS(b);
  93904. #endif
  93905. uval += i;
  93906. cbits += i;
  93907. cbits++; /* skip over stop bit */
  93908. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93909. crc16_update_word_(br, br->buffer[cwords]);
  93910. cwords++;
  93911. cbits = 0;
  93912. }
  93913. goto break1;
  93914. }
  93915. else {
  93916. uval += FLAC__BITS_PER_WORD - cbits;
  93917. crc16_update_word_(br, br->buffer[cwords]);
  93918. cwords++;
  93919. cbits = 0;
  93920. /* didn't find stop bit yet, have to keep going... */
  93921. }
  93922. }
  93923. /* at this point we've eaten up all the whole words; have to try
  93924. * reading through any tail bytes before calling the read callback.
  93925. * this is a repeat of the above logic adjusted for the fact we
  93926. * don't have a whole word. note though if the client is feeding
  93927. * us data a byte at a time (unlikely), br->consumed_bits may not
  93928. * be zero.
  93929. */
  93930. if(br->bytes) {
  93931. const unsigned end = br->bytes * 8;
  93932. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93933. if(b) {
  93934. i = COUNT_ZERO_MSBS(b);
  93935. uval += i;
  93936. cbits += i;
  93937. cbits++; /* skip over stop bit */
  93938. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93939. goto break1;
  93940. }
  93941. else {
  93942. uval += end - cbits;
  93943. cbits += end;
  93944. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93945. /* didn't find stop bit yet, have to keep going... */
  93946. }
  93947. }
  93948. /* flush registers and read; bitreader_read_from_client_() does
  93949. * not touch br->consumed_bits at all but we still need to set
  93950. * it in case it fails and we have to return false.
  93951. */
  93952. br->consumed_bits = cbits;
  93953. br->consumed_words = cwords;
  93954. if(!bitreader_read_from_client_(br))
  93955. return false;
  93956. cwords = br->consumed_words;
  93957. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93958. /* + uval to offset our count by the # of unary bits already
  93959. * consumed before the read, because we will add these back
  93960. * in all at once at break1
  93961. */
  93962. }
  93963. break1:
  93964. ucbits -= uval;
  93965. ucbits--; /* account for stop bit */
  93966. /* read binary part */
  93967. FLAC__ASSERT(cwords <= br->words);
  93968. if(parameter) {
  93969. while(ucbits < parameter) {
  93970. /* flush registers and read; bitreader_read_from_client_() does
  93971. * not touch br->consumed_bits at all but we still need to set
  93972. * it in case it fails and we have to return false.
  93973. */
  93974. br->consumed_bits = cbits;
  93975. br->consumed_words = cwords;
  93976. if(!bitreader_read_from_client_(br))
  93977. return false;
  93978. cwords = br->consumed_words;
  93979. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93980. }
  93981. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93982. if(cbits) {
  93983. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93984. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93985. const brword word = br->buffer[cwords];
  93986. if(parameter < n) {
  93987. uval <<= parameter;
  93988. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93989. cbits += parameter;
  93990. }
  93991. else {
  93992. uval <<= n;
  93993. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93994. crc16_update_word_(br, word);
  93995. cwords++;
  93996. cbits = parameter - n;
  93997. 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 */
  93998. uval <<= cbits;
  93999. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  94000. }
  94001. }
  94002. }
  94003. else {
  94004. cbits = parameter;
  94005. uval <<= parameter;
  94006. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94007. }
  94008. }
  94009. else {
  94010. /* in this case we're starting our read at a partial tail word;
  94011. * the reader has guaranteed that we have at least 'parameter'
  94012. * bits available to read, which makes this case simpler.
  94013. */
  94014. uval <<= parameter;
  94015. if(cbits) {
  94016. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94017. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  94018. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  94019. cbits += parameter;
  94020. }
  94021. else {
  94022. cbits = parameter;
  94023. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94024. }
  94025. }
  94026. }
  94027. ucbits -= parameter;
  94028. /* compose the value */
  94029. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94030. /* are we done? */
  94031. --nvals;
  94032. if(nvals == 0) {
  94033. br->consumed_bits = cbits;
  94034. br->consumed_words = cwords;
  94035. return true;
  94036. }
  94037. uval = 0;
  94038. ++vals;
  94039. }
  94040. }
  94041. #endif
  94042. #if 0 /* UNUSED */
  94043. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  94044. {
  94045. FLAC__uint32 lsbs = 0, msbs = 0;
  94046. unsigned bit, uval, k;
  94047. FLAC__ASSERT(0 != br);
  94048. FLAC__ASSERT(0 != br->buffer);
  94049. k = FLAC__bitmath_ilog2(parameter);
  94050. /* read the unary MSBs and end bit */
  94051. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94052. return false;
  94053. /* read the binary LSBs */
  94054. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94055. return false;
  94056. if(parameter == 1u<<k) {
  94057. /* compose the value */
  94058. uval = (msbs << k) | lsbs;
  94059. }
  94060. else {
  94061. unsigned d = (1 << (k+1)) - parameter;
  94062. if(lsbs >= d) {
  94063. if(!FLAC__bitreader_read_bit(br, &bit))
  94064. return false;
  94065. lsbs <<= 1;
  94066. lsbs |= bit;
  94067. lsbs -= d;
  94068. }
  94069. /* compose the value */
  94070. uval = msbs * parameter + lsbs;
  94071. }
  94072. /* unfold unsigned to signed */
  94073. if(uval & 1)
  94074. *val = -((int)(uval >> 1)) - 1;
  94075. else
  94076. *val = (int)(uval >> 1);
  94077. return true;
  94078. }
  94079. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  94080. {
  94081. FLAC__uint32 lsbs, msbs = 0;
  94082. unsigned bit, k;
  94083. FLAC__ASSERT(0 != br);
  94084. FLAC__ASSERT(0 != br->buffer);
  94085. k = FLAC__bitmath_ilog2(parameter);
  94086. /* read the unary MSBs and end bit */
  94087. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94088. return false;
  94089. /* read the binary LSBs */
  94090. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94091. return false;
  94092. if(parameter == 1u<<k) {
  94093. /* compose the value */
  94094. *val = (msbs << k) | lsbs;
  94095. }
  94096. else {
  94097. unsigned d = (1 << (k+1)) - parameter;
  94098. if(lsbs >= d) {
  94099. if(!FLAC__bitreader_read_bit(br, &bit))
  94100. return false;
  94101. lsbs <<= 1;
  94102. lsbs |= bit;
  94103. lsbs -= d;
  94104. }
  94105. /* compose the value */
  94106. *val = msbs * parameter + lsbs;
  94107. }
  94108. return true;
  94109. }
  94110. #endif /* UNUSED */
  94111. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94112. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94113. {
  94114. FLAC__uint32 v = 0;
  94115. FLAC__uint32 x;
  94116. unsigned i;
  94117. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94118. return false;
  94119. if(raw)
  94120. raw[(*rawlen)++] = (FLAC__byte)x;
  94121. if(!(x & 0x80)) { /* 0xxxxxxx */
  94122. v = x;
  94123. i = 0;
  94124. }
  94125. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94126. v = x & 0x1F;
  94127. i = 1;
  94128. }
  94129. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94130. v = x & 0x0F;
  94131. i = 2;
  94132. }
  94133. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94134. v = x & 0x07;
  94135. i = 3;
  94136. }
  94137. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94138. v = x & 0x03;
  94139. i = 4;
  94140. }
  94141. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94142. v = x & 0x01;
  94143. i = 5;
  94144. }
  94145. else {
  94146. *val = 0xffffffff;
  94147. return true;
  94148. }
  94149. for( ; i; i--) {
  94150. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94151. return false;
  94152. if(raw)
  94153. raw[(*rawlen)++] = (FLAC__byte)x;
  94154. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94155. *val = 0xffffffff;
  94156. return true;
  94157. }
  94158. v <<= 6;
  94159. v |= (x & 0x3F);
  94160. }
  94161. *val = v;
  94162. return true;
  94163. }
  94164. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94165. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94166. {
  94167. FLAC__uint64 v = 0;
  94168. FLAC__uint32 x;
  94169. unsigned i;
  94170. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94171. return false;
  94172. if(raw)
  94173. raw[(*rawlen)++] = (FLAC__byte)x;
  94174. if(!(x & 0x80)) { /* 0xxxxxxx */
  94175. v = x;
  94176. i = 0;
  94177. }
  94178. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94179. v = x & 0x1F;
  94180. i = 1;
  94181. }
  94182. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94183. v = x & 0x0F;
  94184. i = 2;
  94185. }
  94186. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94187. v = x & 0x07;
  94188. i = 3;
  94189. }
  94190. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94191. v = x & 0x03;
  94192. i = 4;
  94193. }
  94194. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94195. v = x & 0x01;
  94196. i = 5;
  94197. }
  94198. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94199. v = 0;
  94200. i = 6;
  94201. }
  94202. else {
  94203. *val = FLAC__U64L(0xffffffffffffffff);
  94204. return true;
  94205. }
  94206. for( ; i; i--) {
  94207. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94208. return false;
  94209. if(raw)
  94210. raw[(*rawlen)++] = (FLAC__byte)x;
  94211. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94212. *val = FLAC__U64L(0xffffffffffffffff);
  94213. return true;
  94214. }
  94215. v <<= 6;
  94216. v |= (x & 0x3F);
  94217. }
  94218. *val = v;
  94219. return true;
  94220. }
  94221. #endif
  94222. /*** End of inlined file: bitreader.c ***/
  94223. /*** Start of inlined file: bitwriter.c ***/
  94224. /*** Start of inlined file: juce_FlacHeader.h ***/
  94225. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94226. // tasks..
  94227. #define VERSION "1.2.1"
  94228. #define FLAC__NO_DLL 1
  94229. #if JUCE_MSVC
  94230. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94231. #endif
  94232. #if JUCE_MAC
  94233. #define FLAC__SYS_DARWIN 1
  94234. #endif
  94235. /*** End of inlined file: juce_FlacHeader.h ***/
  94236. #if JUCE_USE_FLAC
  94237. #if HAVE_CONFIG_H
  94238. # include <config.h>
  94239. #endif
  94240. #include <stdlib.h> /* for malloc() */
  94241. #include <string.h> /* for memcpy(), memset() */
  94242. #ifdef _MSC_VER
  94243. #include <winsock.h> /* for ntohl() */
  94244. #elif defined FLAC__SYS_DARWIN
  94245. #include <machine/endian.h> /* for ntohl() */
  94246. #elif defined __MINGW32__
  94247. #include <winsock.h> /* for ntohl() */
  94248. #else
  94249. #include <netinet/in.h> /* for ntohl() */
  94250. #endif
  94251. #if 0 /* UNUSED */
  94252. #endif
  94253. /*** Start of inlined file: bitwriter.h ***/
  94254. #ifndef FLAC__PRIVATE__BITWRITER_H
  94255. #define FLAC__PRIVATE__BITWRITER_H
  94256. #include <stdio.h> /* for FILE */
  94257. /*
  94258. * opaque structure definition
  94259. */
  94260. struct FLAC__BitWriter;
  94261. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94262. /*
  94263. * construction, deletion, initialization, etc functions
  94264. */
  94265. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94266. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94267. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94268. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94269. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94270. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94271. /*
  94272. * CRC functions
  94273. *
  94274. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94275. */
  94276. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94277. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94278. /*
  94279. * info functions
  94280. */
  94281. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94282. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94283. /*
  94284. * direct buffer access
  94285. *
  94286. * there may be no calls on the bitwriter between get and release.
  94287. * the bitwriter continues to own the returned buffer.
  94288. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94289. */
  94290. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94291. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94292. /*
  94293. * write functions
  94294. */
  94295. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94296. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94297. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94298. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94299. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94300. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94301. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94302. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94303. #if 0 /* UNUSED */
  94304. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94305. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94306. #endif
  94307. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94308. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94309. #if 0 /* UNUSED */
  94310. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94311. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94312. #endif
  94313. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94314. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94315. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94316. #endif
  94317. /*** End of inlined file: bitwriter.h ***/
  94318. /*** Start of inlined file: alloc.h ***/
  94319. #ifndef FLAC__SHARE__ALLOC_H
  94320. #define FLAC__SHARE__ALLOC_H
  94321. #if HAVE_CONFIG_H
  94322. # include <config.h>
  94323. #endif
  94324. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94325. * before #including this file, otherwise SIZE_MAX might not be defined
  94326. */
  94327. #include <limits.h> /* for SIZE_MAX */
  94328. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94329. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94330. #endif
  94331. #include <stdlib.h> /* for size_t, malloc(), etc */
  94332. #ifndef SIZE_MAX
  94333. # ifndef SIZE_T_MAX
  94334. # ifdef _MSC_VER
  94335. # define SIZE_T_MAX UINT_MAX
  94336. # else
  94337. # error
  94338. # endif
  94339. # endif
  94340. # define SIZE_MAX SIZE_T_MAX
  94341. #endif
  94342. #ifndef FLaC__INLINE
  94343. #define FLaC__INLINE
  94344. #endif
  94345. /* avoid malloc()ing 0 bytes, see:
  94346. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94347. */
  94348. static FLaC__INLINE void *safe_malloc_(size_t size)
  94349. {
  94350. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94351. if(!size)
  94352. size++;
  94353. return malloc(size);
  94354. }
  94355. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94356. {
  94357. if(!nmemb || !size)
  94358. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94359. return calloc(nmemb, size);
  94360. }
  94361. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94362. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94363. {
  94364. size2 += size1;
  94365. if(size2 < size1)
  94366. return 0;
  94367. return safe_malloc_(size2);
  94368. }
  94369. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94370. {
  94371. size2 += size1;
  94372. if(size2 < size1)
  94373. return 0;
  94374. size3 += size2;
  94375. if(size3 < size2)
  94376. return 0;
  94377. return safe_malloc_(size3);
  94378. }
  94379. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94380. {
  94381. size2 += size1;
  94382. if(size2 < size1)
  94383. return 0;
  94384. size3 += size2;
  94385. if(size3 < size2)
  94386. return 0;
  94387. size4 += size3;
  94388. if(size4 < size3)
  94389. return 0;
  94390. return safe_malloc_(size4);
  94391. }
  94392. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94393. #if 0
  94394. needs support for cases where sizeof(size_t) != 4
  94395. {
  94396. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94397. if(sizeof(size_t) == 4) {
  94398. if ((double)size1 * (double)size2 < 4294967296.0)
  94399. return malloc(size1*size2);
  94400. }
  94401. return 0;
  94402. }
  94403. #else
  94404. /* better? */
  94405. {
  94406. if(!size1 || !size2)
  94407. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94408. if(size1 > SIZE_MAX / size2)
  94409. return 0;
  94410. return malloc(size1*size2);
  94411. }
  94412. #endif
  94413. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94414. {
  94415. if(!size1 || !size2 || !size3)
  94416. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94417. if(size1 > SIZE_MAX / size2)
  94418. return 0;
  94419. size1 *= size2;
  94420. if(size1 > SIZE_MAX / size3)
  94421. return 0;
  94422. return malloc(size1*size3);
  94423. }
  94424. /* size1*size2 + size3 */
  94425. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94426. {
  94427. if(!size1 || !size2)
  94428. return safe_malloc_(size3);
  94429. if(size1 > SIZE_MAX / size2)
  94430. return 0;
  94431. return safe_malloc_add_2op_(size1*size2, size3);
  94432. }
  94433. /* size1 * (size2 + size3) */
  94434. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94435. {
  94436. if(!size1 || (!size2 && !size3))
  94437. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94438. size2 += size3;
  94439. if(size2 < size3)
  94440. return 0;
  94441. return safe_malloc_mul_2op_(size1, size2);
  94442. }
  94443. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94444. {
  94445. size2 += size1;
  94446. if(size2 < size1)
  94447. return 0;
  94448. return realloc(ptr, size2);
  94449. }
  94450. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94451. {
  94452. size2 += size1;
  94453. if(size2 < size1)
  94454. return 0;
  94455. size3 += size2;
  94456. if(size3 < size2)
  94457. return 0;
  94458. return realloc(ptr, size3);
  94459. }
  94460. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94461. {
  94462. size2 += size1;
  94463. if(size2 < size1)
  94464. return 0;
  94465. size3 += size2;
  94466. if(size3 < size2)
  94467. return 0;
  94468. size4 += size3;
  94469. if(size4 < size3)
  94470. return 0;
  94471. return realloc(ptr, size4);
  94472. }
  94473. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94474. {
  94475. if(!size1 || !size2)
  94476. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94477. if(size1 > SIZE_MAX / size2)
  94478. return 0;
  94479. return realloc(ptr, size1*size2);
  94480. }
  94481. /* size1 * (size2 + size3) */
  94482. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94483. {
  94484. if(!size1 || (!size2 && !size3))
  94485. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94486. size2 += size3;
  94487. if(size2 < size3)
  94488. return 0;
  94489. return safe_realloc_mul_2op_(ptr, size1, size2);
  94490. }
  94491. #endif
  94492. /*** End of inlined file: alloc.h ***/
  94493. /* Things should be fastest when this matches the machine word size */
  94494. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94495. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94496. typedef FLAC__uint32 bwword;
  94497. #define FLAC__BYTES_PER_WORD 4
  94498. #define FLAC__BITS_PER_WORD 32
  94499. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94500. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94501. #if WORDS_BIGENDIAN
  94502. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94503. #else
  94504. #ifdef _MSC_VER
  94505. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94506. #else
  94507. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94508. #endif
  94509. #endif
  94510. /*
  94511. * The default capacity here doesn't matter too much. The buffer always grows
  94512. * to hold whatever is written to it. Usually the encoder will stop adding at
  94513. * a frame or metadata block, then write that out and clear the buffer for the
  94514. * next one.
  94515. */
  94516. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94517. /* When growing, increment 4K at a time */
  94518. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94519. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94520. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94521. #ifdef min
  94522. #undef min
  94523. #endif
  94524. #define min(x,y) ((x)<(y)?(x):(y))
  94525. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94526. #ifdef _MSC_VER
  94527. #define FLAC__U64L(x) x
  94528. #else
  94529. #define FLAC__U64L(x) x##LLU
  94530. #endif
  94531. #ifndef FLaC__INLINE
  94532. #define FLaC__INLINE
  94533. #endif
  94534. struct FLAC__BitWriter {
  94535. bwword *buffer;
  94536. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94537. unsigned capacity; /* capacity of buffer in words */
  94538. unsigned words; /* # of complete words in buffer */
  94539. unsigned bits; /* # of used bits in accum */
  94540. };
  94541. /* * WATCHOUT: The current implementation only grows the buffer. */
  94542. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94543. {
  94544. unsigned new_capacity;
  94545. bwword *new_buffer;
  94546. FLAC__ASSERT(0 != bw);
  94547. FLAC__ASSERT(0 != bw->buffer);
  94548. /* calculate total words needed to store 'bits_to_add' additional bits */
  94549. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94550. /* it's possible (due to pessimism in the growth estimation that
  94551. * leads to this call) that we don't actually need to grow
  94552. */
  94553. if(bw->capacity >= new_capacity)
  94554. return true;
  94555. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94556. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94557. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94558. /* make sure we got everything right */
  94559. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94560. FLAC__ASSERT(new_capacity > bw->capacity);
  94561. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94562. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94563. if(new_buffer == 0)
  94564. return false;
  94565. bw->buffer = new_buffer;
  94566. bw->capacity = new_capacity;
  94567. return true;
  94568. }
  94569. /***********************************************************************
  94570. *
  94571. * Class constructor/destructor
  94572. *
  94573. ***********************************************************************/
  94574. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94575. {
  94576. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94577. /* note that calloc() sets all members to 0 for us */
  94578. return bw;
  94579. }
  94580. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94581. {
  94582. FLAC__ASSERT(0 != bw);
  94583. FLAC__bitwriter_free(bw);
  94584. free(bw);
  94585. }
  94586. /***********************************************************************
  94587. *
  94588. * Public class methods
  94589. *
  94590. ***********************************************************************/
  94591. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94592. {
  94593. FLAC__ASSERT(0 != bw);
  94594. bw->words = bw->bits = 0;
  94595. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94596. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94597. if(bw->buffer == 0)
  94598. return false;
  94599. return true;
  94600. }
  94601. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94602. {
  94603. FLAC__ASSERT(0 != bw);
  94604. if(0 != bw->buffer)
  94605. free(bw->buffer);
  94606. bw->buffer = 0;
  94607. bw->capacity = 0;
  94608. bw->words = bw->bits = 0;
  94609. }
  94610. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94611. {
  94612. bw->words = bw->bits = 0;
  94613. }
  94614. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94615. {
  94616. unsigned i, j;
  94617. if(bw == 0) {
  94618. fprintf(out, "bitwriter is NULL\n");
  94619. }
  94620. else {
  94621. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94622. for(i = 0; i < bw->words; i++) {
  94623. fprintf(out, "%08X: ", i);
  94624. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94625. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94626. fprintf(out, "\n");
  94627. }
  94628. if(bw->bits > 0) {
  94629. fprintf(out, "%08X: ", i);
  94630. for(j = 0; j < bw->bits; j++)
  94631. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94632. fprintf(out, "\n");
  94633. }
  94634. }
  94635. }
  94636. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94637. {
  94638. const FLAC__byte *buffer;
  94639. size_t bytes;
  94640. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94641. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94642. return false;
  94643. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94644. FLAC__bitwriter_release_buffer(bw);
  94645. return true;
  94646. }
  94647. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94648. {
  94649. const FLAC__byte *buffer;
  94650. size_t bytes;
  94651. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94652. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94653. return false;
  94654. *crc = FLAC__crc8(buffer, bytes);
  94655. FLAC__bitwriter_release_buffer(bw);
  94656. return true;
  94657. }
  94658. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94659. {
  94660. return ((bw->bits & 7) == 0);
  94661. }
  94662. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94663. {
  94664. return FLAC__TOTAL_BITS(bw);
  94665. }
  94666. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94667. {
  94668. FLAC__ASSERT((bw->bits & 7) == 0);
  94669. /* double protection */
  94670. if(bw->bits & 7)
  94671. return false;
  94672. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94673. if(bw->bits) {
  94674. FLAC__ASSERT(bw->words <= bw->capacity);
  94675. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94676. return false;
  94677. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94678. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94679. }
  94680. /* now we can just return what we have */
  94681. *buffer = (FLAC__byte*)bw->buffer;
  94682. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94683. return true;
  94684. }
  94685. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94686. {
  94687. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94688. * get-mode' flag could be added everywhere and then cleared here
  94689. */
  94690. (void)bw;
  94691. }
  94692. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94693. {
  94694. unsigned n;
  94695. FLAC__ASSERT(0 != bw);
  94696. FLAC__ASSERT(0 != bw->buffer);
  94697. if(bits == 0)
  94698. return true;
  94699. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94700. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94701. return false;
  94702. /* first part gets to word alignment */
  94703. if(bw->bits) {
  94704. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94705. bw->accum <<= n;
  94706. bits -= n;
  94707. bw->bits += n;
  94708. if(bw->bits == FLAC__BITS_PER_WORD) {
  94709. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94710. bw->bits = 0;
  94711. }
  94712. else
  94713. return true;
  94714. }
  94715. /* do whole words */
  94716. while(bits >= FLAC__BITS_PER_WORD) {
  94717. bw->buffer[bw->words++] = 0;
  94718. bits -= FLAC__BITS_PER_WORD;
  94719. }
  94720. /* do any leftovers */
  94721. if(bits > 0) {
  94722. bw->accum = 0;
  94723. bw->bits = bits;
  94724. }
  94725. return true;
  94726. }
  94727. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94728. {
  94729. register unsigned left;
  94730. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94731. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94732. FLAC__ASSERT(0 != bw);
  94733. FLAC__ASSERT(0 != bw->buffer);
  94734. FLAC__ASSERT(bits <= 32);
  94735. if(bits == 0)
  94736. return true;
  94737. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94738. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94739. return false;
  94740. left = FLAC__BITS_PER_WORD - bw->bits;
  94741. if(bits < left) {
  94742. bw->accum <<= bits;
  94743. bw->accum |= val;
  94744. bw->bits += bits;
  94745. }
  94746. 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 */
  94747. bw->accum <<= left;
  94748. bw->accum |= val >> (bw->bits = bits - left);
  94749. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94750. bw->accum = val;
  94751. }
  94752. else {
  94753. bw->accum = val;
  94754. bw->bits = 0;
  94755. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94756. }
  94757. return true;
  94758. }
  94759. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94760. {
  94761. /* zero-out unused bits */
  94762. if(bits < 32)
  94763. val &= (~(0xffffffff << bits));
  94764. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94765. }
  94766. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94767. {
  94768. /* this could be a little faster but it's not used for much */
  94769. if(bits > 32) {
  94770. return
  94771. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94772. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94773. }
  94774. else
  94775. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94776. }
  94777. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94778. {
  94779. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94780. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94781. return false;
  94782. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94783. return false;
  94784. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94785. return false;
  94786. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94787. return false;
  94788. return true;
  94789. }
  94790. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94791. {
  94792. unsigned i;
  94793. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94794. for(i = 0; i < nvals; i++) {
  94795. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94796. return false;
  94797. }
  94798. return true;
  94799. }
  94800. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94801. {
  94802. if(val < 32)
  94803. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94804. else
  94805. return
  94806. FLAC__bitwriter_write_zeroes(bw, val) &&
  94807. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94808. }
  94809. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94810. {
  94811. FLAC__uint32 uval;
  94812. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94813. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94814. uval = (val<<1) ^ (val>>31);
  94815. return 1 + parameter + (uval >> parameter);
  94816. }
  94817. #if 0 /* UNUSED */
  94818. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94819. {
  94820. unsigned bits, msbs, uval;
  94821. unsigned k;
  94822. FLAC__ASSERT(parameter > 0);
  94823. /* fold signed to unsigned */
  94824. if(val < 0)
  94825. uval = (unsigned)(((-(++val)) << 1) + 1);
  94826. else
  94827. uval = (unsigned)(val << 1);
  94828. k = FLAC__bitmath_ilog2(parameter);
  94829. if(parameter == 1u<<k) {
  94830. FLAC__ASSERT(k <= 30);
  94831. msbs = uval >> k;
  94832. bits = 1 + k + msbs;
  94833. }
  94834. else {
  94835. unsigned q, r, d;
  94836. d = (1 << (k+1)) - parameter;
  94837. q = uval / parameter;
  94838. r = uval - (q * parameter);
  94839. bits = 1 + q + k;
  94840. if(r >= d)
  94841. bits++;
  94842. }
  94843. return bits;
  94844. }
  94845. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94846. {
  94847. unsigned bits, msbs;
  94848. unsigned k;
  94849. FLAC__ASSERT(parameter > 0);
  94850. k = FLAC__bitmath_ilog2(parameter);
  94851. if(parameter == 1u<<k) {
  94852. FLAC__ASSERT(k <= 30);
  94853. msbs = uval >> k;
  94854. bits = 1 + k + msbs;
  94855. }
  94856. else {
  94857. unsigned q, r, d;
  94858. d = (1 << (k+1)) - parameter;
  94859. q = uval / parameter;
  94860. r = uval - (q * parameter);
  94861. bits = 1 + q + k;
  94862. if(r >= d)
  94863. bits++;
  94864. }
  94865. return bits;
  94866. }
  94867. #endif /* UNUSED */
  94868. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94869. {
  94870. unsigned total_bits, interesting_bits, msbs;
  94871. FLAC__uint32 uval, pattern;
  94872. FLAC__ASSERT(0 != bw);
  94873. FLAC__ASSERT(0 != bw->buffer);
  94874. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94875. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94876. uval = (val<<1) ^ (val>>31);
  94877. msbs = uval >> parameter;
  94878. interesting_bits = 1 + parameter;
  94879. total_bits = interesting_bits + msbs;
  94880. pattern = 1 << parameter; /* the unary end bit */
  94881. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94882. if(total_bits <= 32)
  94883. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94884. else
  94885. return
  94886. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94887. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94888. }
  94889. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94890. {
  94891. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94892. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94893. FLAC__uint32 uval;
  94894. unsigned left;
  94895. const unsigned lsbits = 1 + parameter;
  94896. unsigned msbits;
  94897. FLAC__ASSERT(0 != bw);
  94898. FLAC__ASSERT(0 != bw->buffer);
  94899. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94900. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94901. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94902. while(nvals) {
  94903. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94904. uval = (*vals<<1) ^ (*vals>>31);
  94905. msbits = uval >> parameter;
  94906. #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) */
  94907. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94908. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94909. bw->bits = bw->bits + msbits + lsbits;
  94910. uval |= mask1; /* set stop bit */
  94911. uval &= mask2; /* mask off unused top bits */
  94912. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94913. bw->accum <<= msbits;
  94914. bw->accum <<= lsbits;
  94915. bw->accum |= uval;
  94916. if(bw->bits == FLAC__BITS_PER_WORD) {
  94917. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94918. bw->bits = 0;
  94919. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94920. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94921. FLAC__ASSERT(bw->capacity == bw->words);
  94922. return false;
  94923. }
  94924. }
  94925. }
  94926. else {
  94927. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94928. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94929. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94930. bw->bits = bw->bits + msbits + lsbits;
  94931. uval |= mask1; /* set stop bit */
  94932. uval &= mask2; /* mask off unused top bits */
  94933. bw->accum <<= msbits + lsbits;
  94934. bw->accum |= uval;
  94935. }
  94936. else {
  94937. #endif
  94938. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94939. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94940. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94941. return false;
  94942. if(msbits) {
  94943. /* first part gets to word alignment */
  94944. if(bw->bits) {
  94945. left = FLAC__BITS_PER_WORD - bw->bits;
  94946. if(msbits < left) {
  94947. bw->accum <<= msbits;
  94948. bw->bits += msbits;
  94949. goto break1;
  94950. }
  94951. else {
  94952. bw->accum <<= left;
  94953. msbits -= left;
  94954. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94955. bw->bits = 0;
  94956. }
  94957. }
  94958. /* do whole words */
  94959. while(msbits >= FLAC__BITS_PER_WORD) {
  94960. bw->buffer[bw->words++] = 0;
  94961. msbits -= FLAC__BITS_PER_WORD;
  94962. }
  94963. /* do any leftovers */
  94964. if(msbits > 0) {
  94965. bw->accum = 0;
  94966. bw->bits = msbits;
  94967. }
  94968. }
  94969. break1:
  94970. uval |= mask1; /* set stop bit */
  94971. uval &= mask2; /* mask off unused top bits */
  94972. left = FLAC__BITS_PER_WORD - bw->bits;
  94973. if(lsbits < left) {
  94974. bw->accum <<= lsbits;
  94975. bw->accum |= uval;
  94976. bw->bits += lsbits;
  94977. }
  94978. else {
  94979. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94980. * be > lsbits (because of previous assertions) so it would have
  94981. * triggered the (lsbits<left) case above.
  94982. */
  94983. FLAC__ASSERT(bw->bits);
  94984. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94985. bw->accum <<= left;
  94986. bw->accum |= uval >> (bw->bits = lsbits - left);
  94987. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94988. bw->accum = uval;
  94989. }
  94990. #if 1
  94991. }
  94992. #endif
  94993. vals++;
  94994. nvals--;
  94995. }
  94996. return true;
  94997. }
  94998. #if 0 /* UNUSED */
  94999. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  95000. {
  95001. unsigned total_bits, msbs, uval;
  95002. unsigned k;
  95003. FLAC__ASSERT(0 != bw);
  95004. FLAC__ASSERT(0 != bw->buffer);
  95005. FLAC__ASSERT(parameter > 0);
  95006. /* fold signed to unsigned */
  95007. if(val < 0)
  95008. uval = (unsigned)(((-(++val)) << 1) + 1);
  95009. else
  95010. uval = (unsigned)(val << 1);
  95011. k = FLAC__bitmath_ilog2(parameter);
  95012. if(parameter == 1u<<k) {
  95013. unsigned pattern;
  95014. FLAC__ASSERT(k <= 30);
  95015. msbs = uval >> k;
  95016. total_bits = 1 + k + msbs;
  95017. pattern = 1 << k; /* the unary end bit */
  95018. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95019. if(total_bits <= 32) {
  95020. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95021. return false;
  95022. }
  95023. else {
  95024. /* write the unary MSBs */
  95025. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95026. return false;
  95027. /* write the unary end bit and binary LSBs */
  95028. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95029. return false;
  95030. }
  95031. }
  95032. else {
  95033. unsigned q, r, d;
  95034. d = (1 << (k+1)) - parameter;
  95035. q = uval / parameter;
  95036. r = uval - (q * parameter);
  95037. /* write the unary MSBs */
  95038. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95039. return false;
  95040. /* write the unary end bit */
  95041. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95042. return false;
  95043. /* write the binary LSBs */
  95044. if(r >= d) {
  95045. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95046. return false;
  95047. }
  95048. else {
  95049. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95050. return false;
  95051. }
  95052. }
  95053. return true;
  95054. }
  95055. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  95056. {
  95057. unsigned total_bits, msbs;
  95058. unsigned k;
  95059. FLAC__ASSERT(0 != bw);
  95060. FLAC__ASSERT(0 != bw->buffer);
  95061. FLAC__ASSERT(parameter > 0);
  95062. k = FLAC__bitmath_ilog2(parameter);
  95063. if(parameter == 1u<<k) {
  95064. unsigned pattern;
  95065. FLAC__ASSERT(k <= 30);
  95066. msbs = uval >> k;
  95067. total_bits = 1 + k + msbs;
  95068. pattern = 1 << k; /* the unary end bit */
  95069. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95070. if(total_bits <= 32) {
  95071. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95072. return false;
  95073. }
  95074. else {
  95075. /* write the unary MSBs */
  95076. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95077. return false;
  95078. /* write the unary end bit and binary LSBs */
  95079. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95080. return false;
  95081. }
  95082. }
  95083. else {
  95084. unsigned q, r, d;
  95085. d = (1 << (k+1)) - parameter;
  95086. q = uval / parameter;
  95087. r = uval - (q * parameter);
  95088. /* write the unary MSBs */
  95089. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95090. return false;
  95091. /* write the unary end bit */
  95092. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95093. return false;
  95094. /* write the binary LSBs */
  95095. if(r >= d) {
  95096. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95097. return false;
  95098. }
  95099. else {
  95100. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95101. return false;
  95102. }
  95103. }
  95104. return true;
  95105. }
  95106. #endif /* UNUSED */
  95107. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95108. {
  95109. FLAC__bool ok = 1;
  95110. FLAC__ASSERT(0 != bw);
  95111. FLAC__ASSERT(0 != bw->buffer);
  95112. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95113. if(val < 0x80) {
  95114. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95115. }
  95116. else if(val < 0x800) {
  95117. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95118. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95119. }
  95120. else if(val < 0x10000) {
  95121. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95122. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95123. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95124. }
  95125. else if(val < 0x200000) {
  95126. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95127. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95128. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95129. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95130. }
  95131. else if(val < 0x4000000) {
  95132. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95133. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95134. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95135. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95136. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95137. }
  95138. else {
  95139. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95140. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95141. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95142. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95143. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95144. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95145. }
  95146. return ok;
  95147. }
  95148. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95149. {
  95150. FLAC__bool ok = 1;
  95151. FLAC__ASSERT(0 != bw);
  95152. FLAC__ASSERT(0 != bw->buffer);
  95153. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95154. if(val < 0x80) {
  95155. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95156. }
  95157. else if(val < 0x800) {
  95158. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95159. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95160. }
  95161. else if(val < 0x10000) {
  95162. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95163. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95164. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95165. }
  95166. else if(val < 0x200000) {
  95167. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95168. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95169. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95170. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95171. }
  95172. else if(val < 0x4000000) {
  95173. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95174. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95175. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95176. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95177. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95178. }
  95179. else if(val < 0x80000000) {
  95180. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95181. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95182. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95183. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95184. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95185. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95186. }
  95187. else {
  95188. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95189. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95190. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95191. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95192. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95193. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95194. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95195. }
  95196. return ok;
  95197. }
  95198. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95199. {
  95200. /* 0-pad to byte boundary */
  95201. if(bw->bits & 7u)
  95202. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95203. else
  95204. return true;
  95205. }
  95206. #endif
  95207. /*** End of inlined file: bitwriter.c ***/
  95208. /*** Start of inlined file: cpu.c ***/
  95209. /*** Start of inlined file: juce_FlacHeader.h ***/
  95210. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95211. // tasks..
  95212. #define VERSION "1.2.1"
  95213. #define FLAC__NO_DLL 1
  95214. #if JUCE_MSVC
  95215. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95216. #endif
  95217. #if JUCE_MAC
  95218. #define FLAC__SYS_DARWIN 1
  95219. #endif
  95220. /*** End of inlined file: juce_FlacHeader.h ***/
  95221. #if JUCE_USE_FLAC
  95222. #if HAVE_CONFIG_H
  95223. # include <config.h>
  95224. #endif
  95225. #include <stdlib.h>
  95226. #include <stdio.h>
  95227. #if defined FLAC__CPU_IA32
  95228. # include <signal.h>
  95229. #elif defined FLAC__CPU_PPC
  95230. # if !defined FLAC__NO_ASM
  95231. # if defined FLAC__SYS_DARWIN
  95232. # include <sys/sysctl.h>
  95233. # include <mach/mach.h>
  95234. # include <mach/mach_host.h>
  95235. # include <mach/host_info.h>
  95236. # include <mach/machine.h>
  95237. # ifndef CPU_SUBTYPE_POWERPC_970
  95238. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95239. # endif
  95240. # else /* FLAC__SYS_DARWIN */
  95241. # include <signal.h>
  95242. # include <setjmp.h>
  95243. static sigjmp_buf jmpbuf;
  95244. static volatile sig_atomic_t canjump = 0;
  95245. static void sigill_handler (int sig)
  95246. {
  95247. if (!canjump) {
  95248. signal (sig, SIG_DFL);
  95249. raise (sig);
  95250. }
  95251. canjump = 0;
  95252. siglongjmp (jmpbuf, 1);
  95253. }
  95254. # endif /* FLAC__SYS_DARWIN */
  95255. # endif /* FLAC__NO_ASM */
  95256. #endif /* FLAC__CPU_PPC */
  95257. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95258. #include <sys/param.h>
  95259. #include <sys/sysctl.h>
  95260. #include <machine/cpu.h>
  95261. #endif
  95262. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95263. #include <sys/types.h>
  95264. #include <sys/sysctl.h>
  95265. #endif
  95266. #if defined(__APPLE__)
  95267. /* how to get sysctlbyname()? */
  95268. #endif
  95269. /* these are flags in EDX of CPUID AX=00000001 */
  95270. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95271. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95272. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95273. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95274. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95275. /* these are flags in ECX of CPUID AX=00000001 */
  95276. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95277. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95278. /* these are flags in EDX of CPUID AX=80000001 */
  95279. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95280. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95281. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95282. /*
  95283. * Extra stuff needed for detection of OS support for SSE on IA-32
  95284. */
  95285. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95286. # if defined(__linux__)
  95287. /*
  95288. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95289. * modify the return address to jump over the offending SSE instruction
  95290. * and also the operation following it that indicates the instruction
  95291. * executed successfully. In this way we use no global variables and
  95292. * stay thread-safe.
  95293. *
  95294. * 3 + 3 + 6:
  95295. * 3 bytes for "xorps xmm0,xmm0"
  95296. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95297. * 6 bytes extra in case our estimate is wrong
  95298. * 12 bytes puts us in the NOP "landing zone"
  95299. */
  95300. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95301. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95302. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95303. {
  95304. (void)signal;
  95305. sc.eip += 3 + 3 + 6;
  95306. }
  95307. # else
  95308. # include <sys/ucontext.h>
  95309. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95310. {
  95311. (void)signal, (void)si;
  95312. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95313. }
  95314. # endif
  95315. # elif defined(_MSC_VER)
  95316. # include <windows.h>
  95317. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95318. # ifdef USE_TRY_CATCH_FLAVOR
  95319. # else
  95320. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95321. {
  95322. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95323. ep->ContextRecord->Eip += 3 + 3 + 6;
  95324. return EXCEPTION_CONTINUE_EXECUTION;
  95325. }
  95326. return EXCEPTION_CONTINUE_SEARCH;
  95327. }
  95328. # endif
  95329. # endif
  95330. #endif
  95331. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95332. {
  95333. /*
  95334. * IA32-specific
  95335. */
  95336. #ifdef FLAC__CPU_IA32
  95337. info->type = FLAC__CPUINFO_TYPE_IA32;
  95338. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95339. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95340. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95341. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95342. info->data.ia32.cmov = false;
  95343. info->data.ia32.mmx = false;
  95344. info->data.ia32.fxsr = false;
  95345. info->data.ia32.sse = false;
  95346. info->data.ia32.sse2 = false;
  95347. info->data.ia32.sse3 = false;
  95348. info->data.ia32.ssse3 = false;
  95349. info->data.ia32._3dnow = false;
  95350. info->data.ia32.ext3dnow = false;
  95351. info->data.ia32.extmmx = false;
  95352. if(info->data.ia32.cpuid) {
  95353. /* http://www.sandpile.org/ia32/cpuid.htm */
  95354. FLAC__uint32 flags_edx, flags_ecx;
  95355. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95356. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95357. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95358. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95359. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95360. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95361. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95362. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95363. #ifdef FLAC__USE_3DNOW
  95364. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95365. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95366. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95367. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95368. #else
  95369. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95370. #endif
  95371. #ifdef DEBUG
  95372. fprintf(stderr, "CPU info (IA-32):\n");
  95373. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95374. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95375. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95376. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95377. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95378. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95379. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95380. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95381. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95382. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95383. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95384. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95385. #endif
  95386. /*
  95387. * now have to check for OS support of SSE/SSE2
  95388. */
  95389. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95390. #if defined FLAC__NO_SSE_OS
  95391. /* assume user knows better than us; turn it off */
  95392. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95393. #elif defined FLAC__SSE_OS
  95394. /* assume user knows better than us; leave as detected above */
  95395. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95396. int sse = 0;
  95397. size_t len;
  95398. /* at least one of these must work: */
  95399. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95400. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95401. if(!sse)
  95402. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95403. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95404. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95405. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95406. size_t len = sizeof(val);
  95407. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95408. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95409. else { /* double-check SSE2 */
  95410. mib[1] = CPU_SSE2;
  95411. len = sizeof(val);
  95412. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95413. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95414. }
  95415. # else
  95416. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95417. # endif
  95418. #elif defined(__linux__)
  95419. int sse = 0;
  95420. struct sigaction sigill_save;
  95421. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95422. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95423. #else
  95424. struct sigaction sigill_sse;
  95425. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95426. __sigemptyset(&sigill_sse.sa_mask);
  95427. 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 */
  95428. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95429. #endif
  95430. {
  95431. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95432. /* see sigill_handler_sse_os() for an explanation of the following: */
  95433. asm volatile (
  95434. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95435. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95436. "incl %0\n\t" /* SIGILL handler will jump over this */
  95437. /* landing zone */
  95438. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95439. "nop\n\t"
  95440. "nop\n\t"
  95441. "nop\n\t"
  95442. "nop\n\t"
  95443. "nop\n\t"
  95444. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95445. "nop\n\t"
  95446. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95447. : "=r"(sse)
  95448. : "r"(sse)
  95449. );
  95450. sigaction(SIGILL, &sigill_save, NULL);
  95451. }
  95452. if(!sse)
  95453. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95454. #elif defined(_MSC_VER)
  95455. # ifdef USE_TRY_CATCH_FLAVOR
  95456. _try {
  95457. __asm {
  95458. # if _MSC_VER <= 1200
  95459. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95460. _emit 0x0F
  95461. _emit 0x57
  95462. _emit 0xC0
  95463. # else
  95464. xorps xmm0,xmm0
  95465. # endif
  95466. }
  95467. }
  95468. _except(EXCEPTION_EXECUTE_HANDLER) {
  95469. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95470. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95471. }
  95472. # else
  95473. int sse = 0;
  95474. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95475. /* see GCC version above for explanation */
  95476. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95477. /* http://www.codeproject.com/cpp/gccasm.asp */
  95478. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95479. __asm {
  95480. # if _MSC_VER <= 1200
  95481. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95482. _emit 0x0F
  95483. _emit 0x57
  95484. _emit 0xC0
  95485. # else
  95486. xorps xmm0,xmm0
  95487. # endif
  95488. inc sse
  95489. nop
  95490. nop
  95491. nop
  95492. nop
  95493. nop
  95494. nop
  95495. nop
  95496. nop
  95497. nop
  95498. }
  95499. SetUnhandledExceptionFilter(save);
  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. # endif
  95503. #else
  95504. /* no way to test, disable to be safe */
  95505. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95506. #endif
  95507. #ifdef DEBUG
  95508. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95509. #endif
  95510. }
  95511. }
  95512. #else
  95513. info->use_asm = false;
  95514. #endif
  95515. /*
  95516. * PPC-specific
  95517. */
  95518. #elif defined FLAC__CPU_PPC
  95519. info->type = FLAC__CPUINFO_TYPE_PPC;
  95520. # if !defined FLAC__NO_ASM
  95521. info->use_asm = true;
  95522. # ifdef FLAC__USE_ALTIVEC
  95523. # if defined FLAC__SYS_DARWIN
  95524. {
  95525. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95526. size_t len = sizeof(val);
  95527. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95528. }
  95529. {
  95530. host_basic_info_data_t hostInfo;
  95531. mach_msg_type_number_t infoCount;
  95532. infoCount = HOST_BASIC_INFO_COUNT;
  95533. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95534. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95535. }
  95536. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95537. {
  95538. /* no Darwin, do it the brute-force way */
  95539. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95540. info->data.ppc.altivec = 0;
  95541. info->data.ppc.ppc64 = 0;
  95542. signal (SIGILL, sigill_handler);
  95543. canjump = 0;
  95544. if (!sigsetjmp (jmpbuf, 1)) {
  95545. canjump = 1;
  95546. asm volatile (
  95547. "mtspr 256, %0\n\t"
  95548. "vand %%v0, %%v0, %%v0"
  95549. :
  95550. : "r" (-1)
  95551. );
  95552. info->data.ppc.altivec = 1;
  95553. }
  95554. canjump = 0;
  95555. if (!sigsetjmp (jmpbuf, 1)) {
  95556. int x = 0;
  95557. canjump = 1;
  95558. /* PPC64 hardware implements the cntlzd instruction */
  95559. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95560. info->data.ppc.ppc64 = 1;
  95561. }
  95562. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95563. }
  95564. # endif
  95565. # else /* !FLAC__USE_ALTIVEC */
  95566. info->data.ppc.altivec = 0;
  95567. info->data.ppc.ppc64 = 0;
  95568. # endif
  95569. # else
  95570. info->use_asm = false;
  95571. # endif
  95572. /*
  95573. * unknown CPI
  95574. */
  95575. #else
  95576. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95577. info->use_asm = false;
  95578. #endif
  95579. }
  95580. #endif
  95581. /*** End of inlined file: cpu.c ***/
  95582. /*** Start of inlined file: crc.c ***/
  95583. /*** Start of inlined file: juce_FlacHeader.h ***/
  95584. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95585. // tasks..
  95586. #define VERSION "1.2.1"
  95587. #define FLAC__NO_DLL 1
  95588. #if JUCE_MSVC
  95589. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95590. #endif
  95591. #if JUCE_MAC
  95592. #define FLAC__SYS_DARWIN 1
  95593. #endif
  95594. /*** End of inlined file: juce_FlacHeader.h ***/
  95595. #if JUCE_USE_FLAC
  95596. #if HAVE_CONFIG_H
  95597. # include <config.h>
  95598. #endif
  95599. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95600. FLAC__byte const FLAC__crc8_table[256] = {
  95601. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95602. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95603. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95604. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95605. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95606. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95607. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95608. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95609. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95610. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95611. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95612. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95613. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95614. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95615. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95616. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95617. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95618. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95619. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95620. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95621. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95622. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95623. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95624. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95625. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95626. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95627. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95628. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95629. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95630. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95631. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95632. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95633. };
  95634. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95635. unsigned FLAC__crc16_table[256] = {
  95636. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95637. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95638. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95639. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95640. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95641. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95642. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95643. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95644. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95645. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95646. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95647. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95648. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95649. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95650. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95651. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95652. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95653. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95654. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95655. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95656. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95657. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95658. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95659. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95660. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95661. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95662. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95663. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95664. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95665. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95666. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95667. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95668. };
  95669. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95670. {
  95671. *crc = FLAC__crc8_table[*crc ^ data];
  95672. }
  95673. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95674. {
  95675. while(len--)
  95676. *crc = FLAC__crc8_table[*crc ^ *data++];
  95677. }
  95678. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95679. {
  95680. FLAC__uint8 crc = 0;
  95681. while(len--)
  95682. crc = FLAC__crc8_table[crc ^ *data++];
  95683. return crc;
  95684. }
  95685. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95686. {
  95687. unsigned crc = 0;
  95688. while(len--)
  95689. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95690. return crc;
  95691. }
  95692. #endif
  95693. /*** End of inlined file: crc.c ***/
  95694. /*** Start of inlined file: fixed.c ***/
  95695. /*** Start of inlined file: juce_FlacHeader.h ***/
  95696. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95697. // tasks..
  95698. #define VERSION "1.2.1"
  95699. #define FLAC__NO_DLL 1
  95700. #if JUCE_MSVC
  95701. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95702. #endif
  95703. #if JUCE_MAC
  95704. #define FLAC__SYS_DARWIN 1
  95705. #endif
  95706. /*** End of inlined file: juce_FlacHeader.h ***/
  95707. #if JUCE_USE_FLAC
  95708. #if HAVE_CONFIG_H
  95709. # include <config.h>
  95710. #endif
  95711. #include <math.h>
  95712. #include <string.h>
  95713. /*** Start of inlined file: fixed.h ***/
  95714. #ifndef FLAC__PRIVATE__FIXED_H
  95715. #define FLAC__PRIVATE__FIXED_H
  95716. #ifdef HAVE_CONFIG_H
  95717. #include <config.h>
  95718. #endif
  95719. /*** Start of inlined file: float.h ***/
  95720. #ifndef FLAC__PRIVATE__FLOAT_H
  95721. #define FLAC__PRIVATE__FLOAT_H
  95722. #ifdef HAVE_CONFIG_H
  95723. #include <config.h>
  95724. #endif
  95725. /*
  95726. * These typedefs make it easier to ensure that integer versions of
  95727. * the library really only contain integer operations. All the code
  95728. * in libFLAC should use FLAC__float and FLAC__double in place of
  95729. * float and double, and be protected by checks of the macro
  95730. * FLAC__INTEGER_ONLY_LIBRARY.
  95731. *
  95732. * FLAC__real is the basic floating point type used in LPC analysis.
  95733. */
  95734. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95735. typedef double FLAC__double;
  95736. typedef float FLAC__float;
  95737. /*
  95738. * WATCHOUT: changing FLAC__real will change the signatures of many
  95739. * functions that have assembly language equivalents and break them.
  95740. */
  95741. typedef float FLAC__real;
  95742. #else
  95743. /*
  95744. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95745. * for the integer part and lower 16 bits for the fractional part.
  95746. */
  95747. typedef FLAC__int32 FLAC__fixedpoint;
  95748. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95749. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95750. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95751. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95752. extern const FLAC__fixedpoint FLAC__FP_E;
  95753. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95754. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95755. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95756. /*
  95757. * FLAC__fixedpoint_log2()
  95758. * --------------------------------------------------------------------
  95759. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95760. * algorithm by Knuth for x >= 1.0
  95761. *
  95762. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95763. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95764. *
  95765. * 'precision' roughly limits the number of iterations that are done;
  95766. * use (unsigned)(-1) for maximum precision.
  95767. *
  95768. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95769. * function will punt and return 0.
  95770. *
  95771. * The return value will also have 'fracbits' fractional bits.
  95772. */
  95773. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95774. #endif
  95775. #endif
  95776. /*** End of inlined file: float.h ***/
  95777. /*** Start of inlined file: format.h ***/
  95778. #ifndef FLAC__PRIVATE__FORMAT_H
  95779. #define FLAC__PRIVATE__FORMAT_H
  95780. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95781. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95782. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95783. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95784. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95785. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95786. #endif
  95787. /*** End of inlined file: format.h ***/
  95788. /*
  95789. * FLAC__fixed_compute_best_predictor()
  95790. * --------------------------------------------------------------------
  95791. * Compute the best fixed predictor and the expected bits-per-sample
  95792. * of the residual signal for each order. The _wide() version uses
  95793. * 64-bit integers which is statistically necessary when bits-per-
  95794. * sample + log2(blocksize) > 30
  95795. *
  95796. * IN data[0,data_len-1]
  95797. * IN data_len
  95798. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95799. */
  95800. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95801. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95802. # ifndef FLAC__NO_ASM
  95803. # ifdef FLAC__CPU_IA32
  95804. # ifdef FLAC__HAS_NASM
  95805. 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]);
  95806. # endif
  95807. # endif
  95808. # endif
  95809. 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]);
  95810. #else
  95811. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95812. 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]);
  95813. #endif
  95814. /*
  95815. * FLAC__fixed_compute_residual()
  95816. * --------------------------------------------------------------------
  95817. * Compute the residual signal obtained from sutracting the predicted
  95818. * signal from the original.
  95819. *
  95820. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95821. * IN data_len length of original signal
  95822. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95823. * OUT residual[0,data_len-1] residual signal
  95824. */
  95825. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95826. /*
  95827. * FLAC__fixed_restore_signal()
  95828. * --------------------------------------------------------------------
  95829. * Restore the original signal by summing the residual and the
  95830. * predictor.
  95831. *
  95832. * IN residual[0,data_len-1] residual signal
  95833. * IN data_len length of original signal
  95834. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95835. * *** IMPORTANT: the caller must pass in the historical samples:
  95836. * IN data[-order,-1] previously-reconstructed historical samples
  95837. * OUT data[0,data_len-1] original signal
  95838. */
  95839. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95840. #endif
  95841. /*** End of inlined file: fixed.h ***/
  95842. #ifndef M_LN2
  95843. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95844. #define M_LN2 0.69314718055994530942
  95845. #endif
  95846. #ifdef min
  95847. #undef min
  95848. #endif
  95849. #define min(x,y) ((x) < (y)? (x) : (y))
  95850. #ifdef local_abs
  95851. #undef local_abs
  95852. #endif
  95853. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95854. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95855. /* rbps stands for residual bits per sample
  95856. *
  95857. * (ln(2) * err)
  95858. * rbps = log (-----------)
  95859. * 2 ( n )
  95860. */
  95861. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95862. {
  95863. FLAC__uint32 rbps;
  95864. unsigned bits; /* the number of bits required to represent a number */
  95865. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95866. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95867. FLAC__ASSERT(err > 0);
  95868. FLAC__ASSERT(n > 0);
  95869. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95870. if(err <= n)
  95871. return 0;
  95872. /*
  95873. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95874. * These allow us later to know we won't lose too much precision in the
  95875. * fixed-point division (err<<fracbits)/n.
  95876. */
  95877. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95878. err <<= fracbits;
  95879. err /= n;
  95880. /* err now holds err/n with fracbits fractional bits */
  95881. /*
  95882. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95883. * our purposes.
  95884. */
  95885. FLAC__ASSERT(err > 0);
  95886. bits = FLAC__bitmath_ilog2(err)+1;
  95887. if(bits > 16) {
  95888. err >>= (bits-16);
  95889. fracbits -= (bits-16);
  95890. }
  95891. rbps = (FLAC__uint32)err;
  95892. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95893. rbps *= FLAC__FP_LN2;
  95894. fracbits += 16;
  95895. FLAC__ASSERT(fracbits >= 0);
  95896. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95897. {
  95898. const int f = fracbits & 3;
  95899. if(f) {
  95900. rbps >>= f;
  95901. fracbits -= f;
  95902. }
  95903. }
  95904. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95905. if(rbps == 0)
  95906. return 0;
  95907. /*
  95908. * The return value must have 16 fractional bits. Since the whole part
  95909. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95910. * must be >= -3, these assertion allows us to be able to shift rbps
  95911. * left if necessary to get 16 fracbits without losing any bits of the
  95912. * whole part of rbps.
  95913. *
  95914. * There is a slight chance due to accumulated error that the whole part
  95915. * will require 6 bits, so we use 6 in the assertion. Really though as
  95916. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95917. */
  95918. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95919. FLAC__ASSERT(fracbits >= -3);
  95920. /* now shift the decimal point into place */
  95921. if(fracbits < 16)
  95922. return rbps << (16-fracbits);
  95923. else if(fracbits > 16)
  95924. return rbps >> (fracbits-16);
  95925. else
  95926. return rbps;
  95927. }
  95928. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95929. {
  95930. FLAC__uint32 rbps;
  95931. unsigned bits; /* the number of bits required to represent a number */
  95932. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95933. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95934. FLAC__ASSERT(err > 0);
  95935. FLAC__ASSERT(n > 0);
  95936. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95937. if(err <= n)
  95938. return 0;
  95939. /*
  95940. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95941. * These allow us later to know we won't lose too much precision in the
  95942. * fixed-point division (err<<fracbits)/n.
  95943. */
  95944. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95945. err <<= fracbits;
  95946. err /= n;
  95947. /* err now holds err/n with fracbits fractional bits */
  95948. /*
  95949. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95950. * our purposes.
  95951. */
  95952. FLAC__ASSERT(err > 0);
  95953. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95954. if(bits > 16) {
  95955. err >>= (bits-16);
  95956. fracbits -= (bits-16);
  95957. }
  95958. rbps = (FLAC__uint32)err;
  95959. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95960. rbps *= FLAC__FP_LN2;
  95961. fracbits += 16;
  95962. FLAC__ASSERT(fracbits >= 0);
  95963. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95964. {
  95965. const int f = fracbits & 3;
  95966. if(f) {
  95967. rbps >>= f;
  95968. fracbits -= f;
  95969. }
  95970. }
  95971. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95972. if(rbps == 0)
  95973. return 0;
  95974. /*
  95975. * The return value must have 16 fractional bits. Since the whole part
  95976. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95977. * must be >= -3, these assertion allows us to be able to shift rbps
  95978. * left if necessary to get 16 fracbits without losing any bits of the
  95979. * whole part of rbps.
  95980. *
  95981. * There is a slight chance due to accumulated error that the whole part
  95982. * will require 6 bits, so we use 6 in the assertion. Really though as
  95983. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95984. */
  95985. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95986. FLAC__ASSERT(fracbits >= -3);
  95987. /* now shift the decimal point into place */
  95988. if(fracbits < 16)
  95989. return rbps << (16-fracbits);
  95990. else if(fracbits > 16)
  95991. return rbps >> (fracbits-16);
  95992. else
  95993. return rbps;
  95994. }
  95995. #endif
  95996. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95997. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95998. #else
  95999. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96000. #endif
  96001. {
  96002. FLAC__int32 last_error_0 = data[-1];
  96003. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96004. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96005. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96006. FLAC__int32 error, save;
  96007. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96008. unsigned i, order;
  96009. for(i = 0; i < data_len; i++) {
  96010. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96011. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96012. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96013. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96014. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96015. }
  96016. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96017. order = 0;
  96018. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96019. order = 1;
  96020. else if(total_error_2 < min(total_error_3, total_error_4))
  96021. order = 2;
  96022. else if(total_error_3 < total_error_4)
  96023. order = 3;
  96024. else
  96025. order = 4;
  96026. /* Estimate the expected number of bits per residual signal sample. */
  96027. /* 'total_error*' is linearly related to the variance of the residual */
  96028. /* signal, so we use it directly to compute E(|x|) */
  96029. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96030. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96031. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96032. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96033. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96034. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96035. 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);
  96036. 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);
  96037. 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);
  96038. 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);
  96039. 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);
  96040. #else
  96041. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  96042. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  96043. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  96044. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  96045. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  96046. #endif
  96047. return order;
  96048. }
  96049. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96050. 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])
  96051. #else
  96052. 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])
  96053. #endif
  96054. {
  96055. FLAC__int32 last_error_0 = data[-1];
  96056. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96057. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96058. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96059. FLAC__int32 error, save;
  96060. /* total_error_* are 64-bits to avoid overflow when encoding
  96061. * erratic signals when the bits-per-sample and blocksize are
  96062. * large.
  96063. */
  96064. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96065. unsigned i, order;
  96066. for(i = 0; i < data_len; i++) {
  96067. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96068. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96069. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96070. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96071. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96072. }
  96073. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96074. order = 0;
  96075. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96076. order = 1;
  96077. else if(total_error_2 < min(total_error_3, total_error_4))
  96078. order = 2;
  96079. else if(total_error_3 < total_error_4)
  96080. order = 3;
  96081. else
  96082. order = 4;
  96083. /* Estimate the expected number of bits per residual signal sample. */
  96084. /* 'total_error*' is linearly related to the variance of the residual */
  96085. /* signal, so we use it directly to compute E(|x|) */
  96086. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96087. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96088. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96089. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96090. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96091. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96092. #if defined _MSC_VER || defined __MINGW32__
  96093. /* with MSVC you have to spoon feed it the casting */
  96094. 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);
  96095. 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);
  96096. 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);
  96097. 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);
  96098. 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);
  96099. #else
  96100. 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);
  96101. 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);
  96102. 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);
  96103. 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);
  96104. 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);
  96105. #endif
  96106. #else
  96107. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96108. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96109. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96110. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96111. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96112. #endif
  96113. return order;
  96114. }
  96115. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96116. {
  96117. const int idata_len = (int)data_len;
  96118. int i;
  96119. switch(order) {
  96120. case 0:
  96121. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96122. memcpy(residual, data, sizeof(residual[0])*data_len);
  96123. break;
  96124. case 1:
  96125. for(i = 0; i < idata_len; i++)
  96126. residual[i] = data[i] - data[i-1];
  96127. break;
  96128. case 2:
  96129. for(i = 0; i < idata_len; i++)
  96130. #if 1 /* OPT: may be faster with some compilers on some systems */
  96131. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96132. #else
  96133. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96134. #endif
  96135. break;
  96136. case 3:
  96137. for(i = 0; i < idata_len; i++)
  96138. #if 1 /* OPT: may be faster with some compilers on some systems */
  96139. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96140. #else
  96141. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96142. #endif
  96143. break;
  96144. case 4:
  96145. for(i = 0; i < idata_len; i++)
  96146. #if 1 /* OPT: may be faster with some compilers on some systems */
  96147. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96148. #else
  96149. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96150. #endif
  96151. break;
  96152. default:
  96153. FLAC__ASSERT(0);
  96154. }
  96155. }
  96156. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96157. {
  96158. int i, idata_len = (int)data_len;
  96159. switch(order) {
  96160. case 0:
  96161. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96162. memcpy(data, residual, sizeof(residual[0])*data_len);
  96163. break;
  96164. case 1:
  96165. for(i = 0; i < idata_len; i++)
  96166. data[i] = residual[i] + data[i-1];
  96167. break;
  96168. case 2:
  96169. for(i = 0; i < idata_len; i++)
  96170. #if 1 /* OPT: may be faster with some compilers on some systems */
  96171. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96172. #else
  96173. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96174. #endif
  96175. break;
  96176. case 3:
  96177. for(i = 0; i < idata_len; i++)
  96178. #if 1 /* OPT: may be faster with some compilers on some systems */
  96179. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96180. #else
  96181. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96182. #endif
  96183. break;
  96184. case 4:
  96185. for(i = 0; i < idata_len; i++)
  96186. #if 1 /* OPT: may be faster with some compilers on some systems */
  96187. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96188. #else
  96189. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96190. #endif
  96191. break;
  96192. default:
  96193. FLAC__ASSERT(0);
  96194. }
  96195. }
  96196. #endif
  96197. /*** End of inlined file: fixed.c ***/
  96198. /*** Start of inlined file: float.c ***/
  96199. /*** Start of inlined file: juce_FlacHeader.h ***/
  96200. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96201. // tasks..
  96202. #define VERSION "1.2.1"
  96203. #define FLAC__NO_DLL 1
  96204. #if JUCE_MSVC
  96205. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96206. #endif
  96207. #if JUCE_MAC
  96208. #define FLAC__SYS_DARWIN 1
  96209. #endif
  96210. /*** End of inlined file: juce_FlacHeader.h ***/
  96211. #if JUCE_USE_FLAC
  96212. #if HAVE_CONFIG_H
  96213. # include <config.h>
  96214. #endif
  96215. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96216. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96217. #ifdef _MSC_VER
  96218. #define FLAC__U64L(x) x
  96219. #else
  96220. #define FLAC__U64L(x) x##LLU
  96221. #endif
  96222. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96223. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96224. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96225. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96226. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96227. /* Lookup tables for Knuth's logarithm algorithm */
  96228. #define LOG2_LOOKUP_PRECISION 16
  96229. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96230. {
  96231. /*
  96232. * 0 fraction bits
  96233. */
  96234. /* undefined */ 0x00000000,
  96235. /* lg(2/1) = */ 0x00000001,
  96236. /* lg(4/3) = */ 0x00000000,
  96237. /* lg(8/7) = */ 0x00000000,
  96238. /* lg(16/15) = */ 0x00000000,
  96239. /* lg(32/31) = */ 0x00000000,
  96240. /* lg(64/63) = */ 0x00000000,
  96241. /* lg(128/127) = */ 0x00000000,
  96242. /* lg(256/255) = */ 0x00000000,
  96243. /* lg(512/511) = */ 0x00000000,
  96244. /* lg(1024/1023) = */ 0x00000000,
  96245. /* lg(2048/2047) = */ 0x00000000,
  96246. /* lg(4096/4095) = */ 0x00000000,
  96247. /* lg(8192/8191) = */ 0x00000000,
  96248. /* lg(16384/16383) = */ 0x00000000,
  96249. /* lg(32768/32767) = */ 0x00000000
  96250. },
  96251. {
  96252. /*
  96253. * 4 fraction bits
  96254. */
  96255. /* undefined */ 0x00000000,
  96256. /* lg(2/1) = */ 0x00000010,
  96257. /* lg(4/3) = */ 0x00000007,
  96258. /* lg(8/7) = */ 0x00000003,
  96259. /* lg(16/15) = */ 0x00000001,
  96260. /* lg(32/31) = */ 0x00000001,
  96261. /* lg(64/63) = */ 0x00000000,
  96262. /* lg(128/127) = */ 0x00000000,
  96263. /* lg(256/255) = */ 0x00000000,
  96264. /* lg(512/511) = */ 0x00000000,
  96265. /* lg(1024/1023) = */ 0x00000000,
  96266. /* lg(2048/2047) = */ 0x00000000,
  96267. /* lg(4096/4095) = */ 0x00000000,
  96268. /* lg(8192/8191) = */ 0x00000000,
  96269. /* lg(16384/16383) = */ 0x00000000,
  96270. /* lg(32768/32767) = */ 0x00000000
  96271. },
  96272. {
  96273. /*
  96274. * 8 fraction bits
  96275. */
  96276. /* undefined */ 0x00000000,
  96277. /* lg(2/1) = */ 0x00000100,
  96278. /* lg(4/3) = */ 0x0000006a,
  96279. /* lg(8/7) = */ 0x00000031,
  96280. /* lg(16/15) = */ 0x00000018,
  96281. /* lg(32/31) = */ 0x0000000c,
  96282. /* lg(64/63) = */ 0x00000006,
  96283. /* lg(128/127) = */ 0x00000003,
  96284. /* lg(256/255) = */ 0x00000001,
  96285. /* lg(512/511) = */ 0x00000001,
  96286. /* lg(1024/1023) = */ 0x00000000,
  96287. /* lg(2048/2047) = */ 0x00000000,
  96288. /* lg(4096/4095) = */ 0x00000000,
  96289. /* lg(8192/8191) = */ 0x00000000,
  96290. /* lg(16384/16383) = */ 0x00000000,
  96291. /* lg(32768/32767) = */ 0x00000000
  96292. },
  96293. {
  96294. /*
  96295. * 12 fraction bits
  96296. */
  96297. /* undefined */ 0x00000000,
  96298. /* lg(2/1) = */ 0x00001000,
  96299. /* lg(4/3) = */ 0x000006a4,
  96300. /* lg(8/7) = */ 0x00000315,
  96301. /* lg(16/15) = */ 0x0000017d,
  96302. /* lg(32/31) = */ 0x000000bc,
  96303. /* lg(64/63) = */ 0x0000005d,
  96304. /* lg(128/127) = */ 0x0000002e,
  96305. /* lg(256/255) = */ 0x00000017,
  96306. /* lg(512/511) = */ 0x0000000c,
  96307. /* lg(1024/1023) = */ 0x00000006,
  96308. /* lg(2048/2047) = */ 0x00000003,
  96309. /* lg(4096/4095) = */ 0x00000001,
  96310. /* lg(8192/8191) = */ 0x00000001,
  96311. /* lg(16384/16383) = */ 0x00000000,
  96312. /* lg(32768/32767) = */ 0x00000000
  96313. },
  96314. {
  96315. /*
  96316. * 16 fraction bits
  96317. */
  96318. /* undefined */ 0x00000000,
  96319. /* lg(2/1) = */ 0x00010000,
  96320. /* lg(4/3) = */ 0x00006a40,
  96321. /* lg(8/7) = */ 0x00003151,
  96322. /* lg(16/15) = */ 0x000017d6,
  96323. /* lg(32/31) = */ 0x00000bba,
  96324. /* lg(64/63) = */ 0x000005d1,
  96325. /* lg(128/127) = */ 0x000002e6,
  96326. /* lg(256/255) = */ 0x00000172,
  96327. /* lg(512/511) = */ 0x000000b9,
  96328. /* lg(1024/1023) = */ 0x0000005c,
  96329. /* lg(2048/2047) = */ 0x0000002e,
  96330. /* lg(4096/4095) = */ 0x00000017,
  96331. /* lg(8192/8191) = */ 0x0000000c,
  96332. /* lg(16384/16383) = */ 0x00000006,
  96333. /* lg(32768/32767) = */ 0x00000003
  96334. },
  96335. {
  96336. /*
  96337. * 20 fraction bits
  96338. */
  96339. /* undefined */ 0x00000000,
  96340. /* lg(2/1) = */ 0x00100000,
  96341. /* lg(4/3) = */ 0x0006a3fe,
  96342. /* lg(8/7) = */ 0x00031513,
  96343. /* lg(16/15) = */ 0x00017d60,
  96344. /* lg(32/31) = */ 0x0000bb9d,
  96345. /* lg(64/63) = */ 0x00005d10,
  96346. /* lg(128/127) = */ 0x00002e59,
  96347. /* lg(256/255) = */ 0x00001721,
  96348. /* lg(512/511) = */ 0x00000b8e,
  96349. /* lg(1024/1023) = */ 0x000005c6,
  96350. /* lg(2048/2047) = */ 0x000002e3,
  96351. /* lg(4096/4095) = */ 0x00000171,
  96352. /* lg(8192/8191) = */ 0x000000b9,
  96353. /* lg(16384/16383) = */ 0x0000005c,
  96354. /* lg(32768/32767) = */ 0x0000002e
  96355. },
  96356. {
  96357. /*
  96358. * 24 fraction bits
  96359. */
  96360. /* undefined */ 0x00000000,
  96361. /* lg(2/1) = */ 0x01000000,
  96362. /* lg(4/3) = */ 0x006a3fe6,
  96363. /* lg(8/7) = */ 0x00315130,
  96364. /* lg(16/15) = */ 0x0017d605,
  96365. /* lg(32/31) = */ 0x000bb9ca,
  96366. /* lg(64/63) = */ 0x0005d0fc,
  96367. /* lg(128/127) = */ 0x0002e58f,
  96368. /* lg(256/255) = */ 0x0001720e,
  96369. /* lg(512/511) = */ 0x0000b8d8,
  96370. /* lg(1024/1023) = */ 0x00005c61,
  96371. /* lg(2048/2047) = */ 0x00002e2d,
  96372. /* lg(4096/4095) = */ 0x00001716,
  96373. /* lg(8192/8191) = */ 0x00000b8b,
  96374. /* lg(16384/16383) = */ 0x000005c5,
  96375. /* lg(32768/32767) = */ 0x000002e3
  96376. },
  96377. {
  96378. /*
  96379. * 28 fraction bits
  96380. */
  96381. /* undefined */ 0x00000000,
  96382. /* lg(2/1) = */ 0x10000000,
  96383. /* lg(4/3) = */ 0x06a3fe5c,
  96384. /* lg(8/7) = */ 0x03151301,
  96385. /* lg(16/15) = */ 0x017d6049,
  96386. /* lg(32/31) = */ 0x00bb9ca6,
  96387. /* lg(64/63) = */ 0x005d0fba,
  96388. /* lg(128/127) = */ 0x002e58f7,
  96389. /* lg(256/255) = */ 0x001720da,
  96390. /* lg(512/511) = */ 0x000b8d87,
  96391. /* lg(1024/1023) = */ 0x0005c60b,
  96392. /* lg(2048/2047) = */ 0x0002e2d7,
  96393. /* lg(4096/4095) = */ 0x00017160,
  96394. /* lg(8192/8191) = */ 0x0000b8ad,
  96395. /* lg(16384/16383) = */ 0x00005c56,
  96396. /* lg(32768/32767) = */ 0x00002e2b
  96397. }
  96398. };
  96399. #if 0
  96400. static const FLAC__uint64 log2_lookup_wide[] = {
  96401. {
  96402. /*
  96403. * 32 fraction bits
  96404. */
  96405. /* undefined */ 0x00000000,
  96406. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96407. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96408. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96409. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96410. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96411. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96412. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96413. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96414. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96415. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96416. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96417. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96418. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96419. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96420. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96421. },
  96422. {
  96423. /*
  96424. * 48 fraction bits
  96425. */
  96426. /* undefined */ 0x00000000,
  96427. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96428. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96429. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96430. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96431. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96432. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96433. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96434. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96435. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96436. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96437. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96438. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96439. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96440. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96441. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96442. }
  96443. };
  96444. #endif
  96445. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96446. {
  96447. const FLAC__uint32 ONE = (1u << fracbits);
  96448. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96449. FLAC__ASSERT(fracbits < 32);
  96450. FLAC__ASSERT((fracbits & 0x3) == 0);
  96451. if(x < ONE)
  96452. return 0;
  96453. if(precision > LOG2_LOOKUP_PRECISION)
  96454. precision = LOG2_LOOKUP_PRECISION;
  96455. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96456. {
  96457. FLAC__uint32 y = 0;
  96458. FLAC__uint32 z = x >> 1, k = 1;
  96459. while (x > ONE && k < precision) {
  96460. if (x - z >= ONE) {
  96461. x -= z;
  96462. z = x >> k;
  96463. y += table[k];
  96464. }
  96465. else {
  96466. z >>= 1;
  96467. k++;
  96468. }
  96469. }
  96470. return y;
  96471. }
  96472. }
  96473. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96474. #endif
  96475. /*** End of inlined file: float.c ***/
  96476. /*** Start of inlined file: format.c ***/
  96477. /*** Start of inlined file: juce_FlacHeader.h ***/
  96478. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96479. // tasks..
  96480. #define VERSION "1.2.1"
  96481. #define FLAC__NO_DLL 1
  96482. #if JUCE_MSVC
  96483. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96484. #endif
  96485. #if JUCE_MAC
  96486. #define FLAC__SYS_DARWIN 1
  96487. #endif
  96488. /*** End of inlined file: juce_FlacHeader.h ***/
  96489. #if JUCE_USE_FLAC
  96490. #if HAVE_CONFIG_H
  96491. # include <config.h>
  96492. #endif
  96493. #include <stdio.h>
  96494. #include <stdlib.h> /* for qsort() */
  96495. #include <string.h> /* for memset() */
  96496. #ifndef FLaC__INLINE
  96497. #define FLaC__INLINE
  96498. #endif
  96499. #ifdef min
  96500. #undef min
  96501. #endif
  96502. #define min(a,b) ((a)<(b)?(a):(b))
  96503. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96504. #ifdef _MSC_VER
  96505. #define FLAC__U64L(x) x
  96506. #else
  96507. #define FLAC__U64L(x) x##LLU
  96508. #endif
  96509. /* VERSION should come from configure */
  96510. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96511. ;
  96512. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96513. /* yet one more hack because of MSVC6: */
  96514. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96515. #else
  96516. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96517. #endif
  96518. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96519. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96520. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96521. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96522. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96523. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96524. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96525. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96526. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96527. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96528. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96529. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96530. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96531. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96532. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96533. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96534. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96535. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96536. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96537. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96538. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96539. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96540. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96541. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96542. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96543. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96544. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96545. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96546. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96547. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96548. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96549. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96550. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96551. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96552. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96553. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96554. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96555. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96556. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96557. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96558. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96559. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96560. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96561. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96562. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96563. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96564. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96565. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96566. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96567. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96568. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96569. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96570. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96571. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96572. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96573. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96574. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96575. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96576. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96577. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96578. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96579. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96580. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96581. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96582. "PARTITIONED_RICE",
  96583. "PARTITIONED_RICE2"
  96584. };
  96585. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96586. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96587. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96588. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96589. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96590. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96591. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96592. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96593. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96594. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96595. "CONSTANT",
  96596. "VERBATIM",
  96597. "FIXED",
  96598. "LPC"
  96599. };
  96600. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96601. "INDEPENDENT",
  96602. "LEFT_SIDE",
  96603. "RIGHT_SIDE",
  96604. "MID_SIDE"
  96605. };
  96606. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96607. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96608. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96609. };
  96610. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96611. "STREAMINFO",
  96612. "PADDING",
  96613. "APPLICATION",
  96614. "SEEKTABLE",
  96615. "VORBIS_COMMENT",
  96616. "CUESHEET",
  96617. "PICTURE"
  96618. };
  96619. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96620. "Other",
  96621. "32x32 pixels 'file icon' (PNG only)",
  96622. "Other file icon",
  96623. "Cover (front)",
  96624. "Cover (back)",
  96625. "Leaflet page",
  96626. "Media (e.g. label side of CD)",
  96627. "Lead artist/lead performer/soloist",
  96628. "Artist/performer",
  96629. "Conductor",
  96630. "Band/Orchestra",
  96631. "Composer",
  96632. "Lyricist/text writer",
  96633. "Recording Location",
  96634. "During recording",
  96635. "During performance",
  96636. "Movie/video screen capture",
  96637. "A bright coloured fish",
  96638. "Illustration",
  96639. "Band/artist logotype",
  96640. "Publisher/Studio logotype"
  96641. };
  96642. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96643. {
  96644. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96645. return false;
  96646. }
  96647. else
  96648. return true;
  96649. }
  96650. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96651. {
  96652. if(
  96653. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96654. (
  96655. sample_rate >= (1u << 16) &&
  96656. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96657. )
  96658. ) {
  96659. return false;
  96660. }
  96661. else
  96662. return true;
  96663. }
  96664. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96665. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96666. {
  96667. unsigned i;
  96668. FLAC__uint64 prev_sample_number = 0;
  96669. FLAC__bool got_prev = false;
  96670. FLAC__ASSERT(0 != seek_table);
  96671. for(i = 0; i < seek_table->num_points; i++) {
  96672. if(got_prev) {
  96673. if(
  96674. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96675. seek_table->points[i].sample_number <= prev_sample_number
  96676. )
  96677. return false;
  96678. }
  96679. prev_sample_number = seek_table->points[i].sample_number;
  96680. got_prev = true;
  96681. }
  96682. return true;
  96683. }
  96684. /* used as the sort predicate for qsort() */
  96685. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96686. {
  96687. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96688. if(l->sample_number == r->sample_number)
  96689. return 0;
  96690. else if(l->sample_number < r->sample_number)
  96691. return -1;
  96692. else
  96693. return 1;
  96694. }
  96695. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96696. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96697. {
  96698. unsigned i, j;
  96699. FLAC__bool first;
  96700. FLAC__ASSERT(0 != seek_table);
  96701. /* sort the seekpoints */
  96702. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  96703. /* uniquify the seekpoints */
  96704. first = true;
  96705. for(i = j = 0; i < seek_table->num_points; i++) {
  96706. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96707. if(!first) {
  96708. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96709. continue;
  96710. }
  96711. }
  96712. first = false;
  96713. seek_table->points[j++] = seek_table->points[i];
  96714. }
  96715. for(i = j; i < seek_table->num_points; i++) {
  96716. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96717. seek_table->points[i].stream_offset = 0;
  96718. seek_table->points[i].frame_samples = 0;
  96719. }
  96720. return j;
  96721. }
  96722. /*
  96723. * also disallows non-shortest-form encodings, c.f.
  96724. * http://www.unicode.org/versions/corrigendum1.html
  96725. * and a more clear explanation at the end of this section:
  96726. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96727. */
  96728. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96729. {
  96730. FLAC__ASSERT(0 != utf8);
  96731. if ((utf8[0] & 0x80) == 0) {
  96732. return 1;
  96733. }
  96734. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96735. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96736. return 0;
  96737. return 2;
  96738. }
  96739. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96740. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96741. return 0;
  96742. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96743. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96744. return 0;
  96745. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96746. return 0;
  96747. return 3;
  96748. }
  96749. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96750. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96751. return 0;
  96752. return 4;
  96753. }
  96754. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96755. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96756. return 0;
  96757. return 5;
  96758. }
  96759. 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) {
  96760. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96761. return 0;
  96762. return 6;
  96763. }
  96764. else {
  96765. return 0;
  96766. }
  96767. }
  96768. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96769. {
  96770. char c;
  96771. for(c = *name; c; c = *(++name))
  96772. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96773. return false;
  96774. return true;
  96775. }
  96776. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96777. {
  96778. if(length == (unsigned)(-1)) {
  96779. while(*value) {
  96780. unsigned n = utf8len_(value);
  96781. if(n == 0)
  96782. return false;
  96783. value += n;
  96784. }
  96785. }
  96786. else {
  96787. const FLAC__byte *end = value + length;
  96788. while(value < end) {
  96789. unsigned n = utf8len_(value);
  96790. if(n == 0)
  96791. return false;
  96792. value += n;
  96793. }
  96794. if(value != end)
  96795. return false;
  96796. }
  96797. return true;
  96798. }
  96799. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96800. {
  96801. const FLAC__byte *s, *end;
  96802. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96803. if(*s < 0x20 || *s > 0x7D)
  96804. return false;
  96805. }
  96806. if(s == end)
  96807. return false;
  96808. s++; /* skip '=' */
  96809. while(s < end) {
  96810. unsigned n = utf8len_(s);
  96811. if(n == 0)
  96812. return false;
  96813. s += n;
  96814. }
  96815. if(s != end)
  96816. return false;
  96817. return true;
  96818. }
  96819. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96820. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96821. {
  96822. unsigned i, j;
  96823. if(check_cd_da_subset) {
  96824. if(cue_sheet->lead_in < 2 * 44100) {
  96825. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96826. return false;
  96827. }
  96828. if(cue_sheet->lead_in % 588 != 0) {
  96829. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96830. return false;
  96831. }
  96832. }
  96833. if(cue_sheet->num_tracks == 0) {
  96834. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96835. return false;
  96836. }
  96837. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96838. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96839. return false;
  96840. }
  96841. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96842. if(cue_sheet->tracks[i].number == 0) {
  96843. if(violation) *violation = "cue sheet may not have a track number 0";
  96844. return false;
  96845. }
  96846. if(check_cd_da_subset) {
  96847. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96848. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96849. return false;
  96850. }
  96851. }
  96852. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96853. if(violation) {
  96854. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96855. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96856. else
  96857. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96858. }
  96859. return false;
  96860. }
  96861. if(i < cue_sheet->num_tracks - 1) {
  96862. if(cue_sheet->tracks[i].num_indices == 0) {
  96863. if(violation) *violation = "cue sheet track must have at least one index point";
  96864. return false;
  96865. }
  96866. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96867. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96868. return false;
  96869. }
  96870. }
  96871. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96872. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96873. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96874. return false;
  96875. }
  96876. if(j > 0) {
  96877. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96878. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96879. return false;
  96880. }
  96881. }
  96882. }
  96883. }
  96884. return true;
  96885. }
  96886. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96887. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96888. {
  96889. char *p;
  96890. FLAC__byte *b;
  96891. for(p = picture->mime_type; *p; p++) {
  96892. if(*p < 0x20 || *p > 0x7e) {
  96893. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96894. return false;
  96895. }
  96896. }
  96897. for(b = picture->description; *b; ) {
  96898. unsigned n = utf8len_(b);
  96899. if(n == 0) {
  96900. if(violation) *violation = "description string must be valid UTF-8";
  96901. return false;
  96902. }
  96903. b += n;
  96904. }
  96905. return true;
  96906. }
  96907. /*
  96908. * These routines are private to libFLAC
  96909. */
  96910. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96911. {
  96912. return
  96913. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96914. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96915. blocksize,
  96916. predictor_order
  96917. );
  96918. }
  96919. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96920. {
  96921. unsigned max_rice_partition_order = 0;
  96922. while(!(blocksize & 1)) {
  96923. max_rice_partition_order++;
  96924. blocksize >>= 1;
  96925. }
  96926. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96927. }
  96928. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96929. {
  96930. unsigned max_rice_partition_order = limit;
  96931. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96932. max_rice_partition_order--;
  96933. FLAC__ASSERT(
  96934. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96935. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96936. );
  96937. return max_rice_partition_order;
  96938. }
  96939. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96940. {
  96941. FLAC__ASSERT(0 != object);
  96942. object->parameters = 0;
  96943. object->raw_bits = 0;
  96944. object->capacity_by_order = 0;
  96945. }
  96946. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96947. {
  96948. FLAC__ASSERT(0 != object);
  96949. if(0 != object->parameters)
  96950. free(object->parameters);
  96951. if(0 != object->raw_bits)
  96952. free(object->raw_bits);
  96953. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96954. }
  96955. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96956. {
  96957. FLAC__ASSERT(0 != object);
  96958. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96959. if(object->capacity_by_order < max_partition_order) {
  96960. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96961. return false;
  96962. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96963. return false;
  96964. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96965. object->capacity_by_order = max_partition_order;
  96966. }
  96967. return true;
  96968. }
  96969. #endif
  96970. /*** End of inlined file: format.c ***/
  96971. /*** Start of inlined file: lpc_flac.c ***/
  96972. /*** Start of inlined file: juce_FlacHeader.h ***/
  96973. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96974. // tasks..
  96975. #define VERSION "1.2.1"
  96976. #define FLAC__NO_DLL 1
  96977. #if JUCE_MSVC
  96978. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96979. #endif
  96980. #if JUCE_MAC
  96981. #define FLAC__SYS_DARWIN 1
  96982. #endif
  96983. /*** End of inlined file: juce_FlacHeader.h ***/
  96984. #if JUCE_USE_FLAC
  96985. #if HAVE_CONFIG_H
  96986. # include <config.h>
  96987. #endif
  96988. #include <math.h>
  96989. /*** Start of inlined file: lpc.h ***/
  96990. #ifndef FLAC__PRIVATE__LPC_H
  96991. #define FLAC__PRIVATE__LPC_H
  96992. #ifdef HAVE_CONFIG_H
  96993. #include <config.h>
  96994. #endif
  96995. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96996. /*
  96997. * FLAC__lpc_window_data()
  96998. * --------------------------------------------------------------------
  96999. * Applies the given window to the data.
  97000. * OPT: asm implementation
  97001. *
  97002. * IN in[0,data_len-1]
  97003. * IN window[0,data_len-1]
  97004. * OUT out[0,lag-1]
  97005. * IN data_len
  97006. */
  97007. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  97008. /*
  97009. * FLAC__lpc_compute_autocorrelation()
  97010. * --------------------------------------------------------------------
  97011. * Compute the autocorrelation for lags between 0 and lag-1.
  97012. * Assumes data[] outside of [0,data_len-1] == 0.
  97013. * Asserts that lag > 0.
  97014. *
  97015. * IN data[0,data_len-1]
  97016. * IN data_len
  97017. * IN 0 < lag <= data_len
  97018. * OUT autoc[0,lag-1]
  97019. */
  97020. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97021. #ifndef FLAC__NO_ASM
  97022. # ifdef FLAC__CPU_IA32
  97023. # ifdef FLAC__HAS_NASM
  97024. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97025. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97026. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97027. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97028. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97029. # endif
  97030. # endif
  97031. #endif
  97032. /*
  97033. * FLAC__lpc_compute_lp_coefficients()
  97034. * --------------------------------------------------------------------
  97035. * Computes LP coefficients for orders 1..max_order.
  97036. * Do not call if autoc[0] == 0.0. This means the signal is zero
  97037. * and there is no point in calculating a predictor.
  97038. *
  97039. * IN autoc[0,max_order] autocorrelation values
  97040. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  97041. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  97042. * *** IMPORTANT:
  97043. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  97044. * OUT error[0,max_order-1] error for each order (more
  97045. * specifically, the variance of
  97046. * the error signal times # of
  97047. * samples in the signal)
  97048. *
  97049. * Example: if max_order is 9, the LP coefficients for order 9 will be
  97050. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  97051. * in lp_coeff[7][0,7], etc.
  97052. */
  97053. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  97054. /*
  97055. * FLAC__lpc_quantize_coefficients()
  97056. * --------------------------------------------------------------------
  97057. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  97058. * must be less than 32 (sizeof(FLAC__int32)*8).
  97059. *
  97060. * IN lp_coeff[0,order-1] LP coefficients
  97061. * IN order LP order
  97062. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  97063. * desired precision (in bits, including sign
  97064. * bit) of largest coefficient
  97065. * OUT qlp_coeff[0,order-1] quantized coefficients
  97066. * OUT shift # of bits to shift right to get approximated
  97067. * LP coefficients. NOTE: could be negative.
  97068. * RETURN 0 => quantization OK
  97069. * 1 => coefficients require too much shifting for *shift to
  97070. * fit in the LPC subframe header. 'shift' is unset.
  97071. * 2 => coefficients are all zero, which is bad. 'shift' is
  97072. * unset.
  97073. */
  97074. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  97075. /*
  97076. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  97077. * --------------------------------------------------------------------
  97078. * Compute the residual signal obtained from sutracting the predicted
  97079. * signal from the original.
  97080. *
  97081. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  97082. * IN data_len length of original signal
  97083. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97084. * IN order > 0 LP order
  97085. * IN lp_quantization quantization of LP coefficients in bits
  97086. * OUT residual[0,data_len-1] residual signal
  97087. */
  97088. 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[]);
  97089. 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[]);
  97090. #ifndef FLAC__NO_ASM
  97091. # ifdef FLAC__CPU_IA32
  97092. # ifdef FLAC__HAS_NASM
  97093. 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[]);
  97094. 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[]);
  97095. # endif
  97096. # endif
  97097. #endif
  97098. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97099. /*
  97100. * FLAC__lpc_restore_signal()
  97101. * --------------------------------------------------------------------
  97102. * Restore the original signal by summing the residual and the
  97103. * predictor.
  97104. *
  97105. * IN residual[0,data_len-1] residual signal
  97106. * IN data_len length of original signal
  97107. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97108. * IN order > 0 LP order
  97109. * IN lp_quantization quantization of LP coefficients in bits
  97110. * *** IMPORTANT: the caller must pass in the historical samples:
  97111. * IN data[-order,-1] previously-reconstructed historical samples
  97112. * OUT data[0,data_len-1] original signal
  97113. */
  97114. 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[]);
  97115. 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[]);
  97116. #ifndef FLAC__NO_ASM
  97117. # ifdef FLAC__CPU_IA32
  97118. # ifdef FLAC__HAS_NASM
  97119. 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[]);
  97120. 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[]);
  97121. # endif /* FLAC__HAS_NASM */
  97122. # elif defined FLAC__CPU_PPC
  97123. 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[]);
  97124. 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[]);
  97125. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97126. #endif /* FLAC__NO_ASM */
  97127. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97128. /*
  97129. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97130. * --------------------------------------------------------------------
  97131. * Compute the expected number of bits per residual signal sample
  97132. * based on the LP error (which is related to the residual variance).
  97133. *
  97134. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97135. * IN total_samples > 0 # of samples in residual signal
  97136. * RETURN expected bits per sample
  97137. */
  97138. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97139. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97140. /*
  97141. * FLAC__lpc_compute_best_order()
  97142. * --------------------------------------------------------------------
  97143. * Compute the best order from the array of signal errors returned
  97144. * during coefficient computation.
  97145. *
  97146. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97147. * IN max_order > 0 max LP order
  97148. * IN total_samples > 0 # of samples in residual signal
  97149. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97150. * (includes warmup sample size and quantized LP coefficient)
  97151. * RETURN [1,max_order] best order
  97152. */
  97153. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97154. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97155. #endif
  97156. /*** End of inlined file: lpc.h ***/
  97157. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97158. #include <stdio.h>
  97159. #endif
  97160. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97161. #ifndef M_LN2
  97162. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97163. #define M_LN2 0.69314718055994530942
  97164. #endif
  97165. /* OPT: #undef'ing this may improve the speed on some architectures */
  97166. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97167. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97168. {
  97169. unsigned i;
  97170. for(i = 0; i < data_len; i++)
  97171. out[i] = in[i] * window[i];
  97172. }
  97173. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97174. {
  97175. /* a readable, but slower, version */
  97176. #if 0
  97177. FLAC__real d;
  97178. unsigned i;
  97179. FLAC__ASSERT(lag > 0);
  97180. FLAC__ASSERT(lag <= data_len);
  97181. /*
  97182. * Technically we should subtract the mean first like so:
  97183. * for(i = 0; i < data_len; i++)
  97184. * data[i] -= mean;
  97185. * but it appears not to make enough of a difference to matter, and
  97186. * most signals are already closely centered around zero
  97187. */
  97188. while(lag--) {
  97189. for(i = lag, d = 0.0; i < data_len; i++)
  97190. d += data[i] * data[i - lag];
  97191. autoc[lag] = d;
  97192. }
  97193. #endif
  97194. /*
  97195. * this version tends to run faster because of better data locality
  97196. * ('data_len' is usually much larger than 'lag')
  97197. */
  97198. FLAC__real d;
  97199. unsigned sample, coeff;
  97200. const unsigned limit = data_len - lag;
  97201. FLAC__ASSERT(lag > 0);
  97202. FLAC__ASSERT(lag <= data_len);
  97203. for(coeff = 0; coeff < lag; coeff++)
  97204. autoc[coeff] = 0.0;
  97205. for(sample = 0; sample <= limit; sample++) {
  97206. d = data[sample];
  97207. for(coeff = 0; coeff < lag; coeff++)
  97208. autoc[coeff] += d * data[sample+coeff];
  97209. }
  97210. for(; sample < data_len; sample++) {
  97211. d = data[sample];
  97212. for(coeff = 0; coeff < data_len - sample; coeff++)
  97213. autoc[coeff] += d * data[sample+coeff];
  97214. }
  97215. }
  97216. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97217. {
  97218. unsigned i, j;
  97219. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97220. FLAC__ASSERT(0 != max_order);
  97221. FLAC__ASSERT(0 < *max_order);
  97222. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97223. FLAC__ASSERT(autoc[0] != 0.0);
  97224. err = autoc[0];
  97225. for(i = 0; i < *max_order; i++) {
  97226. /* Sum up this iteration's reflection coefficient. */
  97227. r = -autoc[i+1];
  97228. for(j = 0; j < i; j++)
  97229. r -= lpc[j] * autoc[i-j];
  97230. ref[i] = (r/=err);
  97231. /* Update LPC coefficients and total error. */
  97232. lpc[i]=r;
  97233. for(j = 0; j < (i>>1); j++) {
  97234. FLAC__double tmp = lpc[j];
  97235. lpc[j] += r * lpc[i-1-j];
  97236. lpc[i-1-j] += r * tmp;
  97237. }
  97238. if(i & 1)
  97239. lpc[j] += lpc[j] * r;
  97240. err *= (1.0 - r * r);
  97241. /* save this order */
  97242. for(j = 0; j <= i; j++)
  97243. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97244. error[i] = err;
  97245. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97246. if(err == 0.0) {
  97247. *max_order = i+1;
  97248. return;
  97249. }
  97250. }
  97251. }
  97252. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97253. {
  97254. unsigned i;
  97255. FLAC__double cmax;
  97256. FLAC__int32 qmax, qmin;
  97257. FLAC__ASSERT(precision > 0);
  97258. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97259. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97260. precision--;
  97261. qmax = 1 << precision;
  97262. qmin = -qmax;
  97263. qmax--;
  97264. /* calc cmax = max( |lp_coeff[i]| ) */
  97265. cmax = 0.0;
  97266. for(i = 0; i < order; i++) {
  97267. const FLAC__double d = fabs(lp_coeff[i]);
  97268. if(d > cmax)
  97269. cmax = d;
  97270. }
  97271. if(cmax <= 0.0) {
  97272. /* => coefficients are all 0, which means our constant-detect didn't work */
  97273. return 2;
  97274. }
  97275. else {
  97276. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97277. const int min_shiftlimit = -max_shiftlimit - 1;
  97278. int log2cmax;
  97279. (void)frexp(cmax, &log2cmax);
  97280. log2cmax--;
  97281. *shift = (int)precision - log2cmax - 1;
  97282. if(*shift > max_shiftlimit)
  97283. *shift = max_shiftlimit;
  97284. else if(*shift < min_shiftlimit)
  97285. return 1;
  97286. }
  97287. if(*shift >= 0) {
  97288. FLAC__double error = 0.0;
  97289. FLAC__int32 q;
  97290. for(i = 0; i < order; i++) {
  97291. error += lp_coeff[i] * (1 << *shift);
  97292. #if 1 /* unfortunately lround() is C99 */
  97293. if(error >= 0.0)
  97294. q = (FLAC__int32)(error + 0.5);
  97295. else
  97296. q = (FLAC__int32)(error - 0.5);
  97297. #else
  97298. q = lround(error);
  97299. #endif
  97300. #ifdef FLAC__OVERFLOW_DETECT
  97301. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97302. 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]);
  97303. else if(q < qmin)
  97304. 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]);
  97305. #endif
  97306. if(q > qmax)
  97307. q = qmax;
  97308. else if(q < qmin)
  97309. q = qmin;
  97310. error -= q;
  97311. qlp_coeff[i] = q;
  97312. }
  97313. }
  97314. /* negative shift is very rare but due to design flaw, negative shift is
  97315. * a NOP in the decoder, so it must be handled specially by scaling down
  97316. * coeffs
  97317. */
  97318. else {
  97319. const int nshift = -(*shift);
  97320. FLAC__double error = 0.0;
  97321. FLAC__int32 q;
  97322. #ifdef DEBUG
  97323. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97324. #endif
  97325. for(i = 0; i < order; i++) {
  97326. error += lp_coeff[i] / (1 << nshift);
  97327. #if 1 /* unfortunately lround() is C99 */
  97328. if(error >= 0.0)
  97329. q = (FLAC__int32)(error + 0.5);
  97330. else
  97331. q = (FLAC__int32)(error - 0.5);
  97332. #else
  97333. q = lround(error);
  97334. #endif
  97335. #ifdef FLAC__OVERFLOW_DETECT
  97336. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97337. 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]);
  97338. else if(q < qmin)
  97339. 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]);
  97340. #endif
  97341. if(q > qmax)
  97342. q = qmax;
  97343. else if(q < qmin)
  97344. q = qmin;
  97345. error -= q;
  97346. qlp_coeff[i] = q;
  97347. }
  97348. *shift = 0;
  97349. }
  97350. return 0;
  97351. }
  97352. 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[])
  97353. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97354. {
  97355. FLAC__int64 sumo;
  97356. unsigned i, j;
  97357. FLAC__int32 sum;
  97358. const FLAC__int32 *history;
  97359. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97360. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97361. for(i=0;i<order;i++)
  97362. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97363. fprintf(stderr,"\n");
  97364. #endif
  97365. FLAC__ASSERT(order > 0);
  97366. for(i = 0; i < data_len; i++) {
  97367. sumo = 0;
  97368. sum = 0;
  97369. history = data;
  97370. for(j = 0; j < order; j++) {
  97371. sum += qlp_coeff[j] * (*(--history));
  97372. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97373. #if defined _MSC_VER
  97374. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97375. 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);
  97376. #else
  97377. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97378. 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);
  97379. #endif
  97380. }
  97381. *(residual++) = *(data++) - (sum >> lp_quantization);
  97382. }
  97383. /* Here's a slower but clearer version:
  97384. for(i = 0; i < data_len; i++) {
  97385. sum = 0;
  97386. for(j = 0; j < order; j++)
  97387. sum += qlp_coeff[j] * data[i-j-1];
  97388. residual[i] = data[i] - (sum >> lp_quantization);
  97389. }
  97390. */
  97391. }
  97392. #else /* fully unrolled version for normal use */
  97393. {
  97394. int i;
  97395. FLAC__int32 sum;
  97396. FLAC__ASSERT(order > 0);
  97397. FLAC__ASSERT(order <= 32);
  97398. /*
  97399. * We do unique versions up to 12th order since that's the subset limit.
  97400. * Also they are roughly ordered to match frequency of occurrence to
  97401. * minimize branching.
  97402. */
  97403. if(order <= 12) {
  97404. if(order > 8) {
  97405. if(order > 10) {
  97406. if(order == 12) {
  97407. for(i = 0; i < (int)data_len; i++) {
  97408. sum = 0;
  97409. sum += qlp_coeff[11] * data[i-12];
  97410. sum += qlp_coeff[10] * data[i-11];
  97411. sum += qlp_coeff[9] * data[i-10];
  97412. sum += qlp_coeff[8] * data[i-9];
  97413. sum += qlp_coeff[7] * data[i-8];
  97414. sum += qlp_coeff[6] * data[i-7];
  97415. sum += qlp_coeff[5] * data[i-6];
  97416. sum += qlp_coeff[4] * data[i-5];
  97417. sum += qlp_coeff[3] * data[i-4];
  97418. sum += qlp_coeff[2] * data[i-3];
  97419. sum += qlp_coeff[1] * data[i-2];
  97420. sum += qlp_coeff[0] * data[i-1];
  97421. residual[i] = data[i] - (sum >> lp_quantization);
  97422. }
  97423. }
  97424. else { /* order == 11 */
  97425. for(i = 0; i < (int)data_len; i++) {
  97426. sum = 0;
  97427. sum += qlp_coeff[10] * data[i-11];
  97428. sum += qlp_coeff[9] * data[i-10];
  97429. sum += qlp_coeff[8] * data[i-9];
  97430. sum += qlp_coeff[7] * data[i-8];
  97431. sum += qlp_coeff[6] * data[i-7];
  97432. sum += qlp_coeff[5] * data[i-6];
  97433. sum += qlp_coeff[4] * data[i-5];
  97434. sum += qlp_coeff[3] * data[i-4];
  97435. sum += qlp_coeff[2] * data[i-3];
  97436. sum += qlp_coeff[1] * data[i-2];
  97437. sum += qlp_coeff[0] * data[i-1];
  97438. residual[i] = data[i] - (sum >> lp_quantization);
  97439. }
  97440. }
  97441. }
  97442. else {
  97443. if(order == 10) {
  97444. for(i = 0; i < (int)data_len; i++) {
  97445. sum = 0;
  97446. sum += qlp_coeff[9] * data[i-10];
  97447. sum += qlp_coeff[8] * data[i-9];
  97448. sum += qlp_coeff[7] * data[i-8];
  97449. sum += qlp_coeff[6] * data[i-7];
  97450. sum += qlp_coeff[5] * data[i-6];
  97451. sum += qlp_coeff[4] * data[i-5];
  97452. sum += qlp_coeff[3] * data[i-4];
  97453. sum += qlp_coeff[2] * data[i-3];
  97454. sum += qlp_coeff[1] * data[i-2];
  97455. sum += qlp_coeff[0] * data[i-1];
  97456. residual[i] = data[i] - (sum >> lp_quantization);
  97457. }
  97458. }
  97459. else { /* order == 9 */
  97460. for(i = 0; i < (int)data_len; i++) {
  97461. sum = 0;
  97462. sum += qlp_coeff[8] * data[i-9];
  97463. sum += qlp_coeff[7] * data[i-8];
  97464. sum += qlp_coeff[6] * data[i-7];
  97465. sum += qlp_coeff[5] * data[i-6];
  97466. sum += qlp_coeff[4] * data[i-5];
  97467. sum += qlp_coeff[3] * data[i-4];
  97468. sum += qlp_coeff[2] * data[i-3];
  97469. sum += qlp_coeff[1] * data[i-2];
  97470. sum += qlp_coeff[0] * data[i-1];
  97471. residual[i] = data[i] - (sum >> lp_quantization);
  97472. }
  97473. }
  97474. }
  97475. }
  97476. else if(order > 4) {
  97477. if(order > 6) {
  97478. if(order == 8) {
  97479. for(i = 0; i < (int)data_len; i++) {
  97480. sum = 0;
  97481. sum += qlp_coeff[7] * data[i-8];
  97482. sum += qlp_coeff[6] * data[i-7];
  97483. sum += qlp_coeff[5] * data[i-6];
  97484. sum += qlp_coeff[4] * data[i-5];
  97485. sum += qlp_coeff[3] * data[i-4];
  97486. sum += qlp_coeff[2] * data[i-3];
  97487. sum += qlp_coeff[1] * data[i-2];
  97488. sum += qlp_coeff[0] * data[i-1];
  97489. residual[i] = data[i] - (sum >> lp_quantization);
  97490. }
  97491. }
  97492. else { /* order == 7 */
  97493. for(i = 0; i < (int)data_len; i++) {
  97494. sum = 0;
  97495. sum += qlp_coeff[6] * data[i-7];
  97496. sum += qlp_coeff[5] * data[i-6];
  97497. sum += qlp_coeff[4] * data[i-5];
  97498. sum += qlp_coeff[3] * data[i-4];
  97499. sum += qlp_coeff[2] * data[i-3];
  97500. sum += qlp_coeff[1] * data[i-2];
  97501. sum += qlp_coeff[0] * data[i-1];
  97502. residual[i] = data[i] - (sum >> lp_quantization);
  97503. }
  97504. }
  97505. }
  97506. else {
  97507. if(order == 6) {
  97508. for(i = 0; i < (int)data_len; i++) {
  97509. sum = 0;
  97510. sum += qlp_coeff[5] * data[i-6];
  97511. sum += qlp_coeff[4] * data[i-5];
  97512. sum += qlp_coeff[3] * data[i-4];
  97513. sum += qlp_coeff[2] * data[i-3];
  97514. sum += qlp_coeff[1] * data[i-2];
  97515. sum += qlp_coeff[0] * data[i-1];
  97516. residual[i] = data[i] - (sum >> lp_quantization);
  97517. }
  97518. }
  97519. else { /* order == 5 */
  97520. for(i = 0; i < (int)data_len; i++) {
  97521. sum = 0;
  97522. sum += qlp_coeff[4] * data[i-5];
  97523. sum += qlp_coeff[3] * data[i-4];
  97524. sum += qlp_coeff[2] * data[i-3];
  97525. sum += qlp_coeff[1] * data[i-2];
  97526. sum += qlp_coeff[0] * data[i-1];
  97527. residual[i] = data[i] - (sum >> lp_quantization);
  97528. }
  97529. }
  97530. }
  97531. }
  97532. else {
  97533. if(order > 2) {
  97534. if(order == 4) {
  97535. for(i = 0; i < (int)data_len; i++) {
  97536. sum = 0;
  97537. sum += qlp_coeff[3] * data[i-4];
  97538. sum += qlp_coeff[2] * data[i-3];
  97539. sum += qlp_coeff[1] * data[i-2];
  97540. sum += qlp_coeff[0] * data[i-1];
  97541. residual[i] = data[i] - (sum >> lp_quantization);
  97542. }
  97543. }
  97544. else { /* order == 3 */
  97545. for(i = 0; i < (int)data_len; i++) {
  97546. sum = 0;
  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 == 2) {
  97556. for(i = 0; i < (int)data_len; i++) {
  97557. sum = 0;
  97558. sum += qlp_coeff[1] * data[i-2];
  97559. sum += qlp_coeff[0] * data[i-1];
  97560. residual[i] = data[i] - (sum >> lp_quantization);
  97561. }
  97562. }
  97563. else { /* order == 1 */
  97564. for(i = 0; i < (int)data_len; i++)
  97565. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97566. }
  97567. }
  97568. }
  97569. }
  97570. else { /* order > 12 */
  97571. for(i = 0; i < (int)data_len; i++) {
  97572. sum = 0;
  97573. switch(order) {
  97574. case 32: sum += qlp_coeff[31] * data[i-32];
  97575. case 31: sum += qlp_coeff[30] * data[i-31];
  97576. case 30: sum += qlp_coeff[29] * data[i-30];
  97577. case 29: sum += qlp_coeff[28] * data[i-29];
  97578. case 28: sum += qlp_coeff[27] * data[i-28];
  97579. case 27: sum += qlp_coeff[26] * data[i-27];
  97580. case 26: sum += qlp_coeff[25] * data[i-26];
  97581. case 25: sum += qlp_coeff[24] * data[i-25];
  97582. case 24: sum += qlp_coeff[23] * data[i-24];
  97583. case 23: sum += qlp_coeff[22] * data[i-23];
  97584. case 22: sum += qlp_coeff[21] * data[i-22];
  97585. case 21: sum += qlp_coeff[20] * data[i-21];
  97586. case 20: sum += qlp_coeff[19] * data[i-20];
  97587. case 19: sum += qlp_coeff[18] * data[i-19];
  97588. case 18: sum += qlp_coeff[17] * data[i-18];
  97589. case 17: sum += qlp_coeff[16] * data[i-17];
  97590. case 16: sum += qlp_coeff[15] * data[i-16];
  97591. case 15: sum += qlp_coeff[14] * data[i-15];
  97592. case 14: sum += qlp_coeff[13] * data[i-14];
  97593. case 13: sum += qlp_coeff[12] * data[i-13];
  97594. sum += qlp_coeff[11] * data[i-12];
  97595. sum += qlp_coeff[10] * data[i-11];
  97596. sum += qlp_coeff[ 9] * data[i-10];
  97597. sum += qlp_coeff[ 8] * data[i- 9];
  97598. sum += qlp_coeff[ 7] * data[i- 8];
  97599. sum += qlp_coeff[ 6] * data[i- 7];
  97600. sum += qlp_coeff[ 5] * data[i- 6];
  97601. sum += qlp_coeff[ 4] * data[i- 5];
  97602. sum += qlp_coeff[ 3] * data[i- 4];
  97603. sum += qlp_coeff[ 2] * data[i- 3];
  97604. sum += qlp_coeff[ 1] * data[i- 2];
  97605. sum += qlp_coeff[ 0] * data[i- 1];
  97606. }
  97607. residual[i] = data[i] - (sum >> lp_quantization);
  97608. }
  97609. }
  97610. }
  97611. #endif
  97612. 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[])
  97613. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97614. {
  97615. unsigned i, j;
  97616. FLAC__int64 sum;
  97617. const FLAC__int32 *history;
  97618. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97619. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97620. for(i=0;i<order;i++)
  97621. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97622. fprintf(stderr,"\n");
  97623. #endif
  97624. FLAC__ASSERT(order > 0);
  97625. for(i = 0; i < data_len; i++) {
  97626. sum = 0;
  97627. history = data;
  97628. for(j = 0; j < order; j++)
  97629. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97630. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97631. #if defined _MSC_VER
  97632. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97633. #else
  97634. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97635. #endif
  97636. break;
  97637. }
  97638. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97639. #if defined _MSC_VER
  97640. 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));
  97641. #else
  97642. 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)));
  97643. #endif
  97644. break;
  97645. }
  97646. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97647. }
  97648. }
  97649. #else /* fully unrolled version for normal use */
  97650. {
  97651. int i;
  97652. FLAC__int64 sum;
  97653. FLAC__ASSERT(order > 0);
  97654. FLAC__ASSERT(order <= 32);
  97655. /*
  97656. * We do unique versions up to 12th order since that's the subset limit.
  97657. * Also they are roughly ordered to match frequency of occurrence to
  97658. * minimize branching.
  97659. */
  97660. if(order <= 12) {
  97661. if(order > 8) {
  97662. if(order > 10) {
  97663. if(order == 12) {
  97664. for(i = 0; i < (int)data_len; i++) {
  97665. sum = 0;
  97666. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97667. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97668. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97669. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97670. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97671. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97672. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97673. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97674. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97675. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97676. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97677. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97678. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97679. }
  97680. }
  97681. else { /* order == 11 */
  97682. for(i = 0; i < (int)data_len; i++) {
  97683. sum = 0;
  97684. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97685. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97686. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97687. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97688. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97689. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97690. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97691. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97692. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97693. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97694. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97695. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97696. }
  97697. }
  97698. }
  97699. else {
  97700. if(order == 10) {
  97701. for(i = 0; i < (int)data_len; i++) {
  97702. sum = 0;
  97703. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97704. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97705. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97706. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97707. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97708. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97709. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97710. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97711. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97712. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97713. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97714. }
  97715. }
  97716. else { /* order == 9 */
  97717. for(i = 0; i < (int)data_len; i++) {
  97718. sum = 0;
  97719. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97720. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97721. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97722. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97723. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97724. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97725. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97726. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97727. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97728. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97729. }
  97730. }
  97731. }
  97732. }
  97733. else if(order > 4) {
  97734. if(order > 6) {
  97735. if(order == 8) {
  97736. for(i = 0; i < (int)data_len; i++) {
  97737. sum = 0;
  97738. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97739. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97740. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97741. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97742. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97743. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97744. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97745. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97746. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97747. }
  97748. }
  97749. else { /* order == 7 */
  97750. for(i = 0; i < (int)data_len; i++) {
  97751. sum = 0;
  97752. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97753. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97754. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97755. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97756. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97757. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97758. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97759. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97760. }
  97761. }
  97762. }
  97763. else {
  97764. if(order == 6) {
  97765. for(i = 0; i < (int)data_len; i++) {
  97766. sum = 0;
  97767. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97768. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97769. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97770. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97771. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97772. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97773. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97774. }
  97775. }
  97776. else { /* order == 5 */
  97777. for(i = 0; i < (int)data_len; i++) {
  97778. sum = 0;
  97779. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97780. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97781. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97782. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97783. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97784. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97785. }
  97786. }
  97787. }
  97788. }
  97789. else {
  97790. if(order > 2) {
  97791. if(order == 4) {
  97792. for(i = 0; i < (int)data_len; i++) {
  97793. sum = 0;
  97794. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97795. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97796. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97797. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97798. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97799. }
  97800. }
  97801. else { /* order == 3 */
  97802. for(i = 0; i < (int)data_len; i++) {
  97803. sum = 0;
  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 == 2) {
  97813. for(i = 0; i < (int)data_len; i++) {
  97814. sum = 0;
  97815. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97816. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97817. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97818. }
  97819. }
  97820. else { /* order == 1 */
  97821. for(i = 0; i < (int)data_len; i++)
  97822. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97823. }
  97824. }
  97825. }
  97826. }
  97827. else { /* order > 12 */
  97828. for(i = 0; i < (int)data_len; i++) {
  97829. sum = 0;
  97830. switch(order) {
  97831. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97832. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97833. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97834. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97835. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97836. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97837. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97838. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97839. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97840. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97841. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97842. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97843. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97844. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97845. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97846. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97847. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97848. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97849. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97850. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97851. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97852. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97853. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97854. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97855. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97856. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97857. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97858. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97859. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97860. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97861. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97862. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97863. }
  97864. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97865. }
  97866. }
  97867. }
  97868. #endif
  97869. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97870. 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[])
  97871. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97872. {
  97873. FLAC__int64 sumo;
  97874. unsigned i, j;
  97875. FLAC__int32 sum;
  97876. const FLAC__int32 *r = residual, *history;
  97877. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97878. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97879. for(i=0;i<order;i++)
  97880. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97881. fprintf(stderr,"\n");
  97882. #endif
  97883. FLAC__ASSERT(order > 0);
  97884. for(i = 0; i < data_len; i++) {
  97885. sumo = 0;
  97886. sum = 0;
  97887. history = data;
  97888. for(j = 0; j < order; j++) {
  97889. sum += qlp_coeff[j] * (*(--history));
  97890. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97891. #if defined _MSC_VER
  97892. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97893. 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);
  97894. #else
  97895. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97896. 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);
  97897. #endif
  97898. }
  97899. *(data++) = *(r++) + (sum >> lp_quantization);
  97900. }
  97901. /* Here's a slower but clearer version:
  97902. for(i = 0; i < data_len; i++) {
  97903. sum = 0;
  97904. for(j = 0; j < order; j++)
  97905. sum += qlp_coeff[j] * data[i-j-1];
  97906. data[i] = residual[i] + (sum >> lp_quantization);
  97907. }
  97908. */
  97909. }
  97910. #else /* fully unrolled version for normal use */
  97911. {
  97912. int i;
  97913. FLAC__int32 sum;
  97914. FLAC__ASSERT(order > 0);
  97915. FLAC__ASSERT(order <= 32);
  97916. /*
  97917. * We do unique versions up to 12th order since that's the subset limit.
  97918. * Also they are roughly ordered to match frequency of occurrence to
  97919. * minimize branching.
  97920. */
  97921. if(order <= 12) {
  97922. if(order > 8) {
  97923. if(order > 10) {
  97924. if(order == 12) {
  97925. for(i = 0; i < (int)data_len; i++) {
  97926. sum = 0;
  97927. sum += qlp_coeff[11] * data[i-12];
  97928. sum += qlp_coeff[10] * data[i-11];
  97929. sum += qlp_coeff[9] * data[i-10];
  97930. sum += qlp_coeff[8] * data[i-9];
  97931. sum += qlp_coeff[7] * data[i-8];
  97932. sum += qlp_coeff[6] * data[i-7];
  97933. sum += qlp_coeff[5] * data[i-6];
  97934. sum += qlp_coeff[4] * data[i-5];
  97935. sum += qlp_coeff[3] * data[i-4];
  97936. sum += qlp_coeff[2] * data[i-3];
  97937. sum += qlp_coeff[1] * data[i-2];
  97938. sum += qlp_coeff[0] * data[i-1];
  97939. data[i] = residual[i] + (sum >> lp_quantization);
  97940. }
  97941. }
  97942. else { /* order == 11 */
  97943. for(i = 0; i < (int)data_len; i++) {
  97944. sum = 0;
  97945. sum += qlp_coeff[10] * data[i-11];
  97946. sum += qlp_coeff[9] * data[i-10];
  97947. sum += qlp_coeff[8] * data[i-9];
  97948. sum += qlp_coeff[7] * data[i-8];
  97949. sum += qlp_coeff[6] * data[i-7];
  97950. sum += qlp_coeff[5] * data[i-6];
  97951. sum += qlp_coeff[4] * data[i-5];
  97952. sum += qlp_coeff[3] * data[i-4];
  97953. sum += qlp_coeff[2] * data[i-3];
  97954. sum += qlp_coeff[1] * data[i-2];
  97955. sum += qlp_coeff[0] * data[i-1];
  97956. data[i] = residual[i] + (sum >> lp_quantization);
  97957. }
  97958. }
  97959. }
  97960. else {
  97961. if(order == 10) {
  97962. for(i = 0; i < (int)data_len; i++) {
  97963. sum = 0;
  97964. sum += qlp_coeff[9] * data[i-10];
  97965. sum += qlp_coeff[8] * data[i-9];
  97966. sum += qlp_coeff[7] * data[i-8];
  97967. sum += qlp_coeff[6] * data[i-7];
  97968. sum += qlp_coeff[5] * data[i-6];
  97969. sum += qlp_coeff[4] * data[i-5];
  97970. sum += qlp_coeff[3] * data[i-4];
  97971. sum += qlp_coeff[2] * data[i-3];
  97972. sum += qlp_coeff[1] * data[i-2];
  97973. sum += qlp_coeff[0] * data[i-1];
  97974. data[i] = residual[i] + (sum >> lp_quantization);
  97975. }
  97976. }
  97977. else { /* order == 9 */
  97978. for(i = 0; i < (int)data_len; i++) {
  97979. sum = 0;
  97980. sum += qlp_coeff[8] * data[i-9];
  97981. sum += qlp_coeff[7] * data[i-8];
  97982. sum += qlp_coeff[6] * data[i-7];
  97983. sum += qlp_coeff[5] * data[i-6];
  97984. sum += qlp_coeff[4] * data[i-5];
  97985. sum += qlp_coeff[3] * data[i-4];
  97986. sum += qlp_coeff[2] * data[i-3];
  97987. sum += qlp_coeff[1] * data[i-2];
  97988. sum += qlp_coeff[0] * data[i-1];
  97989. data[i] = residual[i] + (sum >> lp_quantization);
  97990. }
  97991. }
  97992. }
  97993. }
  97994. else if(order > 4) {
  97995. if(order > 6) {
  97996. if(order == 8) {
  97997. for(i = 0; i < (int)data_len; i++) {
  97998. sum = 0;
  97999. sum += qlp_coeff[7] * data[i-8];
  98000. sum += qlp_coeff[6] * data[i-7];
  98001. sum += qlp_coeff[5] * data[i-6];
  98002. sum += qlp_coeff[4] * data[i-5];
  98003. sum += qlp_coeff[3] * data[i-4];
  98004. sum += qlp_coeff[2] * data[i-3];
  98005. sum += qlp_coeff[1] * data[i-2];
  98006. sum += qlp_coeff[0] * data[i-1];
  98007. data[i] = residual[i] + (sum >> lp_quantization);
  98008. }
  98009. }
  98010. else { /* order == 7 */
  98011. for(i = 0; i < (int)data_len; i++) {
  98012. sum = 0;
  98013. sum += qlp_coeff[6] * data[i-7];
  98014. sum += qlp_coeff[5] * data[i-6];
  98015. sum += qlp_coeff[4] * data[i-5];
  98016. sum += qlp_coeff[3] * data[i-4];
  98017. sum += qlp_coeff[2] * data[i-3];
  98018. sum += qlp_coeff[1] * data[i-2];
  98019. sum += qlp_coeff[0] * data[i-1];
  98020. data[i] = residual[i] + (sum >> lp_quantization);
  98021. }
  98022. }
  98023. }
  98024. else {
  98025. if(order == 6) {
  98026. for(i = 0; i < (int)data_len; i++) {
  98027. sum = 0;
  98028. sum += qlp_coeff[5] * data[i-6];
  98029. sum += qlp_coeff[4] * data[i-5];
  98030. sum += qlp_coeff[3] * data[i-4];
  98031. sum += qlp_coeff[2] * data[i-3];
  98032. sum += qlp_coeff[1] * data[i-2];
  98033. sum += qlp_coeff[0] * data[i-1];
  98034. data[i] = residual[i] + (sum >> lp_quantization);
  98035. }
  98036. }
  98037. else { /* order == 5 */
  98038. for(i = 0; i < (int)data_len; i++) {
  98039. sum = 0;
  98040. sum += qlp_coeff[4] * data[i-5];
  98041. sum += qlp_coeff[3] * data[i-4];
  98042. sum += qlp_coeff[2] * data[i-3];
  98043. sum += qlp_coeff[1] * data[i-2];
  98044. sum += qlp_coeff[0] * data[i-1];
  98045. data[i] = residual[i] + (sum >> lp_quantization);
  98046. }
  98047. }
  98048. }
  98049. }
  98050. else {
  98051. if(order > 2) {
  98052. if(order == 4) {
  98053. for(i = 0; i < (int)data_len; i++) {
  98054. sum = 0;
  98055. sum += qlp_coeff[3] * data[i-4];
  98056. sum += qlp_coeff[2] * data[i-3];
  98057. sum += qlp_coeff[1] * data[i-2];
  98058. sum += qlp_coeff[0] * data[i-1];
  98059. data[i] = residual[i] + (sum >> lp_quantization);
  98060. }
  98061. }
  98062. else { /* order == 3 */
  98063. for(i = 0; i < (int)data_len; i++) {
  98064. sum = 0;
  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 == 2) {
  98074. for(i = 0; i < (int)data_len; i++) {
  98075. sum = 0;
  98076. sum += qlp_coeff[1] * data[i-2];
  98077. sum += qlp_coeff[0] * data[i-1];
  98078. data[i] = residual[i] + (sum >> lp_quantization);
  98079. }
  98080. }
  98081. else { /* order == 1 */
  98082. for(i = 0; i < (int)data_len; i++)
  98083. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  98084. }
  98085. }
  98086. }
  98087. }
  98088. else { /* order > 12 */
  98089. for(i = 0; i < (int)data_len; i++) {
  98090. sum = 0;
  98091. switch(order) {
  98092. case 32: sum += qlp_coeff[31] * data[i-32];
  98093. case 31: sum += qlp_coeff[30] * data[i-31];
  98094. case 30: sum += qlp_coeff[29] * data[i-30];
  98095. case 29: sum += qlp_coeff[28] * data[i-29];
  98096. case 28: sum += qlp_coeff[27] * data[i-28];
  98097. case 27: sum += qlp_coeff[26] * data[i-27];
  98098. case 26: sum += qlp_coeff[25] * data[i-26];
  98099. case 25: sum += qlp_coeff[24] * data[i-25];
  98100. case 24: sum += qlp_coeff[23] * data[i-24];
  98101. case 23: sum += qlp_coeff[22] * data[i-23];
  98102. case 22: sum += qlp_coeff[21] * data[i-22];
  98103. case 21: sum += qlp_coeff[20] * data[i-21];
  98104. case 20: sum += qlp_coeff[19] * data[i-20];
  98105. case 19: sum += qlp_coeff[18] * data[i-19];
  98106. case 18: sum += qlp_coeff[17] * data[i-18];
  98107. case 17: sum += qlp_coeff[16] * data[i-17];
  98108. case 16: sum += qlp_coeff[15] * data[i-16];
  98109. case 15: sum += qlp_coeff[14] * data[i-15];
  98110. case 14: sum += qlp_coeff[13] * data[i-14];
  98111. case 13: sum += qlp_coeff[12] * data[i-13];
  98112. sum += qlp_coeff[11] * data[i-12];
  98113. sum += qlp_coeff[10] * data[i-11];
  98114. sum += qlp_coeff[ 9] * data[i-10];
  98115. sum += qlp_coeff[ 8] * data[i- 9];
  98116. sum += qlp_coeff[ 7] * data[i- 8];
  98117. sum += qlp_coeff[ 6] * data[i- 7];
  98118. sum += qlp_coeff[ 5] * data[i- 6];
  98119. sum += qlp_coeff[ 4] * data[i- 5];
  98120. sum += qlp_coeff[ 3] * data[i- 4];
  98121. sum += qlp_coeff[ 2] * data[i- 3];
  98122. sum += qlp_coeff[ 1] * data[i- 2];
  98123. sum += qlp_coeff[ 0] * data[i- 1];
  98124. }
  98125. data[i] = residual[i] + (sum >> lp_quantization);
  98126. }
  98127. }
  98128. }
  98129. #endif
  98130. 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[])
  98131. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98132. {
  98133. unsigned i, j;
  98134. FLAC__int64 sum;
  98135. const FLAC__int32 *r = residual, *history;
  98136. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98137. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98138. for(i=0;i<order;i++)
  98139. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98140. fprintf(stderr,"\n");
  98141. #endif
  98142. FLAC__ASSERT(order > 0);
  98143. for(i = 0; i < data_len; i++) {
  98144. sum = 0;
  98145. history = data;
  98146. for(j = 0; j < order; j++)
  98147. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98148. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98149. #ifdef _MSC_VER
  98150. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98151. #else
  98152. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98153. #endif
  98154. break;
  98155. }
  98156. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98157. #ifdef _MSC_VER
  98158. 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));
  98159. #else
  98160. 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)));
  98161. #endif
  98162. break;
  98163. }
  98164. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98165. }
  98166. }
  98167. #else /* fully unrolled version for normal use */
  98168. {
  98169. int i;
  98170. FLAC__int64 sum;
  98171. FLAC__ASSERT(order > 0);
  98172. FLAC__ASSERT(order <= 32);
  98173. /*
  98174. * We do unique versions up to 12th order since that's the subset limit.
  98175. * Also they are roughly ordered to match frequency of occurrence to
  98176. * minimize branching.
  98177. */
  98178. if(order <= 12) {
  98179. if(order > 8) {
  98180. if(order > 10) {
  98181. if(order == 12) {
  98182. for(i = 0; i < (int)data_len; i++) {
  98183. sum = 0;
  98184. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98185. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98186. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98187. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98188. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98189. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98190. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98191. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98192. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98193. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98194. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98195. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98196. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98197. }
  98198. }
  98199. else { /* order == 11 */
  98200. for(i = 0; i < (int)data_len; i++) {
  98201. sum = 0;
  98202. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98203. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98204. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98205. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98206. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98207. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98208. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98209. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98210. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98211. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98212. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98213. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98214. }
  98215. }
  98216. }
  98217. else {
  98218. if(order == 10) {
  98219. for(i = 0; i < (int)data_len; i++) {
  98220. sum = 0;
  98221. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98222. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98223. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98224. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98225. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98226. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98227. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98228. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98229. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98230. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98231. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98232. }
  98233. }
  98234. else { /* order == 9 */
  98235. for(i = 0; i < (int)data_len; i++) {
  98236. sum = 0;
  98237. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98238. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98239. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98240. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98241. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98242. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98243. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98244. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98245. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98246. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98247. }
  98248. }
  98249. }
  98250. }
  98251. else if(order > 4) {
  98252. if(order > 6) {
  98253. if(order == 8) {
  98254. for(i = 0; i < (int)data_len; i++) {
  98255. sum = 0;
  98256. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98257. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98258. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98259. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98260. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98261. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98262. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98263. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98264. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98265. }
  98266. }
  98267. else { /* order == 7 */
  98268. for(i = 0; i < (int)data_len; i++) {
  98269. sum = 0;
  98270. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98271. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98272. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98273. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98274. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98275. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98276. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98277. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98278. }
  98279. }
  98280. }
  98281. else {
  98282. if(order == 6) {
  98283. for(i = 0; i < (int)data_len; i++) {
  98284. sum = 0;
  98285. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98286. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98287. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98288. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98289. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98290. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98291. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98292. }
  98293. }
  98294. else { /* order == 5 */
  98295. for(i = 0; i < (int)data_len; i++) {
  98296. sum = 0;
  98297. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98298. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98299. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98300. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98301. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98302. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98303. }
  98304. }
  98305. }
  98306. }
  98307. else {
  98308. if(order > 2) {
  98309. if(order == 4) {
  98310. for(i = 0; i < (int)data_len; i++) {
  98311. sum = 0;
  98312. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98313. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98314. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98315. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98316. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98317. }
  98318. }
  98319. else { /* order == 3 */
  98320. for(i = 0; i < (int)data_len; i++) {
  98321. sum = 0;
  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 == 2) {
  98331. for(i = 0; i < (int)data_len; i++) {
  98332. sum = 0;
  98333. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98334. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98335. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98336. }
  98337. }
  98338. else { /* order == 1 */
  98339. for(i = 0; i < (int)data_len; i++)
  98340. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98341. }
  98342. }
  98343. }
  98344. }
  98345. else { /* order > 12 */
  98346. for(i = 0; i < (int)data_len; i++) {
  98347. sum = 0;
  98348. switch(order) {
  98349. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98350. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98351. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98352. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98353. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98354. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98355. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98356. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98357. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98358. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98359. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98360. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98361. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98362. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98363. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98364. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98365. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98366. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98367. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98368. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98369. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98370. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98371. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98372. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98373. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98374. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98375. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98376. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98377. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98378. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98379. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98380. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98381. }
  98382. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98383. }
  98384. }
  98385. }
  98386. #endif
  98387. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98388. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98389. {
  98390. FLAC__double error_scale;
  98391. FLAC__ASSERT(total_samples > 0);
  98392. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98393. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98394. }
  98395. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98396. {
  98397. if(lpc_error > 0.0) {
  98398. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98399. if(bps >= 0.0)
  98400. return bps;
  98401. else
  98402. return 0.0;
  98403. }
  98404. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98405. return 1e32;
  98406. }
  98407. else {
  98408. return 0.0;
  98409. }
  98410. }
  98411. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98412. {
  98413. 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 */
  98414. FLAC__double bits, best_bits, error_scale;
  98415. FLAC__ASSERT(max_order > 0);
  98416. FLAC__ASSERT(total_samples > 0);
  98417. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98418. best_index = 0;
  98419. best_bits = (unsigned)(-1);
  98420. for(index = 0, order = 1; index < max_order; index++, order++) {
  98421. 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);
  98422. if(bits < best_bits) {
  98423. best_index = index;
  98424. best_bits = bits;
  98425. }
  98426. }
  98427. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98428. }
  98429. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98430. #endif
  98431. /*** End of inlined file: lpc_flac.c ***/
  98432. /*** Start of inlined file: md5.c ***/
  98433. /*** Start of inlined file: juce_FlacHeader.h ***/
  98434. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98435. // tasks..
  98436. #define VERSION "1.2.1"
  98437. #define FLAC__NO_DLL 1
  98438. #if JUCE_MSVC
  98439. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98440. #endif
  98441. #if JUCE_MAC
  98442. #define FLAC__SYS_DARWIN 1
  98443. #endif
  98444. /*** End of inlined file: juce_FlacHeader.h ***/
  98445. #if JUCE_USE_FLAC
  98446. #if HAVE_CONFIG_H
  98447. # include <config.h>
  98448. #endif
  98449. #include <stdlib.h> /* for malloc() */
  98450. #include <string.h> /* for memcpy() */
  98451. /*** Start of inlined file: md5.h ***/
  98452. #ifndef FLAC__PRIVATE__MD5_H
  98453. #define FLAC__PRIVATE__MD5_H
  98454. /*
  98455. * This is the header file for the MD5 message-digest algorithm.
  98456. * The algorithm is due to Ron Rivest. This code was
  98457. * written by Colin Plumb in 1993, no copyright is claimed.
  98458. * This code is in the public domain; do with it what you wish.
  98459. *
  98460. * Equivalent code is available from RSA Data Security, Inc.
  98461. * This code has been tested against that, and is equivalent,
  98462. * except that you don't need to include two pages of legalese
  98463. * with every copy.
  98464. *
  98465. * To compute the message digest of a chunk of bytes, declare an
  98466. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98467. * needed on buffers full of bytes, and then call MD5Final, which
  98468. * will fill a supplied 16-byte array with the digest.
  98469. *
  98470. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98471. * header definitions; now uses stuff from dpkg's config.h
  98472. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98473. * Still in the public domain.
  98474. *
  98475. * Josh Coalson: made some changes to integrate with libFLAC.
  98476. * Still in the public domain, with no warranty.
  98477. */
  98478. typedef struct {
  98479. FLAC__uint32 in[16];
  98480. FLAC__uint32 buf[4];
  98481. FLAC__uint32 bytes[2];
  98482. FLAC__byte *internal_buf;
  98483. size_t capacity;
  98484. } FLAC__MD5Context;
  98485. void FLAC__MD5Init(FLAC__MD5Context *context);
  98486. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98487. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98488. #endif
  98489. /*** End of inlined file: md5.h ***/
  98490. #ifndef FLaC__INLINE
  98491. #define FLaC__INLINE
  98492. #endif
  98493. /*
  98494. * This code implements the MD5 message-digest algorithm.
  98495. * The algorithm is due to Ron Rivest. This code was
  98496. * written by Colin Plumb in 1993, no copyright is claimed.
  98497. * This code is in the public domain; do with it what you wish.
  98498. *
  98499. * Equivalent code is available from RSA Data Security, Inc.
  98500. * This code has been tested against that, and is equivalent,
  98501. * except that you don't need to include two pages of legalese
  98502. * with every copy.
  98503. *
  98504. * To compute the message digest of a chunk of bytes, declare an
  98505. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98506. * needed on buffers full of bytes, and then call MD5Final, which
  98507. * will fill a supplied 16-byte array with the digest.
  98508. *
  98509. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98510. * definitions; now uses stuff from dpkg's config.h.
  98511. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98512. * Still in the public domain.
  98513. *
  98514. * Josh Coalson: made some changes to integrate with libFLAC.
  98515. * Still in the public domain.
  98516. */
  98517. /* The four core functions - F1 is optimized somewhat */
  98518. /* #define F1(x, y, z) (x & y | ~x & z) */
  98519. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98520. #define F2(x, y, z) F1(z, x, y)
  98521. #define F3(x, y, z) (x ^ y ^ z)
  98522. #define F4(x, y, z) (y ^ (x | ~z))
  98523. /* This is the central step in the MD5 algorithm. */
  98524. #define MD5STEP(f,w,x,y,z,in,s) \
  98525. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98526. /*
  98527. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98528. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98529. * the data and converts bytes into longwords for this routine.
  98530. */
  98531. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98532. {
  98533. register FLAC__uint32 a, b, c, d;
  98534. a = buf[0];
  98535. b = buf[1];
  98536. c = buf[2];
  98537. d = buf[3];
  98538. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98539. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98540. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98541. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98542. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98543. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98544. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98545. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98546. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98547. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98548. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98549. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98550. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98551. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98552. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98553. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98554. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98555. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98556. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98557. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98558. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98559. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98560. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98561. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98562. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98563. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98564. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98565. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98566. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98567. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98568. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98569. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98570. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98571. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98572. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98573. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98574. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98575. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98576. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98577. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98578. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98579. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98580. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98581. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98582. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98583. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98584. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98585. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98586. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98587. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98588. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98589. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98590. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98591. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98592. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98593. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98594. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98595. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98596. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98597. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98598. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98599. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98600. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98601. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98602. buf[0] += a;
  98603. buf[1] += b;
  98604. buf[2] += c;
  98605. buf[3] += d;
  98606. }
  98607. #if WORDS_BIGENDIAN
  98608. //@@@@@@ OPT: use bswap/intrinsics
  98609. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98610. {
  98611. register FLAC__uint32 x;
  98612. do {
  98613. x = *buf;
  98614. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98615. *buf++ = (x >> 16) | (x << 16);
  98616. } while (--words);
  98617. }
  98618. static void byteSwapX16(FLAC__uint32 *buf)
  98619. {
  98620. register FLAC__uint32 x;
  98621. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98622. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98623. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98624. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98625. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98626. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98627. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98628. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98629. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98630. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98631. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98632. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98633. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98634. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98635. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98636. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98637. }
  98638. #else
  98639. #define byteSwap(buf, words)
  98640. #define byteSwapX16(buf)
  98641. #endif
  98642. /*
  98643. * Update context to reflect the concatenation of another buffer full
  98644. * of bytes.
  98645. */
  98646. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98647. {
  98648. FLAC__uint32 t;
  98649. /* Update byte count */
  98650. t = ctx->bytes[0];
  98651. if ((ctx->bytes[0] = t + len) < t)
  98652. ctx->bytes[1]++; /* Carry from low to high */
  98653. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98654. if (t > len) {
  98655. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98656. return;
  98657. }
  98658. /* First chunk is an odd size */
  98659. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98660. byteSwapX16(ctx->in);
  98661. FLAC__MD5Transform(ctx->buf, ctx->in);
  98662. buf += t;
  98663. len -= t;
  98664. /* Process data in 64-byte chunks */
  98665. while (len >= 64) {
  98666. memcpy(ctx->in, buf, 64);
  98667. byteSwapX16(ctx->in);
  98668. FLAC__MD5Transform(ctx->buf, ctx->in);
  98669. buf += 64;
  98670. len -= 64;
  98671. }
  98672. /* Handle any remaining bytes of data. */
  98673. memcpy(ctx->in, buf, len);
  98674. }
  98675. /*
  98676. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98677. * initialization constants.
  98678. */
  98679. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98680. {
  98681. ctx->buf[0] = 0x67452301;
  98682. ctx->buf[1] = 0xefcdab89;
  98683. ctx->buf[2] = 0x98badcfe;
  98684. ctx->buf[3] = 0x10325476;
  98685. ctx->bytes[0] = 0;
  98686. ctx->bytes[1] = 0;
  98687. ctx->internal_buf = 0;
  98688. ctx->capacity = 0;
  98689. }
  98690. /*
  98691. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98692. * 1 0* (64-bit count of bits processed, MSB-first)
  98693. */
  98694. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98695. {
  98696. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98697. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98698. /* Set the first char of padding to 0x80. There is always room. */
  98699. *p++ = 0x80;
  98700. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98701. count = 56 - 1 - count;
  98702. if (count < 0) { /* Padding forces an extra block */
  98703. memset(p, 0, count + 8);
  98704. byteSwapX16(ctx->in);
  98705. FLAC__MD5Transform(ctx->buf, ctx->in);
  98706. p = (FLAC__byte *)ctx->in;
  98707. count = 56;
  98708. }
  98709. memset(p, 0, count);
  98710. byteSwap(ctx->in, 14);
  98711. /* Append length in bits and transform */
  98712. ctx->in[14] = ctx->bytes[0] << 3;
  98713. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98714. FLAC__MD5Transform(ctx->buf, ctx->in);
  98715. byteSwap(ctx->buf, 4);
  98716. memcpy(digest, ctx->buf, 16);
  98717. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98718. if(0 != ctx->internal_buf) {
  98719. free(ctx->internal_buf);
  98720. ctx->internal_buf = 0;
  98721. ctx->capacity = 0;
  98722. }
  98723. }
  98724. /*
  98725. * Convert the incoming audio signal to a byte stream
  98726. */
  98727. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98728. {
  98729. unsigned channel, sample;
  98730. register FLAC__int32 a_word;
  98731. register FLAC__byte *buf_ = buf;
  98732. #if WORDS_BIGENDIAN
  98733. #else
  98734. if(channels == 2 && bytes_per_sample == 2) {
  98735. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98736. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98737. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98738. *buf1_ = (FLAC__int16)signal[1][sample];
  98739. }
  98740. else if(channels == 1 && bytes_per_sample == 2) {
  98741. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98742. for(sample = 0; sample < samples; sample++)
  98743. *buf1_++ = (FLAC__int16)signal[0][sample];
  98744. }
  98745. else
  98746. #endif
  98747. if(bytes_per_sample == 2) {
  98748. if(channels == 2) {
  98749. for(sample = 0; sample < samples; sample++) {
  98750. a_word = signal[0][sample];
  98751. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98752. *buf_++ = (FLAC__byte)a_word;
  98753. a_word = signal[1][sample];
  98754. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98755. *buf_++ = (FLAC__byte)a_word;
  98756. }
  98757. }
  98758. else if(channels == 1) {
  98759. for(sample = 0; sample < samples; sample++) {
  98760. a_word = signal[0][sample];
  98761. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98762. *buf_++ = (FLAC__byte)a_word;
  98763. }
  98764. }
  98765. else {
  98766. for(sample = 0; sample < samples; sample++) {
  98767. for(channel = 0; channel < channels; channel++) {
  98768. a_word = signal[channel][sample];
  98769. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98770. *buf_++ = (FLAC__byte)a_word;
  98771. }
  98772. }
  98773. }
  98774. }
  98775. else if(bytes_per_sample == 3) {
  98776. if(channels == 2) {
  98777. for(sample = 0; sample < samples; sample++) {
  98778. a_word = signal[0][sample];
  98779. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98780. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98781. *buf_++ = (FLAC__byte)a_word;
  98782. a_word = signal[1][sample];
  98783. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98784. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98785. *buf_++ = (FLAC__byte)a_word;
  98786. }
  98787. }
  98788. else if(channels == 1) {
  98789. for(sample = 0; sample < samples; sample++) {
  98790. a_word = signal[0][sample];
  98791. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98792. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98793. *buf_++ = (FLAC__byte)a_word;
  98794. }
  98795. }
  98796. else {
  98797. for(sample = 0; sample < samples; sample++) {
  98798. for(channel = 0; channel < channels; channel++) {
  98799. a_word = signal[channel][sample];
  98800. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98801. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98802. *buf_++ = (FLAC__byte)a_word;
  98803. }
  98804. }
  98805. }
  98806. }
  98807. else if(bytes_per_sample == 1) {
  98808. if(channels == 2) {
  98809. for(sample = 0; sample < samples; sample++) {
  98810. a_word = signal[0][sample];
  98811. *buf_++ = (FLAC__byte)a_word;
  98812. a_word = signal[1][sample];
  98813. *buf_++ = (FLAC__byte)a_word;
  98814. }
  98815. }
  98816. else if(channels == 1) {
  98817. for(sample = 0; sample < samples; sample++) {
  98818. a_word = signal[0][sample];
  98819. *buf_++ = (FLAC__byte)a_word;
  98820. }
  98821. }
  98822. else {
  98823. for(sample = 0; sample < samples; sample++) {
  98824. for(channel = 0; channel < channels; channel++) {
  98825. a_word = signal[channel][sample];
  98826. *buf_++ = (FLAC__byte)a_word;
  98827. }
  98828. }
  98829. }
  98830. }
  98831. else { /* bytes_per_sample == 4, maybe optimize more later */
  98832. for(sample = 0; sample < samples; sample++) {
  98833. for(channel = 0; channel < channels; channel++) {
  98834. a_word = signal[channel][sample];
  98835. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98836. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98837. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98838. *buf_++ = (FLAC__byte)a_word;
  98839. }
  98840. }
  98841. }
  98842. }
  98843. /*
  98844. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98845. */
  98846. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98847. {
  98848. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98849. /* overflow check */
  98850. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98851. return false;
  98852. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98853. return false;
  98854. if(ctx->capacity < bytes_needed) {
  98855. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98856. if(0 == tmp) {
  98857. free(ctx->internal_buf);
  98858. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98859. return false;
  98860. }
  98861. ctx->internal_buf = tmp;
  98862. ctx->capacity = bytes_needed;
  98863. }
  98864. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98865. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98866. return true;
  98867. }
  98868. #endif
  98869. /*** End of inlined file: md5.c ***/
  98870. /*** Start of inlined file: memory.c ***/
  98871. /*** Start of inlined file: juce_FlacHeader.h ***/
  98872. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98873. // tasks..
  98874. #define VERSION "1.2.1"
  98875. #define FLAC__NO_DLL 1
  98876. #if JUCE_MSVC
  98877. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98878. #endif
  98879. #if JUCE_MAC
  98880. #define FLAC__SYS_DARWIN 1
  98881. #endif
  98882. /*** End of inlined file: juce_FlacHeader.h ***/
  98883. #if JUCE_USE_FLAC
  98884. #if HAVE_CONFIG_H
  98885. # include <config.h>
  98886. #endif
  98887. /*** Start of inlined file: memory.h ***/
  98888. #ifndef FLAC__PRIVATE__MEMORY_H
  98889. #define FLAC__PRIVATE__MEMORY_H
  98890. #ifdef HAVE_CONFIG_H
  98891. #include <config.h>
  98892. #endif
  98893. #include <stdlib.h> /* for size_t */
  98894. /* Returns the unaligned address returned by malloc.
  98895. * Use free() on this address to deallocate.
  98896. */
  98897. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98898. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98899. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98900. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98901. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98902. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98903. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98904. #endif
  98905. #endif
  98906. /*** End of inlined file: memory.h ***/
  98907. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98908. {
  98909. void *x;
  98910. FLAC__ASSERT(0 != aligned_address);
  98911. #ifdef FLAC__ALIGN_MALLOC_DATA
  98912. /* align on 32-byte (256-bit) boundary */
  98913. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98914. #ifdef SIZEOF_VOIDP
  98915. #if SIZEOF_VOIDP == 4
  98916. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98917. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98918. #elif SIZEOF_VOIDP == 8
  98919. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98920. #else
  98921. # error Unsupported sizeof(void*)
  98922. #endif
  98923. #else
  98924. /* there's got to be a better way to do this right for all archs */
  98925. if(sizeof(void*) == sizeof(unsigned))
  98926. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98927. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98928. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98929. else
  98930. return 0;
  98931. #endif
  98932. #else
  98933. x = safe_malloc_(bytes);
  98934. *aligned_address = x;
  98935. #endif
  98936. return x;
  98937. }
  98938. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98939. {
  98940. FLAC__int32 *pu; /* unaligned pointer */
  98941. union { /* union needed to comply with C99 pointer aliasing rules */
  98942. FLAC__int32 *pa; /* aligned pointer */
  98943. void *pv; /* aligned pointer alias */
  98944. } u;
  98945. FLAC__ASSERT(elements > 0);
  98946. FLAC__ASSERT(0 != unaligned_pointer);
  98947. FLAC__ASSERT(0 != aligned_pointer);
  98948. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98949. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98950. if(0 == pu) {
  98951. return false;
  98952. }
  98953. else {
  98954. if(*unaligned_pointer != 0)
  98955. free(*unaligned_pointer);
  98956. *unaligned_pointer = pu;
  98957. *aligned_pointer = u.pa;
  98958. return true;
  98959. }
  98960. }
  98961. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98962. {
  98963. FLAC__uint32 *pu; /* unaligned pointer */
  98964. union { /* union needed to comply with C99 pointer aliasing rules */
  98965. FLAC__uint32 *pa; /* aligned pointer */
  98966. void *pv; /* aligned pointer alias */
  98967. } u;
  98968. FLAC__ASSERT(elements > 0);
  98969. FLAC__ASSERT(0 != unaligned_pointer);
  98970. FLAC__ASSERT(0 != aligned_pointer);
  98971. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98972. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98973. if(0 == pu) {
  98974. return false;
  98975. }
  98976. else {
  98977. if(*unaligned_pointer != 0)
  98978. free(*unaligned_pointer);
  98979. *unaligned_pointer = pu;
  98980. *aligned_pointer = u.pa;
  98981. return true;
  98982. }
  98983. }
  98984. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98985. {
  98986. FLAC__uint64 *pu; /* unaligned pointer */
  98987. union { /* union needed to comply with C99 pointer aliasing rules */
  98988. FLAC__uint64 *pa; /* aligned pointer */
  98989. void *pv; /* aligned pointer alias */
  98990. } u;
  98991. FLAC__ASSERT(elements > 0);
  98992. FLAC__ASSERT(0 != unaligned_pointer);
  98993. FLAC__ASSERT(0 != aligned_pointer);
  98994. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98995. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98996. if(0 == pu) {
  98997. return false;
  98998. }
  98999. else {
  99000. if(*unaligned_pointer != 0)
  99001. free(*unaligned_pointer);
  99002. *unaligned_pointer = pu;
  99003. *aligned_pointer = u.pa;
  99004. return true;
  99005. }
  99006. }
  99007. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  99008. {
  99009. unsigned *pu; /* unaligned pointer */
  99010. union { /* union needed to comply with C99 pointer aliasing rules */
  99011. unsigned *pa; /* aligned pointer */
  99012. void *pv; /* aligned pointer alias */
  99013. } u;
  99014. FLAC__ASSERT(elements > 0);
  99015. FLAC__ASSERT(0 != unaligned_pointer);
  99016. FLAC__ASSERT(0 != aligned_pointer);
  99017. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99018. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99019. if(0 == pu) {
  99020. return false;
  99021. }
  99022. else {
  99023. if(*unaligned_pointer != 0)
  99024. free(*unaligned_pointer);
  99025. *unaligned_pointer = pu;
  99026. *aligned_pointer = u.pa;
  99027. return true;
  99028. }
  99029. }
  99030. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99031. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  99032. {
  99033. FLAC__real *pu; /* unaligned pointer */
  99034. union { /* union needed to comply with C99 pointer aliasing rules */
  99035. FLAC__real *pa; /* aligned pointer */
  99036. void *pv; /* aligned pointer alias */
  99037. } u;
  99038. FLAC__ASSERT(elements > 0);
  99039. FLAC__ASSERT(0 != unaligned_pointer);
  99040. FLAC__ASSERT(0 != aligned_pointer);
  99041. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99042. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99043. if(0 == pu) {
  99044. return false;
  99045. }
  99046. else {
  99047. if(*unaligned_pointer != 0)
  99048. free(*unaligned_pointer);
  99049. *unaligned_pointer = pu;
  99050. *aligned_pointer = u.pa;
  99051. return true;
  99052. }
  99053. }
  99054. #endif
  99055. #endif
  99056. /*** End of inlined file: memory.c ***/
  99057. /*** Start of inlined file: stream_decoder.c ***/
  99058. /*** Start of inlined file: juce_FlacHeader.h ***/
  99059. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99060. // tasks..
  99061. #define VERSION "1.2.1"
  99062. #define FLAC__NO_DLL 1
  99063. #if JUCE_MSVC
  99064. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99065. #endif
  99066. #if JUCE_MAC
  99067. #define FLAC__SYS_DARWIN 1
  99068. #endif
  99069. /*** End of inlined file: juce_FlacHeader.h ***/
  99070. #if JUCE_USE_FLAC
  99071. #if HAVE_CONFIG_H
  99072. # include <config.h>
  99073. #endif
  99074. #if defined _MSC_VER || defined __MINGW32__
  99075. #include <io.h> /* for _setmode() */
  99076. #include <fcntl.h> /* for _O_BINARY */
  99077. #endif
  99078. #if defined __CYGWIN__ || defined __EMX__
  99079. #include <io.h> /* for setmode(), O_BINARY */
  99080. #include <fcntl.h> /* for _O_BINARY */
  99081. #endif
  99082. #include <stdio.h>
  99083. #include <stdlib.h> /* for malloc() */
  99084. #include <string.h> /* for memset/memcpy() */
  99085. #include <sys/stat.h> /* for stat() */
  99086. #include <sys/types.h> /* for off_t */
  99087. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99088. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99089. #define fseeko fseek
  99090. #define ftello ftell
  99091. #endif
  99092. #endif
  99093. /*** Start of inlined file: stream_decoder.h ***/
  99094. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99095. #define FLAC__PROTECTED__STREAM_DECODER_H
  99096. #if FLAC__HAS_OGG
  99097. #include "include/private/ogg_decoder_aspect.h"
  99098. #endif
  99099. typedef struct FLAC__StreamDecoderProtected {
  99100. FLAC__StreamDecoderState state;
  99101. unsigned channels;
  99102. FLAC__ChannelAssignment channel_assignment;
  99103. unsigned bits_per_sample;
  99104. unsigned sample_rate; /* in Hz */
  99105. unsigned blocksize; /* in samples (per channel) */
  99106. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99107. #if FLAC__HAS_OGG
  99108. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99109. #endif
  99110. } FLAC__StreamDecoderProtected;
  99111. /*
  99112. * return the number of input bytes consumed
  99113. */
  99114. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99115. #endif
  99116. /*** End of inlined file: stream_decoder.h ***/
  99117. #ifdef max
  99118. #undef max
  99119. #endif
  99120. #define max(a,b) ((a)>(b)?(a):(b))
  99121. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99122. #ifdef _MSC_VER
  99123. #define FLAC__U64L(x) x
  99124. #else
  99125. #define FLAC__U64L(x) x##LLU
  99126. #endif
  99127. /* technically this should be in an "export.c" but this is convenient enough */
  99128. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99129. #if FLAC__HAS_OGG
  99130. 1
  99131. #else
  99132. 0
  99133. #endif
  99134. ;
  99135. /***********************************************************************
  99136. *
  99137. * Private static data
  99138. *
  99139. ***********************************************************************/
  99140. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99141. /***********************************************************************
  99142. *
  99143. * Private class method prototypes
  99144. *
  99145. ***********************************************************************/
  99146. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99147. static FILE *get_binary_stdin_(void);
  99148. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99149. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99150. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99151. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99152. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99153. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99154. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99155. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99156. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99157. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99158. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99159. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99160. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99161. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99162. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99163. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99164. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99165. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99166. 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);
  99167. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99168. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99169. #if FLAC__HAS_OGG
  99170. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99171. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99172. #endif
  99173. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99174. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99175. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99176. #if FLAC__HAS_OGG
  99177. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99178. #endif
  99179. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99180. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99181. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99182. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99183. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99184. /***********************************************************************
  99185. *
  99186. * Private class data
  99187. *
  99188. ***********************************************************************/
  99189. typedef struct FLAC__StreamDecoderPrivate {
  99190. #if FLAC__HAS_OGG
  99191. FLAC__bool is_ogg;
  99192. #endif
  99193. FLAC__StreamDecoderReadCallback read_callback;
  99194. FLAC__StreamDecoderSeekCallback seek_callback;
  99195. FLAC__StreamDecoderTellCallback tell_callback;
  99196. FLAC__StreamDecoderLengthCallback length_callback;
  99197. FLAC__StreamDecoderEofCallback eof_callback;
  99198. FLAC__StreamDecoderWriteCallback write_callback;
  99199. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99200. FLAC__StreamDecoderErrorCallback error_callback;
  99201. /* generic 32-bit datapath: */
  99202. 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[]);
  99203. /* generic 64-bit datapath: */
  99204. 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[]);
  99205. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99206. 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[]);
  99207. /* 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: */
  99208. 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[]);
  99209. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99210. void *client_data;
  99211. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99212. FLAC__BitReader *input;
  99213. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99214. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99215. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99216. unsigned output_capacity, output_channels;
  99217. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99218. FLAC__uint64 samples_decoded;
  99219. FLAC__bool has_stream_info, has_seek_table;
  99220. FLAC__StreamMetadata stream_info;
  99221. FLAC__StreamMetadata seek_table;
  99222. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99223. FLAC__byte *metadata_filter_ids;
  99224. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99225. FLAC__Frame frame;
  99226. FLAC__bool cached; /* true if there is a byte in lookahead */
  99227. FLAC__CPUInfo cpuinfo;
  99228. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99229. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99230. /* unaligned (original) pointers to allocated data */
  99231. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99232. 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 */
  99233. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99234. FLAC__bool is_seeking;
  99235. FLAC__MD5Context md5context;
  99236. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99237. /* (the rest of these are only used for seeking) */
  99238. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99239. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99240. FLAC__uint64 target_sample;
  99241. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99242. #if FLAC__HAS_OGG
  99243. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99244. #endif
  99245. } FLAC__StreamDecoderPrivate;
  99246. /***********************************************************************
  99247. *
  99248. * Public static class data
  99249. *
  99250. ***********************************************************************/
  99251. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99252. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99253. "FLAC__STREAM_DECODER_READ_METADATA",
  99254. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99255. "FLAC__STREAM_DECODER_READ_FRAME",
  99256. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99257. "FLAC__STREAM_DECODER_OGG_ERROR",
  99258. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99259. "FLAC__STREAM_DECODER_ABORTED",
  99260. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99261. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99262. };
  99263. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99264. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99265. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99266. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99267. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99268. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99269. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99270. };
  99271. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99272. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99273. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99274. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99275. };
  99276. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99277. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99278. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99279. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99280. };
  99281. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99282. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99283. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99284. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99285. };
  99286. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99287. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99288. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99289. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99290. };
  99291. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99292. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99293. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99294. };
  99295. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99296. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99297. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99298. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99299. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99300. };
  99301. /***********************************************************************
  99302. *
  99303. * Class constructor/destructor
  99304. *
  99305. ***********************************************************************/
  99306. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99307. {
  99308. FLAC__StreamDecoder *decoder;
  99309. unsigned i;
  99310. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99311. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99312. if(decoder == 0) {
  99313. return 0;
  99314. }
  99315. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99316. if(decoder->protected_ == 0) {
  99317. free(decoder);
  99318. return 0;
  99319. }
  99320. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99321. if(decoder->private_ == 0) {
  99322. free(decoder->protected_);
  99323. free(decoder);
  99324. return 0;
  99325. }
  99326. decoder->private_->input = FLAC__bitreader_new();
  99327. if(decoder->private_->input == 0) {
  99328. free(decoder->private_);
  99329. free(decoder->protected_);
  99330. free(decoder);
  99331. return 0;
  99332. }
  99333. decoder->private_->metadata_filter_ids_capacity = 16;
  99334. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99335. FLAC__bitreader_delete(decoder->private_->input);
  99336. free(decoder->private_);
  99337. free(decoder->protected_);
  99338. free(decoder);
  99339. return 0;
  99340. }
  99341. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99342. decoder->private_->output[i] = 0;
  99343. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99344. }
  99345. decoder->private_->output_capacity = 0;
  99346. decoder->private_->output_channels = 0;
  99347. decoder->private_->has_seek_table = false;
  99348. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99349. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99350. decoder->private_->file = 0;
  99351. set_defaults_dec(decoder);
  99352. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99353. return decoder;
  99354. }
  99355. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99356. {
  99357. unsigned i;
  99358. FLAC__ASSERT(0 != decoder);
  99359. FLAC__ASSERT(0 != decoder->protected_);
  99360. FLAC__ASSERT(0 != decoder->private_);
  99361. FLAC__ASSERT(0 != decoder->private_->input);
  99362. (void)FLAC__stream_decoder_finish(decoder);
  99363. if(0 != decoder->private_->metadata_filter_ids)
  99364. free(decoder->private_->metadata_filter_ids);
  99365. FLAC__bitreader_delete(decoder->private_->input);
  99366. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99367. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99368. free(decoder->private_);
  99369. free(decoder->protected_);
  99370. free(decoder);
  99371. }
  99372. /***********************************************************************
  99373. *
  99374. * Public class methods
  99375. *
  99376. ***********************************************************************/
  99377. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99378. FLAC__StreamDecoder *decoder,
  99379. FLAC__StreamDecoderReadCallback read_callback,
  99380. FLAC__StreamDecoderSeekCallback seek_callback,
  99381. FLAC__StreamDecoderTellCallback tell_callback,
  99382. FLAC__StreamDecoderLengthCallback length_callback,
  99383. FLAC__StreamDecoderEofCallback eof_callback,
  99384. FLAC__StreamDecoderWriteCallback write_callback,
  99385. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99386. FLAC__StreamDecoderErrorCallback error_callback,
  99387. void *client_data,
  99388. FLAC__bool is_ogg
  99389. )
  99390. {
  99391. FLAC__ASSERT(0 != decoder);
  99392. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99393. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99394. #if !FLAC__HAS_OGG
  99395. if(is_ogg)
  99396. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99397. #endif
  99398. if(
  99399. 0 == read_callback ||
  99400. 0 == write_callback ||
  99401. 0 == error_callback ||
  99402. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99403. )
  99404. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99405. #if FLAC__HAS_OGG
  99406. decoder->private_->is_ogg = is_ogg;
  99407. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99408. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99409. #endif
  99410. /*
  99411. * get the CPU info and set the function pointers
  99412. */
  99413. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99414. /* first default to the non-asm routines */
  99415. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99416. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99417. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99418. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99419. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99420. /* now override with asm where appropriate */
  99421. #ifndef FLAC__NO_ASM
  99422. if(decoder->private_->cpuinfo.use_asm) {
  99423. #ifdef FLAC__CPU_IA32
  99424. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99425. #ifdef FLAC__HAS_NASM
  99426. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99427. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99428. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99429. #endif
  99430. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99431. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99432. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99433. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99434. }
  99435. else {
  99436. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99437. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99438. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99439. }
  99440. #endif
  99441. #elif defined FLAC__CPU_PPC
  99442. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99443. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99444. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99445. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99446. }
  99447. #endif
  99448. }
  99449. #endif
  99450. /* from here on, errors are fatal */
  99451. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99452. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99453. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99454. }
  99455. decoder->private_->read_callback = read_callback;
  99456. decoder->private_->seek_callback = seek_callback;
  99457. decoder->private_->tell_callback = tell_callback;
  99458. decoder->private_->length_callback = length_callback;
  99459. decoder->private_->eof_callback = eof_callback;
  99460. decoder->private_->write_callback = write_callback;
  99461. decoder->private_->metadata_callback = metadata_callback;
  99462. decoder->private_->error_callback = error_callback;
  99463. decoder->private_->client_data = client_data;
  99464. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99465. decoder->private_->samples_decoded = 0;
  99466. decoder->private_->has_stream_info = false;
  99467. decoder->private_->cached = false;
  99468. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99469. decoder->private_->is_seeking = false;
  99470. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99471. if(!FLAC__stream_decoder_reset(decoder)) {
  99472. /* above call sets the state for us */
  99473. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99474. }
  99475. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99476. }
  99477. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99478. FLAC__StreamDecoder *decoder,
  99479. FLAC__StreamDecoderReadCallback read_callback,
  99480. FLAC__StreamDecoderSeekCallback seek_callback,
  99481. FLAC__StreamDecoderTellCallback tell_callback,
  99482. FLAC__StreamDecoderLengthCallback length_callback,
  99483. FLAC__StreamDecoderEofCallback eof_callback,
  99484. FLAC__StreamDecoderWriteCallback write_callback,
  99485. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99486. FLAC__StreamDecoderErrorCallback error_callback,
  99487. void *client_data
  99488. )
  99489. {
  99490. return init_stream_internal_dec(
  99491. decoder,
  99492. read_callback,
  99493. seek_callback,
  99494. tell_callback,
  99495. length_callback,
  99496. eof_callback,
  99497. write_callback,
  99498. metadata_callback,
  99499. error_callback,
  99500. client_data,
  99501. /*is_ogg=*/false
  99502. );
  99503. }
  99504. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99505. FLAC__StreamDecoder *decoder,
  99506. FLAC__StreamDecoderReadCallback read_callback,
  99507. FLAC__StreamDecoderSeekCallback seek_callback,
  99508. FLAC__StreamDecoderTellCallback tell_callback,
  99509. FLAC__StreamDecoderLengthCallback length_callback,
  99510. FLAC__StreamDecoderEofCallback eof_callback,
  99511. FLAC__StreamDecoderWriteCallback write_callback,
  99512. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99513. FLAC__StreamDecoderErrorCallback error_callback,
  99514. void *client_data
  99515. )
  99516. {
  99517. return init_stream_internal_dec(
  99518. decoder,
  99519. read_callback,
  99520. seek_callback,
  99521. tell_callback,
  99522. length_callback,
  99523. eof_callback,
  99524. write_callback,
  99525. metadata_callback,
  99526. error_callback,
  99527. client_data,
  99528. /*is_ogg=*/true
  99529. );
  99530. }
  99531. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99532. FLAC__StreamDecoder *decoder,
  99533. FILE *file,
  99534. FLAC__StreamDecoderWriteCallback write_callback,
  99535. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99536. FLAC__StreamDecoderErrorCallback error_callback,
  99537. void *client_data,
  99538. FLAC__bool is_ogg
  99539. )
  99540. {
  99541. FLAC__ASSERT(0 != decoder);
  99542. FLAC__ASSERT(0 != file);
  99543. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99544. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99545. if(0 == write_callback || 0 == error_callback)
  99546. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99547. /*
  99548. * To make sure that our file does not go unclosed after an error, we
  99549. * must assign the FILE pointer before any further error can occur in
  99550. * this routine.
  99551. */
  99552. if(file == stdin)
  99553. file = get_binary_stdin_(); /* just to be safe */
  99554. decoder->private_->file = file;
  99555. return init_stream_internal_dec(
  99556. decoder,
  99557. file_read_callback_dec,
  99558. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99559. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99560. decoder->private_->file == stdin? 0: file_length_callback_,
  99561. file_eof_callback_,
  99562. write_callback,
  99563. metadata_callback,
  99564. error_callback,
  99565. client_data,
  99566. is_ogg
  99567. );
  99568. }
  99569. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99570. FLAC__StreamDecoder *decoder,
  99571. FILE *file,
  99572. FLAC__StreamDecoderWriteCallback write_callback,
  99573. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99574. FLAC__StreamDecoderErrorCallback error_callback,
  99575. void *client_data
  99576. )
  99577. {
  99578. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99579. }
  99580. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99581. FLAC__StreamDecoder *decoder,
  99582. FILE *file,
  99583. FLAC__StreamDecoderWriteCallback write_callback,
  99584. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99585. FLAC__StreamDecoderErrorCallback error_callback,
  99586. void *client_data
  99587. )
  99588. {
  99589. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99590. }
  99591. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99592. FLAC__StreamDecoder *decoder,
  99593. const char *filename,
  99594. FLAC__StreamDecoderWriteCallback write_callback,
  99595. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99596. FLAC__StreamDecoderErrorCallback error_callback,
  99597. void *client_data,
  99598. FLAC__bool is_ogg
  99599. )
  99600. {
  99601. FILE *file;
  99602. FLAC__ASSERT(0 != decoder);
  99603. /*
  99604. * To make sure that our file does not go unclosed after an error, we
  99605. * have to do the same entrance checks here that are later performed
  99606. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99607. */
  99608. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99609. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99610. if(0 == write_callback || 0 == error_callback)
  99611. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99612. file = filename? fopen(filename, "rb") : stdin;
  99613. if(0 == file)
  99614. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99615. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99616. }
  99617. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99618. FLAC__StreamDecoder *decoder,
  99619. const char *filename,
  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, filename, 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. const char *filename,
  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, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99638. }
  99639. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99640. {
  99641. FLAC__bool md5_failed = false;
  99642. unsigned i;
  99643. FLAC__ASSERT(0 != decoder);
  99644. FLAC__ASSERT(0 != decoder->private_);
  99645. FLAC__ASSERT(0 != decoder->protected_);
  99646. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99647. return true;
  99648. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99649. * always call FLAC__MD5Final()
  99650. */
  99651. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99652. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99653. free(decoder->private_->seek_table.data.seek_table.points);
  99654. decoder->private_->seek_table.data.seek_table.points = 0;
  99655. decoder->private_->has_seek_table = false;
  99656. }
  99657. FLAC__bitreader_free(decoder->private_->input);
  99658. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99659. /* WATCHOUT:
  99660. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99661. * output arrays have a buffer of up to 3 zeroes in front
  99662. * (at negative indices) for alignment purposes; we use 4
  99663. * to keep the data well-aligned.
  99664. */
  99665. if(0 != decoder->private_->output[i]) {
  99666. free(decoder->private_->output[i]-4);
  99667. decoder->private_->output[i] = 0;
  99668. }
  99669. if(0 != decoder->private_->residual_unaligned[i]) {
  99670. free(decoder->private_->residual_unaligned[i]);
  99671. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99672. }
  99673. }
  99674. decoder->private_->output_capacity = 0;
  99675. decoder->private_->output_channels = 0;
  99676. #if FLAC__HAS_OGG
  99677. if(decoder->private_->is_ogg)
  99678. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99679. #endif
  99680. if(0 != decoder->private_->file) {
  99681. if(decoder->private_->file != stdin)
  99682. fclose(decoder->private_->file);
  99683. decoder->private_->file = 0;
  99684. }
  99685. if(decoder->private_->do_md5_checking) {
  99686. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99687. md5_failed = true;
  99688. }
  99689. decoder->private_->is_seeking = false;
  99690. set_defaults_dec(decoder);
  99691. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99692. return !md5_failed;
  99693. }
  99694. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99695. {
  99696. FLAC__ASSERT(0 != decoder);
  99697. FLAC__ASSERT(0 != decoder->private_);
  99698. FLAC__ASSERT(0 != decoder->protected_);
  99699. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99700. return false;
  99701. #if FLAC__HAS_OGG
  99702. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99703. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99704. return true;
  99705. #else
  99706. (void)value;
  99707. return false;
  99708. #endif
  99709. }
  99710. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99711. {
  99712. FLAC__ASSERT(0 != decoder);
  99713. FLAC__ASSERT(0 != decoder->protected_);
  99714. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99715. return false;
  99716. decoder->protected_->md5_checking = value;
  99717. return true;
  99718. }
  99719. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99720. {
  99721. FLAC__ASSERT(0 != decoder);
  99722. FLAC__ASSERT(0 != decoder->private_);
  99723. FLAC__ASSERT(0 != decoder->protected_);
  99724. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99725. /* double protection */
  99726. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99727. return false;
  99728. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99729. return false;
  99730. decoder->private_->metadata_filter[type] = true;
  99731. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99732. decoder->private_->metadata_filter_ids_count = 0;
  99733. return true;
  99734. }
  99735. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99736. {
  99737. FLAC__ASSERT(0 != decoder);
  99738. FLAC__ASSERT(0 != decoder->private_);
  99739. FLAC__ASSERT(0 != decoder->protected_);
  99740. FLAC__ASSERT(0 != id);
  99741. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99742. return false;
  99743. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99744. return true;
  99745. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99746. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99747. 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))) {
  99748. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99749. return false;
  99750. }
  99751. decoder->private_->metadata_filter_ids_capacity *= 2;
  99752. }
  99753. 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));
  99754. decoder->private_->metadata_filter_ids_count++;
  99755. return true;
  99756. }
  99757. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99758. {
  99759. unsigned i;
  99760. FLAC__ASSERT(0 != decoder);
  99761. FLAC__ASSERT(0 != decoder->private_);
  99762. FLAC__ASSERT(0 != decoder->protected_);
  99763. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99764. return false;
  99765. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99766. decoder->private_->metadata_filter[i] = true;
  99767. decoder->private_->metadata_filter_ids_count = 0;
  99768. return true;
  99769. }
  99770. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99771. {
  99772. FLAC__ASSERT(0 != decoder);
  99773. FLAC__ASSERT(0 != decoder->private_);
  99774. FLAC__ASSERT(0 != decoder->protected_);
  99775. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99776. /* double protection */
  99777. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99778. return false;
  99779. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99780. return false;
  99781. decoder->private_->metadata_filter[type] = false;
  99782. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99783. decoder->private_->metadata_filter_ids_count = 0;
  99784. return true;
  99785. }
  99786. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99787. {
  99788. FLAC__ASSERT(0 != decoder);
  99789. FLAC__ASSERT(0 != decoder->private_);
  99790. FLAC__ASSERT(0 != decoder->protected_);
  99791. FLAC__ASSERT(0 != id);
  99792. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99793. return false;
  99794. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99795. return true;
  99796. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99797. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99798. 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))) {
  99799. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99800. return false;
  99801. }
  99802. decoder->private_->metadata_filter_ids_capacity *= 2;
  99803. }
  99804. 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));
  99805. decoder->private_->metadata_filter_ids_count++;
  99806. return true;
  99807. }
  99808. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99809. {
  99810. FLAC__ASSERT(0 != decoder);
  99811. FLAC__ASSERT(0 != decoder->private_);
  99812. FLAC__ASSERT(0 != decoder->protected_);
  99813. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99814. return false;
  99815. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99816. decoder->private_->metadata_filter_ids_count = 0;
  99817. return true;
  99818. }
  99819. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99820. {
  99821. FLAC__ASSERT(0 != decoder);
  99822. FLAC__ASSERT(0 != decoder->protected_);
  99823. return decoder->protected_->state;
  99824. }
  99825. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99826. {
  99827. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99828. }
  99829. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99830. {
  99831. FLAC__ASSERT(0 != decoder);
  99832. FLAC__ASSERT(0 != decoder->protected_);
  99833. return decoder->protected_->md5_checking;
  99834. }
  99835. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99836. {
  99837. FLAC__ASSERT(0 != decoder);
  99838. FLAC__ASSERT(0 != decoder->protected_);
  99839. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99840. }
  99841. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99842. {
  99843. FLAC__ASSERT(0 != decoder);
  99844. FLAC__ASSERT(0 != decoder->protected_);
  99845. return decoder->protected_->channels;
  99846. }
  99847. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99848. {
  99849. FLAC__ASSERT(0 != decoder);
  99850. FLAC__ASSERT(0 != decoder->protected_);
  99851. return decoder->protected_->channel_assignment;
  99852. }
  99853. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99854. {
  99855. FLAC__ASSERT(0 != decoder);
  99856. FLAC__ASSERT(0 != decoder->protected_);
  99857. return decoder->protected_->bits_per_sample;
  99858. }
  99859. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99860. {
  99861. FLAC__ASSERT(0 != decoder);
  99862. FLAC__ASSERT(0 != decoder->protected_);
  99863. return decoder->protected_->sample_rate;
  99864. }
  99865. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99866. {
  99867. FLAC__ASSERT(0 != decoder);
  99868. FLAC__ASSERT(0 != decoder->protected_);
  99869. return decoder->protected_->blocksize;
  99870. }
  99871. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99872. {
  99873. FLAC__ASSERT(0 != decoder);
  99874. FLAC__ASSERT(0 != decoder->private_);
  99875. FLAC__ASSERT(0 != position);
  99876. #if FLAC__HAS_OGG
  99877. if(decoder->private_->is_ogg)
  99878. return false;
  99879. #endif
  99880. if(0 == decoder->private_->tell_callback)
  99881. return false;
  99882. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99883. return false;
  99884. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99885. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99886. return false;
  99887. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99888. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99889. return true;
  99890. }
  99891. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99892. {
  99893. FLAC__ASSERT(0 != decoder);
  99894. FLAC__ASSERT(0 != decoder->private_);
  99895. FLAC__ASSERT(0 != decoder->protected_);
  99896. decoder->private_->samples_decoded = 0;
  99897. decoder->private_->do_md5_checking = false;
  99898. #if FLAC__HAS_OGG
  99899. if(decoder->private_->is_ogg)
  99900. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99901. #endif
  99902. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99903. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99904. return false;
  99905. }
  99906. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99907. return true;
  99908. }
  99909. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99910. {
  99911. FLAC__ASSERT(0 != decoder);
  99912. FLAC__ASSERT(0 != decoder->private_);
  99913. FLAC__ASSERT(0 != decoder->protected_);
  99914. if(!FLAC__stream_decoder_flush(decoder)) {
  99915. /* above call sets the state for us */
  99916. return false;
  99917. }
  99918. #if FLAC__HAS_OGG
  99919. /*@@@ could go in !internal_reset_hack block below */
  99920. if(decoder->private_->is_ogg)
  99921. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99922. #endif
  99923. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99924. * (internal_reset_hack) don't try to rewind since we are already at
  99925. * the beginning of the stream and don't want to fail if the input is
  99926. * not seekable.
  99927. */
  99928. if(!decoder->private_->internal_reset_hack) {
  99929. if(decoder->private_->file == stdin)
  99930. return false; /* can't rewind stdin, reset fails */
  99931. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99932. return false; /* seekable and seek fails, reset fails */
  99933. }
  99934. else
  99935. decoder->private_->internal_reset_hack = false;
  99936. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99937. decoder->private_->has_stream_info = false;
  99938. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99939. free(decoder->private_->seek_table.data.seek_table.points);
  99940. decoder->private_->seek_table.data.seek_table.points = 0;
  99941. decoder->private_->has_seek_table = false;
  99942. }
  99943. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99944. /*
  99945. * This goes in reset() and not flush() because according to the spec, a
  99946. * fixed-blocksize stream must stay that way through the whole stream.
  99947. */
  99948. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99949. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99950. * is because md5 checking may be turned on to start and then turned off if
  99951. * a seek occurs. So we init the context here and finalize it in
  99952. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99953. * properly.
  99954. */
  99955. FLAC__MD5Init(&decoder->private_->md5context);
  99956. decoder->private_->first_frame_offset = 0;
  99957. decoder->private_->unparseable_frame_count = 0;
  99958. return true;
  99959. }
  99960. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99961. {
  99962. FLAC__bool got_a_frame;
  99963. FLAC__ASSERT(0 != decoder);
  99964. FLAC__ASSERT(0 != decoder->protected_);
  99965. while(1) {
  99966. switch(decoder->protected_->state) {
  99967. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99968. if(!find_metadata_(decoder))
  99969. return false; /* above function sets the status for us */
  99970. break;
  99971. case FLAC__STREAM_DECODER_READ_METADATA:
  99972. if(!read_metadata_(decoder))
  99973. return false; /* above function sets the status for us */
  99974. else
  99975. return true;
  99976. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99977. if(!frame_sync_(decoder))
  99978. return true; /* above function sets the status for us */
  99979. break;
  99980. case FLAC__STREAM_DECODER_READ_FRAME:
  99981. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99982. return false; /* above function sets the status for us */
  99983. if(got_a_frame)
  99984. return true; /* above function sets the status for us */
  99985. break;
  99986. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99987. case FLAC__STREAM_DECODER_ABORTED:
  99988. return true;
  99989. default:
  99990. FLAC__ASSERT(0);
  99991. return false;
  99992. }
  99993. }
  99994. }
  99995. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99996. {
  99997. FLAC__ASSERT(0 != decoder);
  99998. FLAC__ASSERT(0 != decoder->protected_);
  99999. while(1) {
  100000. switch(decoder->protected_->state) {
  100001. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100002. if(!find_metadata_(decoder))
  100003. return false; /* above function sets the status for us */
  100004. break;
  100005. case FLAC__STREAM_DECODER_READ_METADATA:
  100006. if(!read_metadata_(decoder))
  100007. return false; /* above function sets the status for us */
  100008. break;
  100009. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100010. case FLAC__STREAM_DECODER_READ_FRAME:
  100011. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100012. case FLAC__STREAM_DECODER_ABORTED:
  100013. return true;
  100014. default:
  100015. FLAC__ASSERT(0);
  100016. return false;
  100017. }
  100018. }
  100019. }
  100020. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  100021. {
  100022. FLAC__bool dummy;
  100023. FLAC__ASSERT(0 != decoder);
  100024. FLAC__ASSERT(0 != decoder->protected_);
  100025. while(1) {
  100026. switch(decoder->protected_->state) {
  100027. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100028. if(!find_metadata_(decoder))
  100029. return false; /* above function sets the status for us */
  100030. break;
  100031. case FLAC__STREAM_DECODER_READ_METADATA:
  100032. if(!read_metadata_(decoder))
  100033. return false; /* above function sets the status for us */
  100034. break;
  100035. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100036. if(!frame_sync_(decoder))
  100037. return true; /* above function sets the status for us */
  100038. break;
  100039. case FLAC__STREAM_DECODER_READ_FRAME:
  100040. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  100041. return false; /* above function sets the status for us */
  100042. break;
  100043. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100044. case FLAC__STREAM_DECODER_ABORTED:
  100045. return true;
  100046. default:
  100047. FLAC__ASSERT(0);
  100048. return false;
  100049. }
  100050. }
  100051. }
  100052. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  100053. {
  100054. FLAC__bool got_a_frame;
  100055. FLAC__ASSERT(0 != decoder);
  100056. FLAC__ASSERT(0 != decoder->protected_);
  100057. while(1) {
  100058. switch(decoder->protected_->state) {
  100059. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100060. case FLAC__STREAM_DECODER_READ_METADATA:
  100061. return false; /* above function sets the status for us */
  100062. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100063. if(!frame_sync_(decoder))
  100064. return true; /* above function sets the status for us */
  100065. break;
  100066. case FLAC__STREAM_DECODER_READ_FRAME:
  100067. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  100068. return false; /* above function sets the status for us */
  100069. if(got_a_frame)
  100070. return true; /* above function sets the status for us */
  100071. break;
  100072. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100073. case FLAC__STREAM_DECODER_ABORTED:
  100074. return true;
  100075. default:
  100076. FLAC__ASSERT(0);
  100077. return false;
  100078. }
  100079. }
  100080. }
  100081. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  100082. {
  100083. FLAC__uint64 length;
  100084. FLAC__ASSERT(0 != decoder);
  100085. if(
  100086. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100087. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100088. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100089. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100090. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100091. )
  100092. return false;
  100093. if(0 == decoder->private_->seek_callback)
  100094. return false;
  100095. FLAC__ASSERT(decoder->private_->seek_callback);
  100096. FLAC__ASSERT(decoder->private_->tell_callback);
  100097. FLAC__ASSERT(decoder->private_->length_callback);
  100098. FLAC__ASSERT(decoder->private_->eof_callback);
  100099. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100100. return false;
  100101. decoder->private_->is_seeking = true;
  100102. /* turn off md5 checking if a seek is attempted */
  100103. decoder->private_->do_md5_checking = false;
  100104. /* 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) */
  100105. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100106. decoder->private_->is_seeking = false;
  100107. return false;
  100108. }
  100109. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100110. if(
  100111. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100112. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100113. ) {
  100114. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100115. /* above call sets the state for us */
  100116. decoder->private_->is_seeking = false;
  100117. return false;
  100118. }
  100119. /* check this again in case we didn't know total_samples the first time */
  100120. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100121. decoder->private_->is_seeking = false;
  100122. return false;
  100123. }
  100124. }
  100125. {
  100126. const FLAC__bool ok =
  100127. #if FLAC__HAS_OGG
  100128. decoder->private_->is_ogg?
  100129. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100130. #endif
  100131. seek_to_absolute_sample_(decoder, length, sample)
  100132. ;
  100133. decoder->private_->is_seeking = false;
  100134. return ok;
  100135. }
  100136. }
  100137. /***********************************************************************
  100138. *
  100139. * Protected class methods
  100140. *
  100141. ***********************************************************************/
  100142. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100143. {
  100144. FLAC__ASSERT(0 != decoder);
  100145. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100146. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100147. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100148. }
  100149. /***********************************************************************
  100150. *
  100151. * Private class methods
  100152. *
  100153. ***********************************************************************/
  100154. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100155. {
  100156. #if FLAC__HAS_OGG
  100157. decoder->private_->is_ogg = false;
  100158. #endif
  100159. decoder->private_->read_callback = 0;
  100160. decoder->private_->seek_callback = 0;
  100161. decoder->private_->tell_callback = 0;
  100162. decoder->private_->length_callback = 0;
  100163. decoder->private_->eof_callback = 0;
  100164. decoder->private_->write_callback = 0;
  100165. decoder->private_->metadata_callback = 0;
  100166. decoder->private_->error_callback = 0;
  100167. decoder->private_->client_data = 0;
  100168. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100169. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100170. decoder->private_->metadata_filter_ids_count = 0;
  100171. decoder->protected_->md5_checking = false;
  100172. #if FLAC__HAS_OGG
  100173. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100174. #endif
  100175. }
  100176. /*
  100177. * This will forcibly set stdin to binary mode (for OSes that require it)
  100178. */
  100179. FILE *get_binary_stdin_(void)
  100180. {
  100181. /* if something breaks here it is probably due to the presence or
  100182. * absence of an underscore before the identifiers 'setmode',
  100183. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100184. */
  100185. #if defined _MSC_VER || defined __MINGW32__
  100186. _setmode(_fileno(stdin), _O_BINARY);
  100187. #elif defined __CYGWIN__
  100188. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100189. setmode(_fileno(stdin), _O_BINARY);
  100190. #elif defined __EMX__
  100191. setmode(fileno(stdin), O_BINARY);
  100192. #endif
  100193. return stdin;
  100194. }
  100195. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100196. {
  100197. unsigned i;
  100198. FLAC__int32 *tmp;
  100199. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100200. return true;
  100201. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100202. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100203. if(0 != decoder->private_->output[i]) {
  100204. free(decoder->private_->output[i]-4);
  100205. decoder->private_->output[i] = 0;
  100206. }
  100207. if(0 != decoder->private_->residual_unaligned[i]) {
  100208. free(decoder->private_->residual_unaligned[i]);
  100209. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100210. }
  100211. }
  100212. for(i = 0; i < channels; i++) {
  100213. /* WATCHOUT:
  100214. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100215. * output arrays have a buffer of up to 3 zeroes in front
  100216. * (at negative indices) for alignment purposes; we use 4
  100217. * to keep the data well-aligned.
  100218. */
  100219. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100220. if(tmp == 0) {
  100221. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100222. return false;
  100223. }
  100224. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100225. decoder->private_->output[i] = tmp + 4;
  100226. /* WATCHOUT:
  100227. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100228. */
  100229. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100230. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100231. return false;
  100232. }
  100233. }
  100234. decoder->private_->output_capacity = size;
  100235. decoder->private_->output_channels = channels;
  100236. return true;
  100237. }
  100238. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100239. {
  100240. size_t i;
  100241. FLAC__ASSERT(0 != decoder);
  100242. FLAC__ASSERT(0 != decoder->private_);
  100243. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100244. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100245. return true;
  100246. return false;
  100247. }
  100248. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100249. {
  100250. FLAC__uint32 x;
  100251. unsigned i, id_;
  100252. FLAC__bool first = true;
  100253. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100254. for(i = id_ = 0; i < 4; ) {
  100255. if(decoder->private_->cached) {
  100256. x = (FLAC__uint32)decoder->private_->lookahead;
  100257. decoder->private_->cached = false;
  100258. }
  100259. else {
  100260. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100261. return false; /* read_callback_ sets the state for us */
  100262. }
  100263. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100264. first = true;
  100265. i++;
  100266. id_ = 0;
  100267. continue;
  100268. }
  100269. if(x == ID3V2_TAG_[id_]) {
  100270. id_++;
  100271. i = 0;
  100272. if(id_ == 3) {
  100273. if(!skip_id3v2_tag_(decoder))
  100274. return false; /* skip_id3v2_tag_ sets the state for us */
  100275. }
  100276. continue;
  100277. }
  100278. id_ = 0;
  100279. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100280. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100281. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100282. return false; /* read_callback_ sets the state for us */
  100283. /* 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 */
  100284. /* else we have to check if the second byte is the end of a sync code */
  100285. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100286. decoder->private_->lookahead = (FLAC__byte)x;
  100287. decoder->private_->cached = true;
  100288. }
  100289. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100290. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100291. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100292. return true;
  100293. }
  100294. }
  100295. i = 0;
  100296. if(first) {
  100297. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100298. first = false;
  100299. }
  100300. }
  100301. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100302. return true;
  100303. }
  100304. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100305. {
  100306. FLAC__bool is_last;
  100307. FLAC__uint32 i, x, type, length;
  100308. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100309. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100310. return false; /* read_callback_ sets the state for us */
  100311. is_last = x? true : false;
  100312. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100313. return false; /* read_callback_ sets the state for us */
  100314. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100315. return false; /* read_callback_ sets the state for us */
  100316. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100317. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100318. return false;
  100319. decoder->private_->has_stream_info = true;
  100320. 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))
  100321. decoder->private_->do_md5_checking = false;
  100322. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100323. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100324. }
  100325. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100326. if(!read_metadata_seektable_(decoder, is_last, length))
  100327. return false;
  100328. decoder->private_->has_seek_table = true;
  100329. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100330. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100331. }
  100332. else {
  100333. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100334. unsigned real_length = length;
  100335. FLAC__StreamMetadata block;
  100336. block.is_last = is_last;
  100337. block.type = (FLAC__MetadataType)type;
  100338. block.length = length;
  100339. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100340. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100341. return false; /* read_callback_ sets the state for us */
  100342. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100343. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100344. return false;
  100345. }
  100346. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100347. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100348. skip_it = !skip_it;
  100349. }
  100350. if(skip_it) {
  100351. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100352. return false; /* read_callback_ sets the state for us */
  100353. }
  100354. else {
  100355. switch(type) {
  100356. case FLAC__METADATA_TYPE_PADDING:
  100357. /* skip the padding bytes */
  100358. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100359. return false; /* read_callback_ sets the state for us */
  100360. break;
  100361. case FLAC__METADATA_TYPE_APPLICATION:
  100362. /* remember, we read the ID already */
  100363. if(real_length > 0) {
  100364. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100365. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100366. return false;
  100367. }
  100368. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100369. return false; /* read_callback_ sets the state for us */
  100370. }
  100371. else
  100372. block.data.application.data = 0;
  100373. break;
  100374. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100375. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100376. return false;
  100377. break;
  100378. case FLAC__METADATA_TYPE_CUESHEET:
  100379. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100380. return false;
  100381. break;
  100382. case FLAC__METADATA_TYPE_PICTURE:
  100383. if(!read_metadata_picture_(decoder, &block.data.picture))
  100384. return false;
  100385. break;
  100386. case FLAC__METADATA_TYPE_STREAMINFO:
  100387. case FLAC__METADATA_TYPE_SEEKTABLE:
  100388. FLAC__ASSERT(0);
  100389. break;
  100390. default:
  100391. if(real_length > 0) {
  100392. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100393. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100394. return false;
  100395. }
  100396. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100397. return false; /* read_callback_ sets the state for us */
  100398. }
  100399. else
  100400. block.data.unknown.data = 0;
  100401. break;
  100402. }
  100403. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100404. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100405. /* now we have to free any malloc()ed data in the block */
  100406. switch(type) {
  100407. case FLAC__METADATA_TYPE_PADDING:
  100408. break;
  100409. case FLAC__METADATA_TYPE_APPLICATION:
  100410. if(0 != block.data.application.data)
  100411. free(block.data.application.data);
  100412. break;
  100413. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100414. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100415. free(block.data.vorbis_comment.vendor_string.entry);
  100416. if(block.data.vorbis_comment.num_comments > 0)
  100417. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100418. if(0 != block.data.vorbis_comment.comments[i].entry)
  100419. free(block.data.vorbis_comment.comments[i].entry);
  100420. if(0 != block.data.vorbis_comment.comments)
  100421. free(block.data.vorbis_comment.comments);
  100422. break;
  100423. case FLAC__METADATA_TYPE_CUESHEET:
  100424. if(block.data.cue_sheet.num_tracks > 0)
  100425. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100426. if(0 != block.data.cue_sheet.tracks[i].indices)
  100427. free(block.data.cue_sheet.tracks[i].indices);
  100428. if(0 != block.data.cue_sheet.tracks)
  100429. free(block.data.cue_sheet.tracks);
  100430. break;
  100431. case FLAC__METADATA_TYPE_PICTURE:
  100432. if(0 != block.data.picture.mime_type)
  100433. free(block.data.picture.mime_type);
  100434. if(0 != block.data.picture.description)
  100435. free(block.data.picture.description);
  100436. if(0 != block.data.picture.data)
  100437. free(block.data.picture.data);
  100438. break;
  100439. case FLAC__METADATA_TYPE_STREAMINFO:
  100440. case FLAC__METADATA_TYPE_SEEKTABLE:
  100441. FLAC__ASSERT(0);
  100442. default:
  100443. if(0 != block.data.unknown.data)
  100444. free(block.data.unknown.data);
  100445. break;
  100446. }
  100447. }
  100448. }
  100449. if(is_last) {
  100450. /* if this fails, it's OK, it's just a hint for the seek routine */
  100451. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100452. decoder->private_->first_frame_offset = 0;
  100453. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100454. }
  100455. return true;
  100456. }
  100457. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100458. {
  100459. FLAC__uint32 x;
  100460. unsigned bits, used_bits = 0;
  100461. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100462. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100463. decoder->private_->stream_info.is_last = is_last;
  100464. decoder->private_->stream_info.length = length;
  100465. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100466. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100467. return false; /* read_callback_ sets the state for us */
  100468. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100469. used_bits += bits;
  100470. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100471. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100472. return false; /* read_callback_ sets the state for us */
  100473. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100474. used_bits += bits;
  100475. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100476. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100477. return false; /* read_callback_ sets the state for us */
  100478. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100479. used_bits += bits;
  100480. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100481. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100482. return false; /* read_callback_ sets the state for us */
  100483. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100484. used_bits += bits;
  100485. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100486. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100487. return false; /* read_callback_ sets the state for us */
  100488. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100489. used_bits += bits;
  100490. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100491. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100492. return false; /* read_callback_ sets the state for us */
  100493. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100494. used_bits += bits;
  100495. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100496. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100497. return false; /* read_callback_ sets the state for us */
  100498. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100499. used_bits += bits;
  100500. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100501. 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))
  100502. return false; /* read_callback_ sets the state for us */
  100503. used_bits += bits;
  100504. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100505. return false; /* read_callback_ sets the state for us */
  100506. used_bits += 16*8;
  100507. /* skip the rest of the block */
  100508. FLAC__ASSERT(used_bits % 8 == 0);
  100509. length -= (used_bits / 8);
  100510. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100511. return false; /* read_callback_ sets the state for us */
  100512. return true;
  100513. }
  100514. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100515. {
  100516. FLAC__uint32 i, x;
  100517. FLAC__uint64 xx;
  100518. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100519. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100520. decoder->private_->seek_table.is_last = is_last;
  100521. decoder->private_->seek_table.length = length;
  100522. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100523. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100524. 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)))) {
  100525. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100526. return false;
  100527. }
  100528. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100529. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100530. return false; /* read_callback_ sets the state for us */
  100531. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100532. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100533. return false; /* read_callback_ sets the state for us */
  100534. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100535. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100536. return false; /* read_callback_ sets the state for us */
  100537. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100538. }
  100539. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100540. /* if there is a partial point left, skip over it */
  100541. if(length > 0) {
  100542. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100543. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100544. return false; /* read_callback_ sets the state for us */
  100545. }
  100546. return true;
  100547. }
  100548. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100549. {
  100550. FLAC__uint32 i;
  100551. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100552. /* read vendor string */
  100553. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100554. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100555. return false; /* read_callback_ sets the state for us */
  100556. if(obj->vendor_string.length > 0) {
  100557. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100558. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100559. return false;
  100560. }
  100561. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100562. return false; /* read_callback_ sets the state for us */
  100563. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100564. }
  100565. else
  100566. obj->vendor_string.entry = 0;
  100567. /* read num comments */
  100568. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100569. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100570. return false; /* read_callback_ sets the state for us */
  100571. /* read comments */
  100572. if(obj->num_comments > 0) {
  100573. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100574. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100575. return false;
  100576. }
  100577. for(i = 0; i < obj->num_comments; i++) {
  100578. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100579. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100580. return false; /* read_callback_ sets the state for us */
  100581. if(obj->comments[i].length > 0) {
  100582. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100583. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100584. return false;
  100585. }
  100586. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100587. return false; /* read_callback_ sets the state for us */
  100588. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100589. }
  100590. else
  100591. obj->comments[i].entry = 0;
  100592. }
  100593. }
  100594. else {
  100595. obj->comments = 0;
  100596. }
  100597. return true;
  100598. }
  100599. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100600. {
  100601. FLAC__uint32 i, j, x;
  100602. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100603. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100604. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100605. 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))
  100606. return false; /* read_callback_ sets the state for us */
  100607. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100608. return false; /* read_callback_ sets the state for us */
  100609. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100610. return false; /* read_callback_ sets the state for us */
  100611. obj->is_cd = x? true : false;
  100612. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100613. return false; /* read_callback_ sets the state for us */
  100614. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100615. return false; /* read_callback_ sets the state for us */
  100616. obj->num_tracks = x;
  100617. if(obj->num_tracks > 0) {
  100618. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100619. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100620. return false;
  100621. }
  100622. for(i = 0; i < obj->num_tracks; i++) {
  100623. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100624. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100625. return false; /* read_callback_ sets the state for us */
  100626. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100627. return false; /* read_callback_ sets the state for us */
  100628. track->number = (FLAC__byte)x;
  100629. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100630. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100631. return false; /* read_callback_ sets the state for us */
  100632. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100633. return false; /* read_callback_ sets the state for us */
  100634. track->type = x;
  100635. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100636. return false; /* read_callback_ sets the state for us */
  100637. track->pre_emphasis = x;
  100638. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100639. return false; /* read_callback_ sets the state for us */
  100640. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100641. return false; /* read_callback_ sets the state for us */
  100642. track->num_indices = (FLAC__byte)x;
  100643. if(track->num_indices > 0) {
  100644. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100645. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100646. return false;
  100647. }
  100648. for(j = 0; j < track->num_indices; j++) {
  100649. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100650. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100651. return false; /* read_callback_ sets the state for us */
  100652. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100653. return false; /* read_callback_ sets the state for us */
  100654. index->number = (FLAC__byte)x;
  100655. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100656. return false; /* read_callback_ sets the state for us */
  100657. }
  100658. }
  100659. }
  100660. }
  100661. return true;
  100662. }
  100663. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100664. {
  100665. FLAC__uint32 x;
  100666. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100667. /* read type */
  100668. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100669. return false; /* read_callback_ sets the state for us */
  100670. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100671. /* read MIME type */
  100672. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100673. return false; /* read_callback_ sets the state for us */
  100674. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100675. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100676. return false;
  100677. }
  100678. if(x > 0) {
  100679. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100680. return false; /* read_callback_ sets the state for us */
  100681. }
  100682. obj->mime_type[x] = '\0';
  100683. /* read description */
  100684. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100685. return false; /* read_callback_ sets the state for us */
  100686. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100687. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100688. return false;
  100689. }
  100690. if(x > 0) {
  100691. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100692. return false; /* read_callback_ sets the state for us */
  100693. }
  100694. obj->description[x] = '\0';
  100695. /* read width */
  100696. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100697. return false; /* read_callback_ sets the state for us */
  100698. /* read height */
  100699. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100700. return false; /* read_callback_ sets the state for us */
  100701. /* read depth */
  100702. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100703. return false; /* read_callback_ sets the state for us */
  100704. /* read colors */
  100705. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100706. return false; /* read_callback_ sets the state for us */
  100707. /* read data */
  100708. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100709. return false; /* read_callback_ sets the state for us */
  100710. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100711. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100712. return false;
  100713. }
  100714. if(obj->data_length > 0) {
  100715. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100716. return false; /* read_callback_ sets the state for us */
  100717. }
  100718. return true;
  100719. }
  100720. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100721. {
  100722. FLAC__uint32 x;
  100723. unsigned i, skip;
  100724. /* skip the version and flags bytes */
  100725. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100726. return false; /* read_callback_ sets the state for us */
  100727. /* get the size (in bytes) to skip */
  100728. skip = 0;
  100729. for(i = 0; i < 4; i++) {
  100730. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100731. return false; /* read_callback_ sets the state for us */
  100732. skip <<= 7;
  100733. skip |= (x & 0x7f);
  100734. }
  100735. /* skip the rest of the tag */
  100736. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100737. return false; /* read_callback_ sets the state for us */
  100738. return true;
  100739. }
  100740. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100741. {
  100742. FLAC__uint32 x;
  100743. FLAC__bool first = true;
  100744. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100745. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100746. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100747. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100748. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100749. return true;
  100750. }
  100751. }
  100752. /* make sure we're byte aligned */
  100753. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100754. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100755. return false; /* read_callback_ sets the state for us */
  100756. }
  100757. while(1) {
  100758. if(decoder->private_->cached) {
  100759. x = (FLAC__uint32)decoder->private_->lookahead;
  100760. decoder->private_->cached = false;
  100761. }
  100762. else {
  100763. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100764. return false; /* read_callback_ sets the state for us */
  100765. }
  100766. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100767. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100768. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100769. return false; /* read_callback_ sets the state for us */
  100770. /* 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 */
  100771. /* else we have to check if the second byte is the end of a sync code */
  100772. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100773. decoder->private_->lookahead = (FLAC__byte)x;
  100774. decoder->private_->cached = true;
  100775. }
  100776. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100777. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100778. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100779. return true;
  100780. }
  100781. }
  100782. if(first) {
  100783. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100784. first = false;
  100785. }
  100786. }
  100787. return true;
  100788. }
  100789. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100790. {
  100791. unsigned channel;
  100792. unsigned i;
  100793. FLAC__int32 mid, side;
  100794. unsigned frame_crc; /* the one we calculate from the input stream */
  100795. FLAC__uint32 x;
  100796. *got_a_frame = false;
  100797. /* init the CRC */
  100798. frame_crc = 0;
  100799. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100800. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100801. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100802. if(!read_frame_header_(decoder))
  100803. return false;
  100804. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100805. return true;
  100806. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100807. return false;
  100808. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100809. /*
  100810. * first figure the correct bits-per-sample of the subframe
  100811. */
  100812. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100813. switch(decoder->private_->frame.header.channel_assignment) {
  100814. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100815. /* no adjustment needed */
  100816. break;
  100817. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100818. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100819. if(channel == 1)
  100820. bps++;
  100821. break;
  100822. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100823. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100824. if(channel == 0)
  100825. bps++;
  100826. break;
  100827. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100828. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100829. if(channel == 1)
  100830. bps++;
  100831. break;
  100832. default:
  100833. FLAC__ASSERT(0);
  100834. }
  100835. /*
  100836. * now read it
  100837. */
  100838. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100839. return false;
  100840. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100841. return true;
  100842. }
  100843. if(!read_zero_padding_(decoder))
  100844. return false;
  100845. 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) */
  100846. return true;
  100847. /*
  100848. * Read the frame CRC-16 from the footer and check
  100849. */
  100850. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100851. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100852. return false; /* read_callback_ sets the state for us */
  100853. if(frame_crc == x) {
  100854. if(do_full_decode) {
  100855. /* Undo any special channel coding */
  100856. switch(decoder->private_->frame.header.channel_assignment) {
  100857. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100858. /* do nothing */
  100859. break;
  100860. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100861. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100862. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100863. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100864. break;
  100865. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100866. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100867. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100868. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100869. break;
  100870. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100871. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100872. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100873. #if 1
  100874. mid = decoder->private_->output[0][i];
  100875. side = decoder->private_->output[1][i];
  100876. mid <<= 1;
  100877. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100878. decoder->private_->output[0][i] = (mid + side) >> 1;
  100879. decoder->private_->output[1][i] = (mid - side) >> 1;
  100880. #else
  100881. /* OPT: without 'side' temp variable */
  100882. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100883. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100884. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100885. #endif
  100886. }
  100887. break;
  100888. default:
  100889. FLAC__ASSERT(0);
  100890. break;
  100891. }
  100892. }
  100893. }
  100894. else {
  100895. /* Bad frame, emit error and zero the output signal */
  100896. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100897. if(do_full_decode) {
  100898. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100899. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100900. }
  100901. }
  100902. }
  100903. *got_a_frame = true;
  100904. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100905. if(decoder->private_->next_fixed_block_size)
  100906. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100907. /* put the latest values into the public section of the decoder instance */
  100908. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100909. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100910. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100911. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100912. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100913. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100914. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100915. /* write it */
  100916. if(do_full_decode) {
  100917. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100918. return false;
  100919. }
  100920. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100921. return true;
  100922. }
  100923. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100924. {
  100925. FLAC__uint32 x;
  100926. FLAC__uint64 xx;
  100927. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100928. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100929. unsigned raw_header_len;
  100930. FLAC__bool is_unparseable = false;
  100931. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100932. /* init the raw header with the saved bits from synchronization */
  100933. raw_header[0] = decoder->private_->header_warmup[0];
  100934. raw_header[1] = decoder->private_->header_warmup[1];
  100935. raw_header_len = 2;
  100936. /* check to make sure that reserved bit is 0 */
  100937. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100938. is_unparseable = true;
  100939. /*
  100940. * Note that along the way as we read the header, we look for a sync
  100941. * code inside. If we find one it would indicate that our original
  100942. * sync was bad since there cannot be a sync code in a valid header.
  100943. *
  100944. * Three kinds of things can go wrong when reading the frame header:
  100945. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100946. * If we don't find a sync code, it can end up looking like we read
  100947. * a valid but unparseable header, until getting to the frame header
  100948. * CRC. Even then we could get a false positive on the CRC.
  100949. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100950. * future encoder).
  100951. * 3) We may be on a damaged frame which appears valid but unparseable.
  100952. *
  100953. * For all these reasons, we try and read a complete frame header as
  100954. * long as it seems valid, even if unparseable, up until the frame
  100955. * header CRC.
  100956. */
  100957. /*
  100958. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100959. */
  100960. for(i = 0; i < 2; i++) {
  100961. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100962. return false; /* read_callback_ sets the state for us */
  100963. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100964. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100965. decoder->private_->lookahead = (FLAC__byte)x;
  100966. decoder->private_->cached = true;
  100967. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100968. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100969. return true;
  100970. }
  100971. raw_header[raw_header_len++] = (FLAC__byte)x;
  100972. }
  100973. switch(x = raw_header[2] >> 4) {
  100974. case 0:
  100975. is_unparseable = true;
  100976. break;
  100977. case 1:
  100978. decoder->private_->frame.header.blocksize = 192;
  100979. break;
  100980. case 2:
  100981. case 3:
  100982. case 4:
  100983. case 5:
  100984. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100985. break;
  100986. case 6:
  100987. case 7:
  100988. blocksize_hint = x;
  100989. break;
  100990. case 8:
  100991. case 9:
  100992. case 10:
  100993. case 11:
  100994. case 12:
  100995. case 13:
  100996. case 14:
  100997. case 15:
  100998. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100999. break;
  101000. default:
  101001. FLAC__ASSERT(0);
  101002. break;
  101003. }
  101004. switch(x = raw_header[2] & 0x0f) {
  101005. case 0:
  101006. if(decoder->private_->has_stream_info)
  101007. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  101008. else
  101009. is_unparseable = true;
  101010. break;
  101011. case 1:
  101012. decoder->private_->frame.header.sample_rate = 88200;
  101013. break;
  101014. case 2:
  101015. decoder->private_->frame.header.sample_rate = 176400;
  101016. break;
  101017. case 3:
  101018. decoder->private_->frame.header.sample_rate = 192000;
  101019. break;
  101020. case 4:
  101021. decoder->private_->frame.header.sample_rate = 8000;
  101022. break;
  101023. case 5:
  101024. decoder->private_->frame.header.sample_rate = 16000;
  101025. break;
  101026. case 6:
  101027. decoder->private_->frame.header.sample_rate = 22050;
  101028. break;
  101029. case 7:
  101030. decoder->private_->frame.header.sample_rate = 24000;
  101031. break;
  101032. case 8:
  101033. decoder->private_->frame.header.sample_rate = 32000;
  101034. break;
  101035. case 9:
  101036. decoder->private_->frame.header.sample_rate = 44100;
  101037. break;
  101038. case 10:
  101039. decoder->private_->frame.header.sample_rate = 48000;
  101040. break;
  101041. case 11:
  101042. decoder->private_->frame.header.sample_rate = 96000;
  101043. break;
  101044. case 12:
  101045. case 13:
  101046. case 14:
  101047. sample_rate_hint = x;
  101048. break;
  101049. case 15:
  101050. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101051. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101052. return true;
  101053. default:
  101054. FLAC__ASSERT(0);
  101055. }
  101056. x = (unsigned)(raw_header[3] >> 4);
  101057. if(x & 8) {
  101058. decoder->private_->frame.header.channels = 2;
  101059. switch(x & 7) {
  101060. case 0:
  101061. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  101062. break;
  101063. case 1:
  101064. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  101065. break;
  101066. case 2:
  101067. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  101068. break;
  101069. default:
  101070. is_unparseable = true;
  101071. break;
  101072. }
  101073. }
  101074. else {
  101075. decoder->private_->frame.header.channels = (unsigned)x + 1;
  101076. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101077. }
  101078. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  101079. case 0:
  101080. if(decoder->private_->has_stream_info)
  101081. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101082. else
  101083. is_unparseable = true;
  101084. break;
  101085. case 1:
  101086. decoder->private_->frame.header.bits_per_sample = 8;
  101087. break;
  101088. case 2:
  101089. decoder->private_->frame.header.bits_per_sample = 12;
  101090. break;
  101091. case 4:
  101092. decoder->private_->frame.header.bits_per_sample = 16;
  101093. break;
  101094. case 5:
  101095. decoder->private_->frame.header.bits_per_sample = 20;
  101096. break;
  101097. case 6:
  101098. decoder->private_->frame.header.bits_per_sample = 24;
  101099. break;
  101100. case 3:
  101101. case 7:
  101102. is_unparseable = true;
  101103. break;
  101104. default:
  101105. FLAC__ASSERT(0);
  101106. break;
  101107. }
  101108. /* check to make sure that reserved bit is 0 */
  101109. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101110. is_unparseable = true;
  101111. /* read the frame's starting sample number (or frame number as the case may be) */
  101112. if(
  101113. raw_header[1] & 0x01 ||
  101114. /*@@@ 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 */
  101115. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101116. ) { /* variable blocksize */
  101117. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101118. return false; /* read_callback_ sets the state for us */
  101119. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101120. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101121. decoder->private_->cached = true;
  101122. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101123. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101124. return true;
  101125. }
  101126. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101127. decoder->private_->frame.header.number.sample_number = xx;
  101128. }
  101129. else { /* fixed blocksize */
  101130. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101131. return false; /* read_callback_ sets the state for us */
  101132. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101133. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101134. decoder->private_->cached = true;
  101135. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101136. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101137. return true;
  101138. }
  101139. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101140. decoder->private_->frame.header.number.frame_number = x;
  101141. }
  101142. if(blocksize_hint) {
  101143. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101144. return false; /* read_callback_ sets the state for us */
  101145. raw_header[raw_header_len++] = (FLAC__byte)x;
  101146. if(blocksize_hint == 7) {
  101147. FLAC__uint32 _x;
  101148. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101149. return false; /* read_callback_ sets the state for us */
  101150. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101151. x = (x << 8) | _x;
  101152. }
  101153. decoder->private_->frame.header.blocksize = x+1;
  101154. }
  101155. if(sample_rate_hint) {
  101156. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101157. return false; /* read_callback_ sets the state for us */
  101158. raw_header[raw_header_len++] = (FLAC__byte)x;
  101159. if(sample_rate_hint != 12) {
  101160. FLAC__uint32 _x;
  101161. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101162. return false; /* read_callback_ sets the state for us */
  101163. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101164. x = (x << 8) | _x;
  101165. }
  101166. if(sample_rate_hint == 12)
  101167. decoder->private_->frame.header.sample_rate = x*1000;
  101168. else if(sample_rate_hint == 13)
  101169. decoder->private_->frame.header.sample_rate = x;
  101170. else
  101171. decoder->private_->frame.header.sample_rate = x*10;
  101172. }
  101173. /* read the CRC-8 byte */
  101174. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101175. return false; /* read_callback_ sets the state for us */
  101176. crc8 = (FLAC__byte)x;
  101177. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101178. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101179. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101180. return true;
  101181. }
  101182. /* calculate the sample number from the frame number if needed */
  101183. decoder->private_->next_fixed_block_size = 0;
  101184. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101185. x = decoder->private_->frame.header.number.frame_number;
  101186. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101187. if(decoder->private_->fixed_block_size)
  101188. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101189. else if(decoder->private_->has_stream_info) {
  101190. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101191. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101192. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101193. }
  101194. else
  101195. is_unparseable = true;
  101196. }
  101197. else if(x == 0) {
  101198. decoder->private_->frame.header.number.sample_number = 0;
  101199. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101200. }
  101201. else {
  101202. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101203. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101204. }
  101205. }
  101206. if(is_unparseable) {
  101207. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101208. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101209. return true;
  101210. }
  101211. return true;
  101212. }
  101213. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101214. {
  101215. FLAC__uint32 x;
  101216. FLAC__bool wasted_bits;
  101217. unsigned i;
  101218. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101219. return false; /* read_callback_ sets the state for us */
  101220. wasted_bits = (x & 1);
  101221. x &= 0xfe;
  101222. if(wasted_bits) {
  101223. unsigned u;
  101224. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101225. return false; /* read_callback_ sets the state for us */
  101226. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101227. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101228. }
  101229. else
  101230. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101231. /*
  101232. * Lots of magic numbers here
  101233. */
  101234. if(x & 0x80) {
  101235. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101236. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101237. return true;
  101238. }
  101239. else if(x == 0) {
  101240. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101241. return false;
  101242. }
  101243. else if(x == 2) {
  101244. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101245. return false;
  101246. }
  101247. else if(x < 16) {
  101248. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101249. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101250. return true;
  101251. }
  101252. else if(x <= 24) {
  101253. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101254. return false;
  101255. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101256. return true;
  101257. }
  101258. else if(x < 64) {
  101259. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101260. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101261. return true;
  101262. }
  101263. else {
  101264. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101265. return false;
  101266. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101267. return true;
  101268. }
  101269. if(wasted_bits && do_full_decode) {
  101270. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101271. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101272. decoder->private_->output[channel][i] <<= x;
  101273. }
  101274. return true;
  101275. }
  101276. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101277. {
  101278. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101279. FLAC__int32 x;
  101280. unsigned i;
  101281. FLAC__int32 *output = decoder->private_->output[channel];
  101282. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101283. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101284. return false; /* read_callback_ sets the state for us */
  101285. subframe->value = x;
  101286. /* decode the subframe */
  101287. if(do_full_decode) {
  101288. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101289. output[i] = x;
  101290. }
  101291. return true;
  101292. }
  101293. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101294. {
  101295. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101296. FLAC__int32 i32;
  101297. FLAC__uint32 u32;
  101298. unsigned u;
  101299. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101300. subframe->residual = decoder->private_->residual[channel];
  101301. subframe->order = order;
  101302. /* read warm-up samples */
  101303. for(u = 0; u < order; u++) {
  101304. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101305. return false; /* read_callback_ sets the state for us */
  101306. subframe->warmup[u] = i32;
  101307. }
  101308. /* read entropy coding method info */
  101309. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101310. return false; /* read_callback_ sets the state for us */
  101311. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101312. switch(subframe->entropy_coding_method.type) {
  101313. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101314. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101315. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101316. return false; /* read_callback_ sets the state for us */
  101317. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101318. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101319. break;
  101320. default:
  101321. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101322. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101323. return true;
  101324. }
  101325. /* read residual */
  101326. switch(subframe->entropy_coding_method.type) {
  101327. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101328. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101329. 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))
  101330. return false;
  101331. break;
  101332. default:
  101333. FLAC__ASSERT(0);
  101334. }
  101335. /* decode the subframe */
  101336. if(do_full_decode) {
  101337. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101338. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101339. }
  101340. return true;
  101341. }
  101342. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101343. {
  101344. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101345. FLAC__int32 i32;
  101346. FLAC__uint32 u32;
  101347. unsigned u;
  101348. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101349. subframe->residual = decoder->private_->residual[channel];
  101350. subframe->order = order;
  101351. /* read warm-up samples */
  101352. for(u = 0; u < order; u++) {
  101353. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101354. return false; /* read_callback_ sets the state for us */
  101355. subframe->warmup[u] = i32;
  101356. }
  101357. /* read qlp coeff precision */
  101358. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101359. return false; /* read_callback_ sets the state for us */
  101360. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101361. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101362. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101363. return true;
  101364. }
  101365. subframe->qlp_coeff_precision = u32+1;
  101366. /* read qlp shift */
  101367. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101368. return false; /* read_callback_ sets the state for us */
  101369. subframe->quantization_level = i32;
  101370. /* read quantized lp coefficiencts */
  101371. for(u = 0; u < order; u++) {
  101372. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101373. return false; /* read_callback_ sets the state for us */
  101374. subframe->qlp_coeff[u] = i32;
  101375. }
  101376. /* read entropy coding method info */
  101377. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101378. return false; /* read_callback_ sets the state for us */
  101379. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101380. switch(subframe->entropy_coding_method.type) {
  101381. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101382. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101383. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101384. return false; /* read_callback_ sets the state for us */
  101385. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101386. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101387. break;
  101388. default:
  101389. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101390. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101391. return true;
  101392. }
  101393. /* read residual */
  101394. switch(subframe->entropy_coding_method.type) {
  101395. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101396. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101397. 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))
  101398. return false;
  101399. break;
  101400. default:
  101401. FLAC__ASSERT(0);
  101402. }
  101403. /* decode the subframe */
  101404. if(do_full_decode) {
  101405. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101406. /*@@@@@@ technically not pessimistic enough, should be more like
  101407. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101408. */
  101409. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101410. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101411. if(order <= 8)
  101412. 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);
  101413. else
  101414. 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);
  101415. }
  101416. else
  101417. 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);
  101418. else
  101419. 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);
  101420. }
  101421. return true;
  101422. }
  101423. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101424. {
  101425. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101426. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101427. unsigned i;
  101428. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101429. subframe->data = residual;
  101430. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101431. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101432. return false; /* read_callback_ sets the state for us */
  101433. residual[i] = x;
  101434. }
  101435. /* decode the subframe */
  101436. if(do_full_decode)
  101437. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101438. return true;
  101439. }
  101440. 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)
  101441. {
  101442. FLAC__uint32 rice_parameter;
  101443. int i;
  101444. unsigned partition, sample, u;
  101445. const unsigned partitions = 1u << partition_order;
  101446. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101447. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101448. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101449. /* sanity checks */
  101450. if(partition_order == 0) {
  101451. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101452. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101453. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101454. return true;
  101455. }
  101456. }
  101457. else {
  101458. if(partition_samples < predictor_order) {
  101459. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101460. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101461. return true;
  101462. }
  101463. }
  101464. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101465. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101466. return false;
  101467. }
  101468. sample = 0;
  101469. for(partition = 0; partition < partitions; partition++) {
  101470. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101471. return false; /* read_callback_ sets the state for us */
  101472. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101473. if(rice_parameter < pesc) {
  101474. partitioned_rice_contents->raw_bits[partition] = 0;
  101475. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101476. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101477. return false; /* read_callback_ sets the state for us */
  101478. sample += u;
  101479. }
  101480. else {
  101481. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101482. return false; /* read_callback_ sets the state for us */
  101483. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101484. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101485. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101486. return false; /* read_callback_ sets the state for us */
  101487. residual[sample] = i;
  101488. }
  101489. }
  101490. }
  101491. return true;
  101492. }
  101493. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101494. {
  101495. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101496. FLAC__uint32 zero = 0;
  101497. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101498. return false; /* read_callback_ sets the state for us */
  101499. if(zero != 0) {
  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. }
  101503. }
  101504. return true;
  101505. }
  101506. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101507. {
  101508. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101509. if(
  101510. #if FLAC__HAS_OGG
  101511. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101512. !decoder->private_->is_ogg &&
  101513. #endif
  101514. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101515. ) {
  101516. *bytes = 0;
  101517. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101518. return false;
  101519. }
  101520. else if(*bytes > 0) {
  101521. /* While seeking, it is possible for our seek to land in the
  101522. * middle of audio data that looks exactly like a frame header
  101523. * from a future version of an encoder. When that happens, our
  101524. * error callback will get an
  101525. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101526. * unparseable_frame_count. But there is a remote possibility
  101527. * that it is properly synced at such a "future-codec frame",
  101528. * so to make sure, we wait to see many "unparseable" errors in
  101529. * a row before bailing out.
  101530. */
  101531. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101532. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101533. return false;
  101534. }
  101535. else {
  101536. const FLAC__StreamDecoderReadStatus status =
  101537. #if FLAC__HAS_OGG
  101538. decoder->private_->is_ogg?
  101539. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101540. #endif
  101541. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101542. ;
  101543. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101544. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101545. return false;
  101546. }
  101547. else if(*bytes == 0) {
  101548. if(
  101549. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101550. (
  101551. #if FLAC__HAS_OGG
  101552. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101553. !decoder->private_->is_ogg &&
  101554. #endif
  101555. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101556. )
  101557. ) {
  101558. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101559. return false;
  101560. }
  101561. else
  101562. return true;
  101563. }
  101564. else
  101565. return true;
  101566. }
  101567. }
  101568. else {
  101569. /* abort to avoid a deadlock */
  101570. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101571. return false;
  101572. }
  101573. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101574. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101575. * and at the same time hit the end of the stream (for example, seeking
  101576. * to a point that is after the beginning of the last Ogg page). There
  101577. * is no way to report an Ogg sync loss through the callbacks (see note
  101578. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101579. * So to keep the decoder from stopping at this point we gate the call
  101580. * to the eof_callback and let the Ogg decoder aspect set the
  101581. * end-of-stream state when it is needed.
  101582. */
  101583. }
  101584. #if FLAC__HAS_OGG
  101585. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101586. {
  101587. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101588. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101589. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101590. /* we don't really have a way to handle lost sync via read
  101591. * callback so we'll let it pass and let the underlying
  101592. * FLAC decoder catch the error
  101593. */
  101594. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101595. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101596. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101597. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101598. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101599. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101600. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101601. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101602. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101603. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101604. default:
  101605. FLAC__ASSERT(0);
  101606. /* double protection */
  101607. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101608. }
  101609. }
  101610. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101611. {
  101612. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101613. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101614. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101615. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101616. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101617. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101618. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101619. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101620. default:
  101621. /* double protection: */
  101622. FLAC__ASSERT(0);
  101623. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101624. }
  101625. }
  101626. #endif
  101627. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101628. {
  101629. if(decoder->private_->is_seeking) {
  101630. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101631. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101632. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101633. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101634. #if FLAC__HAS_OGG
  101635. decoder->private_->got_a_frame = true;
  101636. #endif
  101637. decoder->private_->last_frame = *frame; /* save the frame */
  101638. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101639. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101640. /* kick out of seek mode */
  101641. decoder->private_->is_seeking = false;
  101642. /* shift out the samples before target_sample */
  101643. if(delta > 0) {
  101644. unsigned channel;
  101645. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101646. for(channel = 0; channel < frame->header.channels; channel++)
  101647. newbuffer[channel] = buffer[channel] + delta;
  101648. decoder->private_->last_frame.header.blocksize -= delta;
  101649. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101650. /* write the relevant samples */
  101651. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101652. }
  101653. else {
  101654. /* write the relevant samples */
  101655. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101656. }
  101657. }
  101658. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101659. }
  101660. /*
  101661. * If we never got STREAMINFO, turn off MD5 checking to save
  101662. * cycles since we don't have a sum to compare to anyway
  101663. */
  101664. if(!decoder->private_->has_stream_info)
  101665. decoder->private_->do_md5_checking = false;
  101666. if(decoder->private_->do_md5_checking) {
  101667. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101668. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101669. }
  101670. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101671. }
  101672. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101673. {
  101674. if(!decoder->private_->is_seeking)
  101675. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101676. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101677. decoder->private_->unparseable_frame_count++;
  101678. }
  101679. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101680. {
  101681. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101682. FLAC__int64 pos = -1;
  101683. int i;
  101684. unsigned approx_bytes_per_frame;
  101685. FLAC__bool first_seek = true;
  101686. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101687. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101688. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101689. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101690. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101691. /* take these from the current frame in case they've changed mid-stream */
  101692. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101693. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101694. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101695. /* use values from stream info if we didn't decode a frame */
  101696. if(channels == 0)
  101697. channels = decoder->private_->stream_info.data.stream_info.channels;
  101698. if(bps == 0)
  101699. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101700. /* we are just guessing here */
  101701. if(max_framesize > 0)
  101702. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101703. /*
  101704. * Check if it's a known fixed-blocksize stream. Note that though
  101705. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101706. * never get a STREAMINFO block when decoding so the value of
  101707. * min_blocksize might be zero.
  101708. */
  101709. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101710. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101711. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101712. }
  101713. else
  101714. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101715. /*
  101716. * First, we set an upper and lower bound on where in the
  101717. * stream we will search. For now we assume the worst case
  101718. * scenario, which is our best guess at the beginning of
  101719. * the first frame and end of the stream.
  101720. */
  101721. lower_bound = first_frame_offset;
  101722. lower_bound_sample = 0;
  101723. upper_bound = stream_length;
  101724. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101725. /*
  101726. * Now we refine the bounds if we have a seektable with
  101727. * suitable points. Note that according to the spec they
  101728. * must be ordered by ascending sample number.
  101729. *
  101730. * Note: to protect against invalid seek tables we will ignore points
  101731. * that have frame_samples==0 or sample_number>=total_samples
  101732. */
  101733. if(seek_table) {
  101734. FLAC__uint64 new_lower_bound = lower_bound;
  101735. FLAC__uint64 new_upper_bound = upper_bound;
  101736. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101737. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101738. /* find the closest seek point <= target_sample, if it exists */
  101739. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101740. if(
  101741. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101742. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101743. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101744. seek_table->points[i].sample_number <= target_sample
  101745. )
  101746. break;
  101747. }
  101748. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101749. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101750. new_lower_bound_sample = seek_table->points[i].sample_number;
  101751. }
  101752. /* find the closest seek point > target_sample, if it exists */
  101753. for(i = 0; i < (int)seek_table->num_points; i++) {
  101754. if(
  101755. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101756. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101757. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101758. seek_table->points[i].sample_number > target_sample
  101759. )
  101760. break;
  101761. }
  101762. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101763. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101764. new_upper_bound_sample = seek_table->points[i].sample_number;
  101765. }
  101766. /* final protection against unsorted seek tables; keep original values if bogus */
  101767. if(new_upper_bound >= new_lower_bound) {
  101768. lower_bound = new_lower_bound;
  101769. upper_bound = new_upper_bound;
  101770. lower_bound_sample = new_lower_bound_sample;
  101771. upper_bound_sample = new_upper_bound_sample;
  101772. }
  101773. }
  101774. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101775. /* there are 2 insidious ways that the following equality occurs, which
  101776. * we need to fix:
  101777. * 1) total_samples is 0 (unknown) and target_sample is 0
  101778. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101779. * exactly equal to the last seek point in the seek table; this
  101780. * means there is no seek point above it, and upper_bound_samples
  101781. * remains equal to the estimate (of target_samples) we made above
  101782. * in either case it does not hurt to move upper_bound_sample up by 1
  101783. */
  101784. if(upper_bound_sample == lower_bound_sample)
  101785. upper_bound_sample++;
  101786. decoder->private_->target_sample = target_sample;
  101787. while(1) {
  101788. /* check if the bounds are still ok */
  101789. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101790. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101791. return false;
  101792. }
  101793. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101794. #if defined _MSC_VER || defined __MINGW32__
  101795. /* with VC++ you have to spoon feed it the casting */
  101796. 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;
  101797. #else
  101798. 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;
  101799. #endif
  101800. #else
  101801. /* a little less accurate: */
  101802. if(upper_bound - lower_bound < 0xffffffff)
  101803. 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;
  101804. else /* @@@ WATCHOUT, ~2TB limit */
  101805. 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;
  101806. #endif
  101807. if(pos >= (FLAC__int64)upper_bound)
  101808. pos = (FLAC__int64)upper_bound - 1;
  101809. if(pos < (FLAC__int64)lower_bound)
  101810. pos = (FLAC__int64)lower_bound;
  101811. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101812. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101813. return false;
  101814. }
  101815. if(!FLAC__stream_decoder_flush(decoder)) {
  101816. /* above call sets the state for us */
  101817. return false;
  101818. }
  101819. /* Now we need to get a frame. First we need to reset our
  101820. * unparseable_frame_count; if we get too many unparseable
  101821. * frames in a row, the read callback will return
  101822. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101823. * FLAC__stream_decoder_process_single() to return false.
  101824. */
  101825. decoder->private_->unparseable_frame_count = 0;
  101826. if(!FLAC__stream_decoder_process_single(decoder)) {
  101827. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101828. return false;
  101829. }
  101830. /* our write callback will change the state when it gets to the target frame */
  101831. /* 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 */
  101832. #if 0
  101833. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101834. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101835. break;
  101836. #endif
  101837. if(!decoder->private_->is_seeking)
  101838. break;
  101839. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101840. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101841. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101842. if (pos == (FLAC__int64)lower_bound) {
  101843. /* can't move back any more than the first frame, something is fatally wrong */
  101844. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101845. return false;
  101846. }
  101847. /* our last move backwards wasn't big enough, try again */
  101848. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101849. continue;
  101850. }
  101851. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101852. first_seek = false;
  101853. /* make sure we are not seeking in corrupted stream */
  101854. if (this_frame_sample < lower_bound_sample) {
  101855. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101856. return false;
  101857. }
  101858. /* we need to narrow the search */
  101859. if(target_sample < this_frame_sample) {
  101860. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101861. /*@@@@@@ what will decode position be if at end of stream? */
  101862. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101863. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101864. return false;
  101865. }
  101866. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101867. }
  101868. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101869. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101870. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101871. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101872. return false;
  101873. }
  101874. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101875. }
  101876. }
  101877. return true;
  101878. }
  101879. #if FLAC__HAS_OGG
  101880. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101881. {
  101882. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101883. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101884. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101885. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101886. FLAC__bool did_a_seek;
  101887. unsigned iteration = 0;
  101888. /* In the first iterations, we will calculate the target byte position
  101889. * by the distance from the target sample to left_sample and
  101890. * right_sample (let's call it "proportional search"). After that, we
  101891. * will switch to binary search.
  101892. */
  101893. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101894. /* We will switch to a linear search once our current sample is less
  101895. * than this number of samples ahead of the target sample
  101896. */
  101897. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101898. /* If the total number of samples is unknown, use a large value, and
  101899. * force binary search immediately.
  101900. */
  101901. if(right_sample == 0) {
  101902. right_sample = (FLAC__uint64)(-1);
  101903. BINARY_SEARCH_AFTER_ITERATION = 0;
  101904. }
  101905. decoder->private_->target_sample = target_sample;
  101906. for( ; ; iteration++) {
  101907. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101908. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101909. pos = (right_pos + left_pos) / 2;
  101910. }
  101911. else {
  101912. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101913. #if defined _MSC_VER || defined __MINGW32__
  101914. /* with MSVC you have to spoon feed it the casting */
  101915. 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));
  101916. #else
  101917. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101918. #endif
  101919. #else
  101920. /* a little less accurate: */
  101921. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101922. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101923. else /* @@@ WATCHOUT, ~2TB limit */
  101924. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101925. #endif
  101926. /* @@@ TODO: might want to limit pos to some distance
  101927. * before EOF, to make sure we land before the last frame,
  101928. * thereby getting a this_frame_sample and so having a better
  101929. * estimate.
  101930. */
  101931. }
  101932. /* physical seek */
  101933. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101934. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101935. return false;
  101936. }
  101937. if(!FLAC__stream_decoder_flush(decoder)) {
  101938. /* above call sets the state for us */
  101939. return false;
  101940. }
  101941. did_a_seek = true;
  101942. }
  101943. else
  101944. did_a_seek = false;
  101945. decoder->private_->got_a_frame = false;
  101946. if(!FLAC__stream_decoder_process_single(decoder)) {
  101947. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101948. return false;
  101949. }
  101950. if(!decoder->private_->got_a_frame) {
  101951. if(did_a_seek) {
  101952. /* this can happen if we seek to a point after the last frame; we drop
  101953. * to binary search right away in this case to avoid any wasted
  101954. * iterations of proportional search.
  101955. */
  101956. right_pos = pos;
  101957. BINARY_SEARCH_AFTER_ITERATION = 0;
  101958. }
  101959. else {
  101960. /* this can probably only happen if total_samples is unknown and the
  101961. * target_sample is past the end of the stream
  101962. */
  101963. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101964. return false;
  101965. }
  101966. }
  101967. /* our write callback will change the state when it gets to the target frame */
  101968. else if(!decoder->private_->is_seeking) {
  101969. break;
  101970. }
  101971. else {
  101972. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101973. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101974. if (did_a_seek) {
  101975. if (this_frame_sample <= target_sample) {
  101976. /* The 'equal' case should not happen, since
  101977. * FLAC__stream_decoder_process_single()
  101978. * should recognize that it has hit the
  101979. * target sample and we would exit through
  101980. * the 'break' above.
  101981. */
  101982. FLAC__ASSERT(this_frame_sample != target_sample);
  101983. left_sample = this_frame_sample;
  101984. /* sanity check to avoid infinite loop */
  101985. if (left_pos == pos) {
  101986. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101987. return false;
  101988. }
  101989. left_pos = pos;
  101990. }
  101991. else if(this_frame_sample > target_sample) {
  101992. right_sample = this_frame_sample;
  101993. /* sanity check to avoid infinite loop */
  101994. if (right_pos == pos) {
  101995. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101996. return false;
  101997. }
  101998. right_pos = pos;
  101999. }
  102000. }
  102001. }
  102002. }
  102003. return true;
  102004. }
  102005. #endif
  102006. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102007. {
  102008. (void)client_data;
  102009. if(*bytes > 0) {
  102010. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  102011. if(ferror(decoder->private_->file))
  102012. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102013. else if(*bytes == 0)
  102014. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  102015. else
  102016. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102017. }
  102018. else
  102019. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  102020. }
  102021. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102022. {
  102023. (void)client_data;
  102024. if(decoder->private_->file == stdin)
  102025. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  102026. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102027. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  102028. else
  102029. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102030. }
  102031. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102032. {
  102033. off_t pos;
  102034. (void)client_data;
  102035. if(decoder->private_->file == stdin)
  102036. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  102037. else if((pos = ftello(decoder->private_->file)) < 0)
  102038. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  102039. else {
  102040. *absolute_byte_offset = (FLAC__uint64)pos;
  102041. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102042. }
  102043. }
  102044. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  102045. {
  102046. struct stat filestats;
  102047. (void)client_data;
  102048. if(decoder->private_->file == stdin)
  102049. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  102050. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  102051. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  102052. else {
  102053. *stream_length = (FLAC__uint64)filestats.st_size;
  102054. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102055. }
  102056. }
  102057. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  102058. {
  102059. (void)client_data;
  102060. return feof(decoder->private_->file)? true : false;
  102061. }
  102062. #endif
  102063. /*** End of inlined file: stream_decoder.c ***/
  102064. /*** Start of inlined file: stream_encoder.c ***/
  102065. /*** Start of inlined file: juce_FlacHeader.h ***/
  102066. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102067. // tasks..
  102068. #define VERSION "1.2.1"
  102069. #define FLAC__NO_DLL 1
  102070. #if JUCE_MSVC
  102071. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102072. #endif
  102073. #if JUCE_MAC
  102074. #define FLAC__SYS_DARWIN 1
  102075. #endif
  102076. /*** End of inlined file: juce_FlacHeader.h ***/
  102077. #if JUCE_USE_FLAC
  102078. #if HAVE_CONFIG_H
  102079. # include <config.h>
  102080. #endif
  102081. #if defined _MSC_VER || defined __MINGW32__
  102082. #include <io.h> /* for _setmode() */
  102083. #include <fcntl.h> /* for _O_BINARY */
  102084. #endif
  102085. #if defined __CYGWIN__ || defined __EMX__
  102086. #include <io.h> /* for setmode(), O_BINARY */
  102087. #include <fcntl.h> /* for _O_BINARY */
  102088. #endif
  102089. #include <limits.h>
  102090. #include <stdio.h>
  102091. #include <stdlib.h> /* for malloc() */
  102092. #include <string.h> /* for memcpy() */
  102093. #include <sys/types.h> /* for off_t */
  102094. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102095. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102096. #define fseeko fseek
  102097. #define ftello ftell
  102098. #endif
  102099. #endif
  102100. /*** Start of inlined file: stream_encoder.h ***/
  102101. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102102. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102103. #if FLAC__HAS_OGG
  102104. #include "private/ogg_encoder_aspect.h"
  102105. #endif
  102106. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102107. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102108. typedef enum {
  102109. FLAC__APODIZATION_BARTLETT,
  102110. FLAC__APODIZATION_BARTLETT_HANN,
  102111. FLAC__APODIZATION_BLACKMAN,
  102112. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102113. FLAC__APODIZATION_CONNES,
  102114. FLAC__APODIZATION_FLATTOP,
  102115. FLAC__APODIZATION_GAUSS,
  102116. FLAC__APODIZATION_HAMMING,
  102117. FLAC__APODIZATION_HANN,
  102118. FLAC__APODIZATION_KAISER_BESSEL,
  102119. FLAC__APODIZATION_NUTTALL,
  102120. FLAC__APODIZATION_RECTANGLE,
  102121. FLAC__APODIZATION_TRIANGLE,
  102122. FLAC__APODIZATION_TUKEY,
  102123. FLAC__APODIZATION_WELCH
  102124. } FLAC__ApodizationFunction;
  102125. typedef struct {
  102126. FLAC__ApodizationFunction type;
  102127. union {
  102128. struct {
  102129. FLAC__real stddev;
  102130. } gauss;
  102131. struct {
  102132. FLAC__real p;
  102133. } tukey;
  102134. } parameters;
  102135. } FLAC__ApodizationSpecification;
  102136. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102137. typedef struct FLAC__StreamEncoderProtected {
  102138. FLAC__StreamEncoderState state;
  102139. FLAC__bool verify;
  102140. FLAC__bool streamable_subset;
  102141. FLAC__bool do_md5;
  102142. FLAC__bool do_mid_side_stereo;
  102143. FLAC__bool loose_mid_side_stereo;
  102144. unsigned channels;
  102145. unsigned bits_per_sample;
  102146. unsigned sample_rate;
  102147. unsigned blocksize;
  102148. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102149. unsigned num_apodizations;
  102150. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102151. #endif
  102152. unsigned max_lpc_order;
  102153. unsigned qlp_coeff_precision;
  102154. FLAC__bool do_qlp_coeff_prec_search;
  102155. FLAC__bool do_exhaustive_model_search;
  102156. FLAC__bool do_escape_coding;
  102157. unsigned min_residual_partition_order;
  102158. unsigned max_residual_partition_order;
  102159. unsigned rice_parameter_search_dist;
  102160. FLAC__uint64 total_samples_estimate;
  102161. FLAC__StreamMetadata **metadata;
  102162. unsigned num_metadata_blocks;
  102163. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102164. #if FLAC__HAS_OGG
  102165. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102166. #endif
  102167. } FLAC__StreamEncoderProtected;
  102168. #endif
  102169. /*** End of inlined file: stream_encoder.h ***/
  102170. #if FLAC__HAS_OGG
  102171. #include "include/private/ogg_helper.h"
  102172. #include "include/private/ogg_mapping.h"
  102173. #endif
  102174. /*** Start of inlined file: stream_encoder_framing.h ***/
  102175. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102176. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102177. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102178. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102179. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102180. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102181. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102182. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102183. #endif
  102184. /*** End of inlined file: stream_encoder_framing.h ***/
  102185. /*** Start of inlined file: window.h ***/
  102186. #ifndef FLAC__PRIVATE__WINDOW_H
  102187. #define FLAC__PRIVATE__WINDOW_H
  102188. #ifdef HAVE_CONFIG_H
  102189. #include <config.h>
  102190. #endif
  102191. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102192. /*
  102193. * FLAC__window_*()
  102194. * --------------------------------------------------------------------
  102195. * Calculates window coefficients according to different apodization
  102196. * functions.
  102197. *
  102198. * OUT window[0,L-1]
  102199. * IN L (number of points in window)
  102200. */
  102201. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102202. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102203. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102204. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102205. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102206. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102207. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102208. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102209. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102210. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102211. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102212. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102213. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102214. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102215. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102216. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102217. #endif
  102218. /*** End of inlined file: window.h ***/
  102219. #ifndef FLaC__INLINE
  102220. #define FLaC__INLINE
  102221. #endif
  102222. #ifdef min
  102223. #undef min
  102224. #endif
  102225. #define min(x,y) ((x)<(y)?(x):(y))
  102226. #ifdef max
  102227. #undef max
  102228. #endif
  102229. #define max(x,y) ((x)>(y)?(x):(y))
  102230. /* Exact Rice codeword length calculation is off by default. The simple
  102231. * (and fast) estimation (of how many bits a residual value will be
  102232. * encoded with) in this encoder is very good, almost always yielding
  102233. * compression within 0.1% of exact calculation.
  102234. */
  102235. #undef EXACT_RICE_BITS_CALCULATION
  102236. /* Rice parameter searching is off by default. The simple (and fast)
  102237. * parameter estimation in this encoder is very good, almost always
  102238. * yielding compression within 0.1% of the optimal parameters.
  102239. */
  102240. #undef ENABLE_RICE_PARAMETER_SEARCH
  102241. typedef struct {
  102242. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102243. unsigned size; /* of each data[] in samples */
  102244. unsigned tail;
  102245. } verify_input_fifo;
  102246. typedef struct {
  102247. const FLAC__byte *data;
  102248. unsigned capacity;
  102249. unsigned bytes;
  102250. } verify_output;
  102251. typedef enum {
  102252. ENCODER_IN_MAGIC = 0,
  102253. ENCODER_IN_METADATA = 1,
  102254. ENCODER_IN_AUDIO = 2
  102255. } EncoderStateHint;
  102256. static struct CompressionLevels {
  102257. FLAC__bool do_mid_side_stereo;
  102258. FLAC__bool loose_mid_side_stereo;
  102259. unsigned max_lpc_order;
  102260. unsigned qlp_coeff_precision;
  102261. FLAC__bool do_qlp_coeff_prec_search;
  102262. FLAC__bool do_escape_coding;
  102263. FLAC__bool do_exhaustive_model_search;
  102264. unsigned min_residual_partition_order;
  102265. unsigned max_residual_partition_order;
  102266. unsigned rice_parameter_search_dist;
  102267. } compression_levels_[] = {
  102268. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102269. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102270. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102271. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102272. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102273. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102274. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102275. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102276. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102277. };
  102278. /***********************************************************************
  102279. *
  102280. * Private class method prototypes
  102281. *
  102282. ***********************************************************************/
  102283. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102284. static void free_(FLAC__StreamEncoder *encoder);
  102285. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102286. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102287. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102288. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102289. #if FLAC__HAS_OGG
  102290. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102291. #endif
  102292. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102293. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102294. static FLAC__bool process_subframe_(
  102295. FLAC__StreamEncoder *encoder,
  102296. unsigned min_partition_order,
  102297. unsigned max_partition_order,
  102298. const FLAC__FrameHeader *frame_header,
  102299. unsigned subframe_bps,
  102300. const FLAC__int32 integer_signal[],
  102301. FLAC__Subframe *subframe[2],
  102302. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102303. FLAC__int32 *residual[2],
  102304. unsigned *best_subframe,
  102305. unsigned *best_bits
  102306. );
  102307. static FLAC__bool add_subframe_(
  102308. FLAC__StreamEncoder *encoder,
  102309. unsigned blocksize,
  102310. unsigned subframe_bps,
  102311. const FLAC__Subframe *subframe,
  102312. FLAC__BitWriter *frame
  102313. );
  102314. static unsigned evaluate_constant_subframe_(
  102315. FLAC__StreamEncoder *encoder,
  102316. const FLAC__int32 signal,
  102317. unsigned blocksize,
  102318. unsigned subframe_bps,
  102319. FLAC__Subframe *subframe
  102320. );
  102321. static unsigned evaluate_fixed_subframe_(
  102322. FLAC__StreamEncoder *encoder,
  102323. const FLAC__int32 signal[],
  102324. FLAC__int32 residual[],
  102325. FLAC__uint64 abs_residual_partition_sums[],
  102326. unsigned raw_bits_per_partition[],
  102327. unsigned blocksize,
  102328. unsigned subframe_bps,
  102329. unsigned order,
  102330. unsigned rice_parameter,
  102331. unsigned rice_parameter_limit,
  102332. unsigned min_partition_order,
  102333. unsigned max_partition_order,
  102334. FLAC__bool do_escape_coding,
  102335. unsigned rice_parameter_search_dist,
  102336. FLAC__Subframe *subframe,
  102337. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102338. );
  102339. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102340. static unsigned evaluate_lpc_subframe_(
  102341. FLAC__StreamEncoder *encoder,
  102342. const FLAC__int32 signal[],
  102343. FLAC__int32 residual[],
  102344. FLAC__uint64 abs_residual_partition_sums[],
  102345. unsigned raw_bits_per_partition[],
  102346. const FLAC__real lp_coeff[],
  102347. unsigned blocksize,
  102348. unsigned subframe_bps,
  102349. unsigned order,
  102350. unsigned qlp_coeff_precision,
  102351. unsigned rice_parameter,
  102352. unsigned rice_parameter_limit,
  102353. unsigned min_partition_order,
  102354. unsigned max_partition_order,
  102355. FLAC__bool do_escape_coding,
  102356. unsigned rice_parameter_search_dist,
  102357. FLAC__Subframe *subframe,
  102358. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102359. );
  102360. #endif
  102361. static unsigned evaluate_verbatim_subframe_(
  102362. FLAC__StreamEncoder *encoder,
  102363. const FLAC__int32 signal[],
  102364. unsigned blocksize,
  102365. unsigned subframe_bps,
  102366. FLAC__Subframe *subframe
  102367. );
  102368. static unsigned find_best_partition_order_(
  102369. struct FLAC__StreamEncoderPrivate *private_,
  102370. const FLAC__int32 residual[],
  102371. FLAC__uint64 abs_residual_partition_sums[],
  102372. unsigned raw_bits_per_partition[],
  102373. unsigned residual_samples,
  102374. unsigned predictor_order,
  102375. unsigned rice_parameter,
  102376. unsigned rice_parameter_limit,
  102377. unsigned min_partition_order,
  102378. unsigned max_partition_order,
  102379. unsigned bps,
  102380. FLAC__bool do_escape_coding,
  102381. unsigned rice_parameter_search_dist,
  102382. FLAC__EntropyCodingMethod *best_ecm
  102383. );
  102384. static void precompute_partition_info_sums_(
  102385. const FLAC__int32 residual[],
  102386. FLAC__uint64 abs_residual_partition_sums[],
  102387. unsigned residual_samples,
  102388. unsigned predictor_order,
  102389. unsigned min_partition_order,
  102390. unsigned max_partition_order,
  102391. unsigned bps
  102392. );
  102393. static void precompute_partition_info_escapes_(
  102394. const FLAC__int32 residual[],
  102395. unsigned raw_bits_per_partition[],
  102396. unsigned residual_samples,
  102397. unsigned predictor_order,
  102398. unsigned min_partition_order,
  102399. unsigned max_partition_order
  102400. );
  102401. static FLAC__bool set_partitioned_rice_(
  102402. #ifdef EXACT_RICE_BITS_CALCULATION
  102403. const FLAC__int32 residual[],
  102404. #endif
  102405. const FLAC__uint64 abs_residual_partition_sums[],
  102406. const unsigned raw_bits_per_partition[],
  102407. const unsigned residual_samples,
  102408. const unsigned predictor_order,
  102409. const unsigned suggested_rice_parameter,
  102410. const unsigned rice_parameter_limit,
  102411. const unsigned rice_parameter_search_dist,
  102412. const unsigned partition_order,
  102413. const FLAC__bool search_for_escapes,
  102414. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102415. unsigned *bits
  102416. );
  102417. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102418. /* verify-related routines: */
  102419. static void append_to_verify_fifo_(
  102420. verify_input_fifo *fifo,
  102421. const FLAC__int32 * const input[],
  102422. unsigned input_offset,
  102423. unsigned channels,
  102424. unsigned wide_samples
  102425. );
  102426. static void append_to_verify_fifo_interleaved_(
  102427. verify_input_fifo *fifo,
  102428. const FLAC__int32 input[],
  102429. unsigned input_offset,
  102430. unsigned channels,
  102431. unsigned wide_samples
  102432. );
  102433. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102434. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102435. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102436. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102437. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102438. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102439. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102440. 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);
  102441. static FILE *get_binary_stdout_(void);
  102442. /***********************************************************************
  102443. *
  102444. * Private class data
  102445. *
  102446. ***********************************************************************/
  102447. typedef struct FLAC__StreamEncoderPrivate {
  102448. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102449. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102450. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102451. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102452. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102453. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102454. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102455. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102456. #endif
  102457. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102458. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102459. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102460. FLAC__int32 *residual_workspace_mid_side[2][2];
  102461. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102462. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102463. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102464. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102465. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102466. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102467. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102468. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102469. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102470. unsigned best_subframe_mid_side[2];
  102471. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102472. unsigned best_subframe_bits_mid_side[2];
  102473. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102474. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102475. FLAC__BitWriter *frame; /* the current frame being worked on */
  102476. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102477. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102478. FLAC__ChannelAssignment last_channel_assignment;
  102479. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102480. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102481. unsigned current_sample_number;
  102482. unsigned current_frame_number;
  102483. FLAC__MD5Context md5context;
  102484. FLAC__CPUInfo cpuinfo;
  102485. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102486. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102487. #else
  102488. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102489. #endif
  102490. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102491. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102492. 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[]);
  102493. 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[]);
  102494. 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[]);
  102495. #endif
  102496. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102497. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102498. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102499. FLAC__bool disable_constant_subframes;
  102500. FLAC__bool disable_fixed_subframes;
  102501. FLAC__bool disable_verbatim_subframes;
  102502. #if FLAC__HAS_OGG
  102503. FLAC__bool is_ogg;
  102504. #endif
  102505. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102506. FLAC__StreamEncoderSeekCallback seek_callback;
  102507. FLAC__StreamEncoderTellCallback tell_callback;
  102508. FLAC__StreamEncoderWriteCallback write_callback;
  102509. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102510. FLAC__StreamEncoderProgressCallback progress_callback;
  102511. void *client_data;
  102512. unsigned first_seekpoint_to_check;
  102513. FILE *file; /* only used when encoding to a file */
  102514. FLAC__uint64 bytes_written;
  102515. FLAC__uint64 samples_written;
  102516. unsigned frames_written;
  102517. unsigned total_frames_estimate;
  102518. /* unaligned (original) pointers to allocated data */
  102519. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102520. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102521. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102522. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102523. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102524. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102525. FLAC__real *windowed_signal_unaligned;
  102526. #endif
  102527. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102528. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102529. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102530. unsigned *raw_bits_per_partition_unaligned;
  102531. /*
  102532. * These fields have been moved here from private function local
  102533. * declarations merely to save stack space during encoding.
  102534. */
  102535. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102536. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102537. #endif
  102538. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102539. /*
  102540. * The data for the verify section
  102541. */
  102542. struct {
  102543. FLAC__StreamDecoder *decoder;
  102544. EncoderStateHint state_hint;
  102545. FLAC__bool needs_magic_hack;
  102546. verify_input_fifo input_fifo;
  102547. verify_output output;
  102548. struct {
  102549. FLAC__uint64 absolute_sample;
  102550. unsigned frame_number;
  102551. unsigned channel;
  102552. unsigned sample;
  102553. FLAC__int32 expected;
  102554. FLAC__int32 got;
  102555. } error_stats;
  102556. } verify;
  102557. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102558. } FLAC__StreamEncoderPrivate;
  102559. /***********************************************************************
  102560. *
  102561. * Public static class data
  102562. *
  102563. ***********************************************************************/
  102564. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102565. "FLAC__STREAM_ENCODER_OK",
  102566. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102567. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102568. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102569. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102570. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102571. "FLAC__STREAM_ENCODER_IO_ERROR",
  102572. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102573. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102574. };
  102575. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102576. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102577. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102578. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102579. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102580. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102581. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102582. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102583. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102584. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102585. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102586. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102587. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102588. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102589. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102590. };
  102591. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102592. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102593. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102594. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102595. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102596. };
  102597. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102598. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102599. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102600. };
  102601. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102602. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102603. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102604. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102605. };
  102606. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102607. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102608. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102609. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102610. };
  102611. /* Number of samples that will be overread to watch for end of stream. By
  102612. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102613. * always try to read blocksize+1 samples before encoding a block, so that
  102614. * even if the stream has a total sample count that is an integral multiple
  102615. * of the blocksize, we will still notice when we are encoding the last
  102616. * block. This is needed, for example, to correctly set the end-of-stream
  102617. * marker in Ogg FLAC.
  102618. *
  102619. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102620. * not really any reason to change it.
  102621. */
  102622. static const unsigned OVERREAD_ = 1;
  102623. /***********************************************************************
  102624. *
  102625. * Class constructor/destructor
  102626. *
  102627. */
  102628. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102629. {
  102630. FLAC__StreamEncoder *encoder;
  102631. unsigned i;
  102632. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102633. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102634. if(encoder == 0) {
  102635. return 0;
  102636. }
  102637. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102638. if(encoder->protected_ == 0) {
  102639. free(encoder);
  102640. return 0;
  102641. }
  102642. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102643. if(encoder->private_ == 0) {
  102644. free(encoder->protected_);
  102645. free(encoder);
  102646. return 0;
  102647. }
  102648. encoder->private_->frame = FLAC__bitwriter_new();
  102649. if(encoder->private_->frame == 0) {
  102650. free(encoder->private_);
  102651. free(encoder->protected_);
  102652. free(encoder);
  102653. return 0;
  102654. }
  102655. encoder->private_->file = 0;
  102656. set_defaults_enc(encoder);
  102657. encoder->private_->is_being_deleted = false;
  102658. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102659. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102660. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102661. }
  102662. for(i = 0; i < 2; i++) {
  102663. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102664. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102665. }
  102666. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102667. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102668. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102669. }
  102670. for(i = 0; i < 2; i++) {
  102671. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102672. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102673. }
  102674. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102675. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102676. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102677. }
  102678. for(i = 0; i < 2; i++) {
  102679. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102680. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102681. }
  102682. for(i = 0; i < 2; i++)
  102683. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102684. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102685. return encoder;
  102686. }
  102687. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102688. {
  102689. unsigned i;
  102690. FLAC__ASSERT(0 != encoder);
  102691. FLAC__ASSERT(0 != encoder->protected_);
  102692. FLAC__ASSERT(0 != encoder->private_);
  102693. FLAC__ASSERT(0 != encoder->private_->frame);
  102694. encoder->private_->is_being_deleted = true;
  102695. (void)FLAC__stream_encoder_finish(encoder);
  102696. if(0 != encoder->private_->verify.decoder)
  102697. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102698. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102699. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102700. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102701. }
  102702. for(i = 0; i < 2; i++) {
  102703. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102704. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102705. }
  102706. for(i = 0; i < 2; i++)
  102707. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102708. FLAC__bitwriter_delete(encoder->private_->frame);
  102709. free(encoder->private_);
  102710. free(encoder->protected_);
  102711. free(encoder);
  102712. }
  102713. /***********************************************************************
  102714. *
  102715. * Public class methods
  102716. *
  102717. ***********************************************************************/
  102718. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102719. FLAC__StreamEncoder *encoder,
  102720. FLAC__StreamEncoderReadCallback read_callback,
  102721. FLAC__StreamEncoderWriteCallback write_callback,
  102722. FLAC__StreamEncoderSeekCallback seek_callback,
  102723. FLAC__StreamEncoderTellCallback tell_callback,
  102724. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102725. void *client_data,
  102726. FLAC__bool is_ogg
  102727. )
  102728. {
  102729. unsigned i;
  102730. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102731. FLAC__ASSERT(0 != encoder);
  102732. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102733. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102734. #if !FLAC__HAS_OGG
  102735. if(is_ogg)
  102736. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102737. #endif
  102738. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102739. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102740. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102741. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102742. if(encoder->protected_->channels != 2) {
  102743. encoder->protected_->do_mid_side_stereo = false;
  102744. encoder->protected_->loose_mid_side_stereo = false;
  102745. }
  102746. else if(!encoder->protected_->do_mid_side_stereo)
  102747. encoder->protected_->loose_mid_side_stereo = false;
  102748. if(encoder->protected_->bits_per_sample >= 32)
  102749. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102750. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102751. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102752. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102753. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102754. if(encoder->protected_->blocksize == 0) {
  102755. if(encoder->protected_->max_lpc_order == 0)
  102756. encoder->protected_->blocksize = 1152;
  102757. else
  102758. encoder->protected_->blocksize = 4096;
  102759. }
  102760. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102761. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102762. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102763. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102764. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102765. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102766. if(encoder->protected_->qlp_coeff_precision == 0) {
  102767. if(encoder->protected_->bits_per_sample < 16) {
  102768. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102769. /* @@@ until then we'll make a guess */
  102770. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102771. }
  102772. else if(encoder->protected_->bits_per_sample == 16) {
  102773. if(encoder->protected_->blocksize <= 192)
  102774. encoder->protected_->qlp_coeff_precision = 7;
  102775. else if(encoder->protected_->blocksize <= 384)
  102776. encoder->protected_->qlp_coeff_precision = 8;
  102777. else if(encoder->protected_->blocksize <= 576)
  102778. encoder->protected_->qlp_coeff_precision = 9;
  102779. else if(encoder->protected_->blocksize <= 1152)
  102780. encoder->protected_->qlp_coeff_precision = 10;
  102781. else if(encoder->protected_->blocksize <= 2304)
  102782. encoder->protected_->qlp_coeff_precision = 11;
  102783. else if(encoder->protected_->blocksize <= 4608)
  102784. encoder->protected_->qlp_coeff_precision = 12;
  102785. else
  102786. encoder->protected_->qlp_coeff_precision = 13;
  102787. }
  102788. else {
  102789. if(encoder->protected_->blocksize <= 384)
  102790. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102791. else if(encoder->protected_->blocksize <= 1152)
  102792. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102793. else
  102794. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102795. }
  102796. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102797. }
  102798. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102799. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102800. if(encoder->protected_->streamable_subset) {
  102801. if(
  102802. encoder->protected_->blocksize != 192 &&
  102803. encoder->protected_->blocksize != 576 &&
  102804. encoder->protected_->blocksize != 1152 &&
  102805. encoder->protected_->blocksize != 2304 &&
  102806. encoder->protected_->blocksize != 4608 &&
  102807. encoder->protected_->blocksize != 256 &&
  102808. encoder->protected_->blocksize != 512 &&
  102809. encoder->protected_->blocksize != 1024 &&
  102810. encoder->protected_->blocksize != 2048 &&
  102811. encoder->protected_->blocksize != 4096 &&
  102812. encoder->protected_->blocksize != 8192 &&
  102813. encoder->protected_->blocksize != 16384
  102814. )
  102815. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102816. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102817. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102818. if(
  102819. encoder->protected_->bits_per_sample != 8 &&
  102820. encoder->protected_->bits_per_sample != 12 &&
  102821. encoder->protected_->bits_per_sample != 16 &&
  102822. encoder->protected_->bits_per_sample != 20 &&
  102823. encoder->protected_->bits_per_sample != 24
  102824. )
  102825. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102826. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102827. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102828. if(
  102829. encoder->protected_->sample_rate <= 48000 &&
  102830. (
  102831. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102832. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102833. )
  102834. ) {
  102835. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102836. }
  102837. }
  102838. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102839. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102840. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102841. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102842. #if FLAC__HAS_OGG
  102843. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102844. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102845. unsigned i;
  102846. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102847. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102848. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102849. for( ; i > 0; i--)
  102850. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102851. encoder->protected_->metadata[0] = vc;
  102852. break;
  102853. }
  102854. }
  102855. }
  102856. #endif
  102857. /* keep track of any SEEKTABLE block */
  102858. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102859. unsigned i;
  102860. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102861. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102862. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102863. break; /* take only the first one */
  102864. }
  102865. }
  102866. }
  102867. /* validate metadata */
  102868. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102869. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102870. metadata_has_seektable = false;
  102871. metadata_has_vorbis_comment = false;
  102872. metadata_picture_has_type1 = false;
  102873. metadata_picture_has_type2 = false;
  102874. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102875. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102876. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102877. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102878. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102879. if(metadata_has_seektable) /* only one is allowed */
  102880. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102881. metadata_has_seektable = true;
  102882. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102883. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102884. }
  102885. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102886. if(metadata_has_vorbis_comment) /* only one is allowed */
  102887. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102888. metadata_has_vorbis_comment = true;
  102889. }
  102890. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102891. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102892. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102893. }
  102894. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102895. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102896. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102897. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102898. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102899. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102900. metadata_picture_has_type1 = true;
  102901. /* standard icon must be 32x32 pixel PNG */
  102902. if(
  102903. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102904. (
  102905. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102906. m->data.picture.width != 32 ||
  102907. m->data.picture.height != 32
  102908. )
  102909. )
  102910. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102911. }
  102912. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102913. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102914. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102915. metadata_picture_has_type2 = true;
  102916. }
  102917. }
  102918. }
  102919. encoder->private_->input_capacity = 0;
  102920. for(i = 0; i < encoder->protected_->channels; i++) {
  102921. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102922. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102923. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102924. #endif
  102925. }
  102926. for(i = 0; i < 2; i++) {
  102927. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102928. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102929. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102930. #endif
  102931. }
  102932. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102933. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102934. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102935. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102936. #endif
  102937. for(i = 0; i < encoder->protected_->channels; i++) {
  102938. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102939. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102940. encoder->private_->best_subframe[i] = 0;
  102941. }
  102942. for(i = 0; i < 2; i++) {
  102943. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102944. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102945. encoder->private_->best_subframe_mid_side[i] = 0;
  102946. }
  102947. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102948. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102949. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102950. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102951. #else
  102952. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102953. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102954. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102955. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102956. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102957. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102958. 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);
  102959. #endif
  102960. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102961. encoder->private_->loose_mid_side_stereo_frames = 1;
  102962. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102963. encoder->private_->current_sample_number = 0;
  102964. encoder->private_->current_frame_number = 0;
  102965. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102966. 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? */
  102967. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102968. /*
  102969. * get the CPU info and set the function pointers
  102970. */
  102971. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102972. /* first default to the non-asm routines */
  102973. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102974. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102975. #endif
  102976. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102977. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102978. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102979. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102980. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102981. #endif
  102982. /* now override with asm where appropriate */
  102983. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102984. # ifndef FLAC__NO_ASM
  102985. if(encoder->private_->cpuinfo.use_asm) {
  102986. # ifdef FLAC__CPU_IA32
  102987. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102988. # ifdef FLAC__HAS_NASM
  102989. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102990. if(encoder->protected_->max_lpc_order < 4)
  102991. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102992. else if(encoder->protected_->max_lpc_order < 8)
  102993. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102994. else if(encoder->protected_->max_lpc_order < 12)
  102995. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102996. else
  102997. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102998. }
  102999. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  103000. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  103001. else
  103002. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103003. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  103004. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103005. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  103006. }
  103007. else {
  103008. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103009. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103010. }
  103011. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  103012. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  103013. # endif /* FLAC__HAS_NASM */
  103014. # endif /* FLAC__CPU_IA32 */
  103015. }
  103016. # endif /* !FLAC__NO_ASM */
  103017. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  103018. /* finally override based on wide-ness if necessary */
  103019. if(encoder->private_->use_wide_by_block) {
  103020. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  103021. }
  103022. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  103023. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  103024. #if FLAC__HAS_OGG
  103025. encoder->private_->is_ogg = is_ogg;
  103026. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  103027. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103028. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103029. }
  103030. #endif
  103031. encoder->private_->read_callback = read_callback;
  103032. encoder->private_->write_callback = write_callback;
  103033. encoder->private_->seek_callback = seek_callback;
  103034. encoder->private_->tell_callback = tell_callback;
  103035. encoder->private_->metadata_callback = metadata_callback;
  103036. encoder->private_->client_data = client_data;
  103037. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  103038. /* the above function sets the state for us in case of an error */
  103039. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103040. }
  103041. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  103042. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103043. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103044. }
  103045. /*
  103046. * Set up the verify stuff if necessary
  103047. */
  103048. if(encoder->protected_->verify) {
  103049. /*
  103050. * First, set up the fifo which will hold the
  103051. * original signal to compare against
  103052. */
  103053. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  103054. for(i = 0; i < encoder->protected_->channels; i++) {
  103055. 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))) {
  103056. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103057. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103058. }
  103059. }
  103060. encoder->private_->verify.input_fifo.tail = 0;
  103061. /*
  103062. * Now set up a stream decoder for verification
  103063. */
  103064. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  103065. if(0 == encoder->private_->verify.decoder) {
  103066. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103067. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103068. }
  103069. 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) {
  103070. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103071. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103072. }
  103073. }
  103074. encoder->private_->verify.error_stats.absolute_sample = 0;
  103075. encoder->private_->verify.error_stats.frame_number = 0;
  103076. encoder->private_->verify.error_stats.channel = 0;
  103077. encoder->private_->verify.error_stats.sample = 0;
  103078. encoder->private_->verify.error_stats.expected = 0;
  103079. encoder->private_->verify.error_stats.got = 0;
  103080. /*
  103081. * These must be done before we write any metadata, because that
  103082. * calls the write_callback, which uses these values.
  103083. */
  103084. encoder->private_->first_seekpoint_to_check = 0;
  103085. encoder->private_->samples_written = 0;
  103086. encoder->protected_->streaminfo_offset = 0;
  103087. encoder->protected_->seektable_offset = 0;
  103088. encoder->protected_->audio_offset = 0;
  103089. /*
  103090. * write the stream header
  103091. */
  103092. if(encoder->protected_->verify)
  103093. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103094. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103095. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103096. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103097. }
  103098. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103099. /* the above function sets the state for us in case of an error */
  103100. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103101. }
  103102. /*
  103103. * write the STREAMINFO metadata block
  103104. */
  103105. if(encoder->protected_->verify)
  103106. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103107. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103108. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103109. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103110. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103111. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103112. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103113. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103114. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103115. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103116. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103117. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103118. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103119. if(encoder->protected_->do_md5)
  103120. FLAC__MD5Init(&encoder->private_->md5context);
  103121. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103122. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103123. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103124. }
  103125. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103126. /* the above function sets the state for us in case of an error */
  103127. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103128. }
  103129. /*
  103130. * Now that the STREAMINFO block is written, we can init this to an
  103131. * absurdly-high value...
  103132. */
  103133. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103134. /* ... and clear this to 0 */
  103135. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103136. /*
  103137. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103138. * if not, we will write an empty one (FLAC__add_metadata_block()
  103139. * automatically supplies the vendor string).
  103140. *
  103141. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103142. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103143. * true it will have already insured that the metadata list is properly
  103144. * ordered.)
  103145. */
  103146. if(!metadata_has_vorbis_comment) {
  103147. FLAC__StreamMetadata vorbis_comment;
  103148. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103149. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103150. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103151. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103152. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103153. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103154. vorbis_comment.data.vorbis_comment.comments = 0;
  103155. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103156. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103157. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103158. }
  103159. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103160. /* the above function sets the state for us in case of an error */
  103161. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103162. }
  103163. }
  103164. /*
  103165. * write the user's metadata blocks
  103166. */
  103167. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103168. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103169. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], 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 all the metadata is written, we save the stream offset */
  103179. 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 */
  103180. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103181. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103182. }
  103183. if(encoder->protected_->verify)
  103184. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103185. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103186. }
  103187. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103188. FLAC__StreamEncoder *encoder,
  103189. FLAC__StreamEncoderWriteCallback write_callback,
  103190. FLAC__StreamEncoderSeekCallback seek_callback,
  103191. FLAC__StreamEncoderTellCallback tell_callback,
  103192. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103193. void *client_data
  103194. )
  103195. {
  103196. return init_stream_internal_enc(
  103197. encoder,
  103198. /*read_callback=*/0,
  103199. write_callback,
  103200. seek_callback,
  103201. tell_callback,
  103202. metadata_callback,
  103203. client_data,
  103204. /*is_ogg=*/false
  103205. );
  103206. }
  103207. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103208. FLAC__StreamEncoder *encoder,
  103209. FLAC__StreamEncoderReadCallback read_callback,
  103210. FLAC__StreamEncoderWriteCallback write_callback,
  103211. FLAC__StreamEncoderSeekCallback seek_callback,
  103212. FLAC__StreamEncoderTellCallback tell_callback,
  103213. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103214. void *client_data
  103215. )
  103216. {
  103217. return init_stream_internal_enc(
  103218. encoder,
  103219. read_callback,
  103220. write_callback,
  103221. seek_callback,
  103222. tell_callback,
  103223. metadata_callback,
  103224. client_data,
  103225. /*is_ogg=*/true
  103226. );
  103227. }
  103228. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103229. FLAC__StreamEncoder *encoder,
  103230. FILE *file,
  103231. FLAC__StreamEncoderProgressCallback progress_callback,
  103232. void *client_data,
  103233. FLAC__bool is_ogg
  103234. )
  103235. {
  103236. FLAC__StreamEncoderInitStatus init_status;
  103237. FLAC__ASSERT(0 != encoder);
  103238. FLAC__ASSERT(0 != file);
  103239. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103240. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103241. /* double protection */
  103242. if(file == 0) {
  103243. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103244. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103245. }
  103246. /*
  103247. * To make sure that our file does not go unclosed after an error, we
  103248. * must assign the FILE pointer before any further error can occur in
  103249. * this routine.
  103250. */
  103251. if(file == stdout)
  103252. file = get_binary_stdout_(); /* just to be safe */
  103253. encoder->private_->file = file;
  103254. encoder->private_->progress_callback = progress_callback;
  103255. encoder->private_->bytes_written = 0;
  103256. encoder->private_->samples_written = 0;
  103257. encoder->private_->frames_written = 0;
  103258. init_status = init_stream_internal_enc(
  103259. encoder,
  103260. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103261. file_write_callback_,
  103262. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103263. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103264. /*metadata_callback=*/0,
  103265. client_data,
  103266. is_ogg
  103267. );
  103268. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103269. /* the above function sets the state for us in case of an error */
  103270. return init_status;
  103271. }
  103272. {
  103273. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103274. FLAC__ASSERT(blocksize != 0);
  103275. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103276. }
  103277. return init_status;
  103278. }
  103279. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103280. FLAC__StreamEncoder *encoder,
  103281. FILE *file,
  103282. FLAC__StreamEncoderProgressCallback progress_callback,
  103283. void *client_data
  103284. )
  103285. {
  103286. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103287. }
  103288. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103289. FLAC__StreamEncoder *encoder,
  103290. FILE *file,
  103291. FLAC__StreamEncoderProgressCallback progress_callback,
  103292. void *client_data
  103293. )
  103294. {
  103295. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103296. }
  103297. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103298. FLAC__StreamEncoder *encoder,
  103299. const char *filename,
  103300. FLAC__StreamEncoderProgressCallback progress_callback,
  103301. void *client_data,
  103302. FLAC__bool is_ogg
  103303. )
  103304. {
  103305. FILE *file;
  103306. FLAC__ASSERT(0 != encoder);
  103307. /*
  103308. * To make sure that our file does not go unclosed after an error, we
  103309. * have to do the same entrance checks here that are later performed
  103310. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103311. */
  103312. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103313. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103314. file = filename? fopen(filename, "w+b") : stdout;
  103315. if(file == 0) {
  103316. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103317. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103318. }
  103319. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103320. }
  103321. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103322. FLAC__StreamEncoder *encoder,
  103323. const char *filename,
  103324. FLAC__StreamEncoderProgressCallback progress_callback,
  103325. void *client_data
  103326. )
  103327. {
  103328. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103329. }
  103330. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103331. FLAC__StreamEncoder *encoder,
  103332. const char *filename,
  103333. FLAC__StreamEncoderProgressCallback progress_callback,
  103334. void *client_data
  103335. )
  103336. {
  103337. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103338. }
  103339. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103340. {
  103341. FLAC__bool error = false;
  103342. FLAC__ASSERT(0 != encoder);
  103343. FLAC__ASSERT(0 != encoder->private_);
  103344. FLAC__ASSERT(0 != encoder->protected_);
  103345. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103346. return true;
  103347. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103348. if(encoder->private_->current_sample_number != 0) {
  103349. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103350. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103351. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103352. error = true;
  103353. }
  103354. }
  103355. if(encoder->protected_->do_md5)
  103356. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103357. if(!encoder->private_->is_being_deleted) {
  103358. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103359. if(encoder->private_->seek_callback) {
  103360. #if FLAC__HAS_OGG
  103361. if(encoder->private_->is_ogg)
  103362. update_ogg_metadata_(encoder);
  103363. else
  103364. #endif
  103365. update_metadata_(encoder);
  103366. /* check if an error occurred while updating metadata */
  103367. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103368. error = true;
  103369. }
  103370. if(encoder->private_->metadata_callback)
  103371. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103372. }
  103373. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103374. if(!error)
  103375. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103376. error = true;
  103377. }
  103378. }
  103379. if(0 != encoder->private_->file) {
  103380. if(encoder->private_->file != stdout)
  103381. fclose(encoder->private_->file);
  103382. encoder->private_->file = 0;
  103383. }
  103384. #if FLAC__HAS_OGG
  103385. if(encoder->private_->is_ogg)
  103386. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103387. #endif
  103388. free_(encoder);
  103389. set_defaults_enc(encoder);
  103390. if(!error)
  103391. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103392. return !error;
  103393. }
  103394. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103395. {
  103396. FLAC__ASSERT(0 != encoder);
  103397. FLAC__ASSERT(0 != encoder->private_);
  103398. FLAC__ASSERT(0 != encoder->protected_);
  103399. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103400. return false;
  103401. #if FLAC__HAS_OGG
  103402. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103403. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103404. return true;
  103405. #else
  103406. (void)value;
  103407. return false;
  103408. #endif
  103409. }
  103410. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103411. {
  103412. FLAC__ASSERT(0 != encoder);
  103413. FLAC__ASSERT(0 != encoder->private_);
  103414. FLAC__ASSERT(0 != encoder->protected_);
  103415. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103416. return false;
  103417. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103418. encoder->protected_->verify = value;
  103419. #endif
  103420. return true;
  103421. }
  103422. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103423. {
  103424. FLAC__ASSERT(0 != encoder);
  103425. FLAC__ASSERT(0 != encoder->private_);
  103426. FLAC__ASSERT(0 != encoder->protected_);
  103427. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103428. return false;
  103429. encoder->protected_->streamable_subset = value;
  103430. return true;
  103431. }
  103432. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103433. {
  103434. FLAC__ASSERT(0 != encoder);
  103435. FLAC__ASSERT(0 != encoder->private_);
  103436. FLAC__ASSERT(0 != encoder->protected_);
  103437. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103438. return false;
  103439. encoder->protected_->do_md5 = value;
  103440. return true;
  103441. }
  103442. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned 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. encoder->protected_->channels = value;
  103450. return true;
  103451. }
  103452. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103453. {
  103454. FLAC__ASSERT(0 != encoder);
  103455. FLAC__ASSERT(0 != encoder->private_);
  103456. FLAC__ASSERT(0 != encoder->protected_);
  103457. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103458. return false;
  103459. encoder->protected_->bits_per_sample = value;
  103460. return true;
  103461. }
  103462. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103463. {
  103464. FLAC__ASSERT(0 != encoder);
  103465. FLAC__ASSERT(0 != encoder->private_);
  103466. FLAC__ASSERT(0 != encoder->protected_);
  103467. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103468. return false;
  103469. encoder->protected_->sample_rate = value;
  103470. return true;
  103471. }
  103472. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103473. {
  103474. FLAC__bool ok = true;
  103475. FLAC__ASSERT(0 != encoder);
  103476. FLAC__ASSERT(0 != encoder->private_);
  103477. FLAC__ASSERT(0 != encoder->protected_);
  103478. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103479. return false;
  103480. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103481. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103482. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103483. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103484. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103485. #if 0
  103486. /* was: */
  103487. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103488. /* but it's too hard to specify the string in a locale-specific way */
  103489. #else
  103490. encoder->protected_->num_apodizations = 1;
  103491. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103492. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103493. #endif
  103494. #endif
  103495. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103496. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103497. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103498. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103499. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103500. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103501. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103502. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103503. return ok;
  103504. }
  103505. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103506. {
  103507. FLAC__ASSERT(0 != encoder);
  103508. FLAC__ASSERT(0 != encoder->private_);
  103509. FLAC__ASSERT(0 != encoder->protected_);
  103510. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103511. return false;
  103512. encoder->protected_->blocksize = value;
  103513. return true;
  103514. }
  103515. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103516. {
  103517. FLAC__ASSERT(0 != encoder);
  103518. FLAC__ASSERT(0 != encoder->private_);
  103519. FLAC__ASSERT(0 != encoder->protected_);
  103520. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103521. return false;
  103522. encoder->protected_->do_mid_side_stereo = value;
  103523. return true;
  103524. }
  103525. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103526. {
  103527. FLAC__ASSERT(0 != encoder);
  103528. FLAC__ASSERT(0 != encoder->private_);
  103529. FLAC__ASSERT(0 != encoder->protected_);
  103530. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103531. return false;
  103532. encoder->protected_->loose_mid_side_stereo = value;
  103533. return true;
  103534. }
  103535. /*@@@@add to tests*/
  103536. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103537. {
  103538. FLAC__ASSERT(0 != encoder);
  103539. FLAC__ASSERT(0 != encoder->private_);
  103540. FLAC__ASSERT(0 != encoder->protected_);
  103541. FLAC__ASSERT(0 != specification);
  103542. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103543. return false;
  103544. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103545. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103546. #else
  103547. encoder->protected_->num_apodizations = 0;
  103548. while(1) {
  103549. const char *s = strchr(specification, ';');
  103550. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103551. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103552. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103553. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103554. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103555. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103556. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103557. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103558. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103559. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103560. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103561. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103562. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103563. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103564. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103565. if (stddev > 0.0 && stddev <= 0.5) {
  103566. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103567. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103568. }
  103569. }
  103570. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103571. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103572. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103573. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103574. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103575. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103576. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103577. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103578. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103579. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103580. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103581. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103582. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103583. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103584. if (p >= 0.0 && p <= 1.0) {
  103585. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103586. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103587. }
  103588. }
  103589. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103590. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103591. if (encoder->protected_->num_apodizations == 32)
  103592. break;
  103593. if (s)
  103594. specification = s+1;
  103595. else
  103596. break;
  103597. }
  103598. if(encoder->protected_->num_apodizations == 0) {
  103599. encoder->protected_->num_apodizations = 1;
  103600. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103601. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103602. }
  103603. #endif
  103604. return true;
  103605. }
  103606. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103607. {
  103608. FLAC__ASSERT(0 != encoder);
  103609. FLAC__ASSERT(0 != encoder->private_);
  103610. FLAC__ASSERT(0 != encoder->protected_);
  103611. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103612. return false;
  103613. encoder->protected_->max_lpc_order = value;
  103614. return true;
  103615. }
  103616. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103617. {
  103618. FLAC__ASSERT(0 != encoder);
  103619. FLAC__ASSERT(0 != encoder->private_);
  103620. FLAC__ASSERT(0 != encoder->protected_);
  103621. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103622. return false;
  103623. encoder->protected_->qlp_coeff_precision = value;
  103624. return true;
  103625. }
  103626. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103627. {
  103628. FLAC__ASSERT(0 != encoder);
  103629. FLAC__ASSERT(0 != encoder->private_);
  103630. FLAC__ASSERT(0 != encoder->protected_);
  103631. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103632. return false;
  103633. encoder->protected_->do_qlp_coeff_prec_search = value;
  103634. return true;
  103635. }
  103636. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103637. {
  103638. FLAC__ASSERT(0 != encoder);
  103639. FLAC__ASSERT(0 != encoder->private_);
  103640. FLAC__ASSERT(0 != encoder->protected_);
  103641. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103642. return false;
  103643. #if 0
  103644. /*@@@ deprecated: */
  103645. encoder->protected_->do_escape_coding = value;
  103646. #else
  103647. (void)value;
  103648. #endif
  103649. return true;
  103650. }
  103651. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103652. {
  103653. FLAC__ASSERT(0 != encoder);
  103654. FLAC__ASSERT(0 != encoder->private_);
  103655. FLAC__ASSERT(0 != encoder->protected_);
  103656. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103657. return false;
  103658. encoder->protected_->do_exhaustive_model_search = value;
  103659. return true;
  103660. }
  103661. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103662. {
  103663. FLAC__ASSERT(0 != encoder);
  103664. FLAC__ASSERT(0 != encoder->private_);
  103665. FLAC__ASSERT(0 != encoder->protected_);
  103666. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103667. return false;
  103668. encoder->protected_->min_residual_partition_order = value;
  103669. return true;
  103670. }
  103671. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103672. {
  103673. FLAC__ASSERT(0 != encoder);
  103674. FLAC__ASSERT(0 != encoder->private_);
  103675. FLAC__ASSERT(0 != encoder->protected_);
  103676. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103677. return false;
  103678. encoder->protected_->max_residual_partition_order = value;
  103679. return true;
  103680. }
  103681. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103682. {
  103683. FLAC__ASSERT(0 != encoder);
  103684. FLAC__ASSERT(0 != encoder->private_);
  103685. FLAC__ASSERT(0 != encoder->protected_);
  103686. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103687. return false;
  103688. #if 0
  103689. /*@@@ deprecated: */
  103690. encoder->protected_->rice_parameter_search_dist = value;
  103691. #else
  103692. (void)value;
  103693. #endif
  103694. return true;
  103695. }
  103696. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103697. {
  103698. FLAC__ASSERT(0 != encoder);
  103699. FLAC__ASSERT(0 != encoder->private_);
  103700. FLAC__ASSERT(0 != encoder->protected_);
  103701. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103702. return false;
  103703. encoder->protected_->total_samples_estimate = value;
  103704. return true;
  103705. }
  103706. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103707. {
  103708. FLAC__ASSERT(0 != encoder);
  103709. FLAC__ASSERT(0 != encoder->private_);
  103710. FLAC__ASSERT(0 != encoder->protected_);
  103711. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103712. return false;
  103713. if(0 == metadata)
  103714. num_blocks = 0;
  103715. if(0 == num_blocks)
  103716. metadata = 0;
  103717. /* realloc() does not do exactly what we want so... */
  103718. if(encoder->protected_->metadata) {
  103719. free(encoder->protected_->metadata);
  103720. encoder->protected_->metadata = 0;
  103721. encoder->protected_->num_metadata_blocks = 0;
  103722. }
  103723. if(num_blocks) {
  103724. FLAC__StreamMetadata **m;
  103725. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103726. return false;
  103727. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103728. encoder->protected_->metadata = m;
  103729. encoder->protected_->num_metadata_blocks = num_blocks;
  103730. }
  103731. #if FLAC__HAS_OGG
  103732. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103733. return false;
  103734. #endif
  103735. return true;
  103736. }
  103737. /*
  103738. * These three functions are not static, but not publically exposed in
  103739. * include/FLAC/ either. They are used by the test suite.
  103740. */
  103741. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103742. {
  103743. FLAC__ASSERT(0 != encoder);
  103744. FLAC__ASSERT(0 != encoder->private_);
  103745. FLAC__ASSERT(0 != encoder->protected_);
  103746. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103747. return false;
  103748. encoder->private_->disable_constant_subframes = value;
  103749. return true;
  103750. }
  103751. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103752. {
  103753. FLAC__ASSERT(0 != encoder);
  103754. FLAC__ASSERT(0 != encoder->private_);
  103755. FLAC__ASSERT(0 != encoder->protected_);
  103756. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103757. return false;
  103758. encoder->private_->disable_fixed_subframes = value;
  103759. return true;
  103760. }
  103761. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103762. {
  103763. FLAC__ASSERT(0 != encoder);
  103764. FLAC__ASSERT(0 != encoder->private_);
  103765. FLAC__ASSERT(0 != encoder->protected_);
  103766. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103767. return false;
  103768. encoder->private_->disable_verbatim_subframes = value;
  103769. return true;
  103770. }
  103771. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103772. {
  103773. FLAC__ASSERT(0 != encoder);
  103774. FLAC__ASSERT(0 != encoder->private_);
  103775. FLAC__ASSERT(0 != encoder->protected_);
  103776. return encoder->protected_->state;
  103777. }
  103778. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103779. {
  103780. FLAC__ASSERT(0 != encoder);
  103781. FLAC__ASSERT(0 != encoder->private_);
  103782. FLAC__ASSERT(0 != encoder->protected_);
  103783. if(encoder->protected_->verify)
  103784. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103785. else
  103786. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103787. }
  103788. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103789. {
  103790. FLAC__ASSERT(0 != encoder);
  103791. FLAC__ASSERT(0 != encoder->private_);
  103792. FLAC__ASSERT(0 != encoder->protected_);
  103793. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103794. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103795. else
  103796. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103797. }
  103798. 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)
  103799. {
  103800. FLAC__ASSERT(0 != encoder);
  103801. FLAC__ASSERT(0 != encoder->private_);
  103802. FLAC__ASSERT(0 != encoder->protected_);
  103803. if(0 != absolute_sample)
  103804. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103805. if(0 != frame_number)
  103806. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103807. if(0 != channel)
  103808. *channel = encoder->private_->verify.error_stats.channel;
  103809. if(0 != sample)
  103810. *sample = encoder->private_->verify.error_stats.sample;
  103811. if(0 != expected)
  103812. *expected = encoder->private_->verify.error_stats.expected;
  103813. if(0 != got)
  103814. *got = encoder->private_->verify.error_stats.got;
  103815. }
  103816. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103817. {
  103818. FLAC__ASSERT(0 != encoder);
  103819. FLAC__ASSERT(0 != encoder->private_);
  103820. FLAC__ASSERT(0 != encoder->protected_);
  103821. return encoder->protected_->verify;
  103822. }
  103823. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103824. {
  103825. FLAC__ASSERT(0 != encoder);
  103826. FLAC__ASSERT(0 != encoder->private_);
  103827. FLAC__ASSERT(0 != encoder->protected_);
  103828. return encoder->protected_->streamable_subset;
  103829. }
  103830. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103831. {
  103832. FLAC__ASSERT(0 != encoder);
  103833. FLAC__ASSERT(0 != encoder->private_);
  103834. FLAC__ASSERT(0 != encoder->protected_);
  103835. return encoder->protected_->do_md5;
  103836. }
  103837. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103838. {
  103839. FLAC__ASSERT(0 != encoder);
  103840. FLAC__ASSERT(0 != encoder->private_);
  103841. FLAC__ASSERT(0 != encoder->protected_);
  103842. return encoder->protected_->channels;
  103843. }
  103844. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103845. {
  103846. FLAC__ASSERT(0 != encoder);
  103847. FLAC__ASSERT(0 != encoder->private_);
  103848. FLAC__ASSERT(0 != encoder->protected_);
  103849. return encoder->protected_->bits_per_sample;
  103850. }
  103851. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103852. {
  103853. FLAC__ASSERT(0 != encoder);
  103854. FLAC__ASSERT(0 != encoder->private_);
  103855. FLAC__ASSERT(0 != encoder->protected_);
  103856. return encoder->protected_->sample_rate;
  103857. }
  103858. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103859. {
  103860. FLAC__ASSERT(0 != encoder);
  103861. FLAC__ASSERT(0 != encoder->private_);
  103862. FLAC__ASSERT(0 != encoder->protected_);
  103863. return encoder->protected_->blocksize;
  103864. }
  103865. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103866. {
  103867. FLAC__ASSERT(0 != encoder);
  103868. FLAC__ASSERT(0 != encoder->private_);
  103869. FLAC__ASSERT(0 != encoder->protected_);
  103870. return encoder->protected_->do_mid_side_stereo;
  103871. }
  103872. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103873. {
  103874. FLAC__ASSERT(0 != encoder);
  103875. FLAC__ASSERT(0 != encoder->private_);
  103876. FLAC__ASSERT(0 != encoder->protected_);
  103877. return encoder->protected_->loose_mid_side_stereo;
  103878. }
  103879. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103880. {
  103881. FLAC__ASSERT(0 != encoder);
  103882. FLAC__ASSERT(0 != encoder->private_);
  103883. FLAC__ASSERT(0 != encoder->protected_);
  103884. return encoder->protected_->max_lpc_order;
  103885. }
  103886. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103887. {
  103888. FLAC__ASSERT(0 != encoder);
  103889. FLAC__ASSERT(0 != encoder->private_);
  103890. FLAC__ASSERT(0 != encoder->protected_);
  103891. return encoder->protected_->qlp_coeff_precision;
  103892. }
  103893. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103894. {
  103895. FLAC__ASSERT(0 != encoder);
  103896. FLAC__ASSERT(0 != encoder->private_);
  103897. FLAC__ASSERT(0 != encoder->protected_);
  103898. return encoder->protected_->do_qlp_coeff_prec_search;
  103899. }
  103900. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103901. {
  103902. FLAC__ASSERT(0 != encoder);
  103903. FLAC__ASSERT(0 != encoder->private_);
  103904. FLAC__ASSERT(0 != encoder->protected_);
  103905. return encoder->protected_->do_escape_coding;
  103906. }
  103907. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103908. {
  103909. FLAC__ASSERT(0 != encoder);
  103910. FLAC__ASSERT(0 != encoder->private_);
  103911. FLAC__ASSERT(0 != encoder->protected_);
  103912. return encoder->protected_->do_exhaustive_model_search;
  103913. }
  103914. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103915. {
  103916. FLAC__ASSERT(0 != encoder);
  103917. FLAC__ASSERT(0 != encoder->private_);
  103918. FLAC__ASSERT(0 != encoder->protected_);
  103919. return encoder->protected_->min_residual_partition_order;
  103920. }
  103921. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103922. {
  103923. FLAC__ASSERT(0 != encoder);
  103924. FLAC__ASSERT(0 != encoder->private_);
  103925. FLAC__ASSERT(0 != encoder->protected_);
  103926. return encoder->protected_->max_residual_partition_order;
  103927. }
  103928. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103929. {
  103930. FLAC__ASSERT(0 != encoder);
  103931. FLAC__ASSERT(0 != encoder->private_);
  103932. FLAC__ASSERT(0 != encoder->protected_);
  103933. return encoder->protected_->rice_parameter_search_dist;
  103934. }
  103935. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103936. {
  103937. FLAC__ASSERT(0 != encoder);
  103938. FLAC__ASSERT(0 != encoder->private_);
  103939. FLAC__ASSERT(0 != encoder->protected_);
  103940. return encoder->protected_->total_samples_estimate;
  103941. }
  103942. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103943. {
  103944. unsigned i, j = 0, channel;
  103945. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103946. FLAC__ASSERT(0 != encoder);
  103947. FLAC__ASSERT(0 != encoder->private_);
  103948. FLAC__ASSERT(0 != encoder->protected_);
  103949. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103950. do {
  103951. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103952. if(encoder->protected_->verify)
  103953. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103954. for(channel = 0; channel < channels; channel++)
  103955. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103956. if(encoder->protected_->do_mid_side_stereo) {
  103957. FLAC__ASSERT(channels == 2);
  103958. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103959. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103960. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103961. 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' ! */
  103962. }
  103963. }
  103964. else
  103965. j += n;
  103966. encoder->private_->current_sample_number += n;
  103967. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103968. if(encoder->private_->current_sample_number > blocksize) {
  103969. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103970. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103971. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103972. return false;
  103973. /* move unprocessed overread samples to beginnings of arrays */
  103974. for(channel = 0; channel < channels; channel++)
  103975. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103976. if(encoder->protected_->do_mid_side_stereo) {
  103977. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103978. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103979. }
  103980. encoder->private_->current_sample_number = 1;
  103981. }
  103982. } while(j < samples);
  103983. return true;
  103984. }
  103985. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103986. {
  103987. unsigned i, j, k, channel;
  103988. FLAC__int32 x, mid, side;
  103989. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103990. FLAC__ASSERT(0 != encoder);
  103991. FLAC__ASSERT(0 != encoder->private_);
  103992. FLAC__ASSERT(0 != encoder->protected_);
  103993. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103994. j = k = 0;
  103995. /*
  103996. * we have several flavors of the same basic loop, optimized for
  103997. * different conditions:
  103998. */
  103999. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  104000. /*
  104001. * stereo coding: unroll channel loop
  104002. */
  104003. do {
  104004. if(encoder->protected_->verify)
  104005. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  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[0][i] = mid = side = buffer[k++];
  104009. x = buffer[k++];
  104010. encoder->private_->integer_signal[1][i] = x;
  104011. mid += x;
  104012. side -= x;
  104013. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  104014. encoder->private_->integer_signal_mid_side[1][i] = side;
  104015. encoder->private_->integer_signal_mid_side[0][i] = mid;
  104016. }
  104017. encoder->private_->current_sample_number = i;
  104018. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104019. if(i > blocksize) {
  104020. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104021. return false;
  104022. /* move unprocessed overread samples to beginnings of arrays */
  104023. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104024. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104025. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  104026. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  104027. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104028. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104029. encoder->private_->current_sample_number = 1;
  104030. }
  104031. } while(j < samples);
  104032. }
  104033. else {
  104034. /*
  104035. * independent channel coding: buffer each channel in inner loop
  104036. */
  104037. do {
  104038. if(encoder->protected_->verify)
  104039. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104040. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104041. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104042. for(channel = 0; channel < channels; channel++)
  104043. encoder->private_->integer_signal[channel][i] = buffer[k++];
  104044. }
  104045. encoder->private_->current_sample_number = i;
  104046. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104047. if(i > blocksize) {
  104048. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104049. return false;
  104050. /* move unprocessed overread samples to beginnings of arrays */
  104051. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104052. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104053. for(channel = 0; channel < channels; channel++)
  104054. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104055. encoder->private_->current_sample_number = 1;
  104056. }
  104057. } while(j < samples);
  104058. }
  104059. return true;
  104060. }
  104061. /***********************************************************************
  104062. *
  104063. * Private class methods
  104064. *
  104065. ***********************************************************************/
  104066. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  104067. {
  104068. FLAC__ASSERT(0 != encoder);
  104069. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  104070. encoder->protected_->verify = true;
  104071. #else
  104072. encoder->protected_->verify = false;
  104073. #endif
  104074. encoder->protected_->streamable_subset = true;
  104075. encoder->protected_->do_md5 = true;
  104076. encoder->protected_->do_mid_side_stereo = false;
  104077. encoder->protected_->loose_mid_side_stereo = false;
  104078. encoder->protected_->channels = 2;
  104079. encoder->protected_->bits_per_sample = 16;
  104080. encoder->protected_->sample_rate = 44100;
  104081. encoder->protected_->blocksize = 0;
  104082. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104083. encoder->protected_->num_apodizations = 1;
  104084. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104085. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104086. #endif
  104087. encoder->protected_->max_lpc_order = 0;
  104088. encoder->protected_->qlp_coeff_precision = 0;
  104089. encoder->protected_->do_qlp_coeff_prec_search = false;
  104090. encoder->protected_->do_exhaustive_model_search = false;
  104091. encoder->protected_->do_escape_coding = false;
  104092. encoder->protected_->min_residual_partition_order = 0;
  104093. encoder->protected_->max_residual_partition_order = 0;
  104094. encoder->protected_->rice_parameter_search_dist = 0;
  104095. encoder->protected_->total_samples_estimate = 0;
  104096. encoder->protected_->metadata = 0;
  104097. encoder->protected_->num_metadata_blocks = 0;
  104098. encoder->private_->seek_table = 0;
  104099. encoder->private_->disable_constant_subframes = false;
  104100. encoder->private_->disable_fixed_subframes = false;
  104101. encoder->private_->disable_verbatim_subframes = false;
  104102. #if FLAC__HAS_OGG
  104103. encoder->private_->is_ogg = false;
  104104. #endif
  104105. encoder->private_->read_callback = 0;
  104106. encoder->private_->write_callback = 0;
  104107. encoder->private_->seek_callback = 0;
  104108. encoder->private_->tell_callback = 0;
  104109. encoder->private_->metadata_callback = 0;
  104110. encoder->private_->progress_callback = 0;
  104111. encoder->private_->client_data = 0;
  104112. #if FLAC__HAS_OGG
  104113. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104114. #endif
  104115. }
  104116. void free_(FLAC__StreamEncoder *encoder)
  104117. {
  104118. unsigned i, channel;
  104119. FLAC__ASSERT(0 != encoder);
  104120. if(encoder->protected_->metadata) {
  104121. free(encoder->protected_->metadata);
  104122. encoder->protected_->metadata = 0;
  104123. encoder->protected_->num_metadata_blocks = 0;
  104124. }
  104125. for(i = 0; i < encoder->protected_->channels; i++) {
  104126. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104127. free(encoder->private_->integer_signal_unaligned[i]);
  104128. encoder->private_->integer_signal_unaligned[i] = 0;
  104129. }
  104130. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104131. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104132. free(encoder->private_->real_signal_unaligned[i]);
  104133. encoder->private_->real_signal_unaligned[i] = 0;
  104134. }
  104135. #endif
  104136. }
  104137. for(i = 0; i < 2; i++) {
  104138. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104139. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104140. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104141. }
  104142. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104143. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104144. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104145. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104146. }
  104147. #endif
  104148. }
  104149. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104150. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104151. if(0 != encoder->private_->window_unaligned[i]) {
  104152. free(encoder->private_->window_unaligned[i]);
  104153. encoder->private_->window_unaligned[i] = 0;
  104154. }
  104155. }
  104156. if(0 != encoder->private_->windowed_signal_unaligned) {
  104157. free(encoder->private_->windowed_signal_unaligned);
  104158. encoder->private_->windowed_signal_unaligned = 0;
  104159. }
  104160. #endif
  104161. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104162. for(i = 0; i < 2; i++) {
  104163. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104164. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104165. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104166. }
  104167. }
  104168. }
  104169. for(channel = 0; channel < 2; channel++) {
  104170. for(i = 0; i < 2; i++) {
  104171. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104172. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104173. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104174. }
  104175. }
  104176. }
  104177. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104178. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104179. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104180. }
  104181. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104182. free(encoder->private_->raw_bits_per_partition_unaligned);
  104183. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104184. }
  104185. if(encoder->protected_->verify) {
  104186. for(i = 0; i < encoder->protected_->channels; i++) {
  104187. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104188. free(encoder->private_->verify.input_fifo.data[i]);
  104189. encoder->private_->verify.input_fifo.data[i] = 0;
  104190. }
  104191. }
  104192. }
  104193. FLAC__bitwriter_free(encoder->private_->frame);
  104194. }
  104195. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104196. {
  104197. FLAC__bool ok;
  104198. unsigned i, channel;
  104199. FLAC__ASSERT(new_blocksize > 0);
  104200. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104201. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104202. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104203. if(new_blocksize <= encoder->private_->input_capacity)
  104204. return true;
  104205. ok = true;
  104206. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104207. * requires that the input arrays (in our case the integer signals)
  104208. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104209. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104210. */
  104211. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104212. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104213. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104214. encoder->private_->integer_signal[i] += 4;
  104215. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104216. #if 0 /* @@@ currently unused */
  104217. if(encoder->protected_->max_lpc_order > 0)
  104218. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104219. #endif
  104220. #endif
  104221. }
  104222. for(i = 0; ok && i < 2; i++) {
  104223. 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]);
  104224. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104225. encoder->private_->integer_signal_mid_side[i] += 4;
  104226. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104227. #if 0 /* @@@ currently unused */
  104228. if(encoder->protected_->max_lpc_order > 0)
  104229. 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]);
  104230. #endif
  104231. #endif
  104232. }
  104233. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104234. if(ok && encoder->protected_->max_lpc_order > 0) {
  104235. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104236. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104237. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104238. }
  104239. #endif
  104240. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104241. for(i = 0; ok && i < 2; i++) {
  104242. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104243. }
  104244. }
  104245. for(channel = 0; ok && channel < 2; channel++) {
  104246. for(i = 0; ok && i < 2; i++) {
  104247. 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]);
  104248. }
  104249. }
  104250. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104251. /*@@@ 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) */
  104252. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104253. if(encoder->protected_->do_escape_coding)
  104254. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104255. /* now adjust the windows if the blocksize has changed */
  104256. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104257. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104258. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104259. switch(encoder->protected_->apodizations[i].type) {
  104260. case FLAC__APODIZATION_BARTLETT:
  104261. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104262. break;
  104263. case FLAC__APODIZATION_BARTLETT_HANN:
  104264. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104265. break;
  104266. case FLAC__APODIZATION_BLACKMAN:
  104267. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104268. break;
  104269. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104270. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104271. break;
  104272. case FLAC__APODIZATION_CONNES:
  104273. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104274. break;
  104275. case FLAC__APODIZATION_FLATTOP:
  104276. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104277. break;
  104278. case FLAC__APODIZATION_GAUSS:
  104279. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104280. break;
  104281. case FLAC__APODIZATION_HAMMING:
  104282. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104283. break;
  104284. case FLAC__APODIZATION_HANN:
  104285. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104286. break;
  104287. case FLAC__APODIZATION_KAISER_BESSEL:
  104288. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104289. break;
  104290. case FLAC__APODIZATION_NUTTALL:
  104291. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104292. break;
  104293. case FLAC__APODIZATION_RECTANGLE:
  104294. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104295. break;
  104296. case FLAC__APODIZATION_TRIANGLE:
  104297. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104298. break;
  104299. case FLAC__APODIZATION_TUKEY:
  104300. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104301. break;
  104302. case FLAC__APODIZATION_WELCH:
  104303. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104304. break;
  104305. default:
  104306. FLAC__ASSERT(0);
  104307. /* double protection */
  104308. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104309. break;
  104310. }
  104311. }
  104312. }
  104313. #endif
  104314. if(ok)
  104315. encoder->private_->input_capacity = new_blocksize;
  104316. else
  104317. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104318. return ok;
  104319. }
  104320. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104321. {
  104322. const FLAC__byte *buffer;
  104323. size_t bytes;
  104324. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104325. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104326. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104327. return false;
  104328. }
  104329. if(encoder->protected_->verify) {
  104330. encoder->private_->verify.output.data = buffer;
  104331. encoder->private_->verify.output.bytes = bytes;
  104332. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104333. encoder->private_->verify.needs_magic_hack = true;
  104334. }
  104335. else {
  104336. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104337. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104338. FLAC__bitwriter_clear(encoder->private_->frame);
  104339. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104340. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104341. return false;
  104342. }
  104343. }
  104344. }
  104345. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104346. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104347. FLAC__bitwriter_clear(encoder->private_->frame);
  104348. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104349. return false;
  104350. }
  104351. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104352. FLAC__bitwriter_clear(encoder->private_->frame);
  104353. if(samples > 0) {
  104354. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104355. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104356. }
  104357. return true;
  104358. }
  104359. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104360. {
  104361. FLAC__StreamEncoderWriteStatus status;
  104362. FLAC__uint64 output_position = 0;
  104363. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104364. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104365. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104366. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104367. }
  104368. /*
  104369. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104370. */
  104371. if(samples == 0) {
  104372. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104373. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104374. encoder->protected_->streaminfo_offset = output_position;
  104375. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104376. encoder->protected_->seektable_offset = output_position;
  104377. }
  104378. /*
  104379. * Mark the current seek point if hit (if audio_offset == 0 that
  104380. * means we're still writing metadata and haven't hit the first
  104381. * frame yet)
  104382. */
  104383. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104384. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104385. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104386. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104387. FLAC__uint64 test_sample;
  104388. unsigned i;
  104389. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104390. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104391. if(test_sample > frame_last_sample) {
  104392. break;
  104393. }
  104394. else if(test_sample >= frame_first_sample) {
  104395. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104396. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104397. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104398. encoder->private_->first_seekpoint_to_check++;
  104399. /* DO NOT: "break;" and here's why:
  104400. * The seektable template may contain more than one target
  104401. * sample for any given frame; we will keep looping, generating
  104402. * duplicate seekpoints for them, and we'll clean it up later,
  104403. * just before writing the seektable back to the metadata.
  104404. */
  104405. }
  104406. else {
  104407. encoder->private_->first_seekpoint_to_check++;
  104408. }
  104409. }
  104410. }
  104411. #if FLAC__HAS_OGG
  104412. if(encoder->private_->is_ogg) {
  104413. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104414. &encoder->protected_->ogg_encoder_aspect,
  104415. buffer,
  104416. bytes,
  104417. samples,
  104418. encoder->private_->current_frame_number,
  104419. is_last_block,
  104420. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104421. encoder,
  104422. encoder->private_->client_data
  104423. );
  104424. }
  104425. else
  104426. #endif
  104427. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104428. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104429. encoder->private_->bytes_written += bytes;
  104430. encoder->private_->samples_written += samples;
  104431. /* we keep a high watermark on the number of frames written because
  104432. * when the encoder goes back to write metadata, 'current_frame'
  104433. * will drop back to 0.
  104434. */
  104435. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104436. }
  104437. else
  104438. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104439. return status;
  104440. }
  104441. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104442. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104443. {
  104444. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104445. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104446. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104447. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104448. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104449. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104450. FLAC__StreamEncoderSeekStatus seek_status;
  104451. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104452. /* All this is based on intimate knowledge of the stream header
  104453. * layout, but a change to the header format that would break this
  104454. * would also break all streams encoded in the previous format.
  104455. */
  104456. /*
  104457. * Write MD5 signature
  104458. */
  104459. {
  104460. const unsigned md5_offset =
  104461. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104462. (
  104463. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104464. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104465. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104466. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104467. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104468. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104469. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104470. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104471. ) / 8;
  104472. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104473. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104474. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104475. return;
  104476. }
  104477. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104478. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104479. return;
  104480. }
  104481. }
  104482. /*
  104483. * Write total samples
  104484. */
  104485. {
  104486. const unsigned total_samples_byte_offset =
  104487. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104488. (
  104489. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104490. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104491. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104492. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104493. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104494. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104495. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104496. - 4
  104497. ) / 8;
  104498. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104499. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104500. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104501. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104502. b[4] = (FLAC__byte)(samples & 0xFF);
  104503. 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) {
  104504. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104505. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104506. return;
  104507. }
  104508. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104509. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104510. return;
  104511. }
  104512. }
  104513. /*
  104514. * Write min/max framesize
  104515. */
  104516. {
  104517. const unsigned min_framesize_offset =
  104518. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104519. (
  104520. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104521. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104522. ) / 8;
  104523. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104524. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104525. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104526. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104527. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104528. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104529. 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) {
  104530. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104531. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104532. return;
  104533. }
  104534. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104535. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104536. return;
  104537. }
  104538. }
  104539. /*
  104540. * Write seektable
  104541. */
  104542. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104543. unsigned i;
  104544. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104545. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104546. 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) {
  104547. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104548. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104549. return;
  104550. }
  104551. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104552. FLAC__uint64 xx;
  104553. unsigned x;
  104554. xx = encoder->private_->seek_table->points[i].sample_number;
  104555. b[7] = (FLAC__byte)xx; xx >>= 8;
  104556. b[6] = (FLAC__byte)xx; xx >>= 8;
  104557. b[5] = (FLAC__byte)xx; xx >>= 8;
  104558. b[4] = (FLAC__byte)xx; xx >>= 8;
  104559. b[3] = (FLAC__byte)xx; xx >>= 8;
  104560. b[2] = (FLAC__byte)xx; xx >>= 8;
  104561. b[1] = (FLAC__byte)xx; xx >>= 8;
  104562. b[0] = (FLAC__byte)xx; xx >>= 8;
  104563. xx = encoder->private_->seek_table->points[i].stream_offset;
  104564. b[15] = (FLAC__byte)xx; xx >>= 8;
  104565. b[14] = (FLAC__byte)xx; xx >>= 8;
  104566. b[13] = (FLAC__byte)xx; xx >>= 8;
  104567. b[12] = (FLAC__byte)xx; xx >>= 8;
  104568. b[11] = (FLAC__byte)xx; xx >>= 8;
  104569. b[10] = (FLAC__byte)xx; xx >>= 8;
  104570. b[9] = (FLAC__byte)xx; xx >>= 8;
  104571. b[8] = (FLAC__byte)xx; xx >>= 8;
  104572. x = encoder->private_->seek_table->points[i].frame_samples;
  104573. b[17] = (FLAC__byte)x; x >>= 8;
  104574. b[16] = (FLAC__byte)x; x >>= 8;
  104575. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104576. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104577. return;
  104578. }
  104579. }
  104580. }
  104581. }
  104582. #if FLAC__HAS_OGG
  104583. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104584. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104585. {
  104586. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104587. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104588. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104589. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104590. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104591. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104592. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104593. FLAC__STREAM_SYNC_LENGTH
  104594. ;
  104595. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104596. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104597. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104598. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104599. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104600. ogg_page page;
  104601. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104602. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104603. /* Pre-check that client supports seeking, since we don't want the
  104604. * ogg_helper code to ever have to deal with this condition.
  104605. */
  104606. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104607. return;
  104608. /* All this is based on intimate knowledge of the stream header
  104609. * layout, but a change to the header format that would break this
  104610. * would also break all streams encoded in the previous format.
  104611. */
  104612. /**
  104613. ** Write STREAMINFO stats
  104614. **/
  104615. simple_ogg_page__init(&page);
  104616. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104617. simple_ogg_page__clear(&page);
  104618. return; /* state already set */
  104619. }
  104620. /*
  104621. * Write MD5 signature
  104622. */
  104623. {
  104624. const unsigned md5_offset =
  104625. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104626. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104627. (
  104628. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104629. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104630. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104631. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104632. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104633. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104634. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104635. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104636. ) / 8;
  104637. if(md5_offset + 16 > (unsigned)page.body_len) {
  104638. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104639. simple_ogg_page__clear(&page);
  104640. return;
  104641. }
  104642. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104643. }
  104644. /*
  104645. * Write total samples
  104646. */
  104647. {
  104648. const unsigned total_samples_byte_offset =
  104649. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104650. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104651. (
  104652. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104653. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104654. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104655. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104656. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104657. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104658. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104659. - 4
  104660. ) / 8;
  104661. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104662. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104663. simple_ogg_page__clear(&page);
  104664. return;
  104665. }
  104666. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104667. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104668. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104669. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104670. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104671. b[4] = (FLAC__byte)(samples & 0xFF);
  104672. memcpy(page.body + total_samples_byte_offset, b, 5);
  104673. }
  104674. /*
  104675. * Write min/max framesize
  104676. */
  104677. {
  104678. const unsigned min_framesize_offset =
  104679. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104680. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104681. (
  104682. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104683. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104684. ) / 8;
  104685. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104686. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104687. simple_ogg_page__clear(&page);
  104688. return;
  104689. }
  104690. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104691. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104692. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104693. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104694. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104695. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104696. memcpy(page.body + min_framesize_offset, b, 6);
  104697. }
  104698. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104699. simple_ogg_page__clear(&page);
  104700. return; /* state already set */
  104701. }
  104702. simple_ogg_page__clear(&page);
  104703. /*
  104704. * Write seektable
  104705. */
  104706. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104707. unsigned i;
  104708. FLAC__byte *p;
  104709. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104710. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104711. simple_ogg_page__init(&page);
  104712. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104713. simple_ogg_page__clear(&page);
  104714. return; /* state already set */
  104715. }
  104716. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104717. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104718. simple_ogg_page__clear(&page);
  104719. return;
  104720. }
  104721. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104722. FLAC__uint64 xx;
  104723. unsigned x;
  104724. xx = encoder->private_->seek_table->points[i].sample_number;
  104725. b[7] = (FLAC__byte)xx; xx >>= 8;
  104726. b[6] = (FLAC__byte)xx; xx >>= 8;
  104727. b[5] = (FLAC__byte)xx; xx >>= 8;
  104728. b[4] = (FLAC__byte)xx; xx >>= 8;
  104729. b[3] = (FLAC__byte)xx; xx >>= 8;
  104730. b[2] = (FLAC__byte)xx; xx >>= 8;
  104731. b[1] = (FLAC__byte)xx; xx >>= 8;
  104732. b[0] = (FLAC__byte)xx; xx >>= 8;
  104733. xx = encoder->private_->seek_table->points[i].stream_offset;
  104734. b[15] = (FLAC__byte)xx; xx >>= 8;
  104735. b[14] = (FLAC__byte)xx; xx >>= 8;
  104736. b[13] = (FLAC__byte)xx; xx >>= 8;
  104737. b[12] = (FLAC__byte)xx; xx >>= 8;
  104738. b[11] = (FLAC__byte)xx; xx >>= 8;
  104739. b[10] = (FLAC__byte)xx; xx >>= 8;
  104740. b[9] = (FLAC__byte)xx; xx >>= 8;
  104741. b[8] = (FLAC__byte)xx; xx >>= 8;
  104742. x = encoder->private_->seek_table->points[i].frame_samples;
  104743. b[17] = (FLAC__byte)x; x >>= 8;
  104744. b[16] = (FLAC__byte)x; x >>= 8;
  104745. memcpy(p, b, 18);
  104746. }
  104747. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104748. simple_ogg_page__clear(&page);
  104749. return; /* state already set */
  104750. }
  104751. simple_ogg_page__clear(&page);
  104752. }
  104753. }
  104754. #endif
  104755. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104756. {
  104757. FLAC__uint16 crc;
  104758. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104759. /*
  104760. * Accumulate raw signal to the MD5 signature
  104761. */
  104762. 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)) {
  104763. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104764. return false;
  104765. }
  104766. /*
  104767. * Process the frame header and subframes into the frame bitbuffer
  104768. */
  104769. if(!process_subframes_(encoder, is_fractional_block)) {
  104770. /* the above function sets the state for us in case of an error */
  104771. return false;
  104772. }
  104773. /*
  104774. * Zero-pad the frame to a byte_boundary
  104775. */
  104776. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104777. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104778. return false;
  104779. }
  104780. /*
  104781. * CRC-16 the whole thing
  104782. */
  104783. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104784. if(
  104785. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104786. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104787. ) {
  104788. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104789. return false;
  104790. }
  104791. /*
  104792. * Write it
  104793. */
  104794. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104795. /* the above function sets the state for us in case of an error */
  104796. return false;
  104797. }
  104798. /*
  104799. * Get ready for the next frame
  104800. */
  104801. encoder->private_->current_sample_number = 0;
  104802. encoder->private_->current_frame_number++;
  104803. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104804. return true;
  104805. }
  104806. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104807. {
  104808. FLAC__FrameHeader frame_header;
  104809. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104810. FLAC__bool do_independent, do_mid_side;
  104811. /*
  104812. * Calculate the min,max Rice partition orders
  104813. */
  104814. if(is_fractional_block) {
  104815. max_partition_order = 0;
  104816. }
  104817. else {
  104818. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104819. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104820. }
  104821. min_partition_order = min(min_partition_order, max_partition_order);
  104822. /*
  104823. * Setup the frame
  104824. */
  104825. frame_header.blocksize = encoder->protected_->blocksize;
  104826. frame_header.sample_rate = encoder->protected_->sample_rate;
  104827. frame_header.channels = encoder->protected_->channels;
  104828. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104829. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104830. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104831. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104832. /*
  104833. * Figure out what channel assignments to try
  104834. */
  104835. if(encoder->protected_->do_mid_side_stereo) {
  104836. if(encoder->protected_->loose_mid_side_stereo) {
  104837. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104838. do_independent = true;
  104839. do_mid_side = true;
  104840. }
  104841. else {
  104842. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104843. do_mid_side = !do_independent;
  104844. }
  104845. }
  104846. else {
  104847. do_independent = true;
  104848. do_mid_side = true;
  104849. }
  104850. }
  104851. else {
  104852. do_independent = true;
  104853. do_mid_side = false;
  104854. }
  104855. FLAC__ASSERT(do_independent || do_mid_side);
  104856. /*
  104857. * Check for wasted bits; set effective bps for each subframe
  104858. */
  104859. if(do_independent) {
  104860. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104861. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104862. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104863. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104864. }
  104865. }
  104866. if(do_mid_side) {
  104867. FLAC__ASSERT(encoder->protected_->channels == 2);
  104868. for(channel = 0; channel < 2; channel++) {
  104869. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104870. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104871. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104872. }
  104873. }
  104874. /*
  104875. * First do a normal encoding pass of each independent channel
  104876. */
  104877. if(do_independent) {
  104878. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104879. if(!
  104880. process_subframe_(
  104881. encoder,
  104882. min_partition_order,
  104883. max_partition_order,
  104884. &frame_header,
  104885. encoder->private_->subframe_bps[channel],
  104886. encoder->private_->integer_signal[channel],
  104887. encoder->private_->subframe_workspace_ptr[channel],
  104888. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104889. encoder->private_->residual_workspace[channel],
  104890. encoder->private_->best_subframe+channel,
  104891. encoder->private_->best_subframe_bits+channel
  104892. )
  104893. )
  104894. return false;
  104895. }
  104896. }
  104897. /*
  104898. * Now do mid and side channels if requested
  104899. */
  104900. if(do_mid_side) {
  104901. FLAC__ASSERT(encoder->protected_->channels == 2);
  104902. for(channel = 0; channel < 2; channel++) {
  104903. if(!
  104904. process_subframe_(
  104905. encoder,
  104906. min_partition_order,
  104907. max_partition_order,
  104908. &frame_header,
  104909. encoder->private_->subframe_bps_mid_side[channel],
  104910. encoder->private_->integer_signal_mid_side[channel],
  104911. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104912. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104913. encoder->private_->residual_workspace_mid_side[channel],
  104914. encoder->private_->best_subframe_mid_side+channel,
  104915. encoder->private_->best_subframe_bits_mid_side+channel
  104916. )
  104917. )
  104918. return false;
  104919. }
  104920. }
  104921. /*
  104922. * Compose the frame bitbuffer
  104923. */
  104924. if(do_mid_side) {
  104925. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104926. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104927. FLAC__ChannelAssignment channel_assignment;
  104928. FLAC__ASSERT(encoder->protected_->channels == 2);
  104929. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104930. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104931. }
  104932. else {
  104933. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104934. unsigned min_bits;
  104935. int ca;
  104936. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104937. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104938. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104939. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104940. FLAC__ASSERT(do_independent && do_mid_side);
  104941. /* We have to figure out which channel assignent results in the smallest frame */
  104942. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104943. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104944. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104945. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104946. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104947. min_bits = bits[channel_assignment];
  104948. for(ca = 1; ca <= 3; ca++) {
  104949. if(bits[ca] < min_bits) {
  104950. min_bits = bits[ca];
  104951. channel_assignment = (FLAC__ChannelAssignment)ca;
  104952. }
  104953. }
  104954. }
  104955. frame_header.channel_assignment = channel_assignment;
  104956. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104957. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104958. return false;
  104959. }
  104960. switch(channel_assignment) {
  104961. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104962. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104963. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104964. break;
  104965. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104966. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104967. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104968. break;
  104969. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104970. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104971. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104972. break;
  104973. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104974. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104975. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104976. break;
  104977. default:
  104978. FLAC__ASSERT(0);
  104979. }
  104980. switch(channel_assignment) {
  104981. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104982. left_bps = encoder->private_->subframe_bps [0];
  104983. right_bps = encoder->private_->subframe_bps [1];
  104984. break;
  104985. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104986. left_bps = encoder->private_->subframe_bps [0];
  104987. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104988. break;
  104989. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104990. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104991. right_bps = encoder->private_->subframe_bps [1];
  104992. break;
  104993. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104994. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104995. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104996. break;
  104997. default:
  104998. FLAC__ASSERT(0);
  104999. }
  105000. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  105001. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  105002. return false;
  105003. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  105004. return false;
  105005. }
  105006. else {
  105007. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105008. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105009. return false;
  105010. }
  105011. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105012. 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)) {
  105013. /* the above function sets the state for us in case of an error */
  105014. return false;
  105015. }
  105016. }
  105017. }
  105018. if(encoder->protected_->loose_mid_side_stereo) {
  105019. encoder->private_->loose_mid_side_stereo_frame_count++;
  105020. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  105021. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  105022. }
  105023. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  105024. return true;
  105025. }
  105026. FLAC__bool process_subframe_(
  105027. FLAC__StreamEncoder *encoder,
  105028. unsigned min_partition_order,
  105029. unsigned max_partition_order,
  105030. const FLAC__FrameHeader *frame_header,
  105031. unsigned subframe_bps,
  105032. const FLAC__int32 integer_signal[],
  105033. FLAC__Subframe *subframe[2],
  105034. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  105035. FLAC__int32 *residual[2],
  105036. unsigned *best_subframe,
  105037. unsigned *best_bits
  105038. )
  105039. {
  105040. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105041. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105042. #else
  105043. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105044. #endif
  105045. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105046. FLAC__double lpc_residual_bits_per_sample;
  105047. 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 */
  105048. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  105049. unsigned min_lpc_order, max_lpc_order, lpc_order;
  105050. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  105051. #endif
  105052. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  105053. unsigned rice_parameter;
  105054. unsigned _candidate_bits, _best_bits;
  105055. unsigned _best_subframe;
  105056. /* only use RICE2 partitions if stream bps > 16 */
  105057. 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;
  105058. FLAC__ASSERT(frame_header->blocksize > 0);
  105059. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  105060. _best_subframe = 0;
  105061. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  105062. _best_bits = UINT_MAX;
  105063. else
  105064. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105065. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  105066. unsigned signal_is_constant = false;
  105067. 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);
  105068. /* check for constant subframe */
  105069. if(
  105070. !encoder->private_->disable_constant_subframes &&
  105071. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105072. fixed_residual_bits_per_sample[1] == 0.0
  105073. #else
  105074. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  105075. #endif
  105076. ) {
  105077. /* the above means it's possible all samples are the same value; now double-check it: */
  105078. unsigned i;
  105079. signal_is_constant = true;
  105080. for(i = 1; i < frame_header->blocksize; i++) {
  105081. if(integer_signal[0] != integer_signal[i]) {
  105082. signal_is_constant = false;
  105083. break;
  105084. }
  105085. }
  105086. }
  105087. if(signal_is_constant) {
  105088. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105089. if(_candidate_bits < _best_bits) {
  105090. _best_subframe = !_best_subframe;
  105091. _best_bits = _candidate_bits;
  105092. }
  105093. }
  105094. else {
  105095. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105096. /* encode fixed */
  105097. if(encoder->protected_->do_exhaustive_model_search) {
  105098. min_fixed_order = 0;
  105099. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105100. }
  105101. else {
  105102. min_fixed_order = max_fixed_order = guess_fixed_order;
  105103. }
  105104. if(max_fixed_order >= frame_header->blocksize)
  105105. max_fixed_order = frame_header->blocksize - 1;
  105106. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105107. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105108. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105109. continue; /* don't even try */
  105110. 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 */
  105111. #else
  105112. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105113. continue; /* don't even try */
  105114. 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 */
  105115. #endif
  105116. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105117. if(rice_parameter >= rice_parameter_limit) {
  105118. #ifdef DEBUG_VERBOSE
  105119. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105120. #endif
  105121. rice_parameter = rice_parameter_limit - 1;
  105122. }
  105123. _candidate_bits =
  105124. evaluate_fixed_subframe_(
  105125. encoder,
  105126. integer_signal,
  105127. residual[!_best_subframe],
  105128. encoder->private_->abs_residual_partition_sums,
  105129. encoder->private_->raw_bits_per_partition,
  105130. frame_header->blocksize,
  105131. subframe_bps,
  105132. fixed_order,
  105133. rice_parameter,
  105134. rice_parameter_limit,
  105135. min_partition_order,
  105136. max_partition_order,
  105137. encoder->protected_->do_escape_coding,
  105138. encoder->protected_->rice_parameter_search_dist,
  105139. subframe[!_best_subframe],
  105140. partitioned_rice_contents[!_best_subframe]
  105141. );
  105142. if(_candidate_bits < _best_bits) {
  105143. _best_subframe = !_best_subframe;
  105144. _best_bits = _candidate_bits;
  105145. }
  105146. }
  105147. }
  105148. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105149. /* encode lpc */
  105150. if(encoder->protected_->max_lpc_order > 0) {
  105151. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105152. max_lpc_order = frame_header->blocksize-1;
  105153. else
  105154. max_lpc_order = encoder->protected_->max_lpc_order;
  105155. if(max_lpc_order > 0) {
  105156. unsigned a;
  105157. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105158. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105159. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105160. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105161. if(autoc[0] != 0.0) {
  105162. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105163. if(encoder->protected_->do_exhaustive_model_search) {
  105164. min_lpc_order = 1;
  105165. }
  105166. else {
  105167. const unsigned guess_lpc_order =
  105168. FLAC__lpc_compute_best_order(
  105169. lpc_error,
  105170. max_lpc_order,
  105171. frame_header->blocksize,
  105172. subframe_bps + (
  105173. encoder->protected_->do_qlp_coeff_prec_search?
  105174. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105175. encoder->protected_->qlp_coeff_precision
  105176. )
  105177. );
  105178. min_lpc_order = max_lpc_order = guess_lpc_order;
  105179. }
  105180. if(max_lpc_order >= frame_header->blocksize)
  105181. max_lpc_order = frame_header->blocksize - 1;
  105182. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105183. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105184. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105185. continue; /* don't even try */
  105186. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105187. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105188. if(rice_parameter >= rice_parameter_limit) {
  105189. #ifdef DEBUG_VERBOSE
  105190. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105191. #endif
  105192. rice_parameter = rice_parameter_limit - 1;
  105193. }
  105194. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105195. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105196. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105197. if(subframe_bps <= 17) {
  105198. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105199. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105200. }
  105201. else
  105202. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105203. }
  105204. else {
  105205. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105206. }
  105207. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105208. _candidate_bits =
  105209. evaluate_lpc_subframe_(
  105210. encoder,
  105211. integer_signal,
  105212. residual[!_best_subframe],
  105213. encoder->private_->abs_residual_partition_sums,
  105214. encoder->private_->raw_bits_per_partition,
  105215. encoder->private_->lp_coeff[lpc_order-1],
  105216. frame_header->blocksize,
  105217. subframe_bps,
  105218. lpc_order,
  105219. qlp_coeff_precision,
  105220. rice_parameter,
  105221. rice_parameter_limit,
  105222. min_partition_order,
  105223. max_partition_order,
  105224. encoder->protected_->do_escape_coding,
  105225. encoder->protected_->rice_parameter_search_dist,
  105226. subframe[!_best_subframe],
  105227. partitioned_rice_contents[!_best_subframe]
  105228. );
  105229. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105230. if(_candidate_bits < _best_bits) {
  105231. _best_subframe = !_best_subframe;
  105232. _best_bits = _candidate_bits;
  105233. }
  105234. }
  105235. }
  105236. }
  105237. }
  105238. }
  105239. }
  105240. }
  105241. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105242. }
  105243. }
  105244. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105245. if(_best_bits == UINT_MAX) {
  105246. FLAC__ASSERT(_best_subframe == 0);
  105247. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105248. }
  105249. *best_subframe = _best_subframe;
  105250. *best_bits = _best_bits;
  105251. return true;
  105252. }
  105253. FLAC__bool add_subframe_(
  105254. FLAC__StreamEncoder *encoder,
  105255. unsigned blocksize,
  105256. unsigned subframe_bps,
  105257. const FLAC__Subframe *subframe,
  105258. FLAC__BitWriter *frame
  105259. )
  105260. {
  105261. switch(subframe->type) {
  105262. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105263. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105264. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105265. return false;
  105266. }
  105267. break;
  105268. case FLAC__SUBFRAME_TYPE_FIXED:
  105269. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105270. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105271. return false;
  105272. }
  105273. break;
  105274. case FLAC__SUBFRAME_TYPE_LPC:
  105275. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105276. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105277. return false;
  105278. }
  105279. break;
  105280. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105281. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105282. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105283. return false;
  105284. }
  105285. break;
  105286. default:
  105287. FLAC__ASSERT(0);
  105288. }
  105289. return true;
  105290. }
  105291. #define SPOTCHECK_ESTIMATE 0
  105292. #if SPOTCHECK_ESTIMATE
  105293. static void spotcheck_subframe_estimate_(
  105294. FLAC__StreamEncoder *encoder,
  105295. unsigned blocksize,
  105296. unsigned subframe_bps,
  105297. const FLAC__Subframe *subframe,
  105298. unsigned estimate
  105299. )
  105300. {
  105301. FLAC__bool ret;
  105302. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105303. if(frame == 0) {
  105304. fprintf(stderr, "EST: can't allocate frame\n");
  105305. return;
  105306. }
  105307. if(!FLAC__bitwriter_init(frame)) {
  105308. fprintf(stderr, "EST: can't init frame\n");
  105309. return;
  105310. }
  105311. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105312. FLAC__ASSERT(ret);
  105313. {
  105314. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105315. if(estimate != actual)
  105316. 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);
  105317. }
  105318. FLAC__bitwriter_delete(frame);
  105319. }
  105320. #endif
  105321. unsigned evaluate_constant_subframe_(
  105322. FLAC__StreamEncoder *encoder,
  105323. const FLAC__int32 signal,
  105324. unsigned blocksize,
  105325. unsigned subframe_bps,
  105326. FLAC__Subframe *subframe
  105327. )
  105328. {
  105329. unsigned estimate;
  105330. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105331. subframe->data.constant.value = signal;
  105332. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105333. #if SPOTCHECK_ESTIMATE
  105334. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105335. #else
  105336. (void)encoder, (void)blocksize;
  105337. #endif
  105338. return estimate;
  105339. }
  105340. unsigned evaluate_fixed_subframe_(
  105341. FLAC__StreamEncoder *encoder,
  105342. const FLAC__int32 signal[],
  105343. FLAC__int32 residual[],
  105344. FLAC__uint64 abs_residual_partition_sums[],
  105345. unsigned raw_bits_per_partition[],
  105346. unsigned blocksize,
  105347. unsigned subframe_bps,
  105348. unsigned order,
  105349. unsigned rice_parameter,
  105350. unsigned rice_parameter_limit,
  105351. unsigned min_partition_order,
  105352. unsigned max_partition_order,
  105353. FLAC__bool do_escape_coding,
  105354. unsigned rice_parameter_search_dist,
  105355. FLAC__Subframe *subframe,
  105356. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105357. )
  105358. {
  105359. unsigned i, residual_bits, estimate;
  105360. const unsigned residual_samples = blocksize - order;
  105361. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105362. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105363. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105364. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105365. subframe->data.fixed.residual = residual;
  105366. residual_bits =
  105367. find_best_partition_order_(
  105368. encoder->private_,
  105369. residual,
  105370. abs_residual_partition_sums,
  105371. raw_bits_per_partition,
  105372. residual_samples,
  105373. order,
  105374. rice_parameter,
  105375. rice_parameter_limit,
  105376. min_partition_order,
  105377. max_partition_order,
  105378. subframe_bps,
  105379. do_escape_coding,
  105380. rice_parameter_search_dist,
  105381. &subframe->data.fixed.entropy_coding_method
  105382. );
  105383. subframe->data.fixed.order = order;
  105384. for(i = 0; i < order; i++)
  105385. subframe->data.fixed.warmup[i] = signal[i];
  105386. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105387. #if SPOTCHECK_ESTIMATE
  105388. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105389. #endif
  105390. return estimate;
  105391. }
  105392. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105393. unsigned evaluate_lpc_subframe_(
  105394. FLAC__StreamEncoder *encoder,
  105395. const FLAC__int32 signal[],
  105396. FLAC__int32 residual[],
  105397. FLAC__uint64 abs_residual_partition_sums[],
  105398. unsigned raw_bits_per_partition[],
  105399. const FLAC__real lp_coeff[],
  105400. unsigned blocksize,
  105401. unsigned subframe_bps,
  105402. unsigned order,
  105403. unsigned qlp_coeff_precision,
  105404. unsigned rice_parameter,
  105405. unsigned rice_parameter_limit,
  105406. unsigned min_partition_order,
  105407. unsigned max_partition_order,
  105408. FLAC__bool do_escape_coding,
  105409. unsigned rice_parameter_search_dist,
  105410. FLAC__Subframe *subframe,
  105411. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105412. )
  105413. {
  105414. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105415. unsigned i, residual_bits, estimate;
  105416. int quantization, ret;
  105417. const unsigned residual_samples = blocksize - order;
  105418. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105419. if(subframe_bps <= 16) {
  105420. FLAC__ASSERT(order > 0);
  105421. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105422. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105423. }
  105424. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105425. if(ret != 0)
  105426. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105427. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105428. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105429. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105430. else
  105431. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105432. else
  105433. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105434. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105435. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105436. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105437. subframe->data.lpc.residual = residual;
  105438. residual_bits =
  105439. find_best_partition_order_(
  105440. encoder->private_,
  105441. residual,
  105442. abs_residual_partition_sums,
  105443. raw_bits_per_partition,
  105444. residual_samples,
  105445. order,
  105446. rice_parameter,
  105447. rice_parameter_limit,
  105448. min_partition_order,
  105449. max_partition_order,
  105450. subframe_bps,
  105451. do_escape_coding,
  105452. rice_parameter_search_dist,
  105453. &subframe->data.lpc.entropy_coding_method
  105454. );
  105455. subframe->data.lpc.order = order;
  105456. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105457. subframe->data.lpc.quantization_level = quantization;
  105458. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105459. for(i = 0; i < order; i++)
  105460. subframe->data.lpc.warmup[i] = signal[i];
  105461. 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;
  105462. #if SPOTCHECK_ESTIMATE
  105463. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105464. #endif
  105465. return estimate;
  105466. }
  105467. #endif
  105468. unsigned evaluate_verbatim_subframe_(
  105469. FLAC__StreamEncoder *encoder,
  105470. const FLAC__int32 signal[],
  105471. unsigned blocksize,
  105472. unsigned subframe_bps,
  105473. FLAC__Subframe *subframe
  105474. )
  105475. {
  105476. unsigned estimate;
  105477. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105478. subframe->data.verbatim.data = signal;
  105479. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105480. #if SPOTCHECK_ESTIMATE
  105481. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105482. #else
  105483. (void)encoder;
  105484. #endif
  105485. return estimate;
  105486. }
  105487. unsigned find_best_partition_order_(
  105488. FLAC__StreamEncoderPrivate *private_,
  105489. const FLAC__int32 residual[],
  105490. FLAC__uint64 abs_residual_partition_sums[],
  105491. unsigned raw_bits_per_partition[],
  105492. unsigned residual_samples,
  105493. unsigned predictor_order,
  105494. unsigned rice_parameter,
  105495. unsigned rice_parameter_limit,
  105496. unsigned min_partition_order,
  105497. unsigned max_partition_order,
  105498. unsigned bps,
  105499. FLAC__bool do_escape_coding,
  105500. unsigned rice_parameter_search_dist,
  105501. FLAC__EntropyCodingMethod *best_ecm
  105502. )
  105503. {
  105504. unsigned residual_bits, best_residual_bits = 0;
  105505. unsigned best_parameters_index = 0;
  105506. unsigned best_partition_order = 0;
  105507. const unsigned blocksize = residual_samples + predictor_order;
  105508. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105509. min_partition_order = min(min_partition_order, max_partition_order);
  105510. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105511. if(do_escape_coding)
  105512. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105513. {
  105514. int partition_order;
  105515. unsigned sum;
  105516. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105517. if(!
  105518. set_partitioned_rice_(
  105519. #ifdef EXACT_RICE_BITS_CALCULATION
  105520. residual,
  105521. #endif
  105522. abs_residual_partition_sums+sum,
  105523. raw_bits_per_partition+sum,
  105524. residual_samples,
  105525. predictor_order,
  105526. rice_parameter,
  105527. rice_parameter_limit,
  105528. rice_parameter_search_dist,
  105529. (unsigned)partition_order,
  105530. do_escape_coding,
  105531. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105532. &residual_bits
  105533. )
  105534. )
  105535. {
  105536. FLAC__ASSERT(best_residual_bits != 0);
  105537. break;
  105538. }
  105539. sum += 1u << partition_order;
  105540. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105541. best_residual_bits = residual_bits;
  105542. best_parameters_index = !best_parameters_index;
  105543. best_partition_order = partition_order;
  105544. }
  105545. }
  105546. }
  105547. best_ecm->data.partitioned_rice.order = best_partition_order;
  105548. {
  105549. /*
  105550. * We are allowed to de-const the pointer based on our special
  105551. * knowledge; it is const to the outside world.
  105552. */
  105553. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105554. unsigned partition;
  105555. /* save best parameters and raw_bits */
  105556. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105557. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105558. if(do_escape_coding)
  105559. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105560. /*
  105561. * Now need to check if the type should be changed to
  105562. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105563. * size of the rice parameters.
  105564. */
  105565. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105566. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105567. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105568. break;
  105569. }
  105570. }
  105571. }
  105572. return best_residual_bits;
  105573. }
  105574. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105575. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105576. const FLAC__int32 residual[],
  105577. FLAC__uint64 abs_residual_partition_sums[],
  105578. unsigned blocksize,
  105579. unsigned predictor_order,
  105580. unsigned min_partition_order,
  105581. unsigned max_partition_order
  105582. );
  105583. #endif
  105584. void precompute_partition_info_sums_(
  105585. const FLAC__int32 residual[],
  105586. FLAC__uint64 abs_residual_partition_sums[],
  105587. unsigned residual_samples,
  105588. unsigned predictor_order,
  105589. unsigned min_partition_order,
  105590. unsigned max_partition_order,
  105591. unsigned bps
  105592. )
  105593. {
  105594. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105595. unsigned partitions = 1u << max_partition_order;
  105596. FLAC__ASSERT(default_partition_samples > predictor_order);
  105597. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105598. /* slightly pessimistic but still catches all common cases */
  105599. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105600. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105601. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105602. return;
  105603. }
  105604. #endif
  105605. /* first do max_partition_order */
  105606. {
  105607. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105608. /* slightly pessimistic but still catches all common cases */
  105609. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105610. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105611. FLAC__uint32 abs_residual_partition_sum;
  105612. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105613. end += default_partition_samples;
  105614. abs_residual_partition_sum = 0;
  105615. for( ; residual_sample < end; residual_sample++)
  105616. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105617. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105618. }
  105619. }
  105620. else { /* have to pessimistically use 64 bits for accumulator */
  105621. FLAC__uint64 abs_residual_partition_sum;
  105622. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105623. end += default_partition_samples;
  105624. abs_residual_partition_sum = 0;
  105625. for( ; residual_sample < end; residual_sample++)
  105626. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105627. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105628. }
  105629. }
  105630. }
  105631. /* now merge partitions for lower orders */
  105632. {
  105633. unsigned from_partition = 0, to_partition = partitions;
  105634. int partition_order;
  105635. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105636. unsigned i;
  105637. partitions >>= 1;
  105638. for(i = 0; i < partitions; i++) {
  105639. abs_residual_partition_sums[to_partition++] =
  105640. abs_residual_partition_sums[from_partition ] +
  105641. abs_residual_partition_sums[from_partition+1];
  105642. from_partition += 2;
  105643. }
  105644. }
  105645. }
  105646. }
  105647. void precompute_partition_info_escapes_(
  105648. const FLAC__int32 residual[],
  105649. unsigned raw_bits_per_partition[],
  105650. unsigned residual_samples,
  105651. unsigned predictor_order,
  105652. unsigned min_partition_order,
  105653. unsigned max_partition_order
  105654. )
  105655. {
  105656. int partition_order;
  105657. unsigned from_partition, to_partition = 0;
  105658. const unsigned blocksize = residual_samples + predictor_order;
  105659. /* first do max_partition_order */
  105660. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105661. FLAC__int32 r;
  105662. FLAC__uint32 rmax;
  105663. unsigned partition, partition_sample, partition_samples, residual_sample;
  105664. const unsigned partitions = 1u << partition_order;
  105665. const unsigned default_partition_samples = blocksize >> partition_order;
  105666. FLAC__ASSERT(default_partition_samples > predictor_order);
  105667. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105668. partition_samples = default_partition_samples;
  105669. if(partition == 0)
  105670. partition_samples -= predictor_order;
  105671. rmax = 0;
  105672. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105673. r = residual[residual_sample++];
  105674. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105675. if(r < 0)
  105676. rmax |= ~r;
  105677. else
  105678. rmax |= r;
  105679. }
  105680. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105681. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105682. }
  105683. to_partition = partitions;
  105684. break; /*@@@ yuck, should remove the 'for' loop instead */
  105685. }
  105686. /* now merge partitions for lower orders */
  105687. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105688. unsigned m;
  105689. unsigned i;
  105690. const unsigned partitions = 1u << partition_order;
  105691. for(i = 0; i < partitions; i++) {
  105692. m = raw_bits_per_partition[from_partition];
  105693. from_partition++;
  105694. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105695. from_partition++;
  105696. to_partition++;
  105697. }
  105698. }
  105699. }
  105700. #ifdef EXACT_RICE_BITS_CALCULATION
  105701. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105702. const unsigned rice_parameter,
  105703. const unsigned partition_samples,
  105704. const FLAC__int32 *residual
  105705. )
  105706. {
  105707. unsigned i, partition_bits =
  105708. 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 */
  105709. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105710. ;
  105711. for(i = 0; i < partition_samples; i++)
  105712. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105713. return partition_bits;
  105714. }
  105715. #else
  105716. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105717. const unsigned rice_parameter,
  105718. const unsigned partition_samples,
  105719. const FLAC__uint64 abs_residual_partition_sum
  105720. )
  105721. {
  105722. return
  105723. 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 */
  105724. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105725. (
  105726. rice_parameter?
  105727. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105728. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105729. )
  105730. - (partition_samples >> 1)
  105731. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105732. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105733. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105734. * So the subtraction term tries to guess how many extra bits were contributed.
  105735. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105736. */
  105737. ;
  105738. }
  105739. #endif
  105740. FLAC__bool set_partitioned_rice_(
  105741. #ifdef EXACT_RICE_BITS_CALCULATION
  105742. const FLAC__int32 residual[],
  105743. #endif
  105744. const FLAC__uint64 abs_residual_partition_sums[],
  105745. const unsigned raw_bits_per_partition[],
  105746. const unsigned residual_samples,
  105747. const unsigned predictor_order,
  105748. const unsigned suggested_rice_parameter,
  105749. const unsigned rice_parameter_limit,
  105750. const unsigned rice_parameter_search_dist,
  105751. const unsigned partition_order,
  105752. const FLAC__bool search_for_escapes,
  105753. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105754. unsigned *bits
  105755. )
  105756. {
  105757. unsigned rice_parameter, partition_bits;
  105758. unsigned best_partition_bits, best_rice_parameter = 0;
  105759. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105760. unsigned *parameters, *raw_bits;
  105761. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105762. unsigned min_rice_parameter, max_rice_parameter;
  105763. #else
  105764. (void)rice_parameter_search_dist;
  105765. #endif
  105766. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105767. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105768. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105769. parameters = partitioned_rice_contents->parameters;
  105770. raw_bits = partitioned_rice_contents->raw_bits;
  105771. if(partition_order == 0) {
  105772. best_partition_bits = (unsigned)(-1);
  105773. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105774. if(rice_parameter_search_dist) {
  105775. if(suggested_rice_parameter < rice_parameter_search_dist)
  105776. min_rice_parameter = 0;
  105777. else
  105778. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105779. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105780. if(max_rice_parameter >= rice_parameter_limit) {
  105781. #ifdef DEBUG_VERBOSE
  105782. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105783. #endif
  105784. max_rice_parameter = rice_parameter_limit - 1;
  105785. }
  105786. }
  105787. else
  105788. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105789. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105790. #else
  105791. rice_parameter = suggested_rice_parameter;
  105792. #endif
  105793. #ifdef EXACT_RICE_BITS_CALCULATION
  105794. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105795. #else
  105796. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105797. #endif
  105798. if(partition_bits < best_partition_bits) {
  105799. best_rice_parameter = rice_parameter;
  105800. best_partition_bits = partition_bits;
  105801. }
  105802. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105803. }
  105804. #endif
  105805. if(search_for_escapes) {
  105806. 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;
  105807. if(partition_bits <= best_partition_bits) {
  105808. raw_bits[0] = raw_bits_per_partition[0];
  105809. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105810. best_partition_bits = partition_bits;
  105811. }
  105812. else
  105813. raw_bits[0] = 0;
  105814. }
  105815. parameters[0] = best_rice_parameter;
  105816. bits_ += best_partition_bits;
  105817. }
  105818. else {
  105819. unsigned partition, residual_sample;
  105820. unsigned partition_samples;
  105821. FLAC__uint64 mean, k;
  105822. const unsigned partitions = 1u << partition_order;
  105823. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105824. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105825. if(partition == 0) {
  105826. if(partition_samples <= predictor_order)
  105827. return false;
  105828. else
  105829. partition_samples -= predictor_order;
  105830. }
  105831. mean = abs_residual_partition_sums[partition];
  105832. /* we are basically calculating the size in bits of the
  105833. * average residual magnitude in the partition:
  105834. * rice_parameter = floor(log2(mean/partition_samples))
  105835. * 'mean' is not a good name for the variable, it is
  105836. * actually the sum of magnitudes of all residual values
  105837. * in the partition, so the actual mean is
  105838. * mean/partition_samples
  105839. */
  105840. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105841. ;
  105842. if(rice_parameter >= rice_parameter_limit) {
  105843. #ifdef DEBUG_VERBOSE
  105844. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105845. #endif
  105846. rice_parameter = rice_parameter_limit - 1;
  105847. }
  105848. best_partition_bits = (unsigned)(-1);
  105849. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105850. if(rice_parameter_search_dist) {
  105851. if(rice_parameter < rice_parameter_search_dist)
  105852. min_rice_parameter = 0;
  105853. else
  105854. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105855. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105856. if(max_rice_parameter >= rice_parameter_limit) {
  105857. #ifdef DEBUG_VERBOSE
  105858. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105859. #endif
  105860. max_rice_parameter = rice_parameter_limit - 1;
  105861. }
  105862. }
  105863. else
  105864. min_rice_parameter = max_rice_parameter = rice_parameter;
  105865. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105866. #endif
  105867. #ifdef EXACT_RICE_BITS_CALCULATION
  105868. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105869. #else
  105870. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105871. #endif
  105872. if(partition_bits < best_partition_bits) {
  105873. best_rice_parameter = rice_parameter;
  105874. best_partition_bits = partition_bits;
  105875. }
  105876. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105877. }
  105878. #endif
  105879. if(search_for_escapes) {
  105880. 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;
  105881. if(partition_bits <= best_partition_bits) {
  105882. raw_bits[partition] = raw_bits_per_partition[partition];
  105883. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105884. best_partition_bits = partition_bits;
  105885. }
  105886. else
  105887. raw_bits[partition] = 0;
  105888. }
  105889. parameters[partition] = best_rice_parameter;
  105890. bits_ += best_partition_bits;
  105891. residual_sample += partition_samples;
  105892. }
  105893. }
  105894. *bits = bits_;
  105895. return true;
  105896. }
  105897. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105898. {
  105899. unsigned i, shift;
  105900. FLAC__int32 x = 0;
  105901. for(i = 0; i < samples && !(x&1); i++)
  105902. x |= signal[i];
  105903. if(x == 0) {
  105904. shift = 0;
  105905. }
  105906. else {
  105907. for(shift = 0; !(x&1); shift++)
  105908. x >>= 1;
  105909. }
  105910. if(shift > 0) {
  105911. for(i = 0; i < samples; i++)
  105912. signal[i] >>= shift;
  105913. }
  105914. return shift;
  105915. }
  105916. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105917. {
  105918. unsigned channel;
  105919. for(channel = 0; channel < channels; channel++)
  105920. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105921. fifo->tail += wide_samples;
  105922. FLAC__ASSERT(fifo->tail <= fifo->size);
  105923. }
  105924. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105925. {
  105926. unsigned channel;
  105927. unsigned sample, wide_sample;
  105928. unsigned tail = fifo->tail;
  105929. sample = input_offset * channels;
  105930. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105931. for(channel = 0; channel < channels; channel++)
  105932. fifo->data[channel][tail] = input[sample++];
  105933. tail++;
  105934. }
  105935. fifo->tail = tail;
  105936. FLAC__ASSERT(fifo->tail <= fifo->size);
  105937. }
  105938. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105939. {
  105940. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105941. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105942. (void)decoder;
  105943. if(encoder->private_->verify.needs_magic_hack) {
  105944. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105945. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105946. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105947. encoder->private_->verify.needs_magic_hack = false;
  105948. }
  105949. else {
  105950. if(encoded_bytes == 0) {
  105951. /*
  105952. * If we get here, a FIFO underflow has occurred,
  105953. * which means there is a bug somewhere.
  105954. */
  105955. FLAC__ASSERT(0);
  105956. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105957. }
  105958. else if(encoded_bytes < *bytes)
  105959. *bytes = encoded_bytes;
  105960. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105961. encoder->private_->verify.output.data += *bytes;
  105962. encoder->private_->verify.output.bytes -= *bytes;
  105963. }
  105964. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105965. }
  105966. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105967. {
  105968. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105969. unsigned channel;
  105970. const unsigned channels = frame->header.channels;
  105971. const unsigned blocksize = frame->header.blocksize;
  105972. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105973. (void)decoder;
  105974. for(channel = 0; channel < channels; channel++) {
  105975. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105976. unsigned i, sample = 0;
  105977. FLAC__int32 expect = 0, got = 0;
  105978. for(i = 0; i < blocksize; i++) {
  105979. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105980. sample = i;
  105981. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105982. got = (FLAC__int32)buffer[channel][i];
  105983. break;
  105984. }
  105985. }
  105986. FLAC__ASSERT(i < blocksize);
  105987. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105988. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105989. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105990. encoder->private_->verify.error_stats.channel = channel;
  105991. encoder->private_->verify.error_stats.sample = sample;
  105992. encoder->private_->verify.error_stats.expected = expect;
  105993. encoder->private_->verify.error_stats.got = got;
  105994. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105995. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105996. }
  105997. }
  105998. /* dequeue the frame from the fifo */
  105999. encoder->private_->verify.input_fifo.tail -= blocksize;
  106000. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  106001. for(channel = 0; channel < channels; channel++)
  106002. 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]));
  106003. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106004. }
  106005. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  106006. {
  106007. (void)decoder, (void)metadata, (void)client_data;
  106008. }
  106009. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  106010. {
  106011. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106012. (void)decoder, (void)status;
  106013. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  106014. }
  106015. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106016. {
  106017. (void)client_data;
  106018. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  106019. if (*bytes == 0) {
  106020. if (feof(encoder->private_->file))
  106021. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  106022. else if (ferror(encoder->private_->file))
  106023. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  106024. }
  106025. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  106026. }
  106027. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  106028. {
  106029. (void)client_data;
  106030. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  106031. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  106032. else
  106033. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  106034. }
  106035. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  106036. {
  106037. off_t offset;
  106038. (void)client_data;
  106039. offset = ftello(encoder->private_->file);
  106040. if(offset < 0) {
  106041. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  106042. }
  106043. else {
  106044. *absolute_byte_offset = (FLAC__uint64)offset;
  106045. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106046. }
  106047. }
  106048. #ifdef FLAC__VALGRIND_TESTING
  106049. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  106050. {
  106051. size_t ret = fwrite(ptr, size, nmemb, stream);
  106052. if(!ferror(stream))
  106053. fflush(stream);
  106054. return ret;
  106055. }
  106056. #else
  106057. #define local__fwrite fwrite
  106058. #endif
  106059. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  106060. {
  106061. (void)client_data, (void)current_frame;
  106062. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  106063. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  106064. #if FLAC__HAS_OGG
  106065. /* We would like to be able to use 'samples > 0' in the
  106066. * clause here but currently because of the nature of our
  106067. * Ogg writing implementation, 'samples' is always 0 (see
  106068. * ogg_encoder_aspect.c). The downside is extra progress
  106069. * callbacks.
  106070. */
  106071. encoder->private_->is_ogg? true :
  106072. #endif
  106073. samples > 0
  106074. );
  106075. if(call_it) {
  106076. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  106077. * because at this point in the callback chain, the stats
  106078. * have not been updated. Only after we return and control
  106079. * gets back to write_frame_() are the stats updated
  106080. */
  106081. 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);
  106082. }
  106083. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  106084. }
  106085. else
  106086. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106087. }
  106088. /*
  106089. * This will forcibly set stdout to binary mode (for OSes that require it)
  106090. */
  106091. FILE *get_binary_stdout_(void)
  106092. {
  106093. /* if something breaks here it is probably due to the presence or
  106094. * absence of an underscore before the identifiers 'setmode',
  106095. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106096. */
  106097. #if defined _MSC_VER || defined __MINGW32__
  106098. _setmode(_fileno(stdout), _O_BINARY);
  106099. #elif defined __CYGWIN__
  106100. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106101. setmode(_fileno(stdout), _O_BINARY);
  106102. #elif defined __EMX__
  106103. setmode(fileno(stdout), O_BINARY);
  106104. #endif
  106105. return stdout;
  106106. }
  106107. #endif
  106108. /*** End of inlined file: stream_encoder.c ***/
  106109. /*** Start of inlined file: stream_encoder_framing.c ***/
  106110. /*** Start of inlined file: juce_FlacHeader.h ***/
  106111. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106112. // tasks..
  106113. #define VERSION "1.2.1"
  106114. #define FLAC__NO_DLL 1
  106115. #if JUCE_MSVC
  106116. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106117. #endif
  106118. #if JUCE_MAC
  106119. #define FLAC__SYS_DARWIN 1
  106120. #endif
  106121. /*** End of inlined file: juce_FlacHeader.h ***/
  106122. #if JUCE_USE_FLAC
  106123. #if HAVE_CONFIG_H
  106124. # include <config.h>
  106125. #endif
  106126. #include <stdio.h>
  106127. #include <string.h> /* for strlen() */
  106128. #ifdef max
  106129. #undef max
  106130. #endif
  106131. #define max(x,y) ((x)>(y)?(x):(y))
  106132. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106133. 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);
  106134. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106135. {
  106136. unsigned i, j;
  106137. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106138. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106139. return false;
  106140. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106141. return false;
  106142. /*
  106143. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106144. */
  106145. i = metadata->length;
  106146. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106147. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106148. i -= metadata->data.vorbis_comment.vendor_string.length;
  106149. i += vendor_string_length;
  106150. }
  106151. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106152. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106153. return false;
  106154. switch(metadata->type) {
  106155. case FLAC__METADATA_TYPE_STREAMINFO:
  106156. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106157. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106158. return false;
  106159. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106160. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106161. return false;
  106162. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106163. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106164. return false;
  106165. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106166. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106167. return false;
  106168. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106169. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106170. return false;
  106171. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106172. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106173. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106174. return false;
  106175. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106176. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106177. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106178. return false;
  106179. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106180. return false;
  106181. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106182. return false;
  106183. break;
  106184. case FLAC__METADATA_TYPE_PADDING:
  106185. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106186. return false;
  106187. break;
  106188. case FLAC__METADATA_TYPE_APPLICATION:
  106189. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106190. return false;
  106191. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106192. return false;
  106193. break;
  106194. case FLAC__METADATA_TYPE_SEEKTABLE:
  106195. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106196. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106197. return false;
  106198. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106199. return false;
  106200. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106201. return false;
  106202. }
  106203. break;
  106204. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106205. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106206. return false;
  106207. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106208. return false;
  106209. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106210. return false;
  106211. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106212. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106213. return false;
  106214. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106215. return false;
  106216. }
  106217. break;
  106218. case FLAC__METADATA_TYPE_CUESHEET:
  106219. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106220. 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))
  106221. return false;
  106222. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106223. return false;
  106224. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106225. return false;
  106226. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106227. return false;
  106228. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106229. return false;
  106230. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106231. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106232. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106233. return false;
  106234. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106235. return false;
  106236. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106237. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106238. return false;
  106239. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106240. return false;
  106241. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106242. return false;
  106243. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106244. return false;
  106245. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106246. return false;
  106247. for(j = 0; j < track->num_indices; j++) {
  106248. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106249. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106250. return false;
  106251. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106252. return false;
  106253. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106254. return false;
  106255. }
  106256. }
  106257. break;
  106258. case FLAC__METADATA_TYPE_PICTURE:
  106259. {
  106260. size_t len;
  106261. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106262. return false;
  106263. len = strlen(metadata->data.picture.mime_type);
  106264. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106265. return false;
  106266. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106267. return false;
  106268. len = strlen((const char *)metadata->data.picture.description);
  106269. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106270. return false;
  106271. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106272. return false;
  106273. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106274. return false;
  106275. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106276. return false;
  106277. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106278. return false;
  106279. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106280. return false;
  106281. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106282. return false;
  106283. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106284. return false;
  106285. }
  106286. break;
  106287. default:
  106288. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106289. return false;
  106290. break;
  106291. }
  106292. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106293. return true;
  106294. }
  106295. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106296. {
  106297. unsigned u, blocksize_hint, sample_rate_hint;
  106298. FLAC__byte crc;
  106299. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106300. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106301. return false;
  106302. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106303. return false;
  106304. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106305. return false;
  106306. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106307. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106308. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106309. blocksize_hint = 0;
  106310. switch(header->blocksize) {
  106311. case 192: u = 1; break;
  106312. case 576: u = 2; break;
  106313. case 1152: u = 3; break;
  106314. case 2304: u = 4; break;
  106315. case 4608: u = 5; break;
  106316. case 256: u = 8; break;
  106317. case 512: u = 9; break;
  106318. case 1024: u = 10; break;
  106319. case 2048: u = 11; break;
  106320. case 4096: u = 12; break;
  106321. case 8192: u = 13; break;
  106322. case 16384: u = 14; break;
  106323. case 32768: u = 15; break;
  106324. default:
  106325. if(header->blocksize <= 0x100)
  106326. blocksize_hint = u = 6;
  106327. else
  106328. blocksize_hint = u = 7;
  106329. break;
  106330. }
  106331. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106332. return false;
  106333. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106334. sample_rate_hint = 0;
  106335. switch(header->sample_rate) {
  106336. case 88200: u = 1; break;
  106337. case 176400: u = 2; break;
  106338. case 192000: u = 3; break;
  106339. case 8000: u = 4; break;
  106340. case 16000: u = 5; break;
  106341. case 22050: u = 6; break;
  106342. case 24000: u = 7; break;
  106343. case 32000: u = 8; break;
  106344. case 44100: u = 9; break;
  106345. case 48000: u = 10; break;
  106346. case 96000: u = 11; break;
  106347. default:
  106348. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106349. sample_rate_hint = u = 12;
  106350. else if(header->sample_rate % 10 == 0)
  106351. sample_rate_hint = u = 14;
  106352. else if(header->sample_rate <= 0xffff)
  106353. sample_rate_hint = u = 13;
  106354. else
  106355. u = 0;
  106356. break;
  106357. }
  106358. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106359. return false;
  106360. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106361. switch(header->channel_assignment) {
  106362. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106363. u = header->channels - 1;
  106364. break;
  106365. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106366. FLAC__ASSERT(header->channels == 2);
  106367. u = 8;
  106368. break;
  106369. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106370. FLAC__ASSERT(header->channels == 2);
  106371. u = 9;
  106372. break;
  106373. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106374. FLAC__ASSERT(header->channels == 2);
  106375. u = 10;
  106376. break;
  106377. default:
  106378. FLAC__ASSERT(0);
  106379. }
  106380. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106381. return false;
  106382. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106383. switch(header->bits_per_sample) {
  106384. case 8 : u = 1; break;
  106385. case 12: u = 2; break;
  106386. case 16: u = 4; break;
  106387. case 20: u = 5; break;
  106388. case 24: u = 6; break;
  106389. default: u = 0; break;
  106390. }
  106391. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106392. return false;
  106393. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106394. return false;
  106395. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106396. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106397. return false;
  106398. }
  106399. else {
  106400. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106401. return false;
  106402. }
  106403. if(blocksize_hint)
  106404. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106405. return false;
  106406. switch(sample_rate_hint) {
  106407. case 12:
  106408. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106409. return false;
  106410. break;
  106411. case 13:
  106412. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106413. return false;
  106414. break;
  106415. case 14:
  106416. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106417. return false;
  106418. break;
  106419. }
  106420. /* write the CRC */
  106421. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106422. return false;
  106423. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106424. return false;
  106425. return true;
  106426. }
  106427. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106428. {
  106429. FLAC__bool ok;
  106430. ok =
  106431. 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) &&
  106432. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106433. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106434. ;
  106435. return ok;
  106436. }
  106437. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106438. {
  106439. unsigned i;
  106440. 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))
  106441. return false;
  106442. if(wasted_bits)
  106443. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106444. return false;
  106445. for(i = 0; i < subframe->order; i++)
  106446. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106447. return false;
  106448. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106449. return false;
  106450. switch(subframe->entropy_coding_method.type) {
  106451. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106452. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106453. if(!add_residual_partitioned_rice_(
  106454. bw,
  106455. subframe->residual,
  106456. residual_samples,
  106457. subframe->order,
  106458. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106459. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106460. subframe->entropy_coding_method.data.partitioned_rice.order,
  106461. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106462. ))
  106463. return false;
  106464. break;
  106465. default:
  106466. FLAC__ASSERT(0);
  106467. }
  106468. return true;
  106469. }
  106470. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106471. {
  106472. unsigned i;
  106473. 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))
  106474. return false;
  106475. if(wasted_bits)
  106476. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106477. return false;
  106478. for(i = 0; i < subframe->order; i++)
  106479. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106480. return false;
  106481. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106482. return false;
  106483. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106484. return false;
  106485. for(i = 0; i < subframe->order; i++)
  106486. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106487. return false;
  106488. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106489. return false;
  106490. switch(subframe->entropy_coding_method.type) {
  106491. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106492. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106493. if(!add_residual_partitioned_rice_(
  106494. bw,
  106495. subframe->residual,
  106496. residual_samples,
  106497. subframe->order,
  106498. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106499. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106500. subframe->entropy_coding_method.data.partitioned_rice.order,
  106501. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106502. ))
  106503. return false;
  106504. break;
  106505. default:
  106506. FLAC__ASSERT(0);
  106507. }
  106508. return true;
  106509. }
  106510. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106511. {
  106512. unsigned i;
  106513. const FLAC__int32 *signal = subframe->data;
  106514. 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))
  106515. return false;
  106516. if(wasted_bits)
  106517. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106518. return false;
  106519. for(i = 0; i < samples; i++)
  106520. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106521. return false;
  106522. return true;
  106523. }
  106524. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106525. {
  106526. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106527. return false;
  106528. switch(method->type) {
  106529. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106530. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106531. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106532. return false;
  106533. break;
  106534. default:
  106535. FLAC__ASSERT(0);
  106536. }
  106537. return true;
  106538. }
  106539. 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)
  106540. {
  106541. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106542. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106543. if(partition_order == 0) {
  106544. unsigned i;
  106545. if(raw_bits[0] == 0) {
  106546. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106547. return false;
  106548. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106549. return false;
  106550. }
  106551. else {
  106552. FLAC__ASSERT(rice_parameters[0] == 0);
  106553. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106554. return false;
  106555. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106556. return false;
  106557. for(i = 0; i < residual_samples; i++) {
  106558. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106559. return false;
  106560. }
  106561. }
  106562. return true;
  106563. }
  106564. else {
  106565. unsigned i, j, k = 0, k_last = 0;
  106566. unsigned partition_samples;
  106567. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106568. for(i = 0; i < (1u<<partition_order); i++) {
  106569. partition_samples = default_partition_samples;
  106570. if(i == 0)
  106571. partition_samples -= predictor_order;
  106572. k += partition_samples;
  106573. if(raw_bits[i] == 0) {
  106574. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106575. return false;
  106576. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106577. return false;
  106578. }
  106579. else {
  106580. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106581. return false;
  106582. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106583. return false;
  106584. for(j = k_last; j < k; j++) {
  106585. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106586. return false;
  106587. }
  106588. }
  106589. k_last = k;
  106590. }
  106591. return true;
  106592. }
  106593. }
  106594. #endif
  106595. /*** End of inlined file: stream_encoder_framing.c ***/
  106596. /*** Start of inlined file: window_flac.c ***/
  106597. /*** Start of inlined file: juce_FlacHeader.h ***/
  106598. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106599. // tasks..
  106600. #define VERSION "1.2.1"
  106601. #define FLAC__NO_DLL 1
  106602. #if JUCE_MSVC
  106603. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106604. #endif
  106605. #if JUCE_MAC
  106606. #define FLAC__SYS_DARWIN 1
  106607. #endif
  106608. /*** End of inlined file: juce_FlacHeader.h ***/
  106609. #if JUCE_USE_FLAC
  106610. #if HAVE_CONFIG_H
  106611. # include <config.h>
  106612. #endif
  106613. #include <math.h>
  106614. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106615. #ifndef M_PI
  106616. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106617. #define M_PI 3.14159265358979323846
  106618. #endif
  106619. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106620. {
  106621. const FLAC__int32 N = L - 1;
  106622. FLAC__int32 n;
  106623. if (L & 1) {
  106624. for (n = 0; n <= N/2; n++)
  106625. window[n] = 2.0f * n / (float)N;
  106626. for (; n <= N; n++)
  106627. window[n] = 2.0f - 2.0f * n / (float)N;
  106628. }
  106629. else {
  106630. for (n = 0; n <= L/2-1; n++)
  106631. window[n] = 2.0f * n / (float)N;
  106632. for (; n <= N; n++)
  106633. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106634. }
  106635. }
  106636. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106637. {
  106638. const FLAC__int32 N = L - 1;
  106639. FLAC__int32 n;
  106640. for (n = 0; n < L; n++)
  106641. 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)));
  106642. }
  106643. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106644. {
  106645. const FLAC__int32 N = L - 1;
  106646. FLAC__int32 n;
  106647. for (n = 0; n < L; n++)
  106648. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106649. }
  106650. /* 4-term -92dB side-lobe */
  106651. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106652. {
  106653. const FLAC__int32 N = L - 1;
  106654. FLAC__int32 n;
  106655. for (n = 0; n <= N; n++)
  106656. 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));
  106657. }
  106658. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106659. {
  106660. const FLAC__int32 N = L - 1;
  106661. const double N2 = (double)N / 2.;
  106662. FLAC__int32 n;
  106663. for (n = 0; n <= N; n++) {
  106664. double k = ((double)n - N2) / N2;
  106665. k = 1.0f - k * k;
  106666. window[n] = (FLAC__real)(k * k);
  106667. }
  106668. }
  106669. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106670. {
  106671. const FLAC__int32 N = L - 1;
  106672. FLAC__int32 n;
  106673. for (n = 0; n < L; n++)
  106674. 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));
  106675. }
  106676. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106677. {
  106678. const FLAC__int32 N = L - 1;
  106679. const double N2 = (double)N / 2.;
  106680. FLAC__int32 n;
  106681. for (n = 0; n <= N; n++) {
  106682. const double k = ((double)n - N2) / (stddev * N2);
  106683. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106684. }
  106685. }
  106686. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106687. {
  106688. const FLAC__int32 N = L - 1;
  106689. FLAC__int32 n;
  106690. for (n = 0; n < L; n++)
  106691. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106692. }
  106693. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106694. {
  106695. const FLAC__int32 N = L - 1;
  106696. FLAC__int32 n;
  106697. for (n = 0; n < L; n++)
  106698. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106699. }
  106700. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106701. {
  106702. const FLAC__int32 N = L - 1;
  106703. FLAC__int32 n;
  106704. for (n = 0; n < L; n++)
  106705. 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));
  106706. }
  106707. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106708. {
  106709. const FLAC__int32 N = L - 1;
  106710. FLAC__int32 n;
  106711. for (n = 0; n < L; n++)
  106712. 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));
  106713. }
  106714. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106715. {
  106716. FLAC__int32 n;
  106717. for (n = 0; n < L; n++)
  106718. window[n] = 1.0f;
  106719. }
  106720. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106721. {
  106722. FLAC__int32 n;
  106723. if (L & 1) {
  106724. for (n = 1; n <= L+1/2; n++)
  106725. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106726. for (; n <= L; n++)
  106727. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106728. }
  106729. else {
  106730. for (n = 1; n <= L/2; n++)
  106731. window[n-1] = 2.0f * n / (float)L;
  106732. for (; n <= L; n++)
  106733. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106734. }
  106735. }
  106736. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106737. {
  106738. if (p <= 0.0)
  106739. FLAC__window_rectangle(window, L);
  106740. else if (p >= 1.0)
  106741. FLAC__window_hann(window, L);
  106742. else {
  106743. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106744. FLAC__int32 n;
  106745. /* start with rectangle... */
  106746. FLAC__window_rectangle(window, L);
  106747. /* ...replace ends with hann */
  106748. if (Np > 0) {
  106749. for (n = 0; n <= Np; n++) {
  106750. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106751. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106752. }
  106753. }
  106754. }
  106755. }
  106756. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106757. {
  106758. const FLAC__int32 N = L - 1;
  106759. const double N2 = (double)N / 2.;
  106760. FLAC__int32 n;
  106761. for (n = 0; n <= N; n++) {
  106762. const double k = ((double)n - N2) / N2;
  106763. window[n] = (FLAC__real)(1.0f - k * k);
  106764. }
  106765. }
  106766. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106767. #endif
  106768. /*** End of inlined file: window_flac.c ***/
  106769. #else
  106770. #include <FLAC/all.h>
  106771. #endif
  106772. }
  106773. #undef max
  106774. #undef min
  106775. BEGIN_JUCE_NAMESPACE
  106776. static const char* const flacFormatName = "FLAC file";
  106777. static const char* const flacExtensions[] = { ".flac", 0 };
  106778. class FlacReader : public AudioFormatReader
  106779. {
  106780. public:
  106781. FlacReader (InputStream* const in)
  106782. : AudioFormatReader (in, TRANS (flacFormatName)),
  106783. reservoir (2, 0),
  106784. reservoirStart (0),
  106785. samplesInReservoir (0),
  106786. scanningForLength (false)
  106787. {
  106788. using namespace FlacNamespace;
  106789. lengthInSamples = 0;
  106790. decoder = FLAC__stream_decoder_new();
  106791. ok = FLAC__stream_decoder_init_stream (decoder,
  106792. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106793. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106794. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106795. if (ok)
  106796. {
  106797. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106798. if (lengthInSamples == 0 && sampleRate > 0)
  106799. {
  106800. // the length hasn't been stored in the metadata, so we'll need to
  106801. // work it out the length the hard way, by scanning the whole file..
  106802. scanningForLength = true;
  106803. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106804. scanningForLength = false;
  106805. const int64 tempLength = lengthInSamples;
  106806. FLAC__stream_decoder_reset (decoder);
  106807. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106808. lengthInSamples = tempLength;
  106809. }
  106810. }
  106811. }
  106812. ~FlacReader()
  106813. {
  106814. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106815. }
  106816. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106817. {
  106818. sampleRate = info.sample_rate;
  106819. bitsPerSample = info.bits_per_sample;
  106820. lengthInSamples = (unsigned int) info.total_samples;
  106821. numChannels = info.channels;
  106822. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106823. }
  106824. // returns the number of samples read
  106825. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106826. int64 startSampleInFile, int numSamples)
  106827. {
  106828. using namespace FlacNamespace;
  106829. if (! ok)
  106830. return false;
  106831. while (numSamples > 0)
  106832. {
  106833. if (startSampleInFile >= reservoirStart
  106834. && startSampleInFile < reservoirStart + samplesInReservoir)
  106835. {
  106836. const int num = (int) jmin ((int64) numSamples,
  106837. reservoirStart + samplesInReservoir - startSampleInFile);
  106838. jassert (num > 0);
  106839. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106840. if (destSamples[i] != 0)
  106841. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106842. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106843. sizeof (int) * num);
  106844. startOffsetInDestBuffer += num;
  106845. startSampleInFile += num;
  106846. numSamples -= num;
  106847. }
  106848. else
  106849. {
  106850. if (startSampleInFile >= (int) lengthInSamples)
  106851. {
  106852. samplesInReservoir = 0;
  106853. }
  106854. else if (startSampleInFile < reservoirStart
  106855. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106856. {
  106857. // had some problems with flac crashing if the read pos is aligned more
  106858. // accurately than this. Probably fixed in newer versions of the library, though.
  106859. reservoirStart = (int) (startSampleInFile & ~511);
  106860. samplesInReservoir = 0;
  106861. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106862. }
  106863. else
  106864. {
  106865. reservoirStart += samplesInReservoir;
  106866. samplesInReservoir = 0;
  106867. FLAC__stream_decoder_process_single (decoder);
  106868. }
  106869. if (samplesInReservoir == 0)
  106870. break;
  106871. }
  106872. }
  106873. if (numSamples > 0)
  106874. {
  106875. for (int i = numDestChannels; --i >= 0;)
  106876. if (destSamples[i] != 0)
  106877. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106878. sizeof (int) * numSamples);
  106879. }
  106880. return true;
  106881. }
  106882. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106883. {
  106884. if (scanningForLength)
  106885. {
  106886. lengthInSamples += numSamples;
  106887. }
  106888. else
  106889. {
  106890. if (numSamples > reservoir.getNumSamples())
  106891. reservoir.setSize (numChannels, numSamples, false, false, true);
  106892. const int bitsToShift = 32 - bitsPerSample;
  106893. for (int i = 0; i < (int) numChannels; ++i)
  106894. {
  106895. const FlacNamespace::FLAC__int32* src = buffer[i];
  106896. int n = i;
  106897. while (src == 0 && n > 0)
  106898. src = buffer [--n];
  106899. if (src != 0)
  106900. {
  106901. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  106902. for (int j = 0; j < numSamples; ++j)
  106903. dest[j] = src[j] << bitsToShift;
  106904. }
  106905. }
  106906. samplesInReservoir = numSamples;
  106907. }
  106908. }
  106909. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106910. {
  106911. using namespace FlacNamespace;
  106912. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106913. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106914. }
  106915. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106916. {
  106917. using namespace FlacNamespace;
  106918. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106919. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106920. }
  106921. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106922. {
  106923. using namespace FlacNamespace;
  106924. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106925. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106926. }
  106927. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106928. {
  106929. using namespace FlacNamespace;
  106930. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106931. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106932. }
  106933. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106934. {
  106935. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106936. }
  106937. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106938. const FlacNamespace::FLAC__Frame* frame,
  106939. const FlacNamespace::FLAC__int32* const buffer[],
  106940. void* client_data)
  106941. {
  106942. using namespace FlacNamespace;
  106943. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106944. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106945. }
  106946. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106947. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106948. void* client_data)
  106949. {
  106950. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106951. }
  106952. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106953. {
  106954. }
  106955. juce_UseDebuggingNewOperator
  106956. private:
  106957. FlacNamespace::FLAC__StreamDecoder* decoder;
  106958. AudioSampleBuffer reservoir;
  106959. int reservoirStart, samplesInReservoir;
  106960. bool ok, scanningForLength;
  106961. FlacReader (const FlacReader&);
  106962. FlacReader& operator= (const FlacReader&);
  106963. };
  106964. class FlacWriter : public AudioFormatWriter
  106965. {
  106966. public:
  106967. FlacWriter (OutputStream* const out, double sampleRate_,
  106968. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  106969. : AudioFormatWriter (out, TRANS (flacFormatName),
  106970. sampleRate_, numChannels_, bitsPerSample_)
  106971. {
  106972. using namespace FlacNamespace;
  106973. encoder = FLAC__stream_encoder_new();
  106974. if (qualityOptionIndex > 0)
  106975. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  106976. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106977. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106978. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106979. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106980. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106981. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106982. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106983. ok = FLAC__stream_encoder_init_stream (encoder,
  106984. encodeWriteCallback, encodeSeekCallback,
  106985. encodeTellCallback, encodeMetadataCallback,
  106986. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106987. }
  106988. ~FlacWriter()
  106989. {
  106990. if (ok)
  106991. {
  106992. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106993. output->flush();
  106994. }
  106995. else
  106996. {
  106997. output = 0; // to stop the base class deleting this, as it needs to be returned
  106998. // to the caller of createWriter()
  106999. }
  107000. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  107001. }
  107002. bool write (const int** samplesToWrite, int numSamples)
  107003. {
  107004. using namespace FlacNamespace;
  107005. if (! ok)
  107006. return false;
  107007. int* buf[3];
  107008. const int bitsToShift = 32 - bitsPerSample;
  107009. if (bitsToShift > 0)
  107010. {
  107011. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  107012. HeapBlock<int> temp (numSamples * numChannelsToWrite);
  107013. buf[0] = temp.getData();
  107014. buf[1] = temp.getData() + numSamples;
  107015. buf[2] = 0;
  107016. for (int i = numChannelsToWrite; --i >= 0;)
  107017. {
  107018. if (samplesToWrite[i] != 0)
  107019. {
  107020. for (int j = 0; j < numSamples; ++j)
  107021. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  107022. }
  107023. }
  107024. samplesToWrite = const_cast<const int**> (buf);
  107025. }
  107026. return FLAC__stream_encoder_process (encoder,
  107027. (const FLAC__int32**) samplesToWrite,
  107028. numSamples) != 0;
  107029. }
  107030. bool writeData (const void* const data, const int size) const
  107031. {
  107032. return output->write (data, size);
  107033. }
  107034. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  107035. {
  107036. using namespace FlacNamespace;
  107037. b += bytes;
  107038. for (int i = 0; i < bytes; ++i)
  107039. {
  107040. *(--b) = (FLAC__byte) (val & 0xff);
  107041. val >>= 8;
  107042. }
  107043. }
  107044. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  107045. {
  107046. using namespace FlacNamespace;
  107047. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  107048. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  107049. const unsigned int channelsMinus1 = info.channels - 1;
  107050. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  107051. packUint32 (info.min_blocksize, buffer, 2);
  107052. packUint32 (info.max_blocksize, buffer + 2, 2);
  107053. packUint32 (info.min_framesize, buffer + 4, 3);
  107054. packUint32 (info.max_framesize, buffer + 7, 3);
  107055. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  107056. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  107057. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  107058. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  107059. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  107060. memcpy (buffer + 18, info.md5sum, 16);
  107061. const bool seekOk = output->setPosition (4);
  107062. (void) seekOk;
  107063. // if this fails, you've given it an output stream that can't seek! It needs
  107064. // to be able to seek back to write the header
  107065. jassert (seekOk);
  107066. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107067. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107068. }
  107069. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  107070. const FlacNamespace::FLAC__byte buffer[],
  107071. size_t bytes,
  107072. unsigned int /*samples*/,
  107073. unsigned int /*current_frame*/,
  107074. void* client_data)
  107075. {
  107076. using namespace FlacNamespace;
  107077. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  107078. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  107079. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  107080. }
  107081. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  107082. {
  107083. using namespace FlacNamespace;
  107084. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107085. }
  107086. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107087. {
  107088. using namespace FlacNamespace;
  107089. if (client_data == 0)
  107090. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107091. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107092. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107093. }
  107094. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107095. {
  107096. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107097. }
  107098. juce_UseDebuggingNewOperator
  107099. bool ok;
  107100. private:
  107101. FlacNamespace::FLAC__StreamEncoder* encoder;
  107102. FlacWriter (const FlacWriter&);
  107103. FlacWriter& operator= (const FlacWriter&);
  107104. };
  107105. FlacAudioFormat::FlacAudioFormat()
  107106. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107107. {
  107108. }
  107109. FlacAudioFormat::~FlacAudioFormat()
  107110. {
  107111. }
  107112. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107113. {
  107114. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107115. return Array <int> (rates);
  107116. }
  107117. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107118. {
  107119. const int depths[] = { 16, 24, 0 };
  107120. return Array <int> (depths);
  107121. }
  107122. bool FlacAudioFormat::canDoStereo() { return true; }
  107123. bool FlacAudioFormat::canDoMono() { return true; }
  107124. bool FlacAudioFormat::isCompressed() { return true; }
  107125. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107126. const bool deleteStreamIfOpeningFails)
  107127. {
  107128. ScopedPointer<FlacReader> r (new FlacReader (in));
  107129. if (r->sampleRate != 0)
  107130. return r.release();
  107131. if (! deleteStreamIfOpeningFails)
  107132. r->input = 0;
  107133. return 0;
  107134. }
  107135. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107136. double sampleRate,
  107137. unsigned int numberOfChannels,
  107138. int bitsPerSample,
  107139. const StringPairArray& /*metadataValues*/,
  107140. int qualityOptionIndex)
  107141. {
  107142. if (getPossibleBitDepths().contains (bitsPerSample))
  107143. {
  107144. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  107145. if (w->ok)
  107146. return w.release();
  107147. }
  107148. return 0;
  107149. }
  107150. END_JUCE_NAMESPACE
  107151. #endif
  107152. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107153. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107154. #if JUCE_USE_OGGVORBIS
  107155. #if JUCE_MAC
  107156. #define __MACOSX__ 1
  107157. #endif
  107158. namespace OggVorbisNamespace
  107159. {
  107160. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107161. /*** Start of inlined file: vorbisenc.h ***/
  107162. #ifndef _OV_ENC_H_
  107163. #define _OV_ENC_H_
  107164. #ifdef __cplusplus
  107165. extern "C"
  107166. {
  107167. #endif /* __cplusplus */
  107168. /*** Start of inlined file: codec.h ***/
  107169. #ifndef _vorbis_codec_h_
  107170. #define _vorbis_codec_h_
  107171. #ifdef __cplusplus
  107172. extern "C"
  107173. {
  107174. #endif /* __cplusplus */
  107175. /*** Start of inlined file: ogg.h ***/
  107176. #ifndef _OGG_H
  107177. #define _OGG_H
  107178. #ifdef __cplusplus
  107179. extern "C" {
  107180. #endif
  107181. /*** Start of inlined file: os_types.h ***/
  107182. #ifndef _OS_TYPES_H
  107183. #define _OS_TYPES_H
  107184. /* make it easy on the folks that want to compile the libs with a
  107185. different malloc than stdlib */
  107186. #define _ogg_malloc malloc
  107187. #define _ogg_calloc calloc
  107188. #define _ogg_realloc realloc
  107189. #define _ogg_free free
  107190. #if defined(_WIN32)
  107191. # if defined(__CYGWIN__)
  107192. # include <_G_config.h>
  107193. typedef _G_int64_t ogg_int64_t;
  107194. typedef _G_int32_t ogg_int32_t;
  107195. typedef _G_uint32_t ogg_uint32_t;
  107196. typedef _G_int16_t ogg_int16_t;
  107197. typedef _G_uint16_t ogg_uint16_t;
  107198. # elif defined(__MINGW32__)
  107199. typedef short ogg_int16_t;
  107200. typedef unsigned short ogg_uint16_t;
  107201. typedef int ogg_int32_t;
  107202. typedef unsigned int ogg_uint32_t;
  107203. typedef long long ogg_int64_t;
  107204. typedef unsigned long long ogg_uint64_t;
  107205. # elif defined(__MWERKS__)
  107206. typedef long long ogg_int64_t;
  107207. typedef int ogg_int32_t;
  107208. typedef unsigned int ogg_uint32_t;
  107209. typedef short ogg_int16_t;
  107210. typedef unsigned short ogg_uint16_t;
  107211. # else
  107212. /* MSVC/Borland */
  107213. typedef __int64 ogg_int64_t;
  107214. typedef __int32 ogg_int32_t;
  107215. typedef unsigned __int32 ogg_uint32_t;
  107216. typedef __int16 ogg_int16_t;
  107217. typedef unsigned __int16 ogg_uint16_t;
  107218. # endif
  107219. #elif defined(__MACOS__)
  107220. # include <sys/types.h>
  107221. typedef SInt16 ogg_int16_t;
  107222. typedef UInt16 ogg_uint16_t;
  107223. typedef SInt32 ogg_int32_t;
  107224. typedef UInt32 ogg_uint32_t;
  107225. typedef SInt64 ogg_int64_t;
  107226. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107227. # include <sys/types.h>
  107228. typedef int16_t ogg_int16_t;
  107229. typedef u_int16_t ogg_uint16_t;
  107230. typedef int32_t ogg_int32_t;
  107231. typedef u_int32_t ogg_uint32_t;
  107232. typedef int64_t ogg_int64_t;
  107233. #elif defined(__BEOS__)
  107234. /* Be */
  107235. # include <inttypes.h>
  107236. typedef int16_t ogg_int16_t;
  107237. typedef u_int16_t ogg_uint16_t;
  107238. typedef int32_t ogg_int32_t;
  107239. typedef u_int32_t ogg_uint32_t;
  107240. typedef int64_t ogg_int64_t;
  107241. #elif defined (__EMX__)
  107242. /* OS/2 GCC */
  107243. typedef short ogg_int16_t;
  107244. typedef unsigned short ogg_uint16_t;
  107245. typedef int ogg_int32_t;
  107246. typedef unsigned int ogg_uint32_t;
  107247. typedef long long ogg_int64_t;
  107248. #elif defined (DJGPP)
  107249. /* DJGPP */
  107250. typedef short ogg_int16_t;
  107251. typedef int ogg_int32_t;
  107252. typedef unsigned int ogg_uint32_t;
  107253. typedef long long ogg_int64_t;
  107254. #elif defined(R5900)
  107255. /* PS2 EE */
  107256. typedef long ogg_int64_t;
  107257. typedef int ogg_int32_t;
  107258. typedef unsigned ogg_uint32_t;
  107259. typedef short ogg_int16_t;
  107260. #elif defined(__SYMBIAN32__)
  107261. /* Symbian GCC */
  107262. typedef signed short ogg_int16_t;
  107263. typedef unsigned short ogg_uint16_t;
  107264. typedef signed int ogg_int32_t;
  107265. typedef unsigned int ogg_uint32_t;
  107266. typedef long long int ogg_int64_t;
  107267. #else
  107268. # include <sys/types.h>
  107269. /*** Start of inlined file: config_types.h ***/
  107270. #ifndef __CONFIG_TYPES_H__
  107271. #define __CONFIG_TYPES_H__
  107272. typedef int16_t ogg_int16_t;
  107273. typedef unsigned short ogg_uint16_t;
  107274. typedef int32_t ogg_int32_t;
  107275. typedef unsigned int ogg_uint32_t;
  107276. typedef int64_t ogg_int64_t;
  107277. #endif
  107278. /*** End of inlined file: config_types.h ***/
  107279. #endif
  107280. #endif /* _OS_TYPES_H */
  107281. /*** End of inlined file: os_types.h ***/
  107282. typedef struct {
  107283. long endbyte;
  107284. int endbit;
  107285. unsigned char *buffer;
  107286. unsigned char *ptr;
  107287. long storage;
  107288. } oggpack_buffer;
  107289. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107290. typedef struct {
  107291. unsigned char *header;
  107292. long header_len;
  107293. unsigned char *body;
  107294. long body_len;
  107295. } ogg_page;
  107296. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107297. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107298. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107299. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107300. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107301. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107302. }
  107303. /* ogg_stream_state contains the current encode/decode state of a logical
  107304. Ogg bitstream **********************************************************/
  107305. typedef struct {
  107306. unsigned char *body_data; /* bytes from packet bodies */
  107307. long body_storage; /* storage elements allocated */
  107308. long body_fill; /* elements stored; fill mark */
  107309. long body_returned; /* elements of fill returned */
  107310. int *lacing_vals; /* The values that will go to the segment table */
  107311. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107312. this way, but it is simple coupled to the
  107313. lacing fifo */
  107314. long lacing_storage;
  107315. long lacing_fill;
  107316. long lacing_packet;
  107317. long lacing_returned;
  107318. unsigned char header[282]; /* working space for header encode */
  107319. int header_fill;
  107320. int e_o_s; /* set when we have buffered the last packet in the
  107321. logical bitstream */
  107322. int b_o_s; /* set after we've written the initial page
  107323. of a logical bitstream */
  107324. long serialno;
  107325. long pageno;
  107326. ogg_int64_t packetno; /* sequence number for decode; the framing
  107327. knows where there's a hole in the data,
  107328. but we need coupling so that the codec
  107329. (which is in a seperate abstraction
  107330. layer) also knows about the gap */
  107331. ogg_int64_t granulepos;
  107332. } ogg_stream_state;
  107333. /* ogg_packet is used to encapsulate the data and metadata belonging
  107334. to a single raw Ogg/Vorbis packet *************************************/
  107335. typedef struct {
  107336. unsigned char *packet;
  107337. long bytes;
  107338. long b_o_s;
  107339. long e_o_s;
  107340. ogg_int64_t granulepos;
  107341. ogg_int64_t packetno; /* sequence number for decode; the framing
  107342. knows where there's a hole in the data,
  107343. but we need coupling so that the codec
  107344. (which is in a seperate abstraction
  107345. layer) also knows about the gap */
  107346. } ogg_packet;
  107347. typedef struct {
  107348. unsigned char *data;
  107349. int storage;
  107350. int fill;
  107351. int returned;
  107352. int unsynced;
  107353. int headerbytes;
  107354. int bodybytes;
  107355. } ogg_sync_state;
  107356. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107357. extern void oggpack_writeinit(oggpack_buffer *b);
  107358. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107359. extern void oggpack_writealign(oggpack_buffer *b);
  107360. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107361. extern void oggpack_reset(oggpack_buffer *b);
  107362. extern void oggpack_writeclear(oggpack_buffer *b);
  107363. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107364. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107365. extern long oggpack_look(oggpack_buffer *b,int bits);
  107366. extern long oggpack_look1(oggpack_buffer *b);
  107367. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107368. extern void oggpack_adv1(oggpack_buffer *b);
  107369. extern long oggpack_read(oggpack_buffer *b,int bits);
  107370. extern long oggpack_read1(oggpack_buffer *b);
  107371. extern long oggpack_bytes(oggpack_buffer *b);
  107372. extern long oggpack_bits(oggpack_buffer *b);
  107373. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107374. extern void oggpackB_writeinit(oggpack_buffer *b);
  107375. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107376. extern void oggpackB_writealign(oggpack_buffer *b);
  107377. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107378. extern void oggpackB_reset(oggpack_buffer *b);
  107379. extern void oggpackB_writeclear(oggpack_buffer *b);
  107380. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107381. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107382. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107383. extern long oggpackB_look1(oggpack_buffer *b);
  107384. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107385. extern void oggpackB_adv1(oggpack_buffer *b);
  107386. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107387. extern long oggpackB_read1(oggpack_buffer *b);
  107388. extern long oggpackB_bytes(oggpack_buffer *b);
  107389. extern long oggpackB_bits(oggpack_buffer *b);
  107390. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107391. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107392. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107393. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107394. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107395. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107396. extern int ogg_sync_init(ogg_sync_state *oy);
  107397. extern int ogg_sync_clear(ogg_sync_state *oy);
  107398. extern int ogg_sync_reset(ogg_sync_state *oy);
  107399. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107400. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107401. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107402. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107403. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107404. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107405. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107406. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107407. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107408. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107409. extern int ogg_stream_clear(ogg_stream_state *os);
  107410. extern int ogg_stream_reset(ogg_stream_state *os);
  107411. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107412. extern int ogg_stream_destroy(ogg_stream_state *os);
  107413. extern int ogg_stream_eos(ogg_stream_state *os);
  107414. extern void ogg_page_checksum_set(ogg_page *og);
  107415. extern int ogg_page_version(ogg_page *og);
  107416. extern int ogg_page_continued(ogg_page *og);
  107417. extern int ogg_page_bos(ogg_page *og);
  107418. extern int ogg_page_eos(ogg_page *og);
  107419. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107420. extern int ogg_page_serialno(ogg_page *og);
  107421. extern long ogg_page_pageno(ogg_page *og);
  107422. extern int ogg_page_packets(ogg_page *og);
  107423. extern void ogg_packet_clear(ogg_packet *op);
  107424. #ifdef __cplusplus
  107425. }
  107426. #endif
  107427. #endif /* _OGG_H */
  107428. /*** End of inlined file: ogg.h ***/
  107429. typedef struct vorbis_info{
  107430. int version;
  107431. int channels;
  107432. long rate;
  107433. /* The below bitrate declarations are *hints*.
  107434. Combinations of the three values carry the following implications:
  107435. all three set to the same value:
  107436. implies a fixed rate bitstream
  107437. only nominal set:
  107438. implies a VBR stream that averages the nominal bitrate. No hard
  107439. upper/lower limit
  107440. upper and or lower set:
  107441. implies a VBR bitstream that obeys the bitrate limits. nominal
  107442. may also be set to give a nominal rate.
  107443. none set:
  107444. the coder does not care to speculate.
  107445. */
  107446. long bitrate_upper;
  107447. long bitrate_nominal;
  107448. long bitrate_lower;
  107449. long bitrate_window;
  107450. void *codec_setup;
  107451. } vorbis_info;
  107452. /* vorbis_dsp_state buffers the current vorbis audio
  107453. analysis/synthesis state. The DSP state belongs to a specific
  107454. logical bitstream ****************************************************/
  107455. typedef struct vorbis_dsp_state{
  107456. int analysisp;
  107457. vorbis_info *vi;
  107458. float **pcm;
  107459. float **pcmret;
  107460. int pcm_storage;
  107461. int pcm_current;
  107462. int pcm_returned;
  107463. int preextrapolate;
  107464. int eofflag;
  107465. long lW;
  107466. long W;
  107467. long nW;
  107468. long centerW;
  107469. ogg_int64_t granulepos;
  107470. ogg_int64_t sequence;
  107471. ogg_int64_t glue_bits;
  107472. ogg_int64_t time_bits;
  107473. ogg_int64_t floor_bits;
  107474. ogg_int64_t res_bits;
  107475. void *backend_state;
  107476. } vorbis_dsp_state;
  107477. typedef struct vorbis_block{
  107478. /* necessary stream state for linking to the framing abstraction */
  107479. float **pcm; /* this is a pointer into local storage */
  107480. oggpack_buffer opb;
  107481. long lW;
  107482. long W;
  107483. long nW;
  107484. int pcmend;
  107485. int mode;
  107486. int eofflag;
  107487. ogg_int64_t granulepos;
  107488. ogg_int64_t sequence;
  107489. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107490. /* local storage to avoid remallocing; it's up to the mapping to
  107491. structure it */
  107492. void *localstore;
  107493. long localtop;
  107494. long localalloc;
  107495. long totaluse;
  107496. struct alloc_chain *reap;
  107497. /* bitmetrics for the frame */
  107498. long glue_bits;
  107499. long time_bits;
  107500. long floor_bits;
  107501. long res_bits;
  107502. void *internal;
  107503. } vorbis_block;
  107504. /* vorbis_block is a single block of data to be processed as part of
  107505. the analysis/synthesis stream; it belongs to a specific logical
  107506. bitstream, but is independant from other vorbis_blocks belonging to
  107507. that logical bitstream. *************************************************/
  107508. struct alloc_chain{
  107509. void *ptr;
  107510. struct alloc_chain *next;
  107511. };
  107512. /* vorbis_info contains all the setup information specific to the
  107513. specific compression/decompression mode in progress (eg,
  107514. psychoacoustic settings, channel setup, options, codebook
  107515. etc). vorbis_info and substructures are in backends.h.
  107516. *********************************************************************/
  107517. /* the comments are not part of vorbis_info so that vorbis_info can be
  107518. static storage */
  107519. typedef struct vorbis_comment{
  107520. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107521. whatever vendor is set to in encode */
  107522. char **user_comments;
  107523. int *comment_lengths;
  107524. int comments;
  107525. char *vendor;
  107526. } vorbis_comment;
  107527. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107528. and produce a packet (see docs/analysis.txt). The packet is then
  107529. coded into a framed OggSquish bitstream by the second layer (see
  107530. docs/framing.txt). Decode is the reverse process; we sync/frame
  107531. the bitstream and extract individual packets, then decode the
  107532. packet back into PCM audio.
  107533. The extra framing/packetizing is used in streaming formats, such as
  107534. files. Over the net (such as with UDP), the framing and
  107535. packetization aren't necessary as they're provided by the transport
  107536. and the streaming layer is not used */
  107537. /* Vorbis PRIMITIVES: general ***************************************/
  107538. extern void vorbis_info_init(vorbis_info *vi);
  107539. extern void vorbis_info_clear(vorbis_info *vi);
  107540. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107541. extern void vorbis_comment_init(vorbis_comment *vc);
  107542. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107543. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107544. const char *tag, char *contents);
  107545. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107546. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107547. extern void vorbis_comment_clear(vorbis_comment *vc);
  107548. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107549. extern int vorbis_block_clear(vorbis_block *vb);
  107550. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107551. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107552. ogg_int64_t granulepos);
  107553. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107554. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107555. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107556. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107557. vorbis_comment *vc,
  107558. ogg_packet *op,
  107559. ogg_packet *op_comm,
  107560. ogg_packet *op_code);
  107561. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107562. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107563. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107564. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107565. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107566. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107567. ogg_packet *op);
  107568. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107569. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107570. ogg_packet *op);
  107571. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107572. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107573. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107574. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107575. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107576. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107577. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107578. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107579. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107580. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107581. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107582. /* Vorbis ERRORS and return codes ***********************************/
  107583. #define OV_FALSE -1
  107584. #define OV_EOF -2
  107585. #define OV_HOLE -3
  107586. #define OV_EREAD -128
  107587. #define OV_EFAULT -129
  107588. #define OV_EIMPL -130
  107589. #define OV_EINVAL -131
  107590. #define OV_ENOTVORBIS -132
  107591. #define OV_EBADHEADER -133
  107592. #define OV_EVERSION -134
  107593. #define OV_ENOTAUDIO -135
  107594. #define OV_EBADPACKET -136
  107595. #define OV_EBADLINK -137
  107596. #define OV_ENOSEEK -138
  107597. #ifdef __cplusplus
  107598. }
  107599. #endif /* __cplusplus */
  107600. #endif
  107601. /*** End of inlined file: codec.h ***/
  107602. extern int vorbis_encode_init(vorbis_info *vi,
  107603. long channels,
  107604. long rate,
  107605. long max_bitrate,
  107606. long nominal_bitrate,
  107607. long min_bitrate);
  107608. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107609. long channels,
  107610. long rate,
  107611. long max_bitrate,
  107612. long nominal_bitrate,
  107613. long min_bitrate);
  107614. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107615. long channels,
  107616. long rate,
  107617. float quality /* quality level from 0. (lo) to 1. (hi) */
  107618. );
  107619. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107620. long channels,
  107621. long rate,
  107622. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107623. );
  107624. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107625. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107626. /* deprecated rate management supported only for compatability */
  107627. #define OV_ECTL_RATEMANAGE_GET 0x10
  107628. #define OV_ECTL_RATEMANAGE_SET 0x11
  107629. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107630. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107631. struct ovectl_ratemanage_arg {
  107632. int management_active;
  107633. long bitrate_hard_min;
  107634. long bitrate_hard_max;
  107635. double bitrate_hard_window;
  107636. long bitrate_av_lo;
  107637. long bitrate_av_hi;
  107638. double bitrate_av_window;
  107639. double bitrate_av_window_center;
  107640. };
  107641. /* new rate setup */
  107642. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107643. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107644. struct ovectl_ratemanage2_arg {
  107645. int management_active;
  107646. long bitrate_limit_min_kbps;
  107647. long bitrate_limit_max_kbps;
  107648. long bitrate_limit_reservoir_bits;
  107649. double bitrate_limit_reservoir_bias;
  107650. long bitrate_average_kbps;
  107651. double bitrate_average_damping;
  107652. };
  107653. #define OV_ECTL_LOWPASS_GET 0x20
  107654. #define OV_ECTL_LOWPASS_SET 0x21
  107655. #define OV_ECTL_IBLOCK_GET 0x30
  107656. #define OV_ECTL_IBLOCK_SET 0x31
  107657. #ifdef __cplusplus
  107658. }
  107659. #endif /* __cplusplus */
  107660. #endif
  107661. /*** End of inlined file: vorbisenc.h ***/
  107662. /*** Start of inlined file: vorbisfile.h ***/
  107663. #ifndef _OV_FILE_H_
  107664. #define _OV_FILE_H_
  107665. #ifdef __cplusplus
  107666. extern "C"
  107667. {
  107668. #endif /* __cplusplus */
  107669. #include <stdio.h>
  107670. /* The function prototypes for the callbacks are basically the same as for
  107671. * the stdio functions fread, fseek, fclose, ftell.
  107672. * The one difference is that the FILE * arguments have been replaced with
  107673. * a void * - this is to be used as a pointer to whatever internal data these
  107674. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107675. *
  107676. * If you use other functions, check the docs for these functions and return
  107677. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107678. * unseekable
  107679. */
  107680. typedef struct {
  107681. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107682. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107683. int (*close_func) (void *datasource);
  107684. long (*tell_func) (void *datasource);
  107685. } ov_callbacks;
  107686. #define NOTOPEN 0
  107687. #define PARTOPEN 1
  107688. #define OPENED 2
  107689. #define STREAMSET 3
  107690. #define INITSET 4
  107691. typedef struct OggVorbis_File {
  107692. void *datasource; /* Pointer to a FILE *, etc. */
  107693. int seekable;
  107694. ogg_int64_t offset;
  107695. ogg_int64_t end;
  107696. ogg_sync_state oy;
  107697. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107698. stream appears */
  107699. int links;
  107700. ogg_int64_t *offsets;
  107701. ogg_int64_t *dataoffsets;
  107702. long *serialnos;
  107703. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107704. compatability; x2 size, stores both
  107705. beginning and end values */
  107706. vorbis_info *vi;
  107707. vorbis_comment *vc;
  107708. /* Decoding working state local storage */
  107709. ogg_int64_t pcm_offset;
  107710. int ready_state;
  107711. long current_serialno;
  107712. int current_link;
  107713. double bittrack;
  107714. double samptrack;
  107715. ogg_stream_state os; /* take physical pages, weld into a logical
  107716. stream of packets */
  107717. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107718. vorbis_block vb; /* local working space for packet->PCM decode */
  107719. ov_callbacks callbacks;
  107720. } OggVorbis_File;
  107721. extern int ov_clear(OggVorbis_File *vf);
  107722. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107723. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107724. char *initial, long ibytes, ov_callbacks callbacks);
  107725. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107726. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107727. char *initial, long ibytes, ov_callbacks callbacks);
  107728. extern int ov_test_open(OggVorbis_File *vf);
  107729. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107730. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107731. extern long ov_streams(OggVorbis_File *vf);
  107732. extern long ov_seekable(OggVorbis_File *vf);
  107733. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107734. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107735. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107736. extern double ov_time_total(OggVorbis_File *vf,int i);
  107737. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107738. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107739. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107740. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107741. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107742. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107743. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107744. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107745. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107746. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107747. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107748. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107749. extern double ov_time_tell(OggVorbis_File *vf);
  107750. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107751. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107752. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107753. int *bitstream);
  107754. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107755. int bigendianp,int word,int sgned,int *bitstream);
  107756. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107757. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107758. extern int ov_halfrate_p(OggVorbis_File *vf);
  107759. #ifdef __cplusplus
  107760. }
  107761. #endif /* __cplusplus */
  107762. #endif
  107763. /*** End of inlined file: vorbisfile.h ***/
  107764. /*** Start of inlined file: bitwise.c ***/
  107765. /* We're 'LSb' endian; if we write a word but read individual bits,
  107766. then we'll read the lsb first */
  107767. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107768. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107769. // tasks..
  107770. #if JUCE_MSVC
  107771. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107772. #endif
  107773. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107774. #if JUCE_USE_OGGVORBIS
  107775. #include <string.h>
  107776. #include <stdlib.h>
  107777. #define BUFFER_INCREMENT 256
  107778. static const unsigned long mask[]=
  107779. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107780. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107781. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107782. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107783. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107784. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107785. 0x3fffffff,0x7fffffff,0xffffffff };
  107786. static const unsigned int mask8B[]=
  107787. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107788. void oggpack_writeinit(oggpack_buffer *b){
  107789. memset(b,0,sizeof(*b));
  107790. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107791. b->buffer[0]='\0';
  107792. b->storage=BUFFER_INCREMENT;
  107793. }
  107794. void oggpackB_writeinit(oggpack_buffer *b){
  107795. oggpack_writeinit(b);
  107796. }
  107797. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107798. long bytes=bits>>3;
  107799. bits-=bytes*8;
  107800. b->ptr=b->buffer+bytes;
  107801. b->endbit=bits;
  107802. b->endbyte=bytes;
  107803. *b->ptr&=mask[bits];
  107804. }
  107805. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107806. long bytes=bits>>3;
  107807. bits-=bytes*8;
  107808. b->ptr=b->buffer+bytes;
  107809. b->endbit=bits;
  107810. b->endbyte=bytes;
  107811. *b->ptr&=mask8B[bits];
  107812. }
  107813. /* Takes only up to 32 bits. */
  107814. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107815. if(b->endbyte+4>=b->storage){
  107816. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107817. b->storage+=BUFFER_INCREMENT;
  107818. b->ptr=b->buffer+b->endbyte;
  107819. }
  107820. value&=mask[bits];
  107821. bits+=b->endbit;
  107822. b->ptr[0]|=value<<b->endbit;
  107823. if(bits>=8){
  107824. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107825. if(bits>=16){
  107826. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107827. if(bits>=24){
  107828. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107829. if(bits>=32){
  107830. if(b->endbit)
  107831. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107832. else
  107833. b->ptr[4]=0;
  107834. }
  107835. }
  107836. }
  107837. }
  107838. b->endbyte+=bits/8;
  107839. b->ptr+=bits/8;
  107840. b->endbit=bits&7;
  107841. }
  107842. /* Takes only up to 32 bits. */
  107843. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107844. if(b->endbyte+4>=b->storage){
  107845. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107846. b->storage+=BUFFER_INCREMENT;
  107847. b->ptr=b->buffer+b->endbyte;
  107848. }
  107849. value=(value&mask[bits])<<(32-bits);
  107850. bits+=b->endbit;
  107851. b->ptr[0]|=value>>(24+b->endbit);
  107852. if(bits>=8){
  107853. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107854. if(bits>=16){
  107855. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107856. if(bits>=24){
  107857. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107858. if(bits>=32){
  107859. if(b->endbit)
  107860. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107861. else
  107862. b->ptr[4]=0;
  107863. }
  107864. }
  107865. }
  107866. }
  107867. b->endbyte+=bits/8;
  107868. b->ptr+=bits/8;
  107869. b->endbit=bits&7;
  107870. }
  107871. void oggpack_writealign(oggpack_buffer *b){
  107872. int bits=8-b->endbit;
  107873. if(bits<8)
  107874. oggpack_write(b,0,bits);
  107875. }
  107876. void oggpackB_writealign(oggpack_buffer *b){
  107877. int bits=8-b->endbit;
  107878. if(bits<8)
  107879. oggpackB_write(b,0,bits);
  107880. }
  107881. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107882. void *source,
  107883. long bits,
  107884. void (*w)(oggpack_buffer *,
  107885. unsigned long,
  107886. int),
  107887. int msb){
  107888. unsigned char *ptr=(unsigned char *)source;
  107889. long bytes=bits/8;
  107890. bits-=bytes*8;
  107891. if(b->endbit){
  107892. int i;
  107893. /* unaligned copy. Do it the hard way. */
  107894. for(i=0;i<bytes;i++)
  107895. w(b,(unsigned long)(ptr[i]),8);
  107896. }else{
  107897. /* aligned block copy */
  107898. if(b->endbyte+bytes+1>=b->storage){
  107899. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107900. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107901. b->ptr=b->buffer+b->endbyte;
  107902. }
  107903. memmove(b->ptr,source,bytes);
  107904. b->ptr+=bytes;
  107905. b->endbyte+=bytes;
  107906. *b->ptr=0;
  107907. }
  107908. if(bits){
  107909. if(msb)
  107910. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107911. else
  107912. w(b,(unsigned long)(ptr[bytes]),bits);
  107913. }
  107914. }
  107915. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107916. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107917. }
  107918. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107919. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107920. }
  107921. void oggpack_reset(oggpack_buffer *b){
  107922. b->ptr=b->buffer;
  107923. b->buffer[0]=0;
  107924. b->endbit=b->endbyte=0;
  107925. }
  107926. void oggpackB_reset(oggpack_buffer *b){
  107927. oggpack_reset(b);
  107928. }
  107929. void oggpack_writeclear(oggpack_buffer *b){
  107930. _ogg_free(b->buffer);
  107931. memset(b,0,sizeof(*b));
  107932. }
  107933. void oggpackB_writeclear(oggpack_buffer *b){
  107934. oggpack_writeclear(b);
  107935. }
  107936. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107937. memset(b,0,sizeof(*b));
  107938. b->buffer=b->ptr=buf;
  107939. b->storage=bytes;
  107940. }
  107941. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107942. oggpack_readinit(b,buf,bytes);
  107943. }
  107944. /* Read in bits without advancing the bitptr; bits <= 32 */
  107945. long oggpack_look(oggpack_buffer *b,int bits){
  107946. unsigned long ret;
  107947. unsigned long m=mask[bits];
  107948. bits+=b->endbit;
  107949. if(b->endbyte+4>=b->storage){
  107950. /* not the main path */
  107951. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107952. }
  107953. ret=b->ptr[0]>>b->endbit;
  107954. if(bits>8){
  107955. ret|=b->ptr[1]<<(8-b->endbit);
  107956. if(bits>16){
  107957. ret|=b->ptr[2]<<(16-b->endbit);
  107958. if(bits>24){
  107959. ret|=b->ptr[3]<<(24-b->endbit);
  107960. if(bits>32 && b->endbit)
  107961. ret|=b->ptr[4]<<(32-b->endbit);
  107962. }
  107963. }
  107964. }
  107965. return(m&ret);
  107966. }
  107967. /* Read in bits without advancing the bitptr; bits <= 32 */
  107968. long oggpackB_look(oggpack_buffer *b,int bits){
  107969. unsigned long ret;
  107970. int m=32-bits;
  107971. bits+=b->endbit;
  107972. if(b->endbyte+4>=b->storage){
  107973. /* not the main path */
  107974. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107975. }
  107976. ret=b->ptr[0]<<(24+b->endbit);
  107977. if(bits>8){
  107978. ret|=b->ptr[1]<<(16+b->endbit);
  107979. if(bits>16){
  107980. ret|=b->ptr[2]<<(8+b->endbit);
  107981. if(bits>24){
  107982. ret|=b->ptr[3]<<(b->endbit);
  107983. if(bits>32 && b->endbit)
  107984. ret|=b->ptr[4]>>(8-b->endbit);
  107985. }
  107986. }
  107987. }
  107988. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107989. }
  107990. long oggpack_look1(oggpack_buffer *b){
  107991. if(b->endbyte>=b->storage)return(-1);
  107992. return((b->ptr[0]>>b->endbit)&1);
  107993. }
  107994. long oggpackB_look1(oggpack_buffer *b){
  107995. if(b->endbyte>=b->storage)return(-1);
  107996. return((b->ptr[0]>>(7-b->endbit))&1);
  107997. }
  107998. void oggpack_adv(oggpack_buffer *b,int bits){
  107999. bits+=b->endbit;
  108000. b->ptr+=bits/8;
  108001. b->endbyte+=bits/8;
  108002. b->endbit=bits&7;
  108003. }
  108004. void oggpackB_adv(oggpack_buffer *b,int bits){
  108005. oggpack_adv(b,bits);
  108006. }
  108007. void oggpack_adv1(oggpack_buffer *b){
  108008. if(++(b->endbit)>7){
  108009. b->endbit=0;
  108010. b->ptr++;
  108011. b->endbyte++;
  108012. }
  108013. }
  108014. void oggpackB_adv1(oggpack_buffer *b){
  108015. oggpack_adv1(b);
  108016. }
  108017. /* bits <= 32 */
  108018. long oggpack_read(oggpack_buffer *b,int bits){
  108019. long ret;
  108020. unsigned long m=mask[bits];
  108021. bits+=b->endbit;
  108022. if(b->endbyte+4>=b->storage){
  108023. /* not the main path */
  108024. ret=-1L;
  108025. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108026. }
  108027. ret=b->ptr[0]>>b->endbit;
  108028. if(bits>8){
  108029. ret|=b->ptr[1]<<(8-b->endbit);
  108030. if(bits>16){
  108031. ret|=b->ptr[2]<<(16-b->endbit);
  108032. if(bits>24){
  108033. ret|=b->ptr[3]<<(24-b->endbit);
  108034. if(bits>32 && b->endbit){
  108035. ret|=b->ptr[4]<<(32-b->endbit);
  108036. }
  108037. }
  108038. }
  108039. }
  108040. ret&=m;
  108041. overflow:
  108042. b->ptr+=bits/8;
  108043. b->endbyte+=bits/8;
  108044. b->endbit=bits&7;
  108045. return(ret);
  108046. }
  108047. /* bits <= 32 */
  108048. long oggpackB_read(oggpack_buffer *b,int bits){
  108049. long ret;
  108050. long m=32-bits;
  108051. bits+=b->endbit;
  108052. if(b->endbyte+4>=b->storage){
  108053. /* not the main path */
  108054. ret=-1L;
  108055. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108056. }
  108057. ret=b->ptr[0]<<(24+b->endbit);
  108058. if(bits>8){
  108059. ret|=b->ptr[1]<<(16+b->endbit);
  108060. if(bits>16){
  108061. ret|=b->ptr[2]<<(8+b->endbit);
  108062. if(bits>24){
  108063. ret|=b->ptr[3]<<(b->endbit);
  108064. if(bits>32 && b->endbit)
  108065. ret|=b->ptr[4]>>(8-b->endbit);
  108066. }
  108067. }
  108068. }
  108069. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  108070. overflow:
  108071. b->ptr+=bits/8;
  108072. b->endbyte+=bits/8;
  108073. b->endbit=bits&7;
  108074. return(ret);
  108075. }
  108076. long oggpack_read1(oggpack_buffer *b){
  108077. long ret;
  108078. if(b->endbyte>=b->storage){
  108079. /* not the main path */
  108080. ret=-1L;
  108081. goto overflow;
  108082. }
  108083. ret=(b->ptr[0]>>b->endbit)&1;
  108084. overflow:
  108085. b->endbit++;
  108086. if(b->endbit>7){
  108087. b->endbit=0;
  108088. b->ptr++;
  108089. b->endbyte++;
  108090. }
  108091. return(ret);
  108092. }
  108093. long oggpackB_read1(oggpack_buffer *b){
  108094. long ret;
  108095. if(b->endbyte>=b->storage){
  108096. /* not the main path */
  108097. ret=-1L;
  108098. goto overflow;
  108099. }
  108100. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108101. overflow:
  108102. b->endbit++;
  108103. if(b->endbit>7){
  108104. b->endbit=0;
  108105. b->ptr++;
  108106. b->endbyte++;
  108107. }
  108108. return(ret);
  108109. }
  108110. long oggpack_bytes(oggpack_buffer *b){
  108111. return(b->endbyte+(b->endbit+7)/8);
  108112. }
  108113. long oggpack_bits(oggpack_buffer *b){
  108114. return(b->endbyte*8+b->endbit);
  108115. }
  108116. long oggpackB_bytes(oggpack_buffer *b){
  108117. return oggpack_bytes(b);
  108118. }
  108119. long oggpackB_bits(oggpack_buffer *b){
  108120. return oggpack_bits(b);
  108121. }
  108122. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108123. return(b->buffer);
  108124. }
  108125. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108126. return oggpack_get_buffer(b);
  108127. }
  108128. /* Self test of the bitwise routines; everything else is based on
  108129. them, so they damned well better be solid. */
  108130. #ifdef _V_SELFTEST
  108131. #include <stdio.h>
  108132. static int ilog(unsigned int v){
  108133. int ret=0;
  108134. while(v){
  108135. ret++;
  108136. v>>=1;
  108137. }
  108138. return(ret);
  108139. }
  108140. oggpack_buffer o;
  108141. oggpack_buffer r;
  108142. void report(char *in){
  108143. fprintf(stderr,"%s",in);
  108144. exit(1);
  108145. }
  108146. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108147. long bytes,i;
  108148. unsigned char *buffer;
  108149. oggpack_reset(&o);
  108150. for(i=0;i<vals;i++)
  108151. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108152. buffer=oggpack_get_buffer(&o);
  108153. bytes=oggpack_bytes(&o);
  108154. if(bytes!=compsize)report("wrong number of bytes!\n");
  108155. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108156. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108157. report("wrote incorrect value!\n");
  108158. }
  108159. oggpack_readinit(&r,buffer,bytes);
  108160. for(i=0;i<vals;i++){
  108161. int tbit=bits?bits:ilog(b[i]);
  108162. if(oggpack_look(&r,tbit)==-1)
  108163. report("out of data!\n");
  108164. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108165. report("looked at incorrect value!\n");
  108166. if(tbit==1)
  108167. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108168. report("looked at single bit incorrect value!\n");
  108169. if(tbit==1){
  108170. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108171. report("read incorrect single bit value!\n");
  108172. }else{
  108173. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108174. report("read incorrect value!\n");
  108175. }
  108176. }
  108177. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108178. }
  108179. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108180. long bytes,i;
  108181. unsigned char *buffer;
  108182. oggpackB_reset(&o);
  108183. for(i=0;i<vals;i++)
  108184. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108185. buffer=oggpackB_get_buffer(&o);
  108186. bytes=oggpackB_bytes(&o);
  108187. if(bytes!=compsize)report("wrong number of bytes!\n");
  108188. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108189. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108190. report("wrote incorrect value!\n");
  108191. }
  108192. oggpackB_readinit(&r,buffer,bytes);
  108193. for(i=0;i<vals;i++){
  108194. int tbit=bits?bits:ilog(b[i]);
  108195. if(oggpackB_look(&r,tbit)==-1)
  108196. report("out of data!\n");
  108197. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108198. report("looked at incorrect value!\n");
  108199. if(tbit==1)
  108200. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108201. report("looked at single bit incorrect value!\n");
  108202. if(tbit==1){
  108203. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108204. report("read incorrect single bit value!\n");
  108205. }else{
  108206. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108207. report("read incorrect value!\n");
  108208. }
  108209. }
  108210. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108211. }
  108212. int main(void){
  108213. unsigned char *buffer;
  108214. long bytes,i;
  108215. static unsigned long testbuffer1[]=
  108216. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108217. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108218. int test1size=43;
  108219. static unsigned long testbuffer2[]=
  108220. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108221. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108222. 85525151,0,12321,1,349528352};
  108223. int test2size=21;
  108224. static unsigned long testbuffer3[]=
  108225. {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,
  108226. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108227. int test3size=56;
  108228. static unsigned long large[]=
  108229. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108230. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108231. 85525151,0,12321,1,2146528352};
  108232. int onesize=33;
  108233. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108234. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108235. 223,4};
  108236. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108237. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108238. 245,251,128};
  108239. int twosize=6;
  108240. static int two[6]={61,255,255,251,231,29};
  108241. static int twoB[6]={247,63,255,253,249,120};
  108242. int threesize=54;
  108243. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108244. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108245. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108246. 100,52,4,14,18,86,77,1};
  108247. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108248. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108249. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108250. 200,20,254,4,58,106,176,144,0};
  108251. int foursize=38;
  108252. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108253. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108254. 28,2,133,0,1};
  108255. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108256. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108257. 129,10,4,32};
  108258. int fivesize=45;
  108259. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108260. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108261. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108262. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108263. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108264. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108265. int sixsize=7;
  108266. static int six[7]={17,177,170,242,169,19,148};
  108267. static int sixB[7]={136,141,85,79,149,200,41};
  108268. /* Test read/write together */
  108269. /* Later we test against pregenerated bitstreams */
  108270. oggpack_writeinit(&o);
  108271. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108272. cliptest(testbuffer1,test1size,0,one,onesize);
  108273. fprintf(stderr,"ok.");
  108274. fprintf(stderr,"\nNull bit call (LSb): ");
  108275. cliptest(testbuffer3,test3size,0,two,twosize);
  108276. fprintf(stderr,"ok.");
  108277. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108278. cliptest(testbuffer2,test2size,0,three,threesize);
  108279. fprintf(stderr,"ok.");
  108280. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108281. oggpack_reset(&o);
  108282. for(i=0;i<test2size;i++)
  108283. oggpack_write(&o,large[i],32);
  108284. buffer=oggpack_get_buffer(&o);
  108285. bytes=oggpack_bytes(&o);
  108286. oggpack_readinit(&r,buffer,bytes);
  108287. for(i=0;i<test2size;i++){
  108288. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108289. if(oggpack_look(&r,32)!=large[i]){
  108290. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108291. oggpack_look(&r,32),large[i]);
  108292. report("read incorrect value!\n");
  108293. }
  108294. oggpack_adv(&r,32);
  108295. }
  108296. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108297. fprintf(stderr,"ok.");
  108298. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108299. cliptest(testbuffer1,test1size,7,four,foursize);
  108300. fprintf(stderr,"ok.");
  108301. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108302. cliptest(testbuffer2,test2size,17,five,fivesize);
  108303. fprintf(stderr,"ok.");
  108304. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108305. cliptest(testbuffer3,test3size,1,six,sixsize);
  108306. fprintf(stderr,"ok.");
  108307. fprintf(stderr,"\nTesting read past end (LSb): ");
  108308. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108309. for(i=0;i<64;i++){
  108310. if(oggpack_read(&r,1)!=0){
  108311. fprintf(stderr,"failed; got -1 prematurely.\n");
  108312. exit(1);
  108313. }
  108314. }
  108315. if(oggpack_look(&r,1)!=-1 ||
  108316. oggpack_read(&r,1)!=-1){
  108317. fprintf(stderr,"failed; read past end without -1.\n");
  108318. exit(1);
  108319. }
  108320. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108321. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108322. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108323. exit(1);
  108324. }
  108325. if(oggpack_look(&r,18)!=0 ||
  108326. oggpack_look(&r,18)!=0){
  108327. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108328. exit(1);
  108329. }
  108330. if(oggpack_look(&r,19)!=-1 ||
  108331. oggpack_look(&r,19)!=-1){
  108332. fprintf(stderr,"failed; read past end without -1.\n");
  108333. exit(1);
  108334. }
  108335. if(oggpack_look(&r,32)!=-1 ||
  108336. oggpack_look(&r,32)!=-1){
  108337. fprintf(stderr,"failed; read past end without -1.\n");
  108338. exit(1);
  108339. }
  108340. oggpack_writeclear(&o);
  108341. fprintf(stderr,"ok.\n");
  108342. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108343. /* Test read/write together */
  108344. /* Later we test against pregenerated bitstreams */
  108345. oggpackB_writeinit(&o);
  108346. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108347. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108348. fprintf(stderr,"ok.");
  108349. fprintf(stderr,"\nNull bit call (MSb): ");
  108350. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108351. fprintf(stderr,"ok.");
  108352. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108353. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108354. fprintf(stderr,"ok.");
  108355. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108356. oggpackB_reset(&o);
  108357. for(i=0;i<test2size;i++)
  108358. oggpackB_write(&o,large[i],32);
  108359. buffer=oggpackB_get_buffer(&o);
  108360. bytes=oggpackB_bytes(&o);
  108361. oggpackB_readinit(&r,buffer,bytes);
  108362. for(i=0;i<test2size;i++){
  108363. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108364. if(oggpackB_look(&r,32)!=large[i]){
  108365. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108366. oggpackB_look(&r,32),large[i]);
  108367. report("read incorrect value!\n");
  108368. }
  108369. oggpackB_adv(&r,32);
  108370. }
  108371. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108372. fprintf(stderr,"ok.");
  108373. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108374. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108375. fprintf(stderr,"ok.");
  108376. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108377. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108378. fprintf(stderr,"ok.");
  108379. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108380. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108381. fprintf(stderr,"ok.");
  108382. fprintf(stderr,"\nTesting read past end (MSb): ");
  108383. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108384. for(i=0;i<64;i++){
  108385. if(oggpackB_read(&r,1)!=0){
  108386. fprintf(stderr,"failed; got -1 prematurely.\n");
  108387. exit(1);
  108388. }
  108389. }
  108390. if(oggpackB_look(&r,1)!=-1 ||
  108391. oggpackB_read(&r,1)!=-1){
  108392. fprintf(stderr,"failed; read past end without -1.\n");
  108393. exit(1);
  108394. }
  108395. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108396. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108397. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108398. exit(1);
  108399. }
  108400. if(oggpackB_look(&r,18)!=0 ||
  108401. oggpackB_look(&r,18)!=0){
  108402. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108403. exit(1);
  108404. }
  108405. if(oggpackB_look(&r,19)!=-1 ||
  108406. oggpackB_look(&r,19)!=-1){
  108407. fprintf(stderr,"failed; read past end without -1.\n");
  108408. exit(1);
  108409. }
  108410. if(oggpackB_look(&r,32)!=-1 ||
  108411. oggpackB_look(&r,32)!=-1){
  108412. fprintf(stderr,"failed; read past end without -1.\n");
  108413. exit(1);
  108414. }
  108415. oggpackB_writeclear(&o);
  108416. fprintf(stderr,"ok.\n\n");
  108417. return(0);
  108418. }
  108419. #endif /* _V_SELFTEST */
  108420. #undef BUFFER_INCREMENT
  108421. #endif
  108422. /*** End of inlined file: bitwise.c ***/
  108423. /*** Start of inlined file: framing.c ***/
  108424. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108425. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108426. // tasks..
  108427. #if JUCE_MSVC
  108428. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108429. #endif
  108430. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108431. #if JUCE_USE_OGGVORBIS
  108432. #include <stdlib.h>
  108433. #include <string.h>
  108434. /* A complete description of Ogg framing exists in docs/framing.html */
  108435. int ogg_page_version(ogg_page *og){
  108436. return((int)(og->header[4]));
  108437. }
  108438. int ogg_page_continued(ogg_page *og){
  108439. return((int)(og->header[5]&0x01));
  108440. }
  108441. int ogg_page_bos(ogg_page *og){
  108442. return((int)(og->header[5]&0x02));
  108443. }
  108444. int ogg_page_eos(ogg_page *og){
  108445. return((int)(og->header[5]&0x04));
  108446. }
  108447. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108448. unsigned char *page=og->header;
  108449. ogg_int64_t granulepos=page[13]&(0xff);
  108450. granulepos= (granulepos<<8)|(page[12]&0xff);
  108451. granulepos= (granulepos<<8)|(page[11]&0xff);
  108452. granulepos= (granulepos<<8)|(page[10]&0xff);
  108453. granulepos= (granulepos<<8)|(page[9]&0xff);
  108454. granulepos= (granulepos<<8)|(page[8]&0xff);
  108455. granulepos= (granulepos<<8)|(page[7]&0xff);
  108456. granulepos= (granulepos<<8)|(page[6]&0xff);
  108457. return(granulepos);
  108458. }
  108459. int ogg_page_serialno(ogg_page *og){
  108460. return(og->header[14] |
  108461. (og->header[15]<<8) |
  108462. (og->header[16]<<16) |
  108463. (og->header[17]<<24));
  108464. }
  108465. long ogg_page_pageno(ogg_page *og){
  108466. return(og->header[18] |
  108467. (og->header[19]<<8) |
  108468. (og->header[20]<<16) |
  108469. (og->header[21]<<24));
  108470. }
  108471. /* returns the number of packets that are completed on this page (if
  108472. the leading packet is begun on a previous page, but ends on this
  108473. page, it's counted */
  108474. /* NOTE:
  108475. If a page consists of a packet begun on a previous page, and a new
  108476. packet begun (but not completed) on this page, the return will be:
  108477. ogg_page_packets(page) ==1,
  108478. ogg_page_continued(page) !=0
  108479. If a page happens to be a single packet that was begun on a
  108480. previous page, and spans to the next page (in the case of a three or
  108481. more page packet), the return will be:
  108482. ogg_page_packets(page) ==0,
  108483. ogg_page_continued(page) !=0
  108484. */
  108485. int ogg_page_packets(ogg_page *og){
  108486. int i,n=og->header[26],count=0;
  108487. for(i=0;i<n;i++)
  108488. if(og->header[27+i]<255)count++;
  108489. return(count);
  108490. }
  108491. #if 0
  108492. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108493. use the static init below) */
  108494. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108495. int i;
  108496. unsigned long r;
  108497. r = index << 24;
  108498. for (i=0; i<8; i++)
  108499. if (r & 0x80000000UL)
  108500. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108501. polynomial, although we use an
  108502. unreflected alg and an init/final
  108503. of 0, not 0xffffffff */
  108504. else
  108505. r<<=1;
  108506. return (r & 0xffffffffUL);
  108507. }
  108508. #endif
  108509. static const ogg_uint32_t crc_lookup[256]={
  108510. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108511. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108512. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108513. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108514. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108515. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108516. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108517. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108518. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108519. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108520. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108521. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108522. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108523. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108524. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108525. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108526. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108527. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108528. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108529. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108530. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108531. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108532. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108533. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108534. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108535. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108536. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108537. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108538. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108539. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108540. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108541. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108542. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108543. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108544. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108545. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108546. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108547. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108548. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108549. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108550. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108551. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108552. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108553. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108554. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108555. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108556. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108557. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108558. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108559. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108560. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108561. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108562. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108563. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108564. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108565. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108566. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108567. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108568. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108569. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108570. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108571. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108572. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108573. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108574. /* init the encode/decode logical stream state */
  108575. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108576. if(os){
  108577. memset(os,0,sizeof(*os));
  108578. os->body_storage=16*1024;
  108579. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108580. os->lacing_storage=1024;
  108581. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108582. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108583. os->serialno=serialno;
  108584. return(0);
  108585. }
  108586. return(-1);
  108587. }
  108588. /* _clear does not free os, only the non-flat storage within */
  108589. int ogg_stream_clear(ogg_stream_state *os){
  108590. if(os){
  108591. if(os->body_data)_ogg_free(os->body_data);
  108592. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108593. if(os->granule_vals)_ogg_free(os->granule_vals);
  108594. memset(os,0,sizeof(*os));
  108595. }
  108596. return(0);
  108597. }
  108598. int ogg_stream_destroy(ogg_stream_state *os){
  108599. if(os){
  108600. ogg_stream_clear(os);
  108601. _ogg_free(os);
  108602. }
  108603. return(0);
  108604. }
  108605. /* Helpers for ogg_stream_encode; this keeps the structure and
  108606. what's happening fairly clear */
  108607. static void _os_body_expand(ogg_stream_state *os,int needed){
  108608. if(os->body_storage<=os->body_fill+needed){
  108609. os->body_storage+=(needed+1024);
  108610. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108611. }
  108612. }
  108613. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108614. if(os->lacing_storage<=os->lacing_fill+needed){
  108615. os->lacing_storage+=(needed+32);
  108616. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108617. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108618. }
  108619. }
  108620. /* checksum the page */
  108621. /* Direct table CRC; note that this will be faster in the future if we
  108622. perform the checksum silmultaneously with other copies */
  108623. void ogg_page_checksum_set(ogg_page *og){
  108624. if(og){
  108625. ogg_uint32_t crc_reg=0;
  108626. int i;
  108627. /* safety; needed for API behavior, but not framing code */
  108628. og->header[22]=0;
  108629. og->header[23]=0;
  108630. og->header[24]=0;
  108631. og->header[25]=0;
  108632. for(i=0;i<og->header_len;i++)
  108633. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108634. for(i=0;i<og->body_len;i++)
  108635. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108636. og->header[22]=(unsigned char)(crc_reg&0xff);
  108637. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108638. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108639. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108640. }
  108641. }
  108642. /* submit data to the internal buffer of the framing engine */
  108643. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108644. int lacing_vals=op->bytes/255+1,i;
  108645. if(os->body_returned){
  108646. /* advance packet data according to the body_returned pointer. We
  108647. had to keep it around to return a pointer into the buffer last
  108648. call */
  108649. os->body_fill-=os->body_returned;
  108650. if(os->body_fill)
  108651. memmove(os->body_data,os->body_data+os->body_returned,
  108652. os->body_fill);
  108653. os->body_returned=0;
  108654. }
  108655. /* make sure we have the buffer storage */
  108656. _os_body_expand(os,op->bytes);
  108657. _os_lacing_expand(os,lacing_vals);
  108658. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108659. the liability of overly clean abstraction for the time being. It
  108660. will actually be fairly easy to eliminate the extra copy in the
  108661. future */
  108662. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108663. os->body_fill+=op->bytes;
  108664. /* Store lacing vals for this packet */
  108665. for(i=0;i<lacing_vals-1;i++){
  108666. os->lacing_vals[os->lacing_fill+i]=255;
  108667. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108668. }
  108669. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108670. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108671. /* flag the first segment as the beginning of the packet */
  108672. os->lacing_vals[os->lacing_fill]|= 0x100;
  108673. os->lacing_fill+=lacing_vals;
  108674. /* for the sake of completeness */
  108675. os->packetno++;
  108676. if(op->e_o_s)os->e_o_s=1;
  108677. return(0);
  108678. }
  108679. /* This will flush remaining packets into a page (returning nonzero),
  108680. even if there is not enough data to trigger a flush normally
  108681. (undersized page). If there are no packets or partial packets to
  108682. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108683. try to flush a normal sized page like ogg_stream_pageout; a call to
  108684. ogg_stream_flush does not guarantee that all packets have flushed.
  108685. Only a return value of 0 from ogg_stream_flush indicates all packet
  108686. data is flushed into pages.
  108687. since ogg_stream_flush will flush the last page in a stream even if
  108688. it's undersized, you almost certainly want to use ogg_stream_pageout
  108689. (and *not* ogg_stream_flush) unless you specifically need to flush
  108690. an page regardless of size in the middle of a stream. */
  108691. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108692. int i;
  108693. int vals=0;
  108694. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108695. int bytes=0;
  108696. long acc=0;
  108697. ogg_int64_t granule_pos=-1;
  108698. if(maxvals==0)return(0);
  108699. /* construct a page */
  108700. /* decide how many segments to include */
  108701. /* If this is the initial header case, the first page must only include
  108702. the initial header packet */
  108703. if(os->b_o_s==0){ /* 'initial header page' case */
  108704. granule_pos=0;
  108705. for(vals=0;vals<maxvals;vals++){
  108706. if((os->lacing_vals[vals]&0x0ff)<255){
  108707. vals++;
  108708. break;
  108709. }
  108710. }
  108711. }else{
  108712. for(vals=0;vals<maxvals;vals++){
  108713. if(acc>4096)break;
  108714. acc+=os->lacing_vals[vals]&0x0ff;
  108715. if((os->lacing_vals[vals]&0xff)<255)
  108716. granule_pos=os->granule_vals[vals];
  108717. }
  108718. }
  108719. /* construct the header in temp storage */
  108720. memcpy(os->header,"OggS",4);
  108721. /* stream structure version */
  108722. os->header[4]=0x00;
  108723. /* continued packet flag? */
  108724. os->header[5]=0x00;
  108725. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108726. /* first page flag? */
  108727. if(os->b_o_s==0)os->header[5]|=0x02;
  108728. /* last page flag? */
  108729. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108730. os->b_o_s=1;
  108731. /* 64 bits of PCM position */
  108732. for(i=6;i<14;i++){
  108733. os->header[i]=(unsigned char)(granule_pos&0xff);
  108734. granule_pos>>=8;
  108735. }
  108736. /* 32 bits of stream serial number */
  108737. {
  108738. long serialno=os->serialno;
  108739. for(i=14;i<18;i++){
  108740. os->header[i]=(unsigned char)(serialno&0xff);
  108741. serialno>>=8;
  108742. }
  108743. }
  108744. /* 32 bits of page counter (we have both counter and page header
  108745. because this val can roll over) */
  108746. if(os->pageno==-1)os->pageno=0; /* because someone called
  108747. stream_reset; this would be a
  108748. strange thing to do in an
  108749. encode stream, but it has
  108750. plausible uses */
  108751. {
  108752. long pageno=os->pageno++;
  108753. for(i=18;i<22;i++){
  108754. os->header[i]=(unsigned char)(pageno&0xff);
  108755. pageno>>=8;
  108756. }
  108757. }
  108758. /* zero for computation; filled in later */
  108759. os->header[22]=0;
  108760. os->header[23]=0;
  108761. os->header[24]=0;
  108762. os->header[25]=0;
  108763. /* segment table */
  108764. os->header[26]=(unsigned char)(vals&0xff);
  108765. for(i=0;i<vals;i++)
  108766. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108767. /* set pointers in the ogg_page struct */
  108768. og->header=os->header;
  108769. og->header_len=os->header_fill=vals+27;
  108770. og->body=os->body_data+os->body_returned;
  108771. og->body_len=bytes;
  108772. /* advance the lacing data and set the body_returned pointer */
  108773. os->lacing_fill-=vals;
  108774. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108775. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108776. os->body_returned+=bytes;
  108777. /* calculate the checksum */
  108778. ogg_page_checksum_set(og);
  108779. /* done */
  108780. return(1);
  108781. }
  108782. /* This constructs pages from buffered packet segments. The pointers
  108783. returned are to static buffers; do not free. The returned buffers are
  108784. good only until the next call (using the same ogg_stream_state) */
  108785. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108786. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108787. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108788. os->lacing_fill>=255 || /* 'segment table full' case */
  108789. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108790. return(ogg_stream_flush(os,og));
  108791. }
  108792. /* not enough data to construct a page and not end of stream */
  108793. return(0);
  108794. }
  108795. int ogg_stream_eos(ogg_stream_state *os){
  108796. return os->e_o_s;
  108797. }
  108798. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108799. /* This has two layers to place more of the multi-serialno and paging
  108800. control in the application's hands. First, we expose a data buffer
  108801. using ogg_sync_buffer(). The app either copies into the
  108802. buffer, or passes it directly to read(), etc. We then call
  108803. ogg_sync_wrote() to tell how many bytes we just added.
  108804. Pages are returned (pointers into the buffer in ogg_sync_state)
  108805. by ogg_sync_pageout(). The page is then submitted to
  108806. ogg_stream_pagein() along with the appropriate
  108807. ogg_stream_state* (ie, matching serialno). We then get raw
  108808. packets out calling ogg_stream_packetout() with a
  108809. ogg_stream_state. */
  108810. /* initialize the struct to a known state */
  108811. int ogg_sync_init(ogg_sync_state *oy){
  108812. if(oy){
  108813. memset(oy,0,sizeof(*oy));
  108814. }
  108815. return(0);
  108816. }
  108817. /* clear non-flat storage within */
  108818. int ogg_sync_clear(ogg_sync_state *oy){
  108819. if(oy){
  108820. if(oy->data)_ogg_free(oy->data);
  108821. ogg_sync_init(oy);
  108822. }
  108823. return(0);
  108824. }
  108825. int ogg_sync_destroy(ogg_sync_state *oy){
  108826. if(oy){
  108827. ogg_sync_clear(oy);
  108828. _ogg_free(oy);
  108829. }
  108830. return(0);
  108831. }
  108832. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108833. /* first, clear out any space that has been previously returned */
  108834. if(oy->returned){
  108835. oy->fill-=oy->returned;
  108836. if(oy->fill>0)
  108837. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108838. oy->returned=0;
  108839. }
  108840. if(size>oy->storage-oy->fill){
  108841. /* We need to extend the internal buffer */
  108842. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108843. if(oy->data)
  108844. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108845. else
  108846. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108847. oy->storage=newsize;
  108848. }
  108849. /* expose a segment at least as large as requested at the fill mark */
  108850. return((char *)oy->data+oy->fill);
  108851. }
  108852. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108853. if(oy->fill+bytes>oy->storage)return(-1);
  108854. oy->fill+=bytes;
  108855. return(0);
  108856. }
  108857. /* sync the stream. This is meant to be useful for finding page
  108858. boundaries.
  108859. return values for this:
  108860. -n) skipped n bytes
  108861. 0) page not ready; more data (no bytes skipped)
  108862. n) page synced at current location; page length n bytes
  108863. */
  108864. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108865. unsigned char *page=oy->data+oy->returned;
  108866. unsigned char *next;
  108867. long bytes=oy->fill-oy->returned;
  108868. if(oy->headerbytes==0){
  108869. int headerbytes,i;
  108870. if(bytes<27)return(0); /* not enough for a header */
  108871. /* verify capture pattern */
  108872. if(memcmp(page,"OggS",4))goto sync_fail;
  108873. headerbytes=page[26]+27;
  108874. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108875. /* count up body length in the segment table */
  108876. for(i=0;i<page[26];i++)
  108877. oy->bodybytes+=page[27+i];
  108878. oy->headerbytes=headerbytes;
  108879. }
  108880. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108881. /* The whole test page is buffered. Verify the checksum */
  108882. {
  108883. /* Grab the checksum bytes, set the header field to zero */
  108884. char chksum[4];
  108885. ogg_page log;
  108886. memcpy(chksum,page+22,4);
  108887. memset(page+22,0,4);
  108888. /* set up a temp page struct and recompute the checksum */
  108889. log.header=page;
  108890. log.header_len=oy->headerbytes;
  108891. log.body=page+oy->headerbytes;
  108892. log.body_len=oy->bodybytes;
  108893. ogg_page_checksum_set(&log);
  108894. /* Compare */
  108895. if(memcmp(chksum,page+22,4)){
  108896. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108897. at all) */
  108898. /* replace the computed checksum with the one actually read in */
  108899. memcpy(page+22,chksum,4);
  108900. /* Bad checksum. Lose sync */
  108901. goto sync_fail;
  108902. }
  108903. }
  108904. /* yes, have a whole page all ready to go */
  108905. {
  108906. unsigned char *page=oy->data+oy->returned;
  108907. long bytes;
  108908. if(og){
  108909. og->header=page;
  108910. og->header_len=oy->headerbytes;
  108911. og->body=page+oy->headerbytes;
  108912. og->body_len=oy->bodybytes;
  108913. }
  108914. oy->unsynced=0;
  108915. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108916. oy->headerbytes=0;
  108917. oy->bodybytes=0;
  108918. return(bytes);
  108919. }
  108920. sync_fail:
  108921. oy->headerbytes=0;
  108922. oy->bodybytes=0;
  108923. /* search for possible capture */
  108924. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108925. if(!next)
  108926. next=oy->data+oy->fill;
  108927. oy->returned=next-oy->data;
  108928. return(-(next-page));
  108929. }
  108930. /* sync the stream and get a page. Keep trying until we find a page.
  108931. Supress 'sync errors' after reporting the first.
  108932. return values:
  108933. -1) recapture (hole in data)
  108934. 0) need more data
  108935. 1) page returned
  108936. Returns pointers into buffered data; invalidated by next call to
  108937. _stream, _clear, _init, or _buffer */
  108938. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108939. /* all we need to do is verify a page at the head of the stream
  108940. buffer. If it doesn't verify, we look for the next potential
  108941. frame */
  108942. for(;;){
  108943. long ret=ogg_sync_pageseek(oy,og);
  108944. if(ret>0){
  108945. /* have a page */
  108946. return(1);
  108947. }
  108948. if(ret==0){
  108949. /* need more data */
  108950. return(0);
  108951. }
  108952. /* head did not start a synced page... skipped some bytes */
  108953. if(!oy->unsynced){
  108954. oy->unsynced=1;
  108955. return(-1);
  108956. }
  108957. /* loop. keep looking */
  108958. }
  108959. }
  108960. /* add the incoming page to the stream state; we decompose the page
  108961. into packet segments here as well. */
  108962. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108963. unsigned char *header=og->header;
  108964. unsigned char *body=og->body;
  108965. long bodysize=og->body_len;
  108966. int segptr=0;
  108967. int version=ogg_page_version(og);
  108968. int continued=ogg_page_continued(og);
  108969. int bos=ogg_page_bos(og);
  108970. int eos=ogg_page_eos(og);
  108971. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108972. int serialno=ogg_page_serialno(og);
  108973. long pageno=ogg_page_pageno(og);
  108974. int segments=header[26];
  108975. /* clean up 'returned data' */
  108976. {
  108977. long lr=os->lacing_returned;
  108978. long br=os->body_returned;
  108979. /* body data */
  108980. if(br){
  108981. os->body_fill-=br;
  108982. if(os->body_fill)
  108983. memmove(os->body_data,os->body_data+br,os->body_fill);
  108984. os->body_returned=0;
  108985. }
  108986. if(lr){
  108987. /* segment table */
  108988. if(os->lacing_fill-lr){
  108989. memmove(os->lacing_vals,os->lacing_vals+lr,
  108990. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108991. memmove(os->granule_vals,os->granule_vals+lr,
  108992. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108993. }
  108994. os->lacing_fill-=lr;
  108995. os->lacing_packet-=lr;
  108996. os->lacing_returned=0;
  108997. }
  108998. }
  108999. /* check the serial number */
  109000. if(serialno!=os->serialno)return(-1);
  109001. if(version>0)return(-1);
  109002. _os_lacing_expand(os,segments+1);
  109003. /* are we in sequence? */
  109004. if(pageno!=os->pageno){
  109005. int i;
  109006. /* unroll previous partial packet (if any) */
  109007. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  109008. os->body_fill-=os->lacing_vals[i]&0xff;
  109009. os->lacing_fill=os->lacing_packet;
  109010. /* make a note of dropped data in segment table */
  109011. if(os->pageno!=-1){
  109012. os->lacing_vals[os->lacing_fill++]=0x400;
  109013. os->lacing_packet++;
  109014. }
  109015. }
  109016. /* are we a 'continued packet' page? If so, we may need to skip
  109017. some segments */
  109018. if(continued){
  109019. if(os->lacing_fill<1 ||
  109020. os->lacing_vals[os->lacing_fill-1]==0x400){
  109021. bos=0;
  109022. for(;segptr<segments;segptr++){
  109023. int val=header[27+segptr];
  109024. body+=val;
  109025. bodysize-=val;
  109026. if(val<255){
  109027. segptr++;
  109028. break;
  109029. }
  109030. }
  109031. }
  109032. }
  109033. if(bodysize){
  109034. _os_body_expand(os,bodysize);
  109035. memcpy(os->body_data+os->body_fill,body,bodysize);
  109036. os->body_fill+=bodysize;
  109037. }
  109038. {
  109039. int saved=-1;
  109040. while(segptr<segments){
  109041. int val=header[27+segptr];
  109042. os->lacing_vals[os->lacing_fill]=val;
  109043. os->granule_vals[os->lacing_fill]=-1;
  109044. if(bos){
  109045. os->lacing_vals[os->lacing_fill]|=0x100;
  109046. bos=0;
  109047. }
  109048. if(val<255)saved=os->lacing_fill;
  109049. os->lacing_fill++;
  109050. segptr++;
  109051. if(val<255)os->lacing_packet=os->lacing_fill;
  109052. }
  109053. /* set the granulepos on the last granuleval of the last full packet */
  109054. if(saved!=-1){
  109055. os->granule_vals[saved]=granulepos;
  109056. }
  109057. }
  109058. if(eos){
  109059. os->e_o_s=1;
  109060. if(os->lacing_fill>0)
  109061. os->lacing_vals[os->lacing_fill-1]|=0x200;
  109062. }
  109063. os->pageno=pageno+1;
  109064. return(0);
  109065. }
  109066. /* clear things to an initial state. Good to call, eg, before seeking */
  109067. int ogg_sync_reset(ogg_sync_state *oy){
  109068. oy->fill=0;
  109069. oy->returned=0;
  109070. oy->unsynced=0;
  109071. oy->headerbytes=0;
  109072. oy->bodybytes=0;
  109073. return(0);
  109074. }
  109075. int ogg_stream_reset(ogg_stream_state *os){
  109076. os->body_fill=0;
  109077. os->body_returned=0;
  109078. os->lacing_fill=0;
  109079. os->lacing_packet=0;
  109080. os->lacing_returned=0;
  109081. os->header_fill=0;
  109082. os->e_o_s=0;
  109083. os->b_o_s=0;
  109084. os->pageno=-1;
  109085. os->packetno=0;
  109086. os->granulepos=0;
  109087. return(0);
  109088. }
  109089. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109090. ogg_stream_reset(os);
  109091. os->serialno=serialno;
  109092. return(0);
  109093. }
  109094. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109095. /* The last part of decode. We have the stream broken into packet
  109096. segments. Now we need to group them into packets (or return the
  109097. out of sync markers) */
  109098. int ptr=os->lacing_returned;
  109099. if(os->lacing_packet<=ptr)return(0);
  109100. if(os->lacing_vals[ptr]&0x400){
  109101. /* we need to tell the codec there's a gap; it might need to
  109102. handle previous packet dependencies. */
  109103. os->lacing_returned++;
  109104. os->packetno++;
  109105. return(-1);
  109106. }
  109107. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109108. to ask if there's a whole packet
  109109. waiting */
  109110. /* Gather the whole packet. We'll have no holes or a partial packet */
  109111. {
  109112. int size=os->lacing_vals[ptr]&0xff;
  109113. int bytes=size;
  109114. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109115. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109116. while(size==255){
  109117. int val=os->lacing_vals[++ptr];
  109118. size=val&0xff;
  109119. if(val&0x200)eos=0x200;
  109120. bytes+=size;
  109121. }
  109122. if(op){
  109123. op->e_o_s=eos;
  109124. op->b_o_s=bos;
  109125. op->packet=os->body_data+os->body_returned;
  109126. op->packetno=os->packetno;
  109127. op->granulepos=os->granule_vals[ptr];
  109128. op->bytes=bytes;
  109129. }
  109130. if(adv){
  109131. os->body_returned+=bytes;
  109132. os->lacing_returned=ptr+1;
  109133. os->packetno++;
  109134. }
  109135. }
  109136. return(1);
  109137. }
  109138. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109139. return _packetout(os,op,1);
  109140. }
  109141. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109142. return _packetout(os,op,0);
  109143. }
  109144. void ogg_packet_clear(ogg_packet *op) {
  109145. _ogg_free(op->packet);
  109146. memset(op, 0, sizeof(*op));
  109147. }
  109148. #ifdef _V_SELFTEST
  109149. #include <stdio.h>
  109150. ogg_stream_state os_en, os_de;
  109151. ogg_sync_state oy;
  109152. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109153. long j;
  109154. static int sequence=0;
  109155. static int lastno=0;
  109156. if(op->bytes!=len){
  109157. fprintf(stderr,"incorrect packet length!\n");
  109158. exit(1);
  109159. }
  109160. if(op->granulepos!=pos){
  109161. fprintf(stderr,"incorrect packet position!\n");
  109162. exit(1);
  109163. }
  109164. /* packet number just follows sequence/gap; adjust the input number
  109165. for that */
  109166. if(no==0){
  109167. sequence=0;
  109168. }else{
  109169. sequence++;
  109170. if(no>lastno+1)
  109171. sequence++;
  109172. }
  109173. lastno=no;
  109174. if(op->packetno!=sequence){
  109175. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109176. (long)(op->packetno),sequence);
  109177. exit(1);
  109178. }
  109179. /* Test data */
  109180. for(j=0;j<op->bytes;j++)
  109181. if(op->packet[j]!=((j+no)&0xff)){
  109182. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109183. j,op->packet[j],(j+no)&0xff);
  109184. exit(1);
  109185. }
  109186. }
  109187. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109188. long j;
  109189. /* Test data */
  109190. for(j=0;j<og->body_len;j++)
  109191. if(og->body[j]!=data[j]){
  109192. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109193. j,data[j],og->body[j]);
  109194. exit(1);
  109195. }
  109196. /* Test header */
  109197. for(j=0;j<og->header_len;j++){
  109198. if(og->header[j]!=header[j]){
  109199. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109200. for(j=0;j<header[26]+27;j++)
  109201. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109202. fprintf(stderr,"\n");
  109203. exit(1);
  109204. }
  109205. }
  109206. if(og->header_len!=header[26]+27){
  109207. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109208. og->header_len,header[26]+27);
  109209. exit(1);
  109210. }
  109211. }
  109212. void print_header(ogg_page *og){
  109213. int j;
  109214. fprintf(stderr,"\nHEADER:\n");
  109215. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109216. og->header[0],og->header[1],og->header[2],og->header[3],
  109217. (int)og->header[4],(int)og->header[5]);
  109218. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109219. (og->header[9]<<24)|(og->header[8]<<16)|
  109220. (og->header[7]<<8)|og->header[6],
  109221. (og->header[17]<<24)|(og->header[16]<<16)|
  109222. (og->header[15]<<8)|og->header[14],
  109223. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109224. (og->header[19]<<8)|og->header[18]);
  109225. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109226. (int)og->header[22],(int)og->header[23],
  109227. (int)og->header[24],(int)og->header[25],
  109228. (int)og->header[26]);
  109229. for(j=27;j<og->header_len;j++)
  109230. fprintf(stderr,"%d ",(int)og->header[j]);
  109231. fprintf(stderr,")\n\n");
  109232. }
  109233. void copy_page(ogg_page *og){
  109234. unsigned char *temp=_ogg_malloc(og->header_len);
  109235. memcpy(temp,og->header,og->header_len);
  109236. og->header=temp;
  109237. temp=_ogg_malloc(og->body_len);
  109238. memcpy(temp,og->body,og->body_len);
  109239. og->body=temp;
  109240. }
  109241. void free_page(ogg_page *og){
  109242. _ogg_free (og->header);
  109243. _ogg_free (og->body);
  109244. }
  109245. void error(void){
  109246. fprintf(stderr,"error!\n");
  109247. exit(1);
  109248. }
  109249. /* 17 only */
  109250. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109251. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109252. 0x01,0x02,0x03,0x04,0,0,0,0,
  109253. 0x15,0xed,0xec,0x91,
  109254. 1,
  109255. 17};
  109256. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109257. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109258. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109259. 0x01,0x02,0x03,0x04,0,0,0,0,
  109260. 0x59,0x10,0x6c,0x2c,
  109261. 1,
  109262. 17};
  109263. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109264. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109265. 0x01,0x02,0x03,0x04,1,0,0,0,
  109266. 0x89,0x33,0x85,0xce,
  109267. 13,
  109268. 254,255,0,255,1,255,245,255,255,0,
  109269. 255,255,90};
  109270. /* nil packets; beginning,middle,end */
  109271. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109272. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109273. 0x01,0x02,0x03,0x04,0,0,0,0,
  109274. 0xff,0x7b,0x23,0x17,
  109275. 1,
  109276. 0};
  109277. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109278. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109279. 0x01,0x02,0x03,0x04,1,0,0,0,
  109280. 0x5c,0x3f,0x66,0xcb,
  109281. 17,
  109282. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109283. 255,255,90,0};
  109284. /* large initial packet */
  109285. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109286. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109287. 0x01,0x02,0x03,0x04,0,0,0,0,
  109288. 0x01,0x27,0x31,0xaa,
  109289. 18,
  109290. 255,255,255,255,255,255,255,255,
  109291. 255,255,255,255,255,255,255,255,255,10};
  109292. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109293. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109294. 0x01,0x02,0x03,0x04,1,0,0,0,
  109295. 0x7f,0x4e,0x8a,0xd2,
  109296. 4,
  109297. 255,4,255,0};
  109298. /* continuing packet test */
  109299. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109300. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109301. 0x01,0x02,0x03,0x04,0,0,0,0,
  109302. 0xff,0x7b,0x23,0x17,
  109303. 1,
  109304. 0};
  109305. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109306. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109307. 0x01,0x02,0x03,0x04,1,0,0,0,
  109308. 0x54,0x05,0x51,0xc8,
  109309. 17,
  109310. 255,255,255,255,255,255,255,255,
  109311. 255,255,255,255,255,255,255,255,255};
  109312. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109313. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109314. 0x01,0x02,0x03,0x04,2,0,0,0,
  109315. 0xc8,0xc3,0xcb,0xed,
  109316. 5,
  109317. 10,255,4,255,0};
  109318. /* page with the 255 segment limit */
  109319. const int head1_5[] = {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_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109326. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109327. 0x01,0x02,0x03,0x04,1,0,0,0,
  109328. 0xed,0x2a,0x2e,0xa7,
  109329. 255,
  109330. 10,10,10,10,10,10,10,10,
  109331. 10,10,10,10,10,10,10,10,
  109332. 10,10,10,10,10,10,10,10,
  109333. 10,10,10,10,10,10,10,10,
  109334. 10,10,10,10,10,10,10,10,
  109335. 10,10,10,10,10,10,10,10,
  109336. 10,10,10,10,10,10,10,10,
  109337. 10,10,10,10,10,10,10,10,
  109338. 10,10,10,10,10,10,10,10,
  109339. 10,10,10,10,10,10,10,10,
  109340. 10,10,10,10,10,10,10,10,
  109341. 10,10,10,10,10,10,10,10,
  109342. 10,10,10,10,10,10,10,10,
  109343. 10,10,10,10,10,10,10,10,
  109344. 10,10,10,10,10,10,10,10,
  109345. 10,10,10,10,10,10,10,10,
  109346. 10,10,10,10,10,10,10,10,
  109347. 10,10,10,10,10,10,10,10,
  109348. 10,10,10,10,10,10,10,10,
  109349. 10,10,10,10,10,10,10,10,
  109350. 10,10,10,10,10,10,10,10,
  109351. 10,10,10,10,10,10,10,10,
  109352. 10,10,10,10,10,10,10,10,
  109353. 10,10,10,10,10,10,10,10,
  109354. 10,10,10,10,10,10,10,10,
  109355. 10,10,10,10,10,10,10,10,
  109356. 10,10,10,10,10,10,10,10,
  109357. 10,10,10,10,10,10,10,10,
  109358. 10,10,10,10,10,10,10,10,
  109359. 10,10,10,10,10,10,10,10,
  109360. 10,10,10,10,10,10,10,10,
  109361. 10,10,10,10,10,10,10};
  109362. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109363. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109364. 0x01,0x02,0x03,0x04,2,0,0,0,
  109365. 0x6c,0x3b,0x82,0x3d,
  109366. 1,
  109367. 50};
  109368. /* packet that overspans over an entire page */
  109369. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109370. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109371. 0x01,0x02,0x03,0x04,0,0,0,0,
  109372. 0xff,0x7b,0x23,0x17,
  109373. 1,
  109374. 0};
  109375. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109376. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109377. 0x01,0x02,0x03,0x04,1,0,0,0,
  109378. 0x3c,0xd9,0x4d,0x3f,
  109379. 17,
  109380. 100,255,255,255,255,255,255,255,255,
  109381. 255,255,255,255,255,255,255,255};
  109382. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109383. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109384. 0x01,0x02,0x03,0x04,2,0,0,0,
  109385. 0x01,0xd2,0xe5,0xe5,
  109386. 17,
  109387. 255,255,255,255,255,255,255,255,
  109388. 255,255,255,255,255,255,255,255,255};
  109389. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109390. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109391. 0x01,0x02,0x03,0x04,3,0,0,0,
  109392. 0xef,0xdd,0x88,0xde,
  109393. 7,
  109394. 255,255,75,255,4,255,0};
  109395. /* packet that overspans over an entire page */
  109396. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109397. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109398. 0x01,0x02,0x03,0x04,0,0,0,0,
  109399. 0xff,0x7b,0x23,0x17,
  109400. 1,
  109401. 0};
  109402. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109403. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109404. 0x01,0x02,0x03,0x04,1,0,0,0,
  109405. 0x3c,0xd9,0x4d,0x3f,
  109406. 17,
  109407. 100,255,255,255,255,255,255,255,255,
  109408. 255,255,255,255,255,255,255,255};
  109409. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109410. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109411. 0x01,0x02,0x03,0x04,2,0,0,0,
  109412. 0xd4,0xe0,0x60,0xe5,
  109413. 1,0};
  109414. void test_pack(const int *pl, const int **headers, int byteskip,
  109415. int pageskip, int packetskip){
  109416. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109417. long inptr=0;
  109418. long outptr=0;
  109419. long deptr=0;
  109420. long depacket=0;
  109421. long granule_pos=7,pageno=0;
  109422. int i,j,packets,pageout=pageskip;
  109423. int eosflag=0;
  109424. int bosflag=0;
  109425. int byteskipcount=0;
  109426. ogg_stream_reset(&os_en);
  109427. ogg_stream_reset(&os_de);
  109428. ogg_sync_reset(&oy);
  109429. for(packets=0;packets<packetskip;packets++)
  109430. depacket+=pl[packets];
  109431. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109432. for(i=0;i<packets;i++){
  109433. /* construct a test packet */
  109434. ogg_packet op;
  109435. int len=pl[i];
  109436. op.packet=data+inptr;
  109437. op.bytes=len;
  109438. op.e_o_s=(pl[i+1]<0?1:0);
  109439. op.granulepos=granule_pos;
  109440. granule_pos+=1024;
  109441. for(j=0;j<len;j++)data[inptr++]=i+j;
  109442. /* submit the test packet */
  109443. ogg_stream_packetin(&os_en,&op);
  109444. /* retrieve any finished pages */
  109445. {
  109446. ogg_page og;
  109447. while(ogg_stream_pageout(&os_en,&og)){
  109448. /* We have a page. Check it carefully */
  109449. fprintf(stderr,"%ld, ",pageno);
  109450. if(headers[pageno]==NULL){
  109451. fprintf(stderr,"coded too many pages!\n");
  109452. exit(1);
  109453. }
  109454. check_page(data+outptr,headers[pageno],&og);
  109455. outptr+=og.body_len;
  109456. pageno++;
  109457. if(pageskip){
  109458. bosflag=1;
  109459. pageskip--;
  109460. deptr+=og.body_len;
  109461. }
  109462. /* have a complete page; submit it to sync/decode */
  109463. {
  109464. ogg_page og_de;
  109465. ogg_packet op_de,op_de2;
  109466. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109467. char *next=buf;
  109468. byteskipcount+=og.header_len;
  109469. if(byteskipcount>byteskip){
  109470. memcpy(next,og.header,byteskipcount-byteskip);
  109471. next+=byteskipcount-byteskip;
  109472. byteskipcount=byteskip;
  109473. }
  109474. byteskipcount+=og.body_len;
  109475. if(byteskipcount>byteskip){
  109476. memcpy(next,og.body,byteskipcount-byteskip);
  109477. next+=byteskipcount-byteskip;
  109478. byteskipcount=byteskip;
  109479. }
  109480. ogg_sync_wrote(&oy,next-buf);
  109481. while(1){
  109482. int ret=ogg_sync_pageout(&oy,&og_de);
  109483. if(ret==0)break;
  109484. if(ret<0)continue;
  109485. /* got a page. Happy happy. Verify that it's good. */
  109486. fprintf(stderr,"(%ld), ",pageout);
  109487. check_page(data+deptr,headers[pageout],&og_de);
  109488. deptr+=og_de.body_len;
  109489. pageout++;
  109490. /* submit it to deconstitution */
  109491. ogg_stream_pagein(&os_de,&og_de);
  109492. /* packets out? */
  109493. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109494. ogg_stream_packetpeek(&os_de,NULL);
  109495. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109496. /* verify peek and out match */
  109497. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109498. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109499. depacket);
  109500. exit(1);
  109501. }
  109502. /* verify the packet! */
  109503. /* check data */
  109504. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109505. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109506. depacket);
  109507. exit(1);
  109508. }
  109509. /* check bos flag */
  109510. if(bosflag==0 && op_de.b_o_s==0){
  109511. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109512. exit(1);
  109513. }
  109514. if(bosflag && op_de.b_o_s){
  109515. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109516. exit(1);
  109517. }
  109518. bosflag=1;
  109519. depacket+=op_de.bytes;
  109520. /* check eos flag */
  109521. if(eosflag){
  109522. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109523. exit(1);
  109524. }
  109525. if(op_de.e_o_s)eosflag=1;
  109526. /* check granulepos flag */
  109527. if(op_de.granulepos!=-1){
  109528. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109529. }
  109530. }
  109531. }
  109532. }
  109533. }
  109534. }
  109535. }
  109536. _ogg_free(data);
  109537. if(headers[pageno]!=NULL){
  109538. fprintf(stderr,"did not write last page!\n");
  109539. exit(1);
  109540. }
  109541. if(headers[pageout]!=NULL){
  109542. fprintf(stderr,"did not decode last page!\n");
  109543. exit(1);
  109544. }
  109545. if(inptr!=outptr){
  109546. fprintf(stderr,"encoded page data incomplete!\n");
  109547. exit(1);
  109548. }
  109549. if(inptr!=deptr){
  109550. fprintf(stderr,"decoded page data incomplete!\n");
  109551. exit(1);
  109552. }
  109553. if(inptr!=depacket){
  109554. fprintf(stderr,"decoded packet data incomplete!\n");
  109555. exit(1);
  109556. }
  109557. if(!eosflag){
  109558. fprintf(stderr,"Never got a packet with EOS set!\n");
  109559. exit(1);
  109560. }
  109561. fprintf(stderr,"ok.\n");
  109562. }
  109563. int main(void){
  109564. ogg_stream_init(&os_en,0x04030201);
  109565. ogg_stream_init(&os_de,0x04030201);
  109566. ogg_sync_init(&oy);
  109567. /* Exercise each code path in the framing code. Also verify that
  109568. the checksums are working. */
  109569. {
  109570. /* 17 only */
  109571. const int packets[]={17, -1};
  109572. const int *headret[]={head1_0,NULL};
  109573. fprintf(stderr,"testing single page encoding... ");
  109574. test_pack(packets,headret,0,0,0);
  109575. }
  109576. {
  109577. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109578. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109579. const int *headret[]={head1_1,head2_1,NULL};
  109580. fprintf(stderr,"testing basic page encoding... ");
  109581. test_pack(packets,headret,0,0,0);
  109582. }
  109583. {
  109584. /* nil packets; beginning,middle,end */
  109585. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109586. const int *headret[]={head1_2,head2_2,NULL};
  109587. fprintf(stderr,"testing basic nil packets... ");
  109588. test_pack(packets,headret,0,0,0);
  109589. }
  109590. {
  109591. /* large initial packet */
  109592. const int packets[]={4345,259,255,-1};
  109593. const int *headret[]={head1_3,head2_3,NULL};
  109594. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109595. test_pack(packets,headret,0,0,0);
  109596. }
  109597. {
  109598. /* continuing packet test */
  109599. const int packets[]={0,4345,259,255,-1};
  109600. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109601. fprintf(stderr,"testing single packet page span... ");
  109602. test_pack(packets,headret,0,0,0);
  109603. }
  109604. /* page with the 255 segment limit */
  109605. {
  109606. const int packets[]={0,10,10,10,10,10,10,10,10,
  109607. 10,10,10,10,10,10,10,10,
  109608. 10,10,10,10,10,10,10,10,
  109609. 10,10,10,10,10,10,10,10,
  109610. 10,10,10,10,10,10,10,10,
  109611. 10,10,10,10,10,10,10,10,
  109612. 10,10,10,10,10,10,10,10,
  109613. 10,10,10,10,10,10,10,10,
  109614. 10,10,10,10,10,10,10,10,
  109615. 10,10,10,10,10,10,10,10,
  109616. 10,10,10,10,10,10,10,10,
  109617. 10,10,10,10,10,10,10,10,
  109618. 10,10,10,10,10,10,10,10,
  109619. 10,10,10,10,10,10,10,10,
  109620. 10,10,10,10,10,10,10,10,
  109621. 10,10,10,10,10,10,10,10,
  109622. 10,10,10,10,10,10,10,10,
  109623. 10,10,10,10,10,10,10,10,
  109624. 10,10,10,10,10,10,10,10,
  109625. 10,10,10,10,10,10,10,10,
  109626. 10,10,10,10,10,10,10,10,
  109627. 10,10,10,10,10,10,10,10,
  109628. 10,10,10,10,10,10,10,10,
  109629. 10,10,10,10,10,10,10,10,
  109630. 10,10,10,10,10,10,10,10,
  109631. 10,10,10,10,10,10,10,10,
  109632. 10,10,10,10,10,10,10,10,
  109633. 10,10,10,10,10,10,10,10,
  109634. 10,10,10,10,10,10,10,10,
  109635. 10,10,10,10,10,10,10,10,
  109636. 10,10,10,10,10,10,10,10,
  109637. 10,10,10,10,10,10,10,50,-1};
  109638. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109639. fprintf(stderr,"testing max packet segments... ");
  109640. test_pack(packets,headret,0,0,0);
  109641. }
  109642. {
  109643. /* packet that overspans over an entire page */
  109644. const int packets[]={0,100,9000,259,255,-1};
  109645. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109646. fprintf(stderr,"testing very large packets... ");
  109647. test_pack(packets,headret,0,0,0);
  109648. }
  109649. {
  109650. /* test for the libogg 1.1.1 resync in large continuation bug
  109651. found by Josh Coalson) */
  109652. const int packets[]={0,100,9000,259,255,-1};
  109653. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109654. fprintf(stderr,"testing continuation resync in very large packets... ");
  109655. test_pack(packets,headret,100,2,3);
  109656. }
  109657. {
  109658. /* term only page. why not? */
  109659. const int packets[]={0,100,4080,-1};
  109660. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109661. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109662. test_pack(packets,headret,0,0,0);
  109663. }
  109664. {
  109665. /* build a bunch of pages for testing */
  109666. unsigned char *data=_ogg_malloc(1024*1024);
  109667. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109668. int inptr=0,i,j;
  109669. ogg_page og[5];
  109670. ogg_stream_reset(&os_en);
  109671. for(i=0;pl[i]!=-1;i++){
  109672. ogg_packet op;
  109673. int len=pl[i];
  109674. op.packet=data+inptr;
  109675. op.bytes=len;
  109676. op.e_o_s=(pl[i+1]<0?1:0);
  109677. op.granulepos=(i+1)*1000;
  109678. for(j=0;j<len;j++)data[inptr++]=i+j;
  109679. ogg_stream_packetin(&os_en,&op);
  109680. }
  109681. _ogg_free(data);
  109682. /* retrieve finished pages */
  109683. for(i=0;i<5;i++){
  109684. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109685. fprintf(stderr,"Too few pages output building sync tests!\n");
  109686. exit(1);
  109687. }
  109688. copy_page(&og[i]);
  109689. }
  109690. /* Test lost pages on pagein/packetout: no rollback */
  109691. {
  109692. ogg_page temp;
  109693. ogg_packet test;
  109694. fprintf(stderr,"Testing loss of pages... ");
  109695. ogg_sync_reset(&oy);
  109696. ogg_stream_reset(&os_de);
  109697. for(i=0;i<5;i++){
  109698. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109699. og[i].header_len);
  109700. ogg_sync_wrote(&oy,og[i].header_len);
  109701. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109702. ogg_sync_wrote(&oy,og[i].body_len);
  109703. }
  109704. ogg_sync_pageout(&oy,&temp);
  109705. ogg_stream_pagein(&os_de,&temp);
  109706. ogg_sync_pageout(&oy,&temp);
  109707. ogg_stream_pagein(&os_de,&temp);
  109708. ogg_sync_pageout(&oy,&temp);
  109709. /* skip */
  109710. ogg_sync_pageout(&oy,&temp);
  109711. ogg_stream_pagein(&os_de,&temp);
  109712. /* do we get the expected results/packets? */
  109713. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109714. checkpacket(&test,0,0,0);
  109715. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109716. checkpacket(&test,100,1,-1);
  109717. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109718. checkpacket(&test,4079,2,3000);
  109719. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109720. fprintf(stderr,"Error: loss of page did not return error\n");
  109721. exit(1);
  109722. }
  109723. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109724. checkpacket(&test,76,5,-1);
  109725. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109726. checkpacket(&test,34,6,-1);
  109727. fprintf(stderr,"ok.\n");
  109728. }
  109729. /* Test lost pages on pagein/packetout: rollback with continuation */
  109730. {
  109731. ogg_page temp;
  109732. ogg_packet test;
  109733. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109734. ogg_sync_reset(&oy);
  109735. ogg_stream_reset(&os_de);
  109736. for(i=0;i<5;i++){
  109737. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109738. og[i].header_len);
  109739. ogg_sync_wrote(&oy,og[i].header_len);
  109740. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109741. ogg_sync_wrote(&oy,og[i].body_len);
  109742. }
  109743. ogg_sync_pageout(&oy,&temp);
  109744. ogg_stream_pagein(&os_de,&temp);
  109745. ogg_sync_pageout(&oy,&temp);
  109746. ogg_stream_pagein(&os_de,&temp);
  109747. ogg_sync_pageout(&oy,&temp);
  109748. ogg_stream_pagein(&os_de,&temp);
  109749. ogg_sync_pageout(&oy,&temp);
  109750. /* skip */
  109751. ogg_sync_pageout(&oy,&temp);
  109752. ogg_stream_pagein(&os_de,&temp);
  109753. /* do we get the expected results/packets? */
  109754. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109755. checkpacket(&test,0,0,0);
  109756. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109757. checkpacket(&test,100,1,-1);
  109758. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109759. checkpacket(&test,4079,2,3000);
  109760. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109761. checkpacket(&test,2956,3,4000);
  109762. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109763. fprintf(stderr,"Error: loss of page did not return error\n");
  109764. exit(1);
  109765. }
  109766. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109767. checkpacket(&test,300,13,14000);
  109768. fprintf(stderr,"ok.\n");
  109769. }
  109770. /* the rest only test sync */
  109771. {
  109772. ogg_page og_de;
  109773. /* Test fractional page inputs: incomplete capture */
  109774. fprintf(stderr,"Testing sync on partial inputs... ");
  109775. ogg_sync_reset(&oy);
  109776. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109777. 3);
  109778. ogg_sync_wrote(&oy,3);
  109779. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109780. /* Test fractional page inputs: incomplete fixed header */
  109781. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109782. 20);
  109783. ogg_sync_wrote(&oy,20);
  109784. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109785. /* Test fractional page inputs: incomplete header */
  109786. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109787. 5);
  109788. ogg_sync_wrote(&oy,5);
  109789. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109790. /* Test fractional page inputs: incomplete body */
  109791. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109792. og[1].header_len-28);
  109793. ogg_sync_wrote(&oy,og[1].header_len-28);
  109794. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109795. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109796. ogg_sync_wrote(&oy,1000);
  109797. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109798. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109799. og[1].body_len-1000);
  109800. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109801. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109802. fprintf(stderr,"ok.\n");
  109803. }
  109804. /* Test fractional page inputs: page + incomplete capture */
  109805. {
  109806. ogg_page og_de;
  109807. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109808. ogg_sync_reset(&oy);
  109809. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109810. og[1].header_len);
  109811. ogg_sync_wrote(&oy,og[1].header_len);
  109812. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109813. og[1].body_len);
  109814. ogg_sync_wrote(&oy,og[1].body_len);
  109815. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109816. 20);
  109817. ogg_sync_wrote(&oy,20);
  109818. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109819. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109820. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109821. og[1].header_len-20);
  109822. ogg_sync_wrote(&oy,og[1].header_len-20);
  109823. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109824. og[1].body_len);
  109825. ogg_sync_wrote(&oy,og[1].body_len);
  109826. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109827. fprintf(stderr,"ok.\n");
  109828. }
  109829. /* Test recapture: garbage + page */
  109830. {
  109831. ogg_page og_de;
  109832. fprintf(stderr,"Testing search for capture... ");
  109833. ogg_sync_reset(&oy);
  109834. /* 'garbage' */
  109835. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109836. og[1].body_len);
  109837. ogg_sync_wrote(&oy,og[1].body_len);
  109838. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109839. og[1].header_len);
  109840. ogg_sync_wrote(&oy,og[1].header_len);
  109841. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109842. og[1].body_len);
  109843. ogg_sync_wrote(&oy,og[1].body_len);
  109844. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109845. 20);
  109846. ogg_sync_wrote(&oy,20);
  109847. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109848. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109849. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109850. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109851. og[2].header_len-20);
  109852. ogg_sync_wrote(&oy,og[2].header_len-20);
  109853. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109854. og[2].body_len);
  109855. ogg_sync_wrote(&oy,og[2].body_len);
  109856. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109857. fprintf(stderr,"ok.\n");
  109858. }
  109859. /* Test recapture: page + garbage + page */
  109860. {
  109861. ogg_page og_de;
  109862. fprintf(stderr,"Testing recapture... ");
  109863. ogg_sync_reset(&oy);
  109864. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109865. og[1].header_len);
  109866. ogg_sync_wrote(&oy,og[1].header_len);
  109867. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109868. og[1].body_len);
  109869. ogg_sync_wrote(&oy,og[1].body_len);
  109870. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109871. og[2].header_len);
  109872. ogg_sync_wrote(&oy,og[2].header_len);
  109873. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109874. og[2].header_len);
  109875. ogg_sync_wrote(&oy,og[2].header_len);
  109876. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109877. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109878. og[2].body_len-5);
  109879. ogg_sync_wrote(&oy,og[2].body_len-5);
  109880. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109881. og[3].header_len);
  109882. ogg_sync_wrote(&oy,og[3].header_len);
  109883. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109884. og[3].body_len);
  109885. ogg_sync_wrote(&oy,og[3].body_len);
  109886. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109887. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109888. fprintf(stderr,"ok.\n");
  109889. }
  109890. /* Free page data that was previously copied */
  109891. {
  109892. for(i=0;i<5;i++){
  109893. free_page(&og[i]);
  109894. }
  109895. }
  109896. }
  109897. return(0);
  109898. }
  109899. #endif
  109900. #endif
  109901. /*** End of inlined file: framing.c ***/
  109902. /*** Start of inlined file: analysis.c ***/
  109903. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109904. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109905. // tasks..
  109906. #if JUCE_MSVC
  109907. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109908. #endif
  109909. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109910. #if JUCE_USE_OGGVORBIS
  109911. #include <stdio.h>
  109912. #include <string.h>
  109913. #include <math.h>
  109914. /*** Start of inlined file: codec_internal.h ***/
  109915. #ifndef _V_CODECI_H_
  109916. #define _V_CODECI_H_
  109917. /*** Start of inlined file: envelope.h ***/
  109918. #ifndef _V_ENVELOPE_
  109919. #define _V_ENVELOPE_
  109920. /*** Start of inlined file: mdct.h ***/
  109921. #ifndef _OGG_mdct_H_
  109922. #define _OGG_mdct_H_
  109923. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109924. #ifdef MDCT_INTEGERIZED
  109925. #define DATA_TYPE int
  109926. #define REG_TYPE register int
  109927. #define TRIGBITS 14
  109928. #define cPI3_8 6270
  109929. #define cPI2_8 11585
  109930. #define cPI1_8 15137
  109931. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109932. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109933. #define HALVE(x) ((x)>>1)
  109934. #else
  109935. #define DATA_TYPE float
  109936. #define REG_TYPE float
  109937. #define cPI3_8 .38268343236508977175F
  109938. #define cPI2_8 .70710678118654752441F
  109939. #define cPI1_8 .92387953251128675613F
  109940. #define FLOAT_CONV(x) (x)
  109941. #define MULT_NORM(x) (x)
  109942. #define HALVE(x) ((x)*.5f)
  109943. #endif
  109944. typedef struct {
  109945. int n;
  109946. int log2n;
  109947. DATA_TYPE *trig;
  109948. int *bitrev;
  109949. DATA_TYPE scale;
  109950. } mdct_lookup;
  109951. extern void mdct_init(mdct_lookup *lookup,int n);
  109952. extern void mdct_clear(mdct_lookup *l);
  109953. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109954. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109955. #endif
  109956. /*** End of inlined file: mdct.h ***/
  109957. #define VE_PRE 16
  109958. #define VE_WIN 4
  109959. #define VE_POST 2
  109960. #define VE_AMP (VE_PRE+VE_POST-1)
  109961. #define VE_BANDS 7
  109962. #define VE_NEARDC 15
  109963. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109964. #define VE_MAXSTRETCH 12 /* one-third full block */
  109965. typedef struct {
  109966. float ampbuf[VE_AMP];
  109967. int ampptr;
  109968. float nearDC[VE_NEARDC];
  109969. float nearDC_acc;
  109970. float nearDC_partialacc;
  109971. int nearptr;
  109972. } envelope_filter_state;
  109973. typedef struct {
  109974. int begin;
  109975. int end;
  109976. float *window;
  109977. float total;
  109978. } envelope_band;
  109979. typedef struct {
  109980. int ch;
  109981. int winlength;
  109982. int searchstep;
  109983. float minenergy;
  109984. mdct_lookup mdct;
  109985. float *mdct_win;
  109986. envelope_band band[VE_BANDS];
  109987. envelope_filter_state *filter;
  109988. int stretch;
  109989. int *mark;
  109990. long storage;
  109991. long current;
  109992. long curmark;
  109993. long cursor;
  109994. } envelope_lookup;
  109995. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109996. extern void _ve_envelope_clear(envelope_lookup *e);
  109997. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109998. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109999. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  110000. #endif
  110001. /*** End of inlined file: envelope.h ***/
  110002. /*** Start of inlined file: codebook.h ***/
  110003. #ifndef _V_CODEBOOK_H_
  110004. #define _V_CODEBOOK_H_
  110005. /* This structure encapsulates huffman and VQ style encoding books; it
  110006. doesn't do anything specific to either.
  110007. valuelist/quantlist are nonNULL (and q_* significant) only if
  110008. there's entry->value mapping to be done.
  110009. If encode-side mapping must be done (and thus the entry needs to be
  110010. hunted), the auxiliary encode pointer will point to a decision
  110011. tree. This is true of both VQ and huffman, but is mostly useful
  110012. with VQ.
  110013. */
  110014. typedef struct static_codebook{
  110015. long dim; /* codebook dimensions (elements per vector) */
  110016. long entries; /* codebook entries */
  110017. long *lengthlist; /* codeword lengths in bits */
  110018. /* mapping ***************************************************************/
  110019. int maptype; /* 0=none
  110020. 1=implicitly populated values from map column
  110021. 2=listed arbitrary values */
  110022. /* The below does a linear, single monotonic sequence mapping. */
  110023. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  110024. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  110025. int q_quant; /* bits: 0 < quant <= 16 */
  110026. int q_sequencep; /* bitflag */
  110027. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  110028. map == 2: list of dim*entries quantized entry vals
  110029. */
  110030. /* encode helpers ********************************************************/
  110031. struct encode_aux_nearestmatch *nearest_tree;
  110032. struct encode_aux_threshmatch *thresh_tree;
  110033. struct encode_aux_pigeonhole *pigeon_tree;
  110034. int allocedp;
  110035. } static_codebook;
  110036. /* this structures an arbitrary trained book to quickly find the
  110037. nearest cell match */
  110038. typedef struct encode_aux_nearestmatch{
  110039. /* pre-calculated partitioning tree */
  110040. long *ptr0;
  110041. long *ptr1;
  110042. long *p; /* decision points (each is an entry) */
  110043. long *q; /* decision points (each is an entry) */
  110044. long aux; /* number of tree entries */
  110045. long alloc;
  110046. } encode_aux_nearestmatch;
  110047. /* assumes a maptype of 1; encode side only, so that's OK */
  110048. typedef struct encode_aux_threshmatch{
  110049. float *quantthresh;
  110050. long *quantmap;
  110051. int quantvals;
  110052. int threshvals;
  110053. } encode_aux_threshmatch;
  110054. typedef struct encode_aux_pigeonhole{
  110055. float min;
  110056. float del;
  110057. int mapentries;
  110058. int quantvals;
  110059. long *pigeonmap;
  110060. long fittotal;
  110061. long *fitlist;
  110062. long *fitmap;
  110063. long *fitlength;
  110064. } encode_aux_pigeonhole;
  110065. typedef struct codebook{
  110066. long dim; /* codebook dimensions (elements per vector) */
  110067. long entries; /* codebook entries */
  110068. long used_entries; /* populated codebook entries */
  110069. const static_codebook *c;
  110070. /* for encode, the below are entry-ordered, fully populated */
  110071. /* for decode, the below are ordered by bitreversed codeword and only
  110072. used entries are populated */
  110073. float *valuelist; /* list of dim*entries actual entry values */
  110074. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110075. int *dec_index; /* only used if sparseness collapsed */
  110076. char *dec_codelengths;
  110077. ogg_uint32_t *dec_firsttable;
  110078. int dec_firsttablen;
  110079. int dec_maxlength;
  110080. } codebook;
  110081. extern void vorbis_staticbook_clear(static_codebook *b);
  110082. extern void vorbis_staticbook_destroy(static_codebook *b);
  110083. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110084. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110085. extern void vorbis_book_clear(codebook *b);
  110086. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110087. extern float *_book_logdist(const static_codebook *b,float *vals);
  110088. extern float _float32_unpack(long val);
  110089. extern long _float32_pack(float val);
  110090. extern int _best(codebook *book, float *a, int step);
  110091. extern int _ilog(unsigned int v);
  110092. extern long _book_maptype1_quantvals(const static_codebook *b);
  110093. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110094. extern long vorbis_book_codeword(codebook *book,int entry);
  110095. extern long vorbis_book_codelen(codebook *book,int entry);
  110096. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110097. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110098. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110099. extern int vorbis_book_errorv(codebook *book, float *a);
  110100. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110101. oggpack_buffer *b);
  110102. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110103. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110104. oggpack_buffer *b,int n);
  110105. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110106. oggpack_buffer *b,int n);
  110107. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110108. oggpack_buffer *b,int n);
  110109. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110110. long off,int ch,
  110111. oggpack_buffer *b,int n);
  110112. #endif
  110113. /*** End of inlined file: codebook.h ***/
  110114. #define BLOCKTYPE_IMPULSE 0
  110115. #define BLOCKTYPE_PADDING 1
  110116. #define BLOCKTYPE_TRANSITION 0
  110117. #define BLOCKTYPE_LONG 1
  110118. #define PACKETBLOBS 15
  110119. typedef struct vorbis_block_internal{
  110120. float **pcmdelay; /* this is a pointer into local storage */
  110121. float ampmax;
  110122. int blocktype;
  110123. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110124. blob [PACKETBLOBS/2] points to
  110125. the oggpack_buffer in the
  110126. main vorbis_block */
  110127. } vorbis_block_internal;
  110128. typedef void vorbis_look_floor;
  110129. typedef void vorbis_look_residue;
  110130. typedef void vorbis_look_transform;
  110131. /* mode ************************************************************/
  110132. typedef struct {
  110133. int blockflag;
  110134. int windowtype;
  110135. int transformtype;
  110136. int mapping;
  110137. } vorbis_info_mode;
  110138. typedef void vorbis_info_floor;
  110139. typedef void vorbis_info_residue;
  110140. typedef void vorbis_info_mapping;
  110141. /*** Start of inlined file: psy.h ***/
  110142. #ifndef _V_PSY_H_
  110143. #define _V_PSY_H_
  110144. /*** Start of inlined file: smallft.h ***/
  110145. #ifndef _V_SMFT_H_
  110146. #define _V_SMFT_H_
  110147. typedef struct {
  110148. int n;
  110149. float *trigcache;
  110150. int *splitcache;
  110151. } drft_lookup;
  110152. extern void drft_forward(drft_lookup *l,float *data);
  110153. extern void drft_backward(drft_lookup *l,float *data);
  110154. extern void drft_init(drft_lookup *l,int n);
  110155. extern void drft_clear(drft_lookup *l);
  110156. #endif
  110157. /*** End of inlined file: smallft.h ***/
  110158. /*** Start of inlined file: backends.h ***/
  110159. /* this is exposed up here because we need it for static modes.
  110160. Lookups for each backend aren't exposed because there's no reason
  110161. to do so */
  110162. #ifndef _vorbis_backend_h_
  110163. #define _vorbis_backend_h_
  110164. /* this would all be simpler/shorter with templates, but.... */
  110165. /* Floor backend generic *****************************************/
  110166. typedef struct{
  110167. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110168. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110169. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110170. void (*free_info) (vorbis_info_floor *);
  110171. void (*free_look) (vorbis_look_floor *);
  110172. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110173. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110174. void *buffer,float *);
  110175. } vorbis_func_floor;
  110176. typedef struct{
  110177. int order;
  110178. long rate;
  110179. long barkmap;
  110180. int ampbits;
  110181. int ampdB;
  110182. int numbooks; /* <= 16 */
  110183. int books[16];
  110184. float lessthan; /* encode-only config setting hacks for libvorbis */
  110185. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110186. } vorbis_info_floor0;
  110187. #define VIF_POSIT 63
  110188. #define VIF_CLASS 16
  110189. #define VIF_PARTS 31
  110190. typedef struct{
  110191. int partitions; /* 0 to 31 */
  110192. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110193. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110194. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110195. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110196. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110197. int mult; /* 1 2 3 or 4 */
  110198. int postlist[VIF_POSIT+2]; /* first two implicit */
  110199. /* encode side analysis parameters */
  110200. float maxover;
  110201. float maxunder;
  110202. float maxerr;
  110203. float twofitweight;
  110204. float twofitatten;
  110205. int n;
  110206. } vorbis_info_floor1;
  110207. /* Residue backend generic *****************************************/
  110208. typedef struct{
  110209. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110210. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110211. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110212. vorbis_info_residue *);
  110213. void (*free_info) (vorbis_info_residue *);
  110214. void (*free_look) (vorbis_look_residue *);
  110215. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110216. float **,int *,int);
  110217. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110218. vorbis_look_residue *,
  110219. float **,float **,int *,int,long **);
  110220. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110221. float **,int *,int);
  110222. } vorbis_func_residue;
  110223. typedef struct vorbis_info_residue0{
  110224. /* block-partitioned VQ coded straight residue */
  110225. long begin;
  110226. long end;
  110227. /* first stage (lossless partitioning) */
  110228. int grouping; /* group n vectors per partition */
  110229. int partitions; /* possible codebooks for a partition */
  110230. int groupbook; /* huffbook for partitioning */
  110231. int secondstages[64]; /* expanded out to pointers in lookup */
  110232. int booklist[256]; /* list of second stage books */
  110233. float classmetric1[64];
  110234. float classmetric2[64];
  110235. } vorbis_info_residue0;
  110236. /* Mapping backend generic *****************************************/
  110237. typedef struct{
  110238. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110239. oggpack_buffer *);
  110240. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110241. void (*free_info) (vorbis_info_mapping *);
  110242. int (*forward) (struct vorbis_block *vb);
  110243. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110244. } vorbis_func_mapping;
  110245. typedef struct vorbis_info_mapping0{
  110246. int submaps; /* <= 16 */
  110247. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110248. int floorsubmap[16]; /* [mux] submap to floors */
  110249. int residuesubmap[16]; /* [mux] submap to residue */
  110250. int coupling_steps;
  110251. int coupling_mag[256];
  110252. int coupling_ang[256];
  110253. } vorbis_info_mapping0;
  110254. #endif
  110255. /*** End of inlined file: backends.h ***/
  110256. #ifndef EHMER_MAX
  110257. #define EHMER_MAX 56
  110258. #endif
  110259. /* psychoacoustic setup ********************************************/
  110260. #define P_BANDS 17 /* 62Hz to 16kHz */
  110261. #define P_LEVELS 8 /* 30dB to 100dB */
  110262. #define P_LEVEL_0 30. /* 30 dB */
  110263. #define P_NOISECURVES 3
  110264. #define NOISE_COMPAND_LEVELS 40
  110265. typedef struct vorbis_info_psy{
  110266. int blockflag;
  110267. float ath_adjatt;
  110268. float ath_maxatt;
  110269. float tone_masteratt[P_NOISECURVES];
  110270. float tone_centerboost;
  110271. float tone_decay;
  110272. float tone_abs_limit;
  110273. float toneatt[P_BANDS];
  110274. int noisemaskp;
  110275. float noisemaxsupp;
  110276. float noisewindowlo;
  110277. float noisewindowhi;
  110278. int noisewindowlomin;
  110279. int noisewindowhimin;
  110280. int noisewindowfixed;
  110281. float noiseoff[P_NOISECURVES][P_BANDS];
  110282. float noisecompand[NOISE_COMPAND_LEVELS];
  110283. float max_curve_dB;
  110284. int normal_channel_p;
  110285. int normal_point_p;
  110286. int normal_start;
  110287. int normal_partition;
  110288. double normal_thresh;
  110289. } vorbis_info_psy;
  110290. typedef struct{
  110291. int eighth_octave_lines;
  110292. /* for block long/short tuning; encode only */
  110293. float preecho_thresh[VE_BANDS];
  110294. float postecho_thresh[VE_BANDS];
  110295. float stretch_penalty;
  110296. float preecho_minenergy;
  110297. float ampmax_att_per_sec;
  110298. /* channel coupling config */
  110299. int coupling_pkHz[PACKETBLOBS];
  110300. int coupling_pointlimit[2][PACKETBLOBS];
  110301. int coupling_prepointamp[PACKETBLOBS];
  110302. int coupling_postpointamp[PACKETBLOBS];
  110303. int sliding_lowpass[2][PACKETBLOBS];
  110304. } vorbis_info_psy_global;
  110305. typedef struct {
  110306. float ampmax;
  110307. int channels;
  110308. vorbis_info_psy_global *gi;
  110309. int coupling_pointlimit[2][P_NOISECURVES];
  110310. } vorbis_look_psy_global;
  110311. typedef struct {
  110312. int n;
  110313. struct vorbis_info_psy *vi;
  110314. float ***tonecurves;
  110315. float **noiseoffset;
  110316. float *ath;
  110317. long *octave; /* in n.ocshift format */
  110318. long *bark;
  110319. long firstoc;
  110320. long shiftoc;
  110321. int eighth_octave_lines; /* power of two, please */
  110322. int total_octave_lines;
  110323. long rate; /* cache it */
  110324. float m_val; /* Masking compensation value */
  110325. } vorbis_look_psy;
  110326. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110327. vorbis_info_psy_global *gi,int n,long rate);
  110328. extern void _vp_psy_clear(vorbis_look_psy *p);
  110329. extern void *_vi_psy_dup(void *source);
  110330. extern void _vi_psy_free(vorbis_info_psy *i);
  110331. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110332. extern void _vp_remove_floor(vorbis_look_psy *p,
  110333. float *mdct,
  110334. int *icodedflr,
  110335. float *residue,
  110336. int sliding_lowpass);
  110337. extern void _vp_noisemask(vorbis_look_psy *p,
  110338. float *logmdct,
  110339. float *logmask);
  110340. extern void _vp_tonemask(vorbis_look_psy *p,
  110341. float *logfft,
  110342. float *logmask,
  110343. float global_specmax,
  110344. float local_specmax);
  110345. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110346. float *noise,
  110347. float *tone,
  110348. int offset_select,
  110349. float *logmask,
  110350. float *mdct,
  110351. float *logmdct);
  110352. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110353. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110354. vorbis_info_psy_global *g,
  110355. vorbis_look_psy *p,
  110356. vorbis_info_mapping0 *vi,
  110357. float **mdct);
  110358. extern void _vp_couple(int blobno,
  110359. vorbis_info_psy_global *g,
  110360. vorbis_look_psy *p,
  110361. vorbis_info_mapping0 *vi,
  110362. float **res,
  110363. float **mag_memo,
  110364. int **mag_sort,
  110365. int **ifloor,
  110366. int *nonzero,
  110367. int sliding_lowpass);
  110368. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110369. float *in,float *out,int *sortedindex);
  110370. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110371. float *magnitudes,int *sortedindex);
  110372. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110373. vorbis_look_psy *p,
  110374. vorbis_info_mapping0 *vi,
  110375. float **mags);
  110376. extern void hf_reduction(vorbis_info_psy_global *g,
  110377. vorbis_look_psy *p,
  110378. vorbis_info_mapping0 *vi,
  110379. float **mdct);
  110380. #endif
  110381. /*** End of inlined file: psy.h ***/
  110382. /*** Start of inlined file: bitrate.h ***/
  110383. #ifndef _V_BITRATE_H_
  110384. #define _V_BITRATE_H_
  110385. /*** Start of inlined file: os.h ***/
  110386. #ifndef _OS_H
  110387. #define _OS_H
  110388. /********************************************************************
  110389. * *
  110390. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110391. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110392. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110393. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110394. * *
  110395. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110396. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110397. * *
  110398. ********************************************************************
  110399. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110400. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110401. ********************************************************************/
  110402. #ifdef HAVE_CONFIG_H
  110403. #include "config.h"
  110404. #endif
  110405. #include <math.h>
  110406. /*** Start of inlined file: misc.h ***/
  110407. #ifndef _V_RANDOM_H_
  110408. #define _V_RANDOM_H_
  110409. extern int analysis_noisy;
  110410. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110411. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110412. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110413. ogg_int64_t off);
  110414. #ifdef DEBUG_MALLOC
  110415. #define _VDBG_GRAPHFILE "malloc.m"
  110416. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110417. extern void _VDBG_free(void *ptr,char *file,long line);
  110418. #ifndef MISC_C
  110419. #undef _ogg_malloc
  110420. #undef _ogg_calloc
  110421. #undef _ogg_realloc
  110422. #undef _ogg_free
  110423. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110424. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110425. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110426. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110427. #endif
  110428. #endif
  110429. #endif
  110430. /*** End of inlined file: misc.h ***/
  110431. #ifndef _V_IFDEFJAIL_H_
  110432. # define _V_IFDEFJAIL_H_
  110433. # ifdef __GNUC__
  110434. # define STIN static __inline__
  110435. # elif _WIN32
  110436. # define STIN static __inline
  110437. # else
  110438. # define STIN static
  110439. # endif
  110440. #ifdef DJGPP
  110441. # define rint(x) (floor((x)+0.5f))
  110442. #endif
  110443. #ifndef M_PI
  110444. # define M_PI (3.1415926536f)
  110445. #endif
  110446. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110447. # include <malloc.h>
  110448. # define rint(x) (floor((x)+0.5f))
  110449. # define NO_FLOAT_MATH_LIB
  110450. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110451. #endif
  110452. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110453. void *_alloca(size_t size);
  110454. # define alloca _alloca
  110455. #endif
  110456. #ifndef FAST_HYPOT
  110457. # define FAST_HYPOT hypot
  110458. #endif
  110459. #endif
  110460. #ifdef HAVE_ALLOCA_H
  110461. # include <alloca.h>
  110462. #endif
  110463. #ifdef USE_MEMORY_H
  110464. # include <memory.h>
  110465. #endif
  110466. #ifndef min
  110467. # define min(x,y) ((x)>(y)?(y):(x))
  110468. #endif
  110469. #ifndef max
  110470. # define max(x,y) ((x)<(y)?(y):(x))
  110471. #endif
  110472. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110473. # define VORBIS_FPU_CONTROL
  110474. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110475. Because of encapsulation constraints (GCC can't see inside the asm
  110476. block and so we end up doing stupid things like a store/load that
  110477. is collectively a noop), we do it this way */
  110478. /* we must set up the fpu before this works!! */
  110479. typedef ogg_int16_t vorbis_fpu_control;
  110480. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110481. ogg_int16_t ret;
  110482. ogg_int16_t temp;
  110483. __asm__ __volatile__("fnstcw %0\n\t"
  110484. "movw %0,%%dx\n\t"
  110485. "orw $62463,%%dx\n\t"
  110486. "movw %%dx,%1\n\t"
  110487. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110488. *fpu=ret;
  110489. }
  110490. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110491. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110492. }
  110493. /* assumes the FPU is in round mode! */
  110494. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110495. we get extra fst/fld to
  110496. truncate precision */
  110497. int i;
  110498. __asm__("fistl %0": "=m"(i) : "t"(f));
  110499. return(i);
  110500. }
  110501. #endif
  110502. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110503. # define VORBIS_FPU_CONTROL
  110504. typedef ogg_int16_t vorbis_fpu_control;
  110505. static __inline int vorbis_ftoi(double f){
  110506. int i;
  110507. __asm{
  110508. fld f
  110509. fistp i
  110510. }
  110511. return i;
  110512. }
  110513. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110514. }
  110515. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110516. }
  110517. #endif
  110518. #ifndef VORBIS_FPU_CONTROL
  110519. typedef int vorbis_fpu_control;
  110520. static int vorbis_ftoi(double f){
  110521. return (int)(f+.5);
  110522. }
  110523. /* We don't have special code for this compiler/arch, so do it the slow way */
  110524. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110525. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110526. #endif
  110527. #endif /* _OS_H */
  110528. /*** End of inlined file: os.h ***/
  110529. /* encode side bitrate tracking */
  110530. typedef struct bitrate_manager_state {
  110531. int managed;
  110532. long avg_reservoir;
  110533. long minmax_reservoir;
  110534. long avg_bitsper;
  110535. long min_bitsper;
  110536. long max_bitsper;
  110537. long short_per_long;
  110538. double avgfloat;
  110539. vorbis_block *vb;
  110540. int choice;
  110541. } bitrate_manager_state;
  110542. typedef struct bitrate_manager_info{
  110543. long avg_rate;
  110544. long min_rate;
  110545. long max_rate;
  110546. long reservoir_bits;
  110547. double reservoir_bias;
  110548. double slew_damp;
  110549. } bitrate_manager_info;
  110550. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110551. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110552. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110553. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110554. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110555. #endif
  110556. /*** End of inlined file: bitrate.h ***/
  110557. static int ilog(unsigned int v){
  110558. int ret=0;
  110559. while(v){
  110560. ret++;
  110561. v>>=1;
  110562. }
  110563. return(ret);
  110564. }
  110565. static int ilog2(unsigned int v){
  110566. int ret=0;
  110567. if(v)--v;
  110568. while(v){
  110569. ret++;
  110570. v>>=1;
  110571. }
  110572. return(ret);
  110573. }
  110574. typedef struct private_state {
  110575. /* local lookup storage */
  110576. envelope_lookup *ve; /* envelope lookup */
  110577. int window[2];
  110578. vorbis_look_transform **transform[2]; /* block, type */
  110579. drft_lookup fft_look[2];
  110580. int modebits;
  110581. vorbis_look_floor **flr;
  110582. vorbis_look_residue **residue;
  110583. vorbis_look_psy *psy;
  110584. vorbis_look_psy_global *psy_g_look;
  110585. /* local storage, only used on the encoding side. This way the
  110586. application does not need to worry about freeing some packets'
  110587. memory and not others'; packet storage is always tracked.
  110588. Cleared next call to a _dsp_ function */
  110589. unsigned char *header;
  110590. unsigned char *header1;
  110591. unsigned char *header2;
  110592. bitrate_manager_state bms;
  110593. ogg_int64_t sample_count;
  110594. } private_state;
  110595. /* codec_setup_info contains all the setup information specific to the
  110596. specific compression/decompression mode in progress (eg,
  110597. psychoacoustic settings, channel setup, options, codebook
  110598. etc).
  110599. *********************************************************************/
  110600. /*** Start of inlined file: highlevel.h ***/
  110601. typedef struct highlevel_byblocktype {
  110602. double tone_mask_setting;
  110603. double tone_peaklimit_setting;
  110604. double noise_bias_setting;
  110605. double noise_compand_setting;
  110606. } highlevel_byblocktype;
  110607. typedef struct highlevel_encode_setup {
  110608. void *setup;
  110609. int set_in_stone;
  110610. double base_setting;
  110611. double long_setting;
  110612. double short_setting;
  110613. double impulse_noisetune;
  110614. int managed;
  110615. long bitrate_min;
  110616. long bitrate_av;
  110617. double bitrate_av_damp;
  110618. long bitrate_max;
  110619. long bitrate_reservoir;
  110620. double bitrate_reservoir_bias;
  110621. int impulse_block_p;
  110622. int noise_normalize_p;
  110623. double stereo_point_setting;
  110624. double lowpass_kHz;
  110625. double ath_floating_dB;
  110626. double ath_absolute_dB;
  110627. double amplitude_track_dBpersec;
  110628. double trigger_setting;
  110629. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110630. } highlevel_encode_setup;
  110631. /*** End of inlined file: highlevel.h ***/
  110632. typedef struct codec_setup_info {
  110633. /* Vorbis supports only short and long blocks, but allows the
  110634. encoder to choose the sizes */
  110635. long blocksizes[2];
  110636. /* modes are the primary means of supporting on-the-fly different
  110637. blocksizes, different channel mappings (LR or M/A),
  110638. different residue backends, etc. Each mode consists of a
  110639. blocksize flag and a mapping (along with the mapping setup */
  110640. int modes;
  110641. int maps;
  110642. int floors;
  110643. int residues;
  110644. int books;
  110645. int psys; /* encode only */
  110646. vorbis_info_mode *mode_param[64];
  110647. int map_type[64];
  110648. vorbis_info_mapping *map_param[64];
  110649. int floor_type[64];
  110650. vorbis_info_floor *floor_param[64];
  110651. int residue_type[64];
  110652. vorbis_info_residue *residue_param[64];
  110653. static_codebook *book_param[256];
  110654. codebook *fullbooks;
  110655. vorbis_info_psy *psy_param[4]; /* encode only */
  110656. vorbis_info_psy_global psy_g_param;
  110657. bitrate_manager_info bi;
  110658. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110659. highly redundant structure, but
  110660. improves clarity of program flow. */
  110661. int halfrate_flag; /* painless downsample for decode */
  110662. } codec_setup_info;
  110663. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110664. extern void _vp_global_free(vorbis_look_psy_global *look);
  110665. #endif
  110666. /*** End of inlined file: codec_internal.h ***/
  110667. /*** Start of inlined file: registry.h ***/
  110668. #ifndef _V_REG_H_
  110669. #define _V_REG_H_
  110670. #define VI_TRANSFORMB 1
  110671. #define VI_WINDOWB 1
  110672. #define VI_TIMEB 1
  110673. #define VI_FLOORB 2
  110674. #define VI_RESB 3
  110675. #define VI_MAPB 1
  110676. extern vorbis_func_floor *_floor_P[];
  110677. extern vorbis_func_residue *_residue_P[];
  110678. extern vorbis_func_mapping *_mapping_P[];
  110679. #endif
  110680. /*** End of inlined file: registry.h ***/
  110681. /*** Start of inlined file: scales.h ***/
  110682. #ifndef _V_SCALES_H_
  110683. #define _V_SCALES_H_
  110684. #include <math.h>
  110685. /* 20log10(x) */
  110686. #define VORBIS_IEEE_FLOAT32 1
  110687. #ifdef VORBIS_IEEE_FLOAT32
  110688. static float unitnorm(float x){
  110689. union {
  110690. ogg_uint32_t i;
  110691. float f;
  110692. } ix;
  110693. ix.f = x;
  110694. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110695. return ix.f;
  110696. }
  110697. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110698. static float todB(const float *x){
  110699. union {
  110700. ogg_uint32_t i;
  110701. float f;
  110702. } ix;
  110703. ix.f = *x;
  110704. ix.i = ix.i&0x7fffffff;
  110705. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110706. }
  110707. #define todB_nn(x) todB(x)
  110708. #else
  110709. static float unitnorm(float x){
  110710. if(x<0)return(-1.f);
  110711. return(1.f);
  110712. }
  110713. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110714. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110715. #endif
  110716. #define fromdB(x) (exp((x)*.11512925f))
  110717. /* The bark scale equations are approximations, since the original
  110718. table was somewhat hand rolled. The below are chosen to have the
  110719. best possible fit to the rolled tables, thus their somewhat odd
  110720. appearance (these are more accurate and over a longer range than
  110721. the oft-quoted bark equations found in the texts I have). The
  110722. approximations are valid from 0 - 30kHz (nyquist) or so.
  110723. all f in Hz, z in Bark */
  110724. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110725. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110726. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110727. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110728. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110729. 0.0 */
  110730. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110731. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110732. #endif
  110733. /*** End of inlined file: scales.h ***/
  110734. int analysis_noisy=1;
  110735. /* decides between modes, dispatches to the appropriate mapping. */
  110736. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110737. int ret,i;
  110738. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110739. vb->glue_bits=0;
  110740. vb->time_bits=0;
  110741. vb->floor_bits=0;
  110742. vb->res_bits=0;
  110743. /* first things first. Make sure encode is ready */
  110744. for(i=0;i<PACKETBLOBS;i++)
  110745. oggpack_reset(vbi->packetblob[i]);
  110746. /* we only have one mapping type (0), and we let the mapping code
  110747. itself figure out what soft mode to use. This allows easier
  110748. bitrate management */
  110749. if((ret=_mapping_P[0]->forward(vb)))
  110750. return(ret);
  110751. if(op){
  110752. if(vorbis_bitrate_managed(vb))
  110753. /* The app is using a bitmanaged mode... but not using the
  110754. bitrate management interface. */
  110755. return(OV_EINVAL);
  110756. op->packet=oggpack_get_buffer(&vb->opb);
  110757. op->bytes=oggpack_bytes(&vb->opb);
  110758. op->b_o_s=0;
  110759. op->e_o_s=vb->eofflag;
  110760. op->granulepos=vb->granulepos;
  110761. op->packetno=vb->sequence; /* for sake of completeness */
  110762. }
  110763. return(0);
  110764. }
  110765. /* there was no great place to put this.... */
  110766. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110767. int j;
  110768. FILE *of;
  110769. char buffer[80];
  110770. /* if(i==5870){*/
  110771. sprintf(buffer,"%s_%d.m",base,i);
  110772. of=fopen(buffer,"w");
  110773. if(!of)perror("failed to open data dump file");
  110774. for(j=0;j<n;j++){
  110775. if(bark){
  110776. float b=toBARK((4000.f*j/n)+.25);
  110777. fprintf(of,"%f ",b);
  110778. }else
  110779. if(off!=0)
  110780. fprintf(of,"%f ",(double)(j+off)/8000.);
  110781. else
  110782. fprintf(of,"%f ",(double)j);
  110783. if(dB){
  110784. float val;
  110785. if(v[j]==0.)
  110786. val=-140.;
  110787. else
  110788. val=todB(v+j);
  110789. fprintf(of,"%f\n",val);
  110790. }else{
  110791. fprintf(of,"%f\n",v[j]);
  110792. }
  110793. }
  110794. fclose(of);
  110795. /* } */
  110796. }
  110797. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110798. ogg_int64_t off){
  110799. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110800. }
  110801. #endif
  110802. /*** End of inlined file: analysis.c ***/
  110803. /*** Start of inlined file: bitrate.c ***/
  110804. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110805. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110806. // tasks..
  110807. #if JUCE_MSVC
  110808. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110809. #endif
  110810. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110811. #if JUCE_USE_OGGVORBIS
  110812. #include <stdlib.h>
  110813. #include <string.h>
  110814. #include <math.h>
  110815. /* compute bitrate tracking setup */
  110816. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110817. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110818. bitrate_manager_info *bi=&ci->bi;
  110819. memset(bm,0,sizeof(*bm));
  110820. if(bi && (bi->reservoir_bits>0)){
  110821. long ratesamples=vi->rate;
  110822. int halfsamples=ci->blocksizes[0]>>1;
  110823. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110824. bm->managed=1;
  110825. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110826. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110827. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110828. bm->avgfloat=PACKETBLOBS/2;
  110829. /* not a necessary fix, but one that leads to a more balanced
  110830. typical initialization */
  110831. {
  110832. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110833. bm->minmax_reservoir=desired_fill;
  110834. bm->avg_reservoir=desired_fill;
  110835. }
  110836. }
  110837. }
  110838. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110839. memset(bm,0,sizeof(*bm));
  110840. return;
  110841. }
  110842. int vorbis_bitrate_managed(vorbis_block *vb){
  110843. vorbis_dsp_state *vd=vb->vd;
  110844. private_state *b=(private_state*)vd->backend_state;
  110845. bitrate_manager_state *bm=&b->bms;
  110846. if(bm && bm->managed)return(1);
  110847. return(0);
  110848. }
  110849. /* finish taking in the block we just processed */
  110850. int vorbis_bitrate_addblock(vorbis_block *vb){
  110851. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110852. vorbis_dsp_state *vd=vb->vd;
  110853. private_state *b=(private_state*)vd->backend_state;
  110854. bitrate_manager_state *bm=&b->bms;
  110855. vorbis_info *vi=vd->vi;
  110856. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110857. bitrate_manager_info *bi=&ci->bi;
  110858. int choice=rint(bm->avgfloat);
  110859. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110860. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110861. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110862. int samples=ci->blocksizes[vb->W]>>1;
  110863. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110864. if(!bm->managed){
  110865. /* not a bitrate managed stream, but for API simplicity, we'll
  110866. buffer the packet to keep the code path clean */
  110867. if(bm->vb)return(-1); /* one has been submitted without
  110868. being claimed */
  110869. bm->vb=vb;
  110870. return(0);
  110871. }
  110872. bm->vb=vb;
  110873. /* look ahead for avg floater */
  110874. if(bm->avg_bitsper>0){
  110875. double slew=0.;
  110876. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110877. double slewlimit= 15./bi->slew_damp;
  110878. /* choosing a new floater:
  110879. if we're over target, we slew down
  110880. if we're under target, we slew up
  110881. choose slew as follows: look through packetblobs of this frame
  110882. and set slew as the first in the appropriate direction that
  110883. gives us the slew we want. This may mean no slew if delta is
  110884. already favorable.
  110885. Then limit slew to slew max */
  110886. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110887. while(choice>0 && this_bits>avg_target_bits &&
  110888. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110889. choice--;
  110890. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110891. }
  110892. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110893. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110894. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110895. choice++;
  110896. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110897. }
  110898. }
  110899. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110900. if(slew<-slewlimit)slew=-slewlimit;
  110901. if(slew>slewlimit)slew=slewlimit;
  110902. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110903. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110904. }
  110905. /* enforce min(if used) on the current floater (if used) */
  110906. if(bm->min_bitsper>0){
  110907. /* do we need to force the bitrate up? */
  110908. if(this_bits<min_target_bits){
  110909. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110910. choice++;
  110911. if(choice>=PACKETBLOBS)break;
  110912. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110913. }
  110914. }
  110915. }
  110916. /* enforce max (if used) on the current floater (if used) */
  110917. if(bm->max_bitsper>0){
  110918. /* do we need to force the bitrate down? */
  110919. if(this_bits>max_target_bits){
  110920. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110921. choice--;
  110922. if(choice<0)break;
  110923. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110924. }
  110925. }
  110926. }
  110927. /* Choice of packetblobs now made based on floater, and min/max
  110928. requirements. Now boundary check extreme choices */
  110929. if(choice<0){
  110930. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110931. frame will need to be truncated */
  110932. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110933. bm->choice=choice=0;
  110934. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110935. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110936. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110937. }
  110938. }else{
  110939. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110940. if(choice>=PACKETBLOBS)
  110941. choice=PACKETBLOBS-1;
  110942. bm->choice=choice;
  110943. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110944. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110945. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110946. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110947. }
  110948. /* now we have the final packet and the final packet size. Update statistics */
  110949. /* min and max reservoir */
  110950. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110951. if(max_target_bits>0 && this_bits>max_target_bits){
  110952. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110953. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110954. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110955. }else{
  110956. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110957. if(bm->minmax_reservoir>desired_fill){
  110958. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110959. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110960. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110961. }else{
  110962. bm->minmax_reservoir=desired_fill;
  110963. }
  110964. }else{
  110965. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110966. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110967. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110968. }else{
  110969. bm->minmax_reservoir=desired_fill;
  110970. }
  110971. }
  110972. }
  110973. }
  110974. /* avg reservoir */
  110975. if(bm->avg_bitsper>0){
  110976. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110977. bm->avg_reservoir+=this_bits-avg_target_bits;
  110978. }
  110979. return(0);
  110980. }
  110981. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110982. private_state *b=(private_state*)vd->backend_state;
  110983. bitrate_manager_state *bm=&b->bms;
  110984. vorbis_block *vb=bm->vb;
  110985. int choice=PACKETBLOBS/2;
  110986. if(!vb)return 0;
  110987. if(op){
  110988. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110989. if(vorbis_bitrate_managed(vb))
  110990. choice=bm->choice;
  110991. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110992. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110993. op->b_o_s=0;
  110994. op->e_o_s=vb->eofflag;
  110995. op->granulepos=vb->granulepos;
  110996. op->packetno=vb->sequence; /* for sake of completeness */
  110997. }
  110998. bm->vb=0;
  110999. return(1);
  111000. }
  111001. #endif
  111002. /*** End of inlined file: bitrate.c ***/
  111003. /*** Start of inlined file: block.c ***/
  111004. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111005. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111006. // tasks..
  111007. #if JUCE_MSVC
  111008. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111009. #endif
  111010. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111011. #if JUCE_USE_OGGVORBIS
  111012. #include <stdio.h>
  111013. #include <stdlib.h>
  111014. #include <string.h>
  111015. /*** Start of inlined file: window.h ***/
  111016. #ifndef _V_WINDOW_
  111017. #define _V_WINDOW_
  111018. extern float *_vorbis_window_get(int n);
  111019. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  111020. int lW,int W,int nW);
  111021. #endif
  111022. /*** End of inlined file: window.h ***/
  111023. /*** Start of inlined file: lpc.h ***/
  111024. #ifndef _V_LPC_H_
  111025. #define _V_LPC_H_
  111026. /* simple linear scale LPC code */
  111027. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  111028. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111029. float *data,long n);
  111030. #endif
  111031. /*** End of inlined file: lpc.h ***/
  111032. /* pcm accumulator examples (not exhaustive):
  111033. <-------------- lW ---------------->
  111034. <--------------- W ---------------->
  111035. : .....|..... _______________ |
  111036. : .''' | '''_--- | |\ |
  111037. :.....''' |_____--- '''......| | \_______|
  111038. :.................|__________________|_______|__|______|
  111039. |<------ Sl ------>| > Sr < |endW
  111040. |beginSl |endSl | |endSr
  111041. |beginW |endlW |beginSr
  111042. |< lW >|
  111043. <--------------- W ---------------->
  111044. | | .. ______________ |
  111045. | | ' `/ | ---_ |
  111046. |___.'___/`. | ---_____|
  111047. |_______|__|_______|_________________|
  111048. | >|Sl|< |<------ Sr ----->|endW
  111049. | | |endSl |beginSr |endSr
  111050. |beginW | |endlW
  111051. mult[0] |beginSl mult[n]
  111052. <-------------- lW ----------------->
  111053. |<--W-->|
  111054. : .............. ___ | |
  111055. : .''' |`/ \ | |
  111056. :.....''' |/`....\|...|
  111057. :.........................|___|___|___|
  111058. |Sl |Sr |endW
  111059. | | |endSr
  111060. | |beginSr
  111061. | |endSl
  111062. |beginSl
  111063. |beginW
  111064. */
  111065. /* block abstraction setup *********************************************/
  111066. #ifndef WORD_ALIGN
  111067. #define WORD_ALIGN 8
  111068. #endif
  111069. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  111070. int i;
  111071. memset(vb,0,sizeof(*vb));
  111072. vb->vd=v;
  111073. vb->localalloc=0;
  111074. vb->localstore=NULL;
  111075. if(v->analysisp){
  111076. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111077. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111078. vbi->ampmax=-9999;
  111079. for(i=0;i<PACKETBLOBS;i++){
  111080. if(i==PACKETBLOBS/2){
  111081. vbi->packetblob[i]=&vb->opb;
  111082. }else{
  111083. vbi->packetblob[i]=
  111084. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111085. }
  111086. oggpack_writeinit(vbi->packetblob[i]);
  111087. }
  111088. }
  111089. return(0);
  111090. }
  111091. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111092. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111093. if(bytes+vb->localtop>vb->localalloc){
  111094. /* can't just _ogg_realloc... there are outstanding pointers */
  111095. if(vb->localstore){
  111096. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111097. vb->totaluse+=vb->localtop;
  111098. link->next=vb->reap;
  111099. link->ptr=vb->localstore;
  111100. vb->reap=link;
  111101. }
  111102. /* highly conservative */
  111103. vb->localalloc=bytes;
  111104. vb->localstore=_ogg_malloc(vb->localalloc);
  111105. vb->localtop=0;
  111106. }
  111107. {
  111108. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111109. vb->localtop+=bytes;
  111110. return ret;
  111111. }
  111112. }
  111113. /* reap the chain, pull the ripcord */
  111114. void _vorbis_block_ripcord(vorbis_block *vb){
  111115. /* reap the chain */
  111116. struct alloc_chain *reap=vb->reap;
  111117. while(reap){
  111118. struct alloc_chain *next=reap->next;
  111119. _ogg_free(reap->ptr);
  111120. memset(reap,0,sizeof(*reap));
  111121. _ogg_free(reap);
  111122. reap=next;
  111123. }
  111124. /* consolidate storage */
  111125. if(vb->totaluse){
  111126. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111127. vb->localalloc+=vb->totaluse;
  111128. vb->totaluse=0;
  111129. }
  111130. /* pull the ripcord */
  111131. vb->localtop=0;
  111132. vb->reap=NULL;
  111133. }
  111134. int vorbis_block_clear(vorbis_block *vb){
  111135. int i;
  111136. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111137. _vorbis_block_ripcord(vb);
  111138. if(vb->localstore)_ogg_free(vb->localstore);
  111139. if(vbi){
  111140. for(i=0;i<PACKETBLOBS;i++){
  111141. oggpack_writeclear(vbi->packetblob[i]);
  111142. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111143. }
  111144. _ogg_free(vbi);
  111145. }
  111146. memset(vb,0,sizeof(*vb));
  111147. return(0);
  111148. }
  111149. /* Analysis side code, but directly related to blocking. Thus it's
  111150. here and not in analysis.c (which is for analysis transforms only).
  111151. The init is here because some of it is shared */
  111152. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111153. int i;
  111154. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111155. private_state *b=NULL;
  111156. int hs;
  111157. if(ci==NULL) return 1;
  111158. hs=ci->halfrate_flag;
  111159. memset(v,0,sizeof(*v));
  111160. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111161. v->vi=vi;
  111162. b->modebits=ilog2(ci->modes);
  111163. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111164. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111165. /* MDCT is tranform 0 */
  111166. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111167. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111168. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111169. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111170. /* Vorbis I uses only window type 0 */
  111171. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111172. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111173. if(encp){ /* encode/decode differ here */
  111174. /* analysis always needs an fft */
  111175. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111176. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111177. /* finish the codebooks */
  111178. if(!ci->fullbooks){
  111179. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111180. for(i=0;i<ci->books;i++)
  111181. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111182. }
  111183. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111184. for(i=0;i<ci->psys;i++){
  111185. _vp_psy_init(b->psy+i,
  111186. ci->psy_param[i],
  111187. &ci->psy_g_param,
  111188. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111189. vi->rate);
  111190. }
  111191. v->analysisp=1;
  111192. }else{
  111193. /* finish the codebooks */
  111194. if(!ci->fullbooks){
  111195. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111196. for(i=0;i<ci->books;i++){
  111197. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111198. /* decode codebooks are now standalone after init */
  111199. vorbis_staticbook_destroy(ci->book_param[i]);
  111200. ci->book_param[i]=NULL;
  111201. }
  111202. }
  111203. }
  111204. /* initialize the storage vectors. blocksize[1] is small for encode,
  111205. but the correct size for decode */
  111206. v->pcm_storage=ci->blocksizes[1];
  111207. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111208. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111209. {
  111210. int i;
  111211. for(i=0;i<vi->channels;i++)
  111212. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111213. }
  111214. /* all 1 (large block) or 0 (small block) */
  111215. /* explicitly set for the sake of clarity */
  111216. v->lW=0; /* previous window size */
  111217. v->W=0; /* current window size */
  111218. /* all vector indexes */
  111219. v->centerW=ci->blocksizes[1]/2;
  111220. v->pcm_current=v->centerW;
  111221. /* initialize all the backend lookups */
  111222. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111223. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111224. for(i=0;i<ci->floors;i++)
  111225. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111226. look(v,ci->floor_param[i]);
  111227. for(i=0;i<ci->residues;i++)
  111228. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111229. look(v,ci->residue_param[i]);
  111230. return 0;
  111231. }
  111232. /* arbitrary settings and spec-mandated numbers get filled in here */
  111233. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111234. private_state *b=NULL;
  111235. if(_vds_shared_init(v,vi,1))return 1;
  111236. b=(private_state*)v->backend_state;
  111237. b->psy_g_look=_vp_global_look(vi);
  111238. /* Initialize the envelope state storage */
  111239. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111240. _ve_envelope_init(b->ve,vi);
  111241. vorbis_bitrate_init(vi,&b->bms);
  111242. /* compressed audio packets start after the headers
  111243. with sequence number 3 */
  111244. v->sequence=3;
  111245. return(0);
  111246. }
  111247. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111248. int i;
  111249. if(v){
  111250. vorbis_info *vi=v->vi;
  111251. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111252. private_state *b=(private_state*)v->backend_state;
  111253. if(b){
  111254. if(b->ve){
  111255. _ve_envelope_clear(b->ve);
  111256. _ogg_free(b->ve);
  111257. }
  111258. if(b->transform[0]){
  111259. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111260. _ogg_free(b->transform[0][0]);
  111261. _ogg_free(b->transform[0]);
  111262. }
  111263. if(b->transform[1]){
  111264. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111265. _ogg_free(b->transform[1][0]);
  111266. _ogg_free(b->transform[1]);
  111267. }
  111268. if(b->flr){
  111269. for(i=0;i<ci->floors;i++)
  111270. _floor_P[ci->floor_type[i]]->
  111271. free_look(b->flr[i]);
  111272. _ogg_free(b->flr);
  111273. }
  111274. if(b->residue){
  111275. for(i=0;i<ci->residues;i++)
  111276. _residue_P[ci->residue_type[i]]->
  111277. free_look(b->residue[i]);
  111278. _ogg_free(b->residue);
  111279. }
  111280. if(b->psy){
  111281. for(i=0;i<ci->psys;i++)
  111282. _vp_psy_clear(b->psy+i);
  111283. _ogg_free(b->psy);
  111284. }
  111285. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111286. vorbis_bitrate_clear(&b->bms);
  111287. drft_clear(&b->fft_look[0]);
  111288. drft_clear(&b->fft_look[1]);
  111289. }
  111290. if(v->pcm){
  111291. for(i=0;i<vi->channels;i++)
  111292. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111293. _ogg_free(v->pcm);
  111294. if(v->pcmret)_ogg_free(v->pcmret);
  111295. }
  111296. if(b){
  111297. /* free header, header1, header2 */
  111298. if(b->header)_ogg_free(b->header);
  111299. if(b->header1)_ogg_free(b->header1);
  111300. if(b->header2)_ogg_free(b->header2);
  111301. _ogg_free(b);
  111302. }
  111303. memset(v,0,sizeof(*v));
  111304. }
  111305. }
  111306. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111307. int i;
  111308. vorbis_info *vi=v->vi;
  111309. private_state *b=(private_state*)v->backend_state;
  111310. /* free header, header1, header2 */
  111311. if(b->header)_ogg_free(b->header);b->header=NULL;
  111312. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111313. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111314. /* Do we have enough storage space for the requested buffer? If not,
  111315. expand the PCM (and envelope) storage */
  111316. if(v->pcm_current+vals>=v->pcm_storage){
  111317. v->pcm_storage=v->pcm_current+vals*2;
  111318. for(i=0;i<vi->channels;i++){
  111319. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111320. }
  111321. }
  111322. for(i=0;i<vi->channels;i++)
  111323. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111324. return(v->pcmret);
  111325. }
  111326. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111327. int i;
  111328. int order=32;
  111329. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111330. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111331. long j;
  111332. v->preextrapolate=1;
  111333. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111334. for(i=0;i<v->vi->channels;i++){
  111335. /* need to run the extrapolation in reverse! */
  111336. for(j=0;j<v->pcm_current;j++)
  111337. work[j]=v->pcm[i][v->pcm_current-j-1];
  111338. /* prime as above */
  111339. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111340. /* run the predictor filter */
  111341. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111342. order,
  111343. work+v->pcm_current-v->centerW,
  111344. v->centerW);
  111345. for(j=0;j<v->pcm_current;j++)
  111346. v->pcm[i][v->pcm_current-j-1]=work[j];
  111347. }
  111348. }
  111349. }
  111350. /* call with val<=0 to set eof */
  111351. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111352. vorbis_info *vi=v->vi;
  111353. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111354. if(vals<=0){
  111355. int order=32;
  111356. int i;
  111357. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111358. /* if it wasn't done earlier (very short sample) */
  111359. if(!v->preextrapolate)
  111360. _preextrapolate_helper(v);
  111361. /* We're encoding the end of the stream. Just make sure we have
  111362. [at least] a few full blocks of zeroes at the end. */
  111363. /* actually, we don't want zeroes; that could drop a large
  111364. amplitude off a cliff, creating spread spectrum noise that will
  111365. suck to encode. Extrapolate for the sake of cleanliness. */
  111366. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111367. v->eofflag=v->pcm_current;
  111368. v->pcm_current+=ci->blocksizes[1]*3;
  111369. for(i=0;i<vi->channels;i++){
  111370. if(v->eofflag>order*2){
  111371. /* extrapolate with LPC to fill in */
  111372. long n;
  111373. /* make a predictor filter */
  111374. n=v->eofflag;
  111375. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111376. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111377. /* run the predictor filter */
  111378. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111379. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111380. }else{
  111381. /* not enough data to extrapolate (unlikely to happen due to
  111382. guarding the overlap, but bulletproof in case that
  111383. assumtion goes away). zeroes will do. */
  111384. memset(v->pcm[i]+v->eofflag,0,
  111385. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111386. }
  111387. }
  111388. }else{
  111389. if(v->pcm_current+vals>v->pcm_storage)
  111390. return(OV_EINVAL);
  111391. v->pcm_current+=vals;
  111392. /* we may want to reverse extrapolate the beginning of a stream
  111393. too... in case we're beginning on a cliff! */
  111394. /* clumsy, but simple. It only runs once, so simple is good. */
  111395. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111396. _preextrapolate_helper(v);
  111397. }
  111398. return(0);
  111399. }
  111400. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111401. the next block on which to continue analysis */
  111402. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111403. int i;
  111404. vorbis_info *vi=v->vi;
  111405. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111406. private_state *b=(private_state*)v->backend_state;
  111407. vorbis_look_psy_global *g=b->psy_g_look;
  111408. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111409. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111410. /* check to see if we're started... */
  111411. if(!v->preextrapolate)return(0);
  111412. /* check to see if we're done... */
  111413. if(v->eofflag==-1)return(0);
  111414. /* By our invariant, we have lW, W and centerW set. Search for
  111415. the next boundary so we can determine nW (the next window size)
  111416. which lets us compute the shape of the current block's window */
  111417. /* we do an envelope search even on a single blocksize; we may still
  111418. be throwing more bits at impulses, and envelope search handles
  111419. marking impulses too. */
  111420. {
  111421. long bp=_ve_envelope_search(v);
  111422. if(bp==-1){
  111423. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111424. full long block */
  111425. v->nW=0;
  111426. }else{
  111427. if(ci->blocksizes[0]==ci->blocksizes[1])
  111428. v->nW=0;
  111429. else
  111430. v->nW=bp;
  111431. }
  111432. }
  111433. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111434. {
  111435. /* center of next block + next block maximum right side. */
  111436. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111437. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111438. although this check is
  111439. less strict that the
  111440. _ve_envelope_search,
  111441. the search is not run
  111442. if we only use one
  111443. block size */
  111444. }
  111445. /* fill in the block. Note that for a short window, lW and nW are *short*
  111446. regardless of actual settings in the stream */
  111447. _vorbis_block_ripcord(vb);
  111448. vb->lW=v->lW;
  111449. vb->W=v->W;
  111450. vb->nW=v->nW;
  111451. if(v->W){
  111452. if(!v->lW || !v->nW){
  111453. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111454. /*fprintf(stderr,"-");*/
  111455. }else{
  111456. vbi->blocktype=BLOCKTYPE_LONG;
  111457. /*fprintf(stderr,"_");*/
  111458. }
  111459. }else{
  111460. if(_ve_envelope_mark(v)){
  111461. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111462. /*fprintf(stderr,"|");*/
  111463. }else{
  111464. vbi->blocktype=BLOCKTYPE_PADDING;
  111465. /*fprintf(stderr,".");*/
  111466. }
  111467. }
  111468. vb->vd=v;
  111469. vb->sequence=v->sequence++;
  111470. vb->granulepos=v->granulepos;
  111471. vb->pcmend=ci->blocksizes[v->W];
  111472. /* copy the vectors; this uses the local storage in vb */
  111473. /* this tracks 'strongest peak' for later psychoacoustics */
  111474. /* moved to the global psy state; clean this mess up */
  111475. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111476. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111477. vbi->ampmax=g->ampmax;
  111478. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111479. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111480. for(i=0;i<vi->channels;i++){
  111481. vbi->pcmdelay[i]=
  111482. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111483. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111484. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111485. /* before we added the delay
  111486. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111487. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111488. */
  111489. }
  111490. /* handle eof detection: eof==0 means that we've not yet received EOF
  111491. eof>0 marks the last 'real' sample in pcm[]
  111492. eof<0 'no more to do'; doesn't get here */
  111493. if(v->eofflag){
  111494. if(v->centerW>=v->eofflag){
  111495. v->eofflag=-1;
  111496. vb->eofflag=1;
  111497. return(1);
  111498. }
  111499. }
  111500. /* advance storage vectors and clean up */
  111501. {
  111502. int new_centerNext=ci->blocksizes[1]/2;
  111503. int movementW=centerNext-new_centerNext;
  111504. if(movementW>0){
  111505. _ve_envelope_shift(b->ve,movementW);
  111506. v->pcm_current-=movementW;
  111507. for(i=0;i<vi->channels;i++)
  111508. memmove(v->pcm[i],v->pcm[i]+movementW,
  111509. v->pcm_current*sizeof(*v->pcm[i]));
  111510. v->lW=v->W;
  111511. v->W=v->nW;
  111512. v->centerW=new_centerNext;
  111513. if(v->eofflag){
  111514. v->eofflag-=movementW;
  111515. if(v->eofflag<=0)v->eofflag=-1;
  111516. /* do not add padding to end of stream! */
  111517. if(v->centerW>=v->eofflag){
  111518. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111519. }else{
  111520. v->granulepos+=movementW;
  111521. }
  111522. }else{
  111523. v->granulepos+=movementW;
  111524. }
  111525. }
  111526. }
  111527. /* done */
  111528. return(1);
  111529. }
  111530. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111531. vorbis_info *vi=v->vi;
  111532. codec_setup_info *ci;
  111533. int hs;
  111534. if(!v->backend_state)return -1;
  111535. if(!vi)return -1;
  111536. ci=(codec_setup_info*) vi->codec_setup;
  111537. if(!ci)return -1;
  111538. hs=ci->halfrate_flag;
  111539. v->centerW=ci->blocksizes[1]>>(hs+1);
  111540. v->pcm_current=v->centerW>>hs;
  111541. v->pcm_returned=-1;
  111542. v->granulepos=-1;
  111543. v->sequence=-1;
  111544. v->eofflag=0;
  111545. ((private_state *)(v->backend_state))->sample_count=-1;
  111546. return(0);
  111547. }
  111548. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111549. if(_vds_shared_init(v,vi,0)) return 1;
  111550. vorbis_synthesis_restart(v);
  111551. return 0;
  111552. }
  111553. /* Unlike in analysis, the window is only partially applied for each
  111554. block. The time domain envelope is not yet handled at the point of
  111555. calling (as it relies on the previous block). */
  111556. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111557. vorbis_info *vi=v->vi;
  111558. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111559. private_state *b=(private_state*)v->backend_state;
  111560. int hs=ci->halfrate_flag;
  111561. int i,j;
  111562. if(!vb)return(OV_EINVAL);
  111563. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111564. v->lW=v->W;
  111565. v->W=vb->W;
  111566. v->nW=-1;
  111567. if((v->sequence==-1)||
  111568. (v->sequence+1 != vb->sequence)){
  111569. v->granulepos=-1; /* out of sequence; lose count */
  111570. b->sample_count=-1;
  111571. }
  111572. v->sequence=vb->sequence;
  111573. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111574. was called on block */
  111575. int n=ci->blocksizes[v->W]>>(hs+1);
  111576. int n0=ci->blocksizes[0]>>(hs+1);
  111577. int n1=ci->blocksizes[1]>>(hs+1);
  111578. int thisCenter;
  111579. int prevCenter;
  111580. v->glue_bits+=vb->glue_bits;
  111581. v->time_bits+=vb->time_bits;
  111582. v->floor_bits+=vb->floor_bits;
  111583. v->res_bits+=vb->res_bits;
  111584. if(v->centerW){
  111585. thisCenter=n1;
  111586. prevCenter=0;
  111587. }else{
  111588. thisCenter=0;
  111589. prevCenter=n1;
  111590. }
  111591. /* v->pcm is now used like a two-stage double buffer. We don't want
  111592. to have to constantly shift *or* adjust memory usage. Don't
  111593. accept a new block until the old is shifted out */
  111594. for(j=0;j<vi->channels;j++){
  111595. /* the overlap/add section */
  111596. if(v->lW){
  111597. if(v->W){
  111598. /* large/large */
  111599. float *w=_vorbis_window_get(b->window[1]-hs);
  111600. float *pcm=v->pcm[j]+prevCenter;
  111601. float *p=vb->pcm[j];
  111602. for(i=0;i<n1;i++)
  111603. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111604. }else{
  111605. /* large/small */
  111606. float *w=_vorbis_window_get(b->window[0]-hs);
  111607. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111608. float *p=vb->pcm[j];
  111609. for(i=0;i<n0;i++)
  111610. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111611. }
  111612. }else{
  111613. if(v->W){
  111614. /* small/large */
  111615. float *w=_vorbis_window_get(b->window[0]-hs);
  111616. float *pcm=v->pcm[j]+prevCenter;
  111617. float *p=vb->pcm[j]+n1/2-n0/2;
  111618. for(i=0;i<n0;i++)
  111619. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111620. for(;i<n1/2+n0/2;i++)
  111621. pcm[i]=p[i];
  111622. }else{
  111623. /* small/small */
  111624. float *w=_vorbis_window_get(b->window[0]-hs);
  111625. float *pcm=v->pcm[j]+prevCenter;
  111626. float *p=vb->pcm[j];
  111627. for(i=0;i<n0;i++)
  111628. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111629. }
  111630. }
  111631. /* the copy section */
  111632. {
  111633. float *pcm=v->pcm[j]+thisCenter;
  111634. float *p=vb->pcm[j]+n;
  111635. for(i=0;i<n;i++)
  111636. pcm[i]=p[i];
  111637. }
  111638. }
  111639. if(v->centerW)
  111640. v->centerW=0;
  111641. else
  111642. v->centerW=n1;
  111643. /* deal with initial packet state; we do this using the explicit
  111644. pcm_returned==-1 flag otherwise we're sensitive to first block
  111645. being short or long */
  111646. if(v->pcm_returned==-1){
  111647. v->pcm_returned=thisCenter;
  111648. v->pcm_current=thisCenter;
  111649. }else{
  111650. v->pcm_returned=prevCenter;
  111651. v->pcm_current=prevCenter+
  111652. ((ci->blocksizes[v->lW]/4+
  111653. ci->blocksizes[v->W]/4)>>hs);
  111654. }
  111655. }
  111656. /* track the frame number... This is for convenience, but also
  111657. making sure our last packet doesn't end with added padding. If
  111658. the last packet is partial, the number of samples we'll have to
  111659. return will be past the vb->granulepos.
  111660. This is not foolproof! It will be confused if we begin
  111661. decoding at the last page after a seek or hole. In that case,
  111662. we don't have a starting point to judge where the last frame
  111663. is. For this reason, vorbisfile will always try to make sure
  111664. it reads the last two marked pages in proper sequence */
  111665. if(b->sample_count==-1){
  111666. b->sample_count=0;
  111667. }else{
  111668. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111669. }
  111670. if(v->granulepos==-1){
  111671. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111672. v->granulepos=vb->granulepos;
  111673. /* is this a short page? */
  111674. if(b->sample_count>v->granulepos){
  111675. /* corner case; if this is both the first and last audio page,
  111676. then spec says the end is cut, not beginning */
  111677. if(vb->eofflag){
  111678. /* trim the end */
  111679. /* no preceeding granulepos; assume we started at zero (we'd
  111680. have to in a short single-page stream) */
  111681. /* granulepos could be -1 due to a seek, but that would result
  111682. in a long count, not short count */
  111683. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111684. }else{
  111685. /* trim the beginning */
  111686. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111687. if(v->pcm_returned>v->pcm_current)
  111688. v->pcm_returned=v->pcm_current;
  111689. }
  111690. }
  111691. }
  111692. }else{
  111693. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111694. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111695. if(v->granulepos>vb->granulepos){
  111696. long extra=v->granulepos-vb->granulepos;
  111697. if(extra)
  111698. if(vb->eofflag){
  111699. /* partial last frame. Strip the extra samples off */
  111700. v->pcm_current-=extra>>hs;
  111701. } /* else {Shouldn't happen *unless* the bitstream is out of
  111702. spec. Either way, believe the bitstream } */
  111703. } /* else {Shouldn't happen *unless* the bitstream is out of
  111704. spec. Either way, believe the bitstream } */
  111705. v->granulepos=vb->granulepos;
  111706. }
  111707. }
  111708. /* Update, cleanup */
  111709. if(vb->eofflag)v->eofflag=1;
  111710. return(0);
  111711. }
  111712. /* pcm==NULL indicates we just want the pending samples, no more */
  111713. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111714. vorbis_info *vi=v->vi;
  111715. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111716. if(pcm){
  111717. int i;
  111718. for(i=0;i<vi->channels;i++)
  111719. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111720. *pcm=v->pcmret;
  111721. }
  111722. return(v->pcm_current-v->pcm_returned);
  111723. }
  111724. return(0);
  111725. }
  111726. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111727. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111728. v->pcm_returned+=n;
  111729. return(0);
  111730. }
  111731. /* intended for use with a specific vorbisfile feature; we want access
  111732. to the [usually synthetic/postextrapolated] buffer and lapping at
  111733. the end of a decode cycle, specifically, a half-short-block worth.
  111734. This funtion works like pcmout above, except it will also expose
  111735. this implicit buffer data not normally decoded. */
  111736. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111737. vorbis_info *vi=v->vi;
  111738. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111739. int hs=ci->halfrate_flag;
  111740. int n=ci->blocksizes[v->W]>>(hs+1);
  111741. int n0=ci->blocksizes[0]>>(hs+1);
  111742. int n1=ci->blocksizes[1]>>(hs+1);
  111743. int i,j;
  111744. if(v->pcm_returned<0)return 0;
  111745. /* our returned data ends at pcm_returned; because the synthesis pcm
  111746. buffer is a two-fragment ring, that means our data block may be
  111747. fragmented by buffering, wrapping or a short block not filling
  111748. out a buffer. To simplify things, we unfragment if it's at all
  111749. possibly needed. Otherwise, we'd need to call lapout more than
  111750. once as well as hold additional dsp state. Opt for
  111751. simplicity. */
  111752. /* centerW was advanced by blockin; it would be the center of the
  111753. *next* block */
  111754. if(v->centerW==n1){
  111755. /* the data buffer wraps; swap the halves */
  111756. /* slow, sure, small */
  111757. for(j=0;j<vi->channels;j++){
  111758. float *p=v->pcm[j];
  111759. for(i=0;i<n1;i++){
  111760. float temp=p[i];
  111761. p[i]=p[i+n1];
  111762. p[i+n1]=temp;
  111763. }
  111764. }
  111765. v->pcm_current-=n1;
  111766. v->pcm_returned-=n1;
  111767. v->centerW=0;
  111768. }
  111769. /* solidify buffer into contiguous space */
  111770. if((v->lW^v->W)==1){
  111771. /* long/short or short/long */
  111772. for(j=0;j<vi->channels;j++){
  111773. float *s=v->pcm[j];
  111774. float *d=v->pcm[j]+(n1-n0)/2;
  111775. for(i=(n1+n0)/2-1;i>=0;--i)
  111776. d[i]=s[i];
  111777. }
  111778. v->pcm_returned+=(n1-n0)/2;
  111779. v->pcm_current+=(n1-n0)/2;
  111780. }else{
  111781. if(v->lW==0){
  111782. /* short/short */
  111783. for(j=0;j<vi->channels;j++){
  111784. float *s=v->pcm[j];
  111785. float *d=v->pcm[j]+n1-n0;
  111786. for(i=n0-1;i>=0;--i)
  111787. d[i]=s[i];
  111788. }
  111789. v->pcm_returned+=n1-n0;
  111790. v->pcm_current+=n1-n0;
  111791. }
  111792. }
  111793. if(pcm){
  111794. int i;
  111795. for(i=0;i<vi->channels;i++)
  111796. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111797. *pcm=v->pcmret;
  111798. }
  111799. return(n1+n-v->pcm_returned);
  111800. }
  111801. float *vorbis_window(vorbis_dsp_state *v,int W){
  111802. vorbis_info *vi=v->vi;
  111803. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111804. int hs=ci->halfrate_flag;
  111805. private_state *b=(private_state*)v->backend_state;
  111806. if(b->window[W]-1<0)return NULL;
  111807. return _vorbis_window_get(b->window[W]-hs);
  111808. }
  111809. #endif
  111810. /*** End of inlined file: block.c ***/
  111811. /*** Start of inlined file: codebook.c ***/
  111812. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111813. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111814. // tasks..
  111815. #if JUCE_MSVC
  111816. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111817. #endif
  111818. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111819. #if JUCE_USE_OGGVORBIS
  111820. #include <stdlib.h>
  111821. #include <string.h>
  111822. #include <math.h>
  111823. /* packs the given codebook into the bitstream **************************/
  111824. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111825. long i,j;
  111826. int ordered=0;
  111827. /* first the basic parameters */
  111828. oggpack_write(opb,0x564342,24);
  111829. oggpack_write(opb,c->dim,16);
  111830. oggpack_write(opb,c->entries,24);
  111831. /* pack the codewords. There are two packings; length ordered and
  111832. length random. Decide between the two now. */
  111833. for(i=1;i<c->entries;i++)
  111834. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111835. if(i==c->entries)ordered=1;
  111836. if(ordered){
  111837. /* length ordered. We only need to say how many codewords of
  111838. each length. The actual codewords are generated
  111839. deterministically */
  111840. long count=0;
  111841. oggpack_write(opb,1,1); /* ordered */
  111842. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111843. for(i=1;i<c->entries;i++){
  111844. long thisx=c->lengthlist[i];
  111845. long last=c->lengthlist[i-1];
  111846. if(thisx>last){
  111847. for(j=last;j<thisx;j++){
  111848. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111849. count=i;
  111850. }
  111851. }
  111852. }
  111853. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111854. }else{
  111855. /* length random. Again, we don't code the codeword itself, just
  111856. the length. This time, though, we have to encode each length */
  111857. oggpack_write(opb,0,1); /* unordered */
  111858. /* algortihmic mapping has use for 'unused entries', which we tag
  111859. here. The algorithmic mapping happens as usual, but the unused
  111860. entry has no codeword. */
  111861. for(i=0;i<c->entries;i++)
  111862. if(c->lengthlist[i]==0)break;
  111863. if(i==c->entries){
  111864. oggpack_write(opb,0,1); /* no unused entries */
  111865. for(i=0;i<c->entries;i++)
  111866. oggpack_write(opb,c->lengthlist[i]-1,5);
  111867. }else{
  111868. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111869. for(i=0;i<c->entries;i++){
  111870. if(c->lengthlist[i]==0){
  111871. oggpack_write(opb,0,1);
  111872. }else{
  111873. oggpack_write(opb,1,1);
  111874. oggpack_write(opb,c->lengthlist[i]-1,5);
  111875. }
  111876. }
  111877. }
  111878. }
  111879. /* is the entry number the desired return value, or do we have a
  111880. mapping? If we have a mapping, what type? */
  111881. oggpack_write(opb,c->maptype,4);
  111882. switch(c->maptype){
  111883. case 0:
  111884. /* no mapping */
  111885. break;
  111886. case 1:case 2:
  111887. /* implicitly populated value mapping */
  111888. /* explicitly populated value mapping */
  111889. if(!c->quantlist){
  111890. /* no quantlist? error */
  111891. return(-1);
  111892. }
  111893. /* values that define the dequantization */
  111894. oggpack_write(opb,c->q_min,32);
  111895. oggpack_write(opb,c->q_delta,32);
  111896. oggpack_write(opb,c->q_quant-1,4);
  111897. oggpack_write(opb,c->q_sequencep,1);
  111898. {
  111899. int quantvals;
  111900. switch(c->maptype){
  111901. case 1:
  111902. /* a single column of (c->entries/c->dim) quantized values for
  111903. building a full value list algorithmically (square lattice) */
  111904. quantvals=_book_maptype1_quantvals(c);
  111905. break;
  111906. case 2:
  111907. /* every value (c->entries*c->dim total) specified explicitly */
  111908. quantvals=c->entries*c->dim;
  111909. break;
  111910. default: /* NOT_REACHABLE */
  111911. quantvals=-1;
  111912. }
  111913. /* quantized values */
  111914. for(i=0;i<quantvals;i++)
  111915. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111916. }
  111917. break;
  111918. default:
  111919. /* error case; we don't have any other map types now */
  111920. return(-1);
  111921. }
  111922. return(0);
  111923. }
  111924. /* unpacks a codebook from the packet buffer into the codebook struct,
  111925. readies the codebook auxiliary structures for decode *************/
  111926. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111927. long i,j;
  111928. memset(s,0,sizeof(*s));
  111929. s->allocedp=1;
  111930. /* make sure alignment is correct */
  111931. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111932. /* first the basic parameters */
  111933. s->dim=oggpack_read(opb,16);
  111934. s->entries=oggpack_read(opb,24);
  111935. if(s->entries==-1)goto _eofout;
  111936. /* codeword ordering.... length ordered or unordered? */
  111937. switch((int)oggpack_read(opb,1)){
  111938. case 0:
  111939. /* unordered */
  111940. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111941. /* allocated but unused entries? */
  111942. if(oggpack_read(opb,1)){
  111943. /* yes, unused entries */
  111944. for(i=0;i<s->entries;i++){
  111945. if(oggpack_read(opb,1)){
  111946. long num=oggpack_read(opb,5);
  111947. if(num==-1)goto _eofout;
  111948. s->lengthlist[i]=num+1;
  111949. }else
  111950. s->lengthlist[i]=0;
  111951. }
  111952. }else{
  111953. /* all entries used; no tagging */
  111954. for(i=0;i<s->entries;i++){
  111955. long num=oggpack_read(opb,5);
  111956. if(num==-1)goto _eofout;
  111957. s->lengthlist[i]=num+1;
  111958. }
  111959. }
  111960. break;
  111961. case 1:
  111962. /* ordered */
  111963. {
  111964. long length=oggpack_read(opb,5)+1;
  111965. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111966. for(i=0;i<s->entries;){
  111967. long num=oggpack_read(opb,_ilog(s->entries-i));
  111968. if(num==-1)goto _eofout;
  111969. for(j=0;j<num && i<s->entries;j++,i++)
  111970. s->lengthlist[i]=length;
  111971. length++;
  111972. }
  111973. }
  111974. break;
  111975. default:
  111976. /* EOF */
  111977. return(-1);
  111978. }
  111979. /* Do we have a mapping to unpack? */
  111980. switch((s->maptype=oggpack_read(opb,4))){
  111981. case 0:
  111982. /* no mapping */
  111983. break;
  111984. case 1: case 2:
  111985. /* implicitly populated value mapping */
  111986. /* explicitly populated value mapping */
  111987. s->q_min=oggpack_read(opb,32);
  111988. s->q_delta=oggpack_read(opb,32);
  111989. s->q_quant=oggpack_read(opb,4)+1;
  111990. s->q_sequencep=oggpack_read(opb,1);
  111991. {
  111992. int quantvals=0;
  111993. switch(s->maptype){
  111994. case 1:
  111995. quantvals=_book_maptype1_quantvals(s);
  111996. break;
  111997. case 2:
  111998. quantvals=s->entries*s->dim;
  111999. break;
  112000. }
  112001. /* quantized values */
  112002. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  112003. for(i=0;i<quantvals;i++)
  112004. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  112005. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  112006. }
  112007. break;
  112008. default:
  112009. goto _errout;
  112010. }
  112011. /* all set */
  112012. return(0);
  112013. _errout:
  112014. _eofout:
  112015. vorbis_staticbook_clear(s);
  112016. return(-1);
  112017. }
  112018. /* returns the number of bits ************************************************/
  112019. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  112020. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  112021. return(book->c->lengthlist[a]);
  112022. }
  112023. /* One the encode side, our vector writers are each designed for a
  112024. specific purpose, and the encoder is not flexible without modification:
  112025. The LSP vector coder uses a single stage nearest-match with no
  112026. interleave, so no step and no error return. This is specced by floor0
  112027. and doesn't change.
  112028. Residue0 encoding interleaves, uses multiple stages, and each stage
  112029. peels of a specific amount of resolution from a lattice (thus we want
  112030. to match by threshold, not nearest match). Residue doesn't *have* to
  112031. be encoded that way, but to change it, one will need to add more
  112032. infrastructure on the encode side (decode side is specced and simpler) */
  112033. /* floor0 LSP (single stage, non interleaved, nearest match) */
  112034. /* returns entry number and *modifies a* to the quantization value *****/
  112035. int vorbis_book_errorv(codebook *book,float *a){
  112036. int dim=book->dim,k;
  112037. int best=_best(book,a,1);
  112038. for(k=0;k<dim;k++)
  112039. a[k]=(book->valuelist+best*dim)[k];
  112040. return(best);
  112041. }
  112042. /* returns the number of bits and *modifies a* to the quantization value *****/
  112043. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  112044. int k,dim=book->dim;
  112045. for(k=0;k<dim;k++)
  112046. a[k]=(book->valuelist+best*dim)[k];
  112047. return(vorbis_book_encode(book,best,b));
  112048. }
  112049. /* the 'eliminate the decode tree' optimization actually requires the
  112050. codewords to be MSb first, not LSb. This is an annoying inelegancy
  112051. (and one of the first places where carefully thought out design
  112052. turned out to be wrong; Vorbis II and future Ogg codecs should go
  112053. to an MSb bitpacker), but not actually the huge hit it appears to
  112054. be. The first-stage decode table catches most words so that
  112055. bitreverse is not in the main execution path. */
  112056. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  112057. int read=book->dec_maxlength;
  112058. long lo,hi;
  112059. long lok = oggpack_look(b,book->dec_firsttablen);
  112060. if (lok >= 0) {
  112061. long entry = book->dec_firsttable[lok];
  112062. if(entry&0x80000000UL){
  112063. lo=(entry>>15)&0x7fff;
  112064. hi=book->used_entries-(entry&0x7fff);
  112065. }else{
  112066. oggpack_adv(b, book->dec_codelengths[entry-1]);
  112067. return(entry-1);
  112068. }
  112069. }else{
  112070. lo=0;
  112071. hi=book->used_entries;
  112072. }
  112073. lok = oggpack_look(b, read);
  112074. while(lok<0 && read>1)
  112075. lok = oggpack_look(b, --read);
  112076. if(lok<0)return -1;
  112077. /* bisect search for the codeword in the ordered list */
  112078. {
  112079. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112080. while(hi-lo>1){
  112081. long p=(hi-lo)>>1;
  112082. long test=book->codelist[lo+p]>testword;
  112083. lo+=p&(test-1);
  112084. hi-=p&(-test);
  112085. }
  112086. if(book->dec_codelengths[lo]<=read){
  112087. oggpack_adv(b, book->dec_codelengths[lo]);
  112088. return(lo);
  112089. }
  112090. }
  112091. oggpack_adv(b, read);
  112092. return(-1);
  112093. }
  112094. /* Decode side is specced and easier, because we don't need to find
  112095. matches using different criteria; we simply read and map. There are
  112096. two things we need to do 'depending':
  112097. We may need to support interleave. We don't really, but it's
  112098. convenient to do it here rather than rebuild the vector later.
  112099. Cascades may be additive or multiplicitive; this is not inherent in
  112100. the codebook, but set in the code using the codebook. Like
  112101. interleaving, it's easiest to do it here.
  112102. addmul==0 -> declarative (set the value)
  112103. addmul==1 -> additive
  112104. addmul==2 -> multiplicitive */
  112105. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112106. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112107. long packed_entry=decode_packed_entry_number(book,b);
  112108. if(packed_entry>=0)
  112109. return(book->dec_index[packed_entry]);
  112110. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112111. return(packed_entry);
  112112. }
  112113. /* returns 0 on OK or -1 on eof *************************************/
  112114. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112115. int step=n/book->dim;
  112116. long *entry = (long*)alloca(sizeof(*entry)*step);
  112117. float **t = (float**)alloca(sizeof(*t)*step);
  112118. int i,j,o;
  112119. for (i = 0; i < step; i++) {
  112120. entry[i]=decode_packed_entry_number(book,b);
  112121. if(entry[i]==-1)return(-1);
  112122. t[i] = book->valuelist+entry[i]*book->dim;
  112123. }
  112124. for(i=0,o=0;i<book->dim;i++,o+=step)
  112125. for (j=0;j<step;j++)
  112126. a[o+j]+=t[j][i];
  112127. return(0);
  112128. }
  112129. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112130. int i,j,entry;
  112131. float *t;
  112132. if(book->dim>8){
  112133. for(i=0;i<n;){
  112134. entry = decode_packed_entry_number(book,b);
  112135. if(entry==-1)return(-1);
  112136. t = book->valuelist+entry*book->dim;
  112137. for (j=0;j<book->dim;)
  112138. a[i++]+=t[j++];
  112139. }
  112140. }else{
  112141. for(i=0;i<n;){
  112142. entry = decode_packed_entry_number(book,b);
  112143. if(entry==-1)return(-1);
  112144. t = book->valuelist+entry*book->dim;
  112145. j=0;
  112146. switch((int)book->dim){
  112147. case 8:
  112148. a[i++]+=t[j++];
  112149. case 7:
  112150. a[i++]+=t[j++];
  112151. case 6:
  112152. a[i++]+=t[j++];
  112153. case 5:
  112154. a[i++]+=t[j++];
  112155. case 4:
  112156. a[i++]+=t[j++];
  112157. case 3:
  112158. a[i++]+=t[j++];
  112159. case 2:
  112160. a[i++]+=t[j++];
  112161. case 1:
  112162. a[i++]+=t[j++];
  112163. case 0:
  112164. break;
  112165. }
  112166. }
  112167. }
  112168. return(0);
  112169. }
  112170. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112171. int i,j,entry;
  112172. float *t;
  112173. for(i=0;i<n;){
  112174. entry = decode_packed_entry_number(book,b);
  112175. if(entry==-1)return(-1);
  112176. t = book->valuelist+entry*book->dim;
  112177. for (j=0;j<book->dim;)
  112178. a[i++]=t[j++];
  112179. }
  112180. return(0);
  112181. }
  112182. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112183. oggpack_buffer *b,int n){
  112184. long i,j,entry;
  112185. int chptr=0;
  112186. for(i=offset/ch;i<(offset+n)/ch;){
  112187. entry = decode_packed_entry_number(book,b);
  112188. if(entry==-1)return(-1);
  112189. {
  112190. const float *t = book->valuelist+entry*book->dim;
  112191. for (j=0;j<book->dim;j++){
  112192. a[chptr++][i]+=t[j];
  112193. if(chptr==ch){
  112194. chptr=0;
  112195. i++;
  112196. }
  112197. }
  112198. }
  112199. }
  112200. return(0);
  112201. }
  112202. #ifdef _V_SELFTEST
  112203. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112204. number of vectors through (keeping track of the quantized values),
  112205. and decode using the unpacked book. quantized version of in should
  112206. exactly equal out */
  112207. #include <stdio.h>
  112208. #include "vorbis/book/lsp20_0.vqh"
  112209. #include "vorbis/book/res0a_13.vqh"
  112210. #define TESTSIZE 40
  112211. float test1[TESTSIZE]={
  112212. 0.105939f,
  112213. 0.215373f,
  112214. 0.429117f,
  112215. 0.587974f,
  112216. 0.181173f,
  112217. 0.296583f,
  112218. 0.515707f,
  112219. 0.715261f,
  112220. 0.162327f,
  112221. 0.263834f,
  112222. 0.342876f,
  112223. 0.406025f,
  112224. 0.103571f,
  112225. 0.223561f,
  112226. 0.368513f,
  112227. 0.540313f,
  112228. 0.136672f,
  112229. 0.395882f,
  112230. 0.587183f,
  112231. 0.652476f,
  112232. 0.114338f,
  112233. 0.417300f,
  112234. 0.525486f,
  112235. 0.698679f,
  112236. 0.147492f,
  112237. 0.324481f,
  112238. 0.643089f,
  112239. 0.757582f,
  112240. 0.139556f,
  112241. 0.215795f,
  112242. 0.324559f,
  112243. 0.399387f,
  112244. 0.120236f,
  112245. 0.267420f,
  112246. 0.446940f,
  112247. 0.608760f,
  112248. 0.115587f,
  112249. 0.287234f,
  112250. 0.571081f,
  112251. 0.708603f,
  112252. };
  112253. float test3[TESTSIZE]={
  112254. 0,1,-2,3,4,-5,6,7,8,9,
  112255. 8,-2,7,-1,4,6,8,3,1,-9,
  112256. 10,11,12,13,14,15,26,17,18,19,
  112257. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112258. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112259. &_vq_book_res0a_13,NULL};
  112260. float *testvec[]={test1,test3};
  112261. int main(){
  112262. oggpack_buffer write;
  112263. oggpack_buffer read;
  112264. long ptr=0,i;
  112265. oggpack_writeinit(&write);
  112266. fprintf(stderr,"Testing codebook abstraction...:\n");
  112267. while(testlist[ptr]){
  112268. codebook c;
  112269. static_codebook s;
  112270. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112271. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112272. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112273. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112274. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112275. /* pack the codebook, write the testvector */
  112276. oggpack_reset(&write);
  112277. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112278. we can write */
  112279. vorbis_staticbook_pack(testlist[ptr],&write);
  112280. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112281. for(i=0;i<TESTSIZE;i+=c.dim){
  112282. int best=_best(&c,qv+i,1);
  112283. vorbis_book_encodev(&c,best,qv+i,&write);
  112284. }
  112285. vorbis_book_clear(&c);
  112286. fprintf(stderr,"OK.\n");
  112287. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112288. /* transfer the write data to a read buffer and unpack/read */
  112289. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112290. if(vorbis_staticbook_unpack(&read,&s)){
  112291. fprintf(stderr,"Error unpacking codebook.\n");
  112292. exit(1);
  112293. }
  112294. if(vorbis_book_init_decode(&c,&s)){
  112295. fprintf(stderr,"Error initializing codebook.\n");
  112296. exit(1);
  112297. }
  112298. for(i=0;i<TESTSIZE;i+=c.dim)
  112299. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112300. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112301. exit(1);
  112302. }
  112303. for(i=0;i<TESTSIZE;i++)
  112304. if(fabs(qv[i]-iv[i])>.000001){
  112305. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112306. iv[i],qv[i],i);
  112307. exit(1);
  112308. }
  112309. fprintf(stderr,"OK\n");
  112310. ptr++;
  112311. }
  112312. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112313. exit(0);
  112314. }
  112315. #endif
  112316. #endif
  112317. /*** End of inlined file: codebook.c ***/
  112318. /*** Start of inlined file: envelope.c ***/
  112319. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112320. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112321. // tasks..
  112322. #if JUCE_MSVC
  112323. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112324. #endif
  112325. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112326. #if JUCE_USE_OGGVORBIS
  112327. #include <stdlib.h>
  112328. #include <string.h>
  112329. #include <stdio.h>
  112330. #include <math.h>
  112331. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112332. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112333. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112334. int ch=vi->channels;
  112335. int i,j;
  112336. int n=e->winlength=128;
  112337. e->searchstep=64; /* not random */
  112338. e->minenergy=gi->preecho_minenergy;
  112339. e->ch=ch;
  112340. e->storage=128;
  112341. e->cursor=ci->blocksizes[1]/2;
  112342. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112343. mdct_init(&e->mdct,n);
  112344. for(i=0;i<n;i++){
  112345. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112346. e->mdct_win[i]*=e->mdct_win[i];
  112347. }
  112348. /* magic follows */
  112349. e->band[0].begin=2; e->band[0].end=4;
  112350. e->band[1].begin=4; e->band[1].end=5;
  112351. e->band[2].begin=6; e->band[2].end=6;
  112352. e->band[3].begin=9; e->band[3].end=8;
  112353. e->band[4].begin=13; e->band[4].end=8;
  112354. e->band[5].begin=17; e->band[5].end=8;
  112355. e->band[6].begin=22; e->band[6].end=8;
  112356. for(j=0;j<VE_BANDS;j++){
  112357. n=e->band[j].end;
  112358. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112359. for(i=0;i<n;i++){
  112360. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112361. e->band[j].total+=e->band[j].window[i];
  112362. }
  112363. e->band[j].total=1./e->band[j].total;
  112364. }
  112365. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112366. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112367. }
  112368. void _ve_envelope_clear(envelope_lookup *e){
  112369. int i;
  112370. mdct_clear(&e->mdct);
  112371. for(i=0;i<VE_BANDS;i++)
  112372. _ogg_free(e->band[i].window);
  112373. _ogg_free(e->mdct_win);
  112374. _ogg_free(e->filter);
  112375. _ogg_free(e->mark);
  112376. memset(e,0,sizeof(*e));
  112377. }
  112378. /* fairly straight threshhold-by-band based until we find something
  112379. that works better and isn't patented. */
  112380. static int _ve_amp(envelope_lookup *ve,
  112381. vorbis_info_psy_global *gi,
  112382. float *data,
  112383. envelope_band *bands,
  112384. envelope_filter_state *filters,
  112385. long pos){
  112386. long n=ve->winlength;
  112387. int ret=0;
  112388. long i,j;
  112389. float decay;
  112390. /* we want to have a 'minimum bar' for energy, else we're just
  112391. basing blocks on quantization noise that outweighs the signal
  112392. itself (for low power signals) */
  112393. float minV=ve->minenergy;
  112394. float *vec=(float*) alloca(n*sizeof(*vec));
  112395. /* stretch is used to gradually lengthen the number of windows
  112396. considered prevoius-to-potential-trigger */
  112397. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112398. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112399. if(penalty<0.f)penalty=0.f;
  112400. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112401. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112402. totalshift+pos*ve->searchstep);*/
  112403. /* window and transform */
  112404. for(i=0;i<n;i++)
  112405. vec[i]=data[i]*ve->mdct_win[i];
  112406. mdct_forward(&ve->mdct,vec,vec);
  112407. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112408. /* near-DC spreading function; this has nothing to do with
  112409. psychoacoustics, just sidelobe leakage and window size */
  112410. {
  112411. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112412. int ptr=filters->nearptr;
  112413. /* the accumulation is regularly refreshed from scratch to avoid
  112414. floating point creep */
  112415. if(ptr==0){
  112416. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112417. filters->nearDC_partialacc=temp;
  112418. }else{
  112419. decay=filters->nearDC_acc+=temp;
  112420. filters->nearDC_partialacc+=temp;
  112421. }
  112422. filters->nearDC_acc-=filters->nearDC[ptr];
  112423. filters->nearDC[ptr]=temp;
  112424. decay*=(1./(VE_NEARDC+1));
  112425. filters->nearptr++;
  112426. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112427. decay=todB(&decay)*.5-15.f;
  112428. }
  112429. /* perform spreading and limiting, also smooth the spectrum. yes,
  112430. the MDCT results in all real coefficients, but it still *behaves*
  112431. like real/imaginary pairs */
  112432. for(i=0;i<n/2;i+=2){
  112433. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112434. val=todB(&val)*.5f;
  112435. if(val<decay)val=decay;
  112436. if(val<minV)val=minV;
  112437. vec[i>>1]=val;
  112438. decay-=8.;
  112439. }
  112440. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112441. /* perform preecho/postecho triggering by band */
  112442. for(j=0;j<VE_BANDS;j++){
  112443. float acc=0.;
  112444. float valmax,valmin;
  112445. /* accumulate amplitude */
  112446. for(i=0;i<bands[j].end;i++)
  112447. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112448. acc*=bands[j].total;
  112449. /* convert amplitude to delta */
  112450. {
  112451. int p,thisx=filters[j].ampptr;
  112452. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112453. p=thisx;
  112454. p--;
  112455. if(p<0)p+=VE_AMP;
  112456. postmax=max(acc,filters[j].ampbuf[p]);
  112457. postmin=min(acc,filters[j].ampbuf[p]);
  112458. for(i=0;i<stretch;i++){
  112459. p--;
  112460. if(p<0)p+=VE_AMP;
  112461. premax=max(premax,filters[j].ampbuf[p]);
  112462. premin=min(premin,filters[j].ampbuf[p]);
  112463. }
  112464. valmin=postmin-premin;
  112465. valmax=postmax-premax;
  112466. /*filters[j].markers[pos]=valmax;*/
  112467. filters[j].ampbuf[thisx]=acc;
  112468. filters[j].ampptr++;
  112469. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112470. }
  112471. /* look at min/max, decide trigger */
  112472. if(valmax>gi->preecho_thresh[j]+penalty){
  112473. ret|=1;
  112474. ret|=4;
  112475. }
  112476. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112477. }
  112478. return(ret);
  112479. }
  112480. #if 0
  112481. static int seq=0;
  112482. static ogg_int64_t totalshift=-1024;
  112483. #endif
  112484. long _ve_envelope_search(vorbis_dsp_state *v){
  112485. vorbis_info *vi=v->vi;
  112486. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112487. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112488. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112489. long i,j;
  112490. int first=ve->current/ve->searchstep;
  112491. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112492. if(first<0)first=0;
  112493. /* make sure we have enough storage to match the PCM */
  112494. if(last+VE_WIN+VE_POST>ve->storage){
  112495. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112496. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112497. }
  112498. for(j=first;j<last;j++){
  112499. int ret=0;
  112500. ve->stretch++;
  112501. if(ve->stretch>VE_MAXSTRETCH*2)
  112502. ve->stretch=VE_MAXSTRETCH*2;
  112503. for(i=0;i<ve->ch;i++){
  112504. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112505. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112506. }
  112507. ve->mark[j+VE_POST]=0;
  112508. if(ret&1){
  112509. ve->mark[j]=1;
  112510. ve->mark[j+1]=1;
  112511. }
  112512. if(ret&2){
  112513. ve->mark[j]=1;
  112514. if(j>0)ve->mark[j-1]=1;
  112515. }
  112516. if(ret&4)ve->stretch=-1;
  112517. }
  112518. ve->current=last*ve->searchstep;
  112519. {
  112520. long centerW=v->centerW;
  112521. long testW=
  112522. centerW+
  112523. ci->blocksizes[v->W]/4+
  112524. ci->blocksizes[1]/2+
  112525. ci->blocksizes[0]/4;
  112526. j=ve->cursor;
  112527. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112528. working back one window */
  112529. if(j>=testW)return(1);
  112530. ve->cursor=j;
  112531. if(ve->mark[j/ve->searchstep]){
  112532. if(j>centerW){
  112533. #if 0
  112534. if(j>ve->curmark){
  112535. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112536. int l,m;
  112537. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112538. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112539. seq,
  112540. (totalshift+ve->cursor)/44100.,
  112541. (totalshift+j)/44100.);
  112542. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112543. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112544. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112545. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112546. for(m=0;m<VE_BANDS;m++){
  112547. char buf[80];
  112548. sprintf(buf,"delL%d",m);
  112549. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112550. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112551. }
  112552. for(m=0;m<VE_BANDS;m++){
  112553. char buf[80];
  112554. sprintf(buf,"delR%d",m);
  112555. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112556. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112557. }
  112558. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112559. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112560. seq++;
  112561. }
  112562. #endif
  112563. ve->curmark=j;
  112564. if(j>=testW)return(1);
  112565. return(0);
  112566. }
  112567. }
  112568. j+=ve->searchstep;
  112569. }
  112570. }
  112571. return(-1);
  112572. }
  112573. int _ve_envelope_mark(vorbis_dsp_state *v){
  112574. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112575. vorbis_info *vi=v->vi;
  112576. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112577. long centerW=v->centerW;
  112578. long beginW=centerW-ci->blocksizes[v->W]/4;
  112579. long endW=centerW+ci->blocksizes[v->W]/4;
  112580. if(v->W){
  112581. beginW-=ci->blocksizes[v->lW]/4;
  112582. endW+=ci->blocksizes[v->nW]/4;
  112583. }else{
  112584. beginW-=ci->blocksizes[0]/4;
  112585. endW+=ci->blocksizes[0]/4;
  112586. }
  112587. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112588. {
  112589. long first=beginW/ve->searchstep;
  112590. long last=endW/ve->searchstep;
  112591. long i;
  112592. for(i=first;i<last;i++)
  112593. if(ve->mark[i])return(1);
  112594. }
  112595. return(0);
  112596. }
  112597. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112598. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112599. ahead of ve->current */
  112600. int smallshift=shift/e->searchstep;
  112601. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112602. #if 0
  112603. for(i=0;i<VE_BANDS*e->ch;i++)
  112604. memmove(e->filter[i].markers,
  112605. e->filter[i].markers+smallshift,
  112606. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112607. totalshift+=shift;
  112608. #endif
  112609. e->current-=shift;
  112610. if(e->curmark>=0)
  112611. e->curmark-=shift;
  112612. e->cursor-=shift;
  112613. }
  112614. #endif
  112615. /*** End of inlined file: envelope.c ***/
  112616. /*** Start of inlined file: floor0.c ***/
  112617. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112618. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112619. // tasks..
  112620. #if JUCE_MSVC
  112621. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112622. #endif
  112623. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112624. #if JUCE_USE_OGGVORBIS
  112625. #include <stdlib.h>
  112626. #include <string.h>
  112627. #include <math.h>
  112628. /*** Start of inlined file: lsp.h ***/
  112629. #ifndef _V_LSP_H_
  112630. #define _V_LSP_H_
  112631. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112632. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112633. float *lsp,int m,
  112634. float amp,float ampoffset);
  112635. #endif
  112636. /*** End of inlined file: lsp.h ***/
  112637. #include <stdio.h>
  112638. typedef struct {
  112639. int ln;
  112640. int m;
  112641. int **linearmap;
  112642. int n[2];
  112643. vorbis_info_floor0 *vi;
  112644. long bits;
  112645. long frames;
  112646. } vorbis_look_floor0;
  112647. /***********************************************/
  112648. static void floor0_free_info(vorbis_info_floor *i){
  112649. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112650. if(info){
  112651. memset(info,0,sizeof(*info));
  112652. _ogg_free(info);
  112653. }
  112654. }
  112655. static void floor0_free_look(vorbis_look_floor *i){
  112656. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112657. if(look){
  112658. if(look->linearmap){
  112659. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112660. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112661. _ogg_free(look->linearmap);
  112662. }
  112663. memset(look,0,sizeof(*look));
  112664. _ogg_free(look);
  112665. }
  112666. }
  112667. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112668. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112669. int j;
  112670. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112671. info->order=oggpack_read(opb,8);
  112672. info->rate=oggpack_read(opb,16);
  112673. info->barkmap=oggpack_read(opb,16);
  112674. info->ampbits=oggpack_read(opb,6);
  112675. info->ampdB=oggpack_read(opb,8);
  112676. info->numbooks=oggpack_read(opb,4)+1;
  112677. if(info->order<1)goto err_out;
  112678. if(info->rate<1)goto err_out;
  112679. if(info->barkmap<1)goto err_out;
  112680. if(info->numbooks<1)goto err_out;
  112681. for(j=0;j<info->numbooks;j++){
  112682. info->books[j]=oggpack_read(opb,8);
  112683. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112684. }
  112685. return(info);
  112686. err_out:
  112687. floor0_free_info(info);
  112688. return(NULL);
  112689. }
  112690. /* initialize Bark scale and normalization lookups. We could do this
  112691. with static tables, but Vorbis allows a number of possible
  112692. combinations, so it's best to do it computationally.
  112693. The below is authoritative in terms of defining scale mapping.
  112694. Note that the scale depends on the sampling rate as well as the
  112695. linear block and mapping sizes */
  112696. static void floor0_map_lazy_init(vorbis_block *vb,
  112697. vorbis_info_floor *infoX,
  112698. vorbis_look_floor0 *look){
  112699. if(!look->linearmap[vb->W]){
  112700. vorbis_dsp_state *vd=vb->vd;
  112701. vorbis_info *vi=vd->vi;
  112702. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112703. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112704. int W=vb->W;
  112705. int n=ci->blocksizes[W]/2,j;
  112706. /* we choose a scaling constant so that:
  112707. floor(bark(rate/2-1)*C)=mapped-1
  112708. floor(bark(rate/2)*C)=mapped */
  112709. float scale=look->ln/toBARK(info->rate/2.f);
  112710. /* the mapping from a linear scale to a smaller bark scale is
  112711. straightforward. We do *not* make sure that the linear mapping
  112712. does not skip bark-scale bins; the decoder simply skips them and
  112713. the encoder may do what it wishes in filling them. They're
  112714. necessary in some mapping combinations to keep the scale spacing
  112715. accurate */
  112716. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112717. for(j=0;j<n;j++){
  112718. int val=floor( toBARK((info->rate/2.f)/n*j)
  112719. *scale); /* bark numbers represent band edges */
  112720. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112721. look->linearmap[W][j]=val;
  112722. }
  112723. look->linearmap[W][j]=-1;
  112724. look->n[W]=n;
  112725. }
  112726. }
  112727. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112728. vorbis_info_floor *i){
  112729. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112730. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112731. look->m=info->order;
  112732. look->ln=info->barkmap;
  112733. look->vi=info;
  112734. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112735. return look;
  112736. }
  112737. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112738. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112739. vorbis_info_floor0 *info=look->vi;
  112740. int j,k;
  112741. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112742. if(ampraw>0){ /* also handles the -1 out of data case */
  112743. long maxval=(1<<info->ampbits)-1;
  112744. float amp=(float)ampraw/maxval*info->ampdB;
  112745. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112746. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112747. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112748. codebook *b=ci->fullbooks+info->books[booknum];
  112749. float last=0.f;
  112750. /* the additional b->dim is a guard against any possible stack
  112751. smash; b->dim is provably more than we can overflow the
  112752. vector */
  112753. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112754. for(j=0;j<look->m;j+=b->dim)
  112755. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112756. for(j=0;j<look->m;){
  112757. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112758. last=lsp[j-1];
  112759. }
  112760. lsp[look->m]=amp;
  112761. return(lsp);
  112762. }
  112763. }
  112764. eop:
  112765. return(NULL);
  112766. }
  112767. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112768. void *memo,float *out){
  112769. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112770. vorbis_info_floor0 *info=look->vi;
  112771. floor0_map_lazy_init(vb,info,look);
  112772. if(memo){
  112773. float *lsp=(float *)memo;
  112774. float amp=lsp[look->m];
  112775. /* take the coefficients back to a spectral envelope curve */
  112776. vorbis_lsp_to_curve(out,
  112777. look->linearmap[vb->W],
  112778. look->n[vb->W],
  112779. look->ln,
  112780. lsp,look->m,amp,(float)info->ampdB);
  112781. return(1);
  112782. }
  112783. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112784. return(0);
  112785. }
  112786. /* export hooks */
  112787. vorbis_func_floor floor0_exportbundle={
  112788. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112789. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112790. };
  112791. #endif
  112792. /*** End of inlined file: floor0.c ***/
  112793. /*** Start of inlined file: floor1.c ***/
  112794. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112795. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112796. // tasks..
  112797. #if JUCE_MSVC
  112798. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112799. #endif
  112800. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112801. #if JUCE_USE_OGGVORBIS
  112802. #include <stdlib.h>
  112803. #include <string.h>
  112804. #include <math.h>
  112805. #include <stdio.h>
  112806. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112807. typedef struct {
  112808. int sorted_index[VIF_POSIT+2];
  112809. int forward_index[VIF_POSIT+2];
  112810. int reverse_index[VIF_POSIT+2];
  112811. int hineighbor[VIF_POSIT];
  112812. int loneighbor[VIF_POSIT];
  112813. int posts;
  112814. int n;
  112815. int quant_q;
  112816. vorbis_info_floor1 *vi;
  112817. long phrasebits;
  112818. long postbits;
  112819. long frames;
  112820. } vorbis_look_floor1;
  112821. typedef struct lsfit_acc{
  112822. long x0;
  112823. long x1;
  112824. long xa;
  112825. long ya;
  112826. long x2a;
  112827. long y2a;
  112828. long xya;
  112829. long an;
  112830. } lsfit_acc;
  112831. /***********************************************/
  112832. static void floor1_free_info(vorbis_info_floor *i){
  112833. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112834. if(info){
  112835. memset(info,0,sizeof(*info));
  112836. _ogg_free(info);
  112837. }
  112838. }
  112839. static void floor1_free_look(vorbis_look_floor *i){
  112840. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112841. if(look){
  112842. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112843. (float)look->phrasebits/look->frames,
  112844. (float)look->postbits/look->frames,
  112845. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112846. memset(look,0,sizeof(*look));
  112847. _ogg_free(look);
  112848. }
  112849. }
  112850. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112851. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112852. int j,k;
  112853. int count=0;
  112854. int rangebits;
  112855. int maxposit=info->postlist[1];
  112856. int maxclass=-1;
  112857. /* save out partitions */
  112858. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112859. for(j=0;j<info->partitions;j++){
  112860. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112861. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112862. }
  112863. /* save out partition classes */
  112864. for(j=0;j<maxclass+1;j++){
  112865. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112866. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112867. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112868. for(k=0;k<(1<<info->class_subs[j]);k++)
  112869. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112870. }
  112871. /* save out the post list */
  112872. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112873. oggpack_write(opb,ilog2(maxposit),4);
  112874. rangebits=ilog2(maxposit);
  112875. for(j=0,k=0;j<info->partitions;j++){
  112876. count+=info->class_dim[info->partitionclass[j]];
  112877. for(;k<count;k++)
  112878. oggpack_write(opb,info->postlist[k+2],rangebits);
  112879. }
  112880. }
  112881. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112882. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112883. int j,k,count=0,maxclass=-1,rangebits;
  112884. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112885. /* read partitions */
  112886. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112887. for(j=0;j<info->partitions;j++){
  112888. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112889. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112890. }
  112891. /* read partition classes */
  112892. for(j=0;j<maxclass+1;j++){
  112893. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112894. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112895. if(info->class_subs[j]<0)
  112896. goto err_out;
  112897. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112898. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112899. goto err_out;
  112900. for(k=0;k<(1<<info->class_subs[j]);k++){
  112901. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112902. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112903. goto err_out;
  112904. }
  112905. }
  112906. /* read the post list */
  112907. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112908. rangebits=oggpack_read(opb,4);
  112909. for(j=0,k=0;j<info->partitions;j++){
  112910. count+=info->class_dim[info->partitionclass[j]];
  112911. for(;k<count;k++){
  112912. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112913. if(t<0 || t>=(1<<rangebits))
  112914. goto err_out;
  112915. }
  112916. }
  112917. info->postlist[0]=0;
  112918. info->postlist[1]=1<<rangebits;
  112919. return(info);
  112920. err_out:
  112921. floor1_free_info(info);
  112922. return(NULL);
  112923. }
  112924. static int icomp(const void *a,const void *b){
  112925. return(**(int **)a-**(int **)b);
  112926. }
  112927. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112928. vorbis_info_floor *in){
  112929. int *sortpointer[VIF_POSIT+2];
  112930. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112931. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112932. int i,j,n=0;
  112933. look->vi=info;
  112934. look->n=info->postlist[1];
  112935. /* we drop each position value in-between already decoded values,
  112936. and use linear interpolation to predict each new value past the
  112937. edges. The positions are read in the order of the position
  112938. list... we precompute the bounding positions in the lookup. Of
  112939. course, the neighbors can change (if a position is declined), but
  112940. this is an initial mapping */
  112941. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112942. n+=2;
  112943. look->posts=n;
  112944. /* also store a sorted position index */
  112945. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112946. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112947. /* points from sort order back to range number */
  112948. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112949. /* points from range order to sorted position */
  112950. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112951. /* we actually need the post values too */
  112952. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112953. /* quantize values to multiplier spec */
  112954. switch(info->mult){
  112955. case 1: /* 1024 -> 256 */
  112956. look->quant_q=256;
  112957. break;
  112958. case 2: /* 1024 -> 128 */
  112959. look->quant_q=128;
  112960. break;
  112961. case 3: /* 1024 -> 86 */
  112962. look->quant_q=86;
  112963. break;
  112964. case 4: /* 1024 -> 64 */
  112965. look->quant_q=64;
  112966. break;
  112967. }
  112968. /* discover our neighbors for decode where we don't use fit flags
  112969. (that would push the neighbors outward) */
  112970. for(i=0;i<n-2;i++){
  112971. int lo=0;
  112972. int hi=1;
  112973. int lx=0;
  112974. int hx=look->n;
  112975. int currentx=info->postlist[i+2];
  112976. for(j=0;j<i+2;j++){
  112977. int x=info->postlist[j];
  112978. if(x>lx && x<currentx){
  112979. lo=j;
  112980. lx=x;
  112981. }
  112982. if(x<hx && x>currentx){
  112983. hi=j;
  112984. hx=x;
  112985. }
  112986. }
  112987. look->loneighbor[i]=lo;
  112988. look->hineighbor[i]=hi;
  112989. }
  112990. return(look);
  112991. }
  112992. static int render_point(int x0,int x1,int y0,int y1,int x){
  112993. y0&=0x7fff; /* mask off flag */
  112994. y1&=0x7fff;
  112995. {
  112996. int dy=y1-y0;
  112997. int adx=x1-x0;
  112998. int ady=abs(dy);
  112999. int err=ady*(x-x0);
  113000. int off=err/adx;
  113001. if(dy<0)return(y0-off);
  113002. return(y0+off);
  113003. }
  113004. }
  113005. static int vorbis_dBquant(const float *x){
  113006. int i= *x*7.3142857f+1023.5f;
  113007. if(i>1023)return(1023);
  113008. if(i<0)return(0);
  113009. return i;
  113010. }
  113011. static float FLOOR1_fromdB_LOOKUP[256]={
  113012. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  113013. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  113014. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  113015. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  113016. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  113017. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  113018. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  113019. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  113020. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  113021. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  113022. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  113023. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  113024. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  113025. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  113026. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  113027. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  113028. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  113029. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  113030. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  113031. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  113032. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  113033. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  113034. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  113035. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  113036. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  113037. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  113038. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  113039. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  113040. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  113041. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  113042. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  113043. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  113044. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  113045. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  113046. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  113047. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  113048. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  113049. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  113050. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  113051. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  113052. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  113053. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  113054. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  113055. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  113056. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  113057. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  113058. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  113059. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  113060. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  113061. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  113062. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  113063. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  113064. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  113065. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  113066. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  113067. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  113068. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  113069. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  113070. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  113071. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  113072. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113073. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113074. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113075. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113076. };
  113077. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113078. int dy=y1-y0;
  113079. int adx=x1-x0;
  113080. int ady=abs(dy);
  113081. int base=dy/adx;
  113082. int sy=(dy<0?base-1:base+1);
  113083. int x=x0;
  113084. int y=y0;
  113085. int err=0;
  113086. ady-=abs(base*adx);
  113087. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113088. while(++x<x1){
  113089. err=err+ady;
  113090. if(err>=adx){
  113091. err-=adx;
  113092. y+=sy;
  113093. }else{
  113094. y+=base;
  113095. }
  113096. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113097. }
  113098. }
  113099. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113100. int dy=y1-y0;
  113101. int adx=x1-x0;
  113102. int ady=abs(dy);
  113103. int base=dy/adx;
  113104. int sy=(dy<0?base-1:base+1);
  113105. int x=x0;
  113106. int y=y0;
  113107. int err=0;
  113108. ady-=abs(base*adx);
  113109. d[x]=y;
  113110. while(++x<x1){
  113111. err=err+ady;
  113112. if(err>=adx){
  113113. err-=adx;
  113114. y+=sy;
  113115. }else{
  113116. y+=base;
  113117. }
  113118. d[x]=y;
  113119. }
  113120. }
  113121. /* the floor has already been filtered to only include relevant sections */
  113122. static int accumulate_fit(const float *flr,const float *mdct,
  113123. int x0, int x1,lsfit_acc *a,
  113124. int n,vorbis_info_floor1 *info){
  113125. long i;
  113126. 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;
  113127. memset(a,0,sizeof(*a));
  113128. a->x0=x0;
  113129. a->x1=x1;
  113130. if(x1>=n)x1=n-1;
  113131. for(i=x0;i<=x1;i++){
  113132. int quantized=vorbis_dBquant(flr+i);
  113133. if(quantized){
  113134. if(mdct[i]+info->twofitatten>=flr[i]){
  113135. xa += i;
  113136. ya += quantized;
  113137. x2a += i*i;
  113138. y2a += quantized*quantized;
  113139. xya += i*quantized;
  113140. na++;
  113141. }else{
  113142. xb += i;
  113143. yb += quantized;
  113144. x2b += i*i;
  113145. y2b += quantized*quantized;
  113146. xyb += i*quantized;
  113147. nb++;
  113148. }
  113149. }
  113150. }
  113151. xb+=xa;
  113152. yb+=ya;
  113153. x2b+=x2a;
  113154. y2b+=y2a;
  113155. xyb+=xya;
  113156. nb+=na;
  113157. /* weight toward the actually used frequencies if we meet the threshhold */
  113158. {
  113159. int weight=nb*info->twofitweight/(na+1);
  113160. a->xa=xa*weight+xb;
  113161. a->ya=ya*weight+yb;
  113162. a->x2a=x2a*weight+x2b;
  113163. a->y2a=y2a*weight+y2b;
  113164. a->xya=xya*weight+xyb;
  113165. a->an=na*weight+nb;
  113166. }
  113167. return(na);
  113168. }
  113169. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113170. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113171. long x0=a[0].x0;
  113172. long x1=a[fits-1].x1;
  113173. for(i=0;i<fits;i++){
  113174. x+=a[i].xa;
  113175. y+=a[i].ya;
  113176. x2+=a[i].x2a;
  113177. y2+=a[i].y2a;
  113178. xy+=a[i].xya;
  113179. an+=a[i].an;
  113180. }
  113181. if(*y0>=0){
  113182. x+= x0;
  113183. y+= *y0;
  113184. x2+= x0 * x0;
  113185. y2+= *y0 * *y0;
  113186. xy+= *y0 * x0;
  113187. an++;
  113188. }
  113189. if(*y1>=0){
  113190. x+= x1;
  113191. y+= *y1;
  113192. x2+= x1 * x1;
  113193. y2+= *y1 * *y1;
  113194. xy+= *y1 * x1;
  113195. an++;
  113196. }
  113197. if(an){
  113198. /* need 64 bit multiplies, which C doesn't give portably as int */
  113199. double fx=x;
  113200. double fy=y;
  113201. double fx2=x2;
  113202. double fxy=xy;
  113203. double denom=1./(an*fx2-fx*fx);
  113204. double a=(fy*fx2-fxy*fx)*denom;
  113205. double b=(an*fxy-fx*fy)*denom;
  113206. *y0=rint(a+b*x0);
  113207. *y1=rint(a+b*x1);
  113208. /* limit to our range! */
  113209. if(*y0>1023)*y0=1023;
  113210. if(*y1>1023)*y1=1023;
  113211. if(*y0<0)*y0=0;
  113212. if(*y1<0)*y1=0;
  113213. }else{
  113214. *y0=0;
  113215. *y1=0;
  113216. }
  113217. }
  113218. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113219. long y=0;
  113220. int i;
  113221. for(i=0;i<fits && y==0;i++)
  113222. y+=a[i].ya;
  113223. *y0=*y1=y;
  113224. }*/
  113225. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113226. const float *mdct,
  113227. vorbis_info_floor1 *info){
  113228. int dy=y1-y0;
  113229. int adx=x1-x0;
  113230. int ady=abs(dy);
  113231. int base=dy/adx;
  113232. int sy=(dy<0?base-1:base+1);
  113233. int x=x0;
  113234. int y=y0;
  113235. int err=0;
  113236. int val=vorbis_dBquant(mask+x);
  113237. int mse=0;
  113238. int n=0;
  113239. ady-=abs(base*adx);
  113240. mse=(y-val);
  113241. mse*=mse;
  113242. n++;
  113243. if(mdct[x]+info->twofitatten>=mask[x]){
  113244. if(y+info->maxover<val)return(1);
  113245. if(y-info->maxunder>val)return(1);
  113246. }
  113247. while(++x<x1){
  113248. err=err+ady;
  113249. if(err>=adx){
  113250. err-=adx;
  113251. y+=sy;
  113252. }else{
  113253. y+=base;
  113254. }
  113255. val=vorbis_dBquant(mask+x);
  113256. mse+=((y-val)*(y-val));
  113257. n++;
  113258. if(mdct[x]+info->twofitatten>=mask[x]){
  113259. if(val){
  113260. if(y+info->maxover<val)return(1);
  113261. if(y-info->maxunder>val)return(1);
  113262. }
  113263. }
  113264. }
  113265. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113266. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113267. if(mse/n>info->maxerr)return(1);
  113268. return(0);
  113269. }
  113270. static int post_Y(int *A,int *B,int pos){
  113271. if(A[pos]<0)
  113272. return B[pos];
  113273. if(B[pos]<0)
  113274. return A[pos];
  113275. return (A[pos]+B[pos])>>1;
  113276. }
  113277. int *floor1_fit(vorbis_block *vb,void *look_,
  113278. const float *logmdct, /* in */
  113279. const float *logmask){
  113280. long i,j;
  113281. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113282. vorbis_info_floor1 *info=look->vi;
  113283. long n=look->n;
  113284. long posts=look->posts;
  113285. long nonzero=0;
  113286. lsfit_acc fits[VIF_POSIT+1];
  113287. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113288. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113289. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113290. int hineighbor[VIF_POSIT+2];
  113291. int *output=NULL;
  113292. int memo[VIF_POSIT+2];
  113293. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113294. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113295. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113296. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113297. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113298. /* quantize the relevant floor points and collect them into line fit
  113299. structures (one per minimal division) at the same time */
  113300. if(posts==0){
  113301. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113302. }else{
  113303. for(i=0;i<posts-1;i++)
  113304. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113305. look->sorted_index[i+1],fits+i,
  113306. n,info);
  113307. }
  113308. if(nonzero){
  113309. /* start by fitting the implicit base case.... */
  113310. int y0=-200;
  113311. int y1=-200;
  113312. fit_line(fits,posts-1,&y0,&y1);
  113313. fit_valueA[0]=y0;
  113314. fit_valueB[0]=y0;
  113315. fit_valueB[1]=y1;
  113316. fit_valueA[1]=y1;
  113317. /* Non degenerate case */
  113318. /* start progressive splitting. This is a greedy, non-optimal
  113319. algorithm, but simple and close enough to the best
  113320. answer. */
  113321. for(i=2;i<posts;i++){
  113322. int sortpos=look->reverse_index[i];
  113323. int ln=loneighbor[sortpos];
  113324. int hn=hineighbor[sortpos];
  113325. /* eliminate repeat searches of a particular range with a memo */
  113326. if(memo[ln]!=hn){
  113327. /* haven't performed this error search yet */
  113328. int lsortpos=look->reverse_index[ln];
  113329. int hsortpos=look->reverse_index[hn];
  113330. memo[ln]=hn;
  113331. {
  113332. /* A note: we want to bound/minimize *local*, not global, error */
  113333. int lx=info->postlist[ln];
  113334. int hx=info->postlist[hn];
  113335. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113336. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113337. if(ly==-1 || hy==-1){
  113338. exit(1);
  113339. }
  113340. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113341. /* outside error bounds/begin search area. Split it. */
  113342. int ly0=-200;
  113343. int ly1=-200;
  113344. int hy0=-200;
  113345. int hy1=-200;
  113346. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113347. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113348. /* store new edge values */
  113349. fit_valueB[ln]=ly0;
  113350. if(ln==0)fit_valueA[ln]=ly0;
  113351. fit_valueA[i]=ly1;
  113352. fit_valueB[i]=hy0;
  113353. fit_valueA[hn]=hy1;
  113354. if(hn==1)fit_valueB[hn]=hy1;
  113355. if(ly1>=0 || hy0>=0){
  113356. /* store new neighbor values */
  113357. for(j=sortpos-1;j>=0;j--)
  113358. if(hineighbor[j]==hn)
  113359. hineighbor[j]=i;
  113360. else
  113361. break;
  113362. for(j=sortpos+1;j<posts;j++)
  113363. if(loneighbor[j]==ln)
  113364. loneighbor[j]=i;
  113365. else
  113366. break;
  113367. }
  113368. }else{
  113369. fit_valueA[i]=-200;
  113370. fit_valueB[i]=-200;
  113371. }
  113372. }
  113373. }
  113374. }
  113375. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113376. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113377. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113378. /* fill in posts marked as not using a fit; we will zero
  113379. back out to 'unused' when encoding them so long as curve
  113380. interpolation doesn't force them into use */
  113381. for(i=2;i<posts;i++){
  113382. int ln=look->loneighbor[i-2];
  113383. int hn=look->hineighbor[i-2];
  113384. int x0=info->postlist[ln];
  113385. int x1=info->postlist[hn];
  113386. int y0=output[ln];
  113387. int y1=output[hn];
  113388. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113389. int vx=post_Y(fit_valueA,fit_valueB,i);
  113390. if(vx>=0 && predicted!=vx){
  113391. output[i]=vx;
  113392. }else{
  113393. output[i]= predicted|0x8000;
  113394. }
  113395. }
  113396. }
  113397. return(output);
  113398. }
  113399. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113400. int *A,int *B,
  113401. int del){
  113402. long i;
  113403. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113404. long posts=look->posts;
  113405. int *output=NULL;
  113406. if(A && B){
  113407. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113408. for(i=0;i<posts;i++){
  113409. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113410. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113411. }
  113412. }
  113413. return(output);
  113414. }
  113415. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113416. void*look_,
  113417. int *post,int *ilogmask){
  113418. long i,j;
  113419. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113420. vorbis_info_floor1 *info=look->vi;
  113421. long posts=look->posts;
  113422. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113423. int out[VIF_POSIT+2];
  113424. static_codebook **sbooks=ci->book_param;
  113425. codebook *books=ci->fullbooks;
  113426. static long seq=0;
  113427. /* quantize values to multiplier spec */
  113428. if(post){
  113429. for(i=0;i<posts;i++){
  113430. int val=post[i]&0x7fff;
  113431. switch(info->mult){
  113432. case 1: /* 1024 -> 256 */
  113433. val>>=2;
  113434. break;
  113435. case 2: /* 1024 -> 128 */
  113436. val>>=3;
  113437. break;
  113438. case 3: /* 1024 -> 86 */
  113439. val/=12;
  113440. break;
  113441. case 4: /* 1024 -> 64 */
  113442. val>>=4;
  113443. break;
  113444. }
  113445. post[i]=val | (post[i]&0x8000);
  113446. }
  113447. out[0]=post[0];
  113448. out[1]=post[1];
  113449. /* find prediction values for each post and subtract them */
  113450. for(i=2;i<posts;i++){
  113451. int ln=look->loneighbor[i-2];
  113452. int hn=look->hineighbor[i-2];
  113453. int x0=info->postlist[ln];
  113454. int x1=info->postlist[hn];
  113455. int y0=post[ln];
  113456. int y1=post[hn];
  113457. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113458. if((post[i]&0x8000) || (predicted==post[i])){
  113459. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113460. in interpolation */
  113461. out[i]=0;
  113462. }else{
  113463. int headroom=(look->quant_q-predicted<predicted?
  113464. look->quant_q-predicted:predicted);
  113465. int val=post[i]-predicted;
  113466. /* at this point the 'deviation' value is in the range +/- max
  113467. range, but the real, unique range can always be mapped to
  113468. only [0-maxrange). So we want to wrap the deviation into
  113469. this limited range, but do it in the way that least screws
  113470. an essentially gaussian probability distribution. */
  113471. if(val<0)
  113472. if(val<-headroom)
  113473. val=headroom-val-1;
  113474. else
  113475. val=-1-(val<<1);
  113476. else
  113477. if(val>=headroom)
  113478. val= val+headroom;
  113479. else
  113480. val<<=1;
  113481. out[i]=val;
  113482. post[ln]&=0x7fff;
  113483. post[hn]&=0x7fff;
  113484. }
  113485. }
  113486. /* we have everything we need. pack it out */
  113487. /* mark nontrivial floor */
  113488. oggpack_write(opb,1,1);
  113489. /* beginning/end post */
  113490. look->frames++;
  113491. look->postbits+=ilog(look->quant_q-1)*2;
  113492. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113493. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113494. /* partition by partition */
  113495. for(i=0,j=2;i<info->partitions;i++){
  113496. int classx=info->partitionclass[i];
  113497. int cdim=info->class_dim[classx];
  113498. int csubbits=info->class_subs[classx];
  113499. int csub=1<<csubbits;
  113500. int bookas[8]={0,0,0,0,0,0,0,0};
  113501. int cval=0;
  113502. int cshift=0;
  113503. int k,l;
  113504. /* generate the partition's first stage cascade value */
  113505. if(csubbits){
  113506. int maxval[8];
  113507. for(k=0;k<csub;k++){
  113508. int booknum=info->class_subbook[classx][k];
  113509. if(booknum<0){
  113510. maxval[k]=1;
  113511. }else{
  113512. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113513. }
  113514. }
  113515. for(k=0;k<cdim;k++){
  113516. for(l=0;l<csub;l++){
  113517. int val=out[j+k];
  113518. if(val<maxval[l]){
  113519. bookas[k]=l;
  113520. break;
  113521. }
  113522. }
  113523. cval|= bookas[k]<<cshift;
  113524. cshift+=csubbits;
  113525. }
  113526. /* write it */
  113527. look->phrasebits+=
  113528. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113529. #ifdef TRAIN_FLOOR1
  113530. {
  113531. FILE *of;
  113532. char buffer[80];
  113533. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113534. vb->pcmend/2,posts-2,class);
  113535. of=fopen(buffer,"a");
  113536. fprintf(of,"%d\n",cval);
  113537. fclose(of);
  113538. }
  113539. #endif
  113540. }
  113541. /* write post values */
  113542. for(k=0;k<cdim;k++){
  113543. int book=info->class_subbook[classx][bookas[k]];
  113544. if(book>=0){
  113545. /* hack to allow training with 'bad' books */
  113546. if(out[j+k]<(books+book)->entries)
  113547. look->postbits+=vorbis_book_encode(books+book,
  113548. out[j+k],opb);
  113549. /*else
  113550. fprintf(stderr,"+!");*/
  113551. #ifdef TRAIN_FLOOR1
  113552. {
  113553. FILE *of;
  113554. char buffer[80];
  113555. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113556. vb->pcmend/2,posts-2,class,bookas[k]);
  113557. of=fopen(buffer,"a");
  113558. fprintf(of,"%d\n",out[j+k]);
  113559. fclose(of);
  113560. }
  113561. #endif
  113562. }
  113563. }
  113564. j+=cdim;
  113565. }
  113566. {
  113567. /* generate quantized floor equivalent to what we'd unpack in decode */
  113568. /* render the lines */
  113569. int hx=0;
  113570. int lx=0;
  113571. int ly=post[0]*info->mult;
  113572. for(j=1;j<look->posts;j++){
  113573. int current=look->forward_index[j];
  113574. int hy=post[current]&0x7fff;
  113575. if(hy==post[current]){
  113576. hy*=info->mult;
  113577. hx=info->postlist[current];
  113578. render_line0(lx,hx,ly,hy,ilogmask);
  113579. lx=hx;
  113580. ly=hy;
  113581. }
  113582. }
  113583. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113584. seq++;
  113585. return(1);
  113586. }
  113587. }else{
  113588. oggpack_write(opb,0,1);
  113589. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113590. seq++;
  113591. return(0);
  113592. }
  113593. }
  113594. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113595. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113596. vorbis_info_floor1 *info=look->vi;
  113597. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113598. int i,j,k;
  113599. codebook *books=ci->fullbooks;
  113600. /* unpack wrapped/predicted values from stream */
  113601. if(oggpack_read(&vb->opb,1)==1){
  113602. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113603. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113604. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113605. /* partition by partition */
  113606. for(i=0,j=2;i<info->partitions;i++){
  113607. int classx=info->partitionclass[i];
  113608. int cdim=info->class_dim[classx];
  113609. int csubbits=info->class_subs[classx];
  113610. int csub=1<<csubbits;
  113611. int cval=0;
  113612. /* decode the partition's first stage cascade value */
  113613. if(csubbits){
  113614. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113615. if(cval==-1)goto eop;
  113616. }
  113617. for(k=0;k<cdim;k++){
  113618. int book=info->class_subbook[classx][cval&(csub-1)];
  113619. cval>>=csubbits;
  113620. if(book>=0){
  113621. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113622. goto eop;
  113623. }else{
  113624. fit_value[j+k]=0;
  113625. }
  113626. }
  113627. j+=cdim;
  113628. }
  113629. /* unwrap positive values and reconsitute via linear interpolation */
  113630. for(i=2;i<look->posts;i++){
  113631. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113632. info->postlist[look->hineighbor[i-2]],
  113633. fit_value[look->loneighbor[i-2]],
  113634. fit_value[look->hineighbor[i-2]],
  113635. info->postlist[i]);
  113636. int hiroom=look->quant_q-predicted;
  113637. int loroom=predicted;
  113638. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113639. int val=fit_value[i];
  113640. if(val){
  113641. if(val>=room){
  113642. if(hiroom>loroom){
  113643. val = val-loroom;
  113644. }else{
  113645. val = -1-(val-hiroom);
  113646. }
  113647. }else{
  113648. if(val&1){
  113649. val= -((val+1)>>1);
  113650. }else{
  113651. val>>=1;
  113652. }
  113653. }
  113654. fit_value[i]=val+predicted;
  113655. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113656. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113657. }else{
  113658. fit_value[i]=predicted|0x8000;
  113659. }
  113660. }
  113661. return(fit_value);
  113662. }
  113663. eop:
  113664. return(NULL);
  113665. }
  113666. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113667. float *out){
  113668. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113669. vorbis_info_floor1 *info=look->vi;
  113670. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113671. int n=ci->blocksizes[vb->W]/2;
  113672. int j;
  113673. if(memo){
  113674. /* render the lines */
  113675. int *fit_value=(int *)memo;
  113676. int hx=0;
  113677. int lx=0;
  113678. int ly=fit_value[0]*info->mult;
  113679. for(j=1;j<look->posts;j++){
  113680. int current=look->forward_index[j];
  113681. int hy=fit_value[current]&0x7fff;
  113682. if(hy==fit_value[current]){
  113683. hy*=info->mult;
  113684. hx=info->postlist[current];
  113685. render_line(lx,hx,ly,hy,out);
  113686. lx=hx;
  113687. ly=hy;
  113688. }
  113689. }
  113690. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113691. return(1);
  113692. }
  113693. memset(out,0,sizeof(*out)*n);
  113694. return(0);
  113695. }
  113696. /* export hooks */
  113697. vorbis_func_floor floor1_exportbundle={
  113698. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113699. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113700. };
  113701. #endif
  113702. /*** End of inlined file: floor1.c ***/
  113703. /*** Start of inlined file: info.c ***/
  113704. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113705. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113706. // tasks..
  113707. #if JUCE_MSVC
  113708. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113709. #endif
  113710. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113711. #if JUCE_USE_OGGVORBIS
  113712. /* general handling of the header and the vorbis_info structure (and
  113713. substructures) */
  113714. #include <stdlib.h>
  113715. #include <string.h>
  113716. #include <ctype.h>
  113717. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113718. while(bytes--){
  113719. oggpack_write(o,*s++,8);
  113720. }
  113721. }
  113722. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113723. while(bytes--){
  113724. *buf++=oggpack_read(o,8);
  113725. }
  113726. }
  113727. void vorbis_comment_init(vorbis_comment *vc){
  113728. memset(vc,0,sizeof(*vc));
  113729. }
  113730. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113731. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113732. (vc->comments+2)*sizeof(*vc->user_comments));
  113733. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113734. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113735. vc->comment_lengths[vc->comments]=strlen(comment);
  113736. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113737. strcpy(vc->user_comments[vc->comments], comment);
  113738. vc->comments++;
  113739. vc->user_comments[vc->comments]=NULL;
  113740. }
  113741. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113742. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113743. strcpy(comment, tag);
  113744. strcat(comment, "=");
  113745. strcat(comment, contents);
  113746. vorbis_comment_add(vc, comment);
  113747. }
  113748. /* This is more or less the same as strncasecmp - but that doesn't exist
  113749. * everywhere, and this is a fairly trivial function, so we include it */
  113750. static int tagcompare(const char *s1, const char *s2, int n){
  113751. int c=0;
  113752. while(c < n){
  113753. if(toupper(s1[c]) != toupper(s2[c]))
  113754. return !0;
  113755. c++;
  113756. }
  113757. return 0;
  113758. }
  113759. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113760. long i;
  113761. int found = 0;
  113762. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113763. char *fulltag = (char*)alloca(taglen+ 1);
  113764. strcpy(fulltag, tag);
  113765. strcat(fulltag, "=");
  113766. for(i=0;i<vc->comments;i++){
  113767. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113768. if(count == found)
  113769. /* We return a pointer to the data, not a copy */
  113770. return vc->user_comments[i] + taglen;
  113771. else
  113772. found++;
  113773. }
  113774. }
  113775. return NULL; /* didn't find anything */
  113776. }
  113777. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113778. int i,count=0;
  113779. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113780. char *fulltag = (char*)alloca(taglen+1);
  113781. strcpy(fulltag,tag);
  113782. strcat(fulltag, "=");
  113783. for(i=0;i<vc->comments;i++){
  113784. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113785. count++;
  113786. }
  113787. return count;
  113788. }
  113789. void vorbis_comment_clear(vorbis_comment *vc){
  113790. if(vc){
  113791. long i;
  113792. for(i=0;i<vc->comments;i++)
  113793. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113794. if(vc->user_comments)_ogg_free(vc->user_comments);
  113795. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113796. if(vc->vendor)_ogg_free(vc->vendor);
  113797. }
  113798. memset(vc,0,sizeof(*vc));
  113799. }
  113800. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113801. They may be equal, but short will never ge greater than long */
  113802. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113803. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113804. return ci ? ci->blocksizes[zo] : -1;
  113805. }
  113806. /* used by synthesis, which has a full, alloced vi */
  113807. void vorbis_info_init(vorbis_info *vi){
  113808. memset(vi,0,sizeof(*vi));
  113809. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113810. }
  113811. void vorbis_info_clear(vorbis_info *vi){
  113812. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113813. int i;
  113814. if(ci){
  113815. for(i=0;i<ci->modes;i++)
  113816. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113817. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113818. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113819. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113820. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113821. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113822. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113823. for(i=0;i<ci->books;i++){
  113824. if(ci->book_param[i]){
  113825. /* knows if the book was not alloced */
  113826. vorbis_staticbook_destroy(ci->book_param[i]);
  113827. }
  113828. if(ci->fullbooks)
  113829. vorbis_book_clear(ci->fullbooks+i);
  113830. }
  113831. if(ci->fullbooks)
  113832. _ogg_free(ci->fullbooks);
  113833. for(i=0;i<ci->psys;i++)
  113834. _vi_psy_free(ci->psy_param[i]);
  113835. _ogg_free(ci);
  113836. }
  113837. memset(vi,0,sizeof(*vi));
  113838. }
  113839. /* Header packing/unpacking ********************************************/
  113840. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113841. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113842. if(!ci)return(OV_EFAULT);
  113843. vi->version=oggpack_read(opb,32);
  113844. if(vi->version!=0)return(OV_EVERSION);
  113845. vi->channels=oggpack_read(opb,8);
  113846. vi->rate=oggpack_read(opb,32);
  113847. vi->bitrate_upper=oggpack_read(opb,32);
  113848. vi->bitrate_nominal=oggpack_read(opb,32);
  113849. vi->bitrate_lower=oggpack_read(opb,32);
  113850. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113851. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113852. if(vi->rate<1)goto err_out;
  113853. if(vi->channels<1)goto err_out;
  113854. if(ci->blocksizes[0]<8)goto err_out;
  113855. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113856. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113857. return(0);
  113858. err_out:
  113859. vorbis_info_clear(vi);
  113860. return(OV_EBADHEADER);
  113861. }
  113862. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113863. int i;
  113864. int vendorlen=oggpack_read(opb,32);
  113865. if(vendorlen<0)goto err_out;
  113866. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113867. _v_readstring(opb,vc->vendor,vendorlen);
  113868. vc->comments=oggpack_read(opb,32);
  113869. if(vc->comments<0)goto err_out;
  113870. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113871. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113872. for(i=0;i<vc->comments;i++){
  113873. int len=oggpack_read(opb,32);
  113874. if(len<0)goto err_out;
  113875. vc->comment_lengths[i]=len;
  113876. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113877. _v_readstring(opb,vc->user_comments[i],len);
  113878. }
  113879. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113880. return(0);
  113881. err_out:
  113882. vorbis_comment_clear(vc);
  113883. return(OV_EBADHEADER);
  113884. }
  113885. /* all of the real encoding details are here. The modes, books,
  113886. everything */
  113887. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113888. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113889. int i;
  113890. if(!ci)return(OV_EFAULT);
  113891. /* codebooks */
  113892. ci->books=oggpack_read(opb,8)+1;
  113893. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113894. for(i=0;i<ci->books;i++){
  113895. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113896. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113897. }
  113898. /* time backend settings; hooks are unused */
  113899. {
  113900. int times=oggpack_read(opb,6)+1;
  113901. for(i=0;i<times;i++){
  113902. int test=oggpack_read(opb,16);
  113903. if(test<0 || test>=VI_TIMEB)goto err_out;
  113904. }
  113905. }
  113906. /* floor backend settings */
  113907. ci->floors=oggpack_read(opb,6)+1;
  113908. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113909. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113910. for(i=0;i<ci->floors;i++){
  113911. ci->floor_type[i]=oggpack_read(opb,16);
  113912. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113913. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113914. if(!ci->floor_param[i])goto err_out;
  113915. }
  113916. /* residue backend settings */
  113917. ci->residues=oggpack_read(opb,6)+1;
  113918. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113919. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113920. for(i=0;i<ci->residues;i++){
  113921. ci->residue_type[i]=oggpack_read(opb,16);
  113922. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113923. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113924. if(!ci->residue_param[i])goto err_out;
  113925. }
  113926. /* map backend settings */
  113927. ci->maps=oggpack_read(opb,6)+1;
  113928. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113929. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113930. for(i=0;i<ci->maps;i++){
  113931. ci->map_type[i]=oggpack_read(opb,16);
  113932. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113933. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113934. if(!ci->map_param[i])goto err_out;
  113935. }
  113936. /* mode settings */
  113937. ci->modes=oggpack_read(opb,6)+1;
  113938. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113939. for(i=0;i<ci->modes;i++){
  113940. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113941. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113942. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113943. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113944. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113945. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113946. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113947. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113948. }
  113949. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113950. return(0);
  113951. err_out:
  113952. vorbis_info_clear(vi);
  113953. return(OV_EBADHEADER);
  113954. }
  113955. /* The Vorbis header is in three packets; the initial small packet in
  113956. the first page that identifies basic parameters, a second packet
  113957. with bitstream comments and a third packet that holds the
  113958. codebook. */
  113959. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113960. oggpack_buffer opb;
  113961. if(op){
  113962. oggpack_readinit(&opb,op->packet,op->bytes);
  113963. /* Which of the three types of header is this? */
  113964. /* Also verify header-ness, vorbis */
  113965. {
  113966. char buffer[6];
  113967. int packtype=oggpack_read(&opb,8);
  113968. memset(buffer,0,6);
  113969. _v_readstring(&opb,buffer,6);
  113970. if(memcmp(buffer,"vorbis",6)){
  113971. /* not a vorbis header */
  113972. return(OV_ENOTVORBIS);
  113973. }
  113974. switch(packtype){
  113975. case 0x01: /* least significant *bit* is read first */
  113976. if(!op->b_o_s){
  113977. /* Not the initial packet */
  113978. return(OV_EBADHEADER);
  113979. }
  113980. if(vi->rate!=0){
  113981. /* previously initialized info header */
  113982. return(OV_EBADHEADER);
  113983. }
  113984. return(_vorbis_unpack_info(vi,&opb));
  113985. case 0x03: /* least significant *bit* is read first */
  113986. if(vi->rate==0){
  113987. /* um... we didn't get the initial header */
  113988. return(OV_EBADHEADER);
  113989. }
  113990. return(_vorbis_unpack_comment(vc,&opb));
  113991. case 0x05: /* least significant *bit* is read first */
  113992. if(vi->rate==0 || vc->vendor==NULL){
  113993. /* um... we didn;t get the initial header or comments yet */
  113994. return(OV_EBADHEADER);
  113995. }
  113996. return(_vorbis_unpack_books(vi,&opb));
  113997. default:
  113998. /* Not a valid vorbis header type */
  113999. return(OV_EBADHEADER);
  114000. break;
  114001. }
  114002. }
  114003. }
  114004. return(OV_EBADHEADER);
  114005. }
  114006. /* pack side **********************************************************/
  114007. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  114008. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114009. if(!ci)return(OV_EFAULT);
  114010. /* preamble */
  114011. oggpack_write(opb,0x01,8);
  114012. _v_writestring(opb,"vorbis", 6);
  114013. /* basic information about the stream */
  114014. oggpack_write(opb,0x00,32);
  114015. oggpack_write(opb,vi->channels,8);
  114016. oggpack_write(opb,vi->rate,32);
  114017. oggpack_write(opb,vi->bitrate_upper,32);
  114018. oggpack_write(opb,vi->bitrate_nominal,32);
  114019. oggpack_write(opb,vi->bitrate_lower,32);
  114020. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  114021. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  114022. oggpack_write(opb,1,1);
  114023. return(0);
  114024. }
  114025. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  114026. char temp[]="Xiph.Org libVorbis I 20050304";
  114027. int bytes = strlen(temp);
  114028. /* preamble */
  114029. oggpack_write(opb,0x03,8);
  114030. _v_writestring(opb,"vorbis", 6);
  114031. /* vendor */
  114032. oggpack_write(opb,bytes,32);
  114033. _v_writestring(opb,temp, bytes);
  114034. /* comments */
  114035. oggpack_write(opb,vc->comments,32);
  114036. if(vc->comments){
  114037. int i;
  114038. for(i=0;i<vc->comments;i++){
  114039. if(vc->user_comments[i]){
  114040. oggpack_write(opb,vc->comment_lengths[i],32);
  114041. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  114042. }else{
  114043. oggpack_write(opb,0,32);
  114044. }
  114045. }
  114046. }
  114047. oggpack_write(opb,1,1);
  114048. return(0);
  114049. }
  114050. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  114051. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114052. int i;
  114053. if(!ci)return(OV_EFAULT);
  114054. oggpack_write(opb,0x05,8);
  114055. _v_writestring(opb,"vorbis", 6);
  114056. /* books */
  114057. oggpack_write(opb,ci->books-1,8);
  114058. for(i=0;i<ci->books;i++)
  114059. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  114060. /* times; hook placeholders */
  114061. oggpack_write(opb,0,6);
  114062. oggpack_write(opb,0,16);
  114063. /* floors */
  114064. oggpack_write(opb,ci->floors-1,6);
  114065. for(i=0;i<ci->floors;i++){
  114066. oggpack_write(opb,ci->floor_type[i],16);
  114067. if(_floor_P[ci->floor_type[i]]->pack)
  114068. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  114069. else
  114070. goto err_out;
  114071. }
  114072. /* residues */
  114073. oggpack_write(opb,ci->residues-1,6);
  114074. for(i=0;i<ci->residues;i++){
  114075. oggpack_write(opb,ci->residue_type[i],16);
  114076. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114077. }
  114078. /* maps */
  114079. oggpack_write(opb,ci->maps-1,6);
  114080. for(i=0;i<ci->maps;i++){
  114081. oggpack_write(opb,ci->map_type[i],16);
  114082. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114083. }
  114084. /* modes */
  114085. oggpack_write(opb,ci->modes-1,6);
  114086. for(i=0;i<ci->modes;i++){
  114087. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114088. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114089. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114090. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114091. }
  114092. oggpack_write(opb,1,1);
  114093. return(0);
  114094. err_out:
  114095. return(-1);
  114096. }
  114097. int vorbis_commentheader_out(vorbis_comment *vc,
  114098. ogg_packet *op){
  114099. oggpack_buffer opb;
  114100. oggpack_writeinit(&opb);
  114101. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114102. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114103. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114104. op->bytes=oggpack_bytes(&opb);
  114105. op->b_o_s=0;
  114106. op->e_o_s=0;
  114107. op->granulepos=0;
  114108. op->packetno=1;
  114109. return 0;
  114110. }
  114111. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114112. vorbis_comment *vc,
  114113. ogg_packet *op,
  114114. ogg_packet *op_comm,
  114115. ogg_packet *op_code){
  114116. int ret=OV_EIMPL;
  114117. vorbis_info *vi=v->vi;
  114118. oggpack_buffer opb;
  114119. private_state *b=(private_state*)v->backend_state;
  114120. if(!b){
  114121. ret=OV_EFAULT;
  114122. goto err_out;
  114123. }
  114124. /* first header packet **********************************************/
  114125. oggpack_writeinit(&opb);
  114126. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114127. /* build the packet */
  114128. if(b->header)_ogg_free(b->header);
  114129. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114130. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114131. op->packet=b->header;
  114132. op->bytes=oggpack_bytes(&opb);
  114133. op->b_o_s=1;
  114134. op->e_o_s=0;
  114135. op->granulepos=0;
  114136. op->packetno=0;
  114137. /* second header packet (comments) **********************************/
  114138. oggpack_reset(&opb);
  114139. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114140. if(b->header1)_ogg_free(b->header1);
  114141. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114142. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114143. op_comm->packet=b->header1;
  114144. op_comm->bytes=oggpack_bytes(&opb);
  114145. op_comm->b_o_s=0;
  114146. op_comm->e_o_s=0;
  114147. op_comm->granulepos=0;
  114148. op_comm->packetno=1;
  114149. /* third header packet (modes/codebooks) ****************************/
  114150. oggpack_reset(&opb);
  114151. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114152. if(b->header2)_ogg_free(b->header2);
  114153. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114154. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114155. op_code->packet=b->header2;
  114156. op_code->bytes=oggpack_bytes(&opb);
  114157. op_code->b_o_s=0;
  114158. op_code->e_o_s=0;
  114159. op_code->granulepos=0;
  114160. op_code->packetno=2;
  114161. oggpack_writeclear(&opb);
  114162. return(0);
  114163. err_out:
  114164. oggpack_writeclear(&opb);
  114165. memset(op,0,sizeof(*op));
  114166. memset(op_comm,0,sizeof(*op_comm));
  114167. memset(op_code,0,sizeof(*op_code));
  114168. if(b->header)_ogg_free(b->header);
  114169. if(b->header1)_ogg_free(b->header1);
  114170. if(b->header2)_ogg_free(b->header2);
  114171. b->header=NULL;
  114172. b->header1=NULL;
  114173. b->header2=NULL;
  114174. return(ret);
  114175. }
  114176. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114177. if(granulepos>=0)
  114178. return((double)granulepos/v->vi->rate);
  114179. return(-1);
  114180. }
  114181. #endif
  114182. /*** End of inlined file: info.c ***/
  114183. /*** Start of inlined file: lpc.c ***/
  114184. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114185. are derived from code written by Jutta Degener and Carsten Bormann;
  114186. thus we include their copyright below. The entirety of this file
  114187. is freely redistributable on the condition that both of these
  114188. copyright notices are preserved without modification. */
  114189. /* Preserved Copyright: *********************************************/
  114190. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114191. Technische Universita"t Berlin
  114192. Any use of this software is permitted provided that this notice is not
  114193. removed and that neither the authors nor the Technische Universita"t
  114194. Berlin are deemed to have made any representations as to the
  114195. suitability of this software for any purpose nor are held responsible
  114196. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114197. THIS SOFTWARE.
  114198. As a matter of courtesy, the authors request to be informed about uses
  114199. this software has found, about bugs in this software, and about any
  114200. improvements that may be of general interest.
  114201. Berlin, 28.11.1994
  114202. Jutta Degener
  114203. Carsten Bormann
  114204. *********************************************************************/
  114205. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114206. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114207. // tasks..
  114208. #if JUCE_MSVC
  114209. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114210. #endif
  114211. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114212. #if JUCE_USE_OGGVORBIS
  114213. #include <stdlib.h>
  114214. #include <string.h>
  114215. #include <math.h>
  114216. /* Autocorrelation LPC coeff generation algorithm invented by
  114217. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114218. /* Input : n elements of time doamin data
  114219. Output: m lpc coefficients, excitation energy */
  114220. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114221. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114222. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114223. double error;
  114224. int i,j;
  114225. /* autocorrelation, p+1 lag coefficients */
  114226. j=m+1;
  114227. while(j--){
  114228. double d=0; /* double needed for accumulator depth */
  114229. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114230. aut[j]=d;
  114231. }
  114232. /* Generate lpc coefficients from autocorr values */
  114233. error=aut[0];
  114234. for(i=0;i<m;i++){
  114235. double r= -aut[i+1];
  114236. if(error==0){
  114237. memset(lpci,0,m*sizeof(*lpci));
  114238. return 0;
  114239. }
  114240. /* Sum up this iteration's reflection coefficient; note that in
  114241. Vorbis we don't save it. If anyone wants to recycle this code
  114242. and needs reflection coefficients, save the results of 'r' from
  114243. each iteration. */
  114244. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114245. r/=error;
  114246. /* Update LPC coefficients and total error */
  114247. lpc[i]=r;
  114248. for(j=0;j<i/2;j++){
  114249. double tmp=lpc[j];
  114250. lpc[j]+=r*lpc[i-1-j];
  114251. lpc[i-1-j]+=r*tmp;
  114252. }
  114253. if(i%2)lpc[j]+=lpc[j]*r;
  114254. error*=1.f-r*r;
  114255. }
  114256. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114257. /* we need the error value to know how big an impulse to hit the
  114258. filter with later */
  114259. return error;
  114260. }
  114261. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114262. float *data,long n){
  114263. /* in: coeff[0...m-1] LPC coefficients
  114264. prime[0...m-1] initial values (allocated size of n+m-1)
  114265. out: data[0...n-1] data samples */
  114266. long i,j,o,p;
  114267. float y;
  114268. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114269. if(!prime)
  114270. for(i=0;i<m;i++)
  114271. work[i]=0.f;
  114272. else
  114273. for(i=0;i<m;i++)
  114274. work[i]=prime[i];
  114275. for(i=0;i<n;i++){
  114276. y=0;
  114277. o=i;
  114278. p=m;
  114279. for(j=0;j<m;j++)
  114280. y-=work[o++]*coeff[--p];
  114281. data[i]=work[o]=y;
  114282. }
  114283. }
  114284. #endif
  114285. /*** End of inlined file: lpc.c ***/
  114286. /*** Start of inlined file: lsp.c ***/
  114287. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114288. an iterative root polisher (CACM algorithm 283). It *is* possible
  114289. to confuse this algorithm into not converging; that should only
  114290. happen with absurdly closely spaced roots (very sharp peaks in the
  114291. LPC f response) which in turn should be impossible in our use of
  114292. the code. If this *does* happen anyway, it's a bug in the floor
  114293. finder; find the cause of the confusion (probably a single bin
  114294. spike or accidental near-float-limit resolution problems) and
  114295. correct it. */
  114296. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114297. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114298. // tasks..
  114299. #if JUCE_MSVC
  114300. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114301. #endif
  114302. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114303. #if JUCE_USE_OGGVORBIS
  114304. #include <math.h>
  114305. #include <string.h>
  114306. #include <stdlib.h>
  114307. /*** Start of inlined file: lookup.h ***/
  114308. #ifndef _V_LOOKUP_H_
  114309. #ifdef FLOAT_LOOKUP
  114310. extern float vorbis_coslook(float a);
  114311. extern float vorbis_invsqlook(float a);
  114312. extern float vorbis_invsq2explook(int a);
  114313. extern float vorbis_fromdBlook(float a);
  114314. #endif
  114315. #ifdef INT_LOOKUP
  114316. extern long vorbis_invsqlook_i(long a,long e);
  114317. extern long vorbis_coslook_i(long a);
  114318. extern float vorbis_fromdBlook_i(long a);
  114319. #endif
  114320. #endif
  114321. /*** End of inlined file: lookup.h ***/
  114322. /* three possible LSP to f curve functions; the exact computation
  114323. (float), a lookup based float implementation, and an integer
  114324. implementation. The float lookup is likely the optimal choice on
  114325. any machine with an FPU. The integer implementation is *not* fixed
  114326. point (due to the need for a large dynamic range and thus a
  114327. seperately tracked exponent) and thus much more complex than the
  114328. relatively simple float implementations. It's mostly for future
  114329. work on a fully fixed point implementation for processors like the
  114330. ARM family. */
  114331. /* undefine both for the 'old' but more precise implementation */
  114332. #define FLOAT_LOOKUP
  114333. #undef INT_LOOKUP
  114334. #ifdef FLOAT_LOOKUP
  114335. /*** Start of inlined file: lookup.c ***/
  114336. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114337. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114338. // tasks..
  114339. #if JUCE_MSVC
  114340. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114341. #endif
  114342. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114343. #if JUCE_USE_OGGVORBIS
  114344. #include <math.h>
  114345. /*** Start of inlined file: lookup.h ***/
  114346. #ifndef _V_LOOKUP_H_
  114347. #ifdef FLOAT_LOOKUP
  114348. extern float vorbis_coslook(float a);
  114349. extern float vorbis_invsqlook(float a);
  114350. extern float vorbis_invsq2explook(int a);
  114351. extern float vorbis_fromdBlook(float a);
  114352. #endif
  114353. #ifdef INT_LOOKUP
  114354. extern long vorbis_invsqlook_i(long a,long e);
  114355. extern long vorbis_coslook_i(long a);
  114356. extern float vorbis_fromdBlook_i(long a);
  114357. #endif
  114358. #endif
  114359. /*** End of inlined file: lookup.h ***/
  114360. /*** Start of inlined file: lookup_data.h ***/
  114361. #ifndef _V_LOOKUP_DATA_H_
  114362. #ifdef FLOAT_LOOKUP
  114363. #define COS_LOOKUP_SZ 128
  114364. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114365. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114366. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114367. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114368. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114369. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114370. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114371. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114372. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114373. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114374. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114375. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114376. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114377. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114378. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114379. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114380. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114381. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114382. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114383. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114384. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114385. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114386. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114387. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114388. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114389. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114390. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114391. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114392. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114393. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114394. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114395. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114396. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114397. -1.0000000000000f,
  114398. };
  114399. #define INVSQ_LOOKUP_SZ 32
  114400. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114401. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114402. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114403. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114404. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114405. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114406. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114407. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114408. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114409. 1.000000000000f,
  114410. };
  114411. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114412. #define INVSQ2EXP_LOOKUP_MAX 32
  114413. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114414. INVSQ2EXP_LOOKUP_MIN+1]={
  114415. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114416. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114417. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114418. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114419. 256.f, 181.019336f, 128.f, 90.50966799f,
  114420. 64.f, 45.254834f, 32.f, 22.627417f,
  114421. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114422. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114423. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114424. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114425. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114426. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114427. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114428. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114429. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114430. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114431. 1.525878906e-05f,
  114432. };
  114433. #endif
  114434. #define FROMdB_LOOKUP_SZ 35
  114435. #define FROMdB2_LOOKUP_SZ 32
  114436. #define FROMdB_SHIFT 5
  114437. #define FROMdB2_SHIFT 3
  114438. #define FROMdB2_MASK 31
  114439. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114440. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114441. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114442. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114443. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114444. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114445. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114446. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114447. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114448. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114449. };
  114450. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114451. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114452. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114453. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114454. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114455. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114456. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114457. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114458. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114459. };
  114460. #ifdef INT_LOOKUP
  114461. #define INVSQ_LOOKUP_I_SHIFT 10
  114462. #define INVSQ_LOOKUP_I_MASK 1023
  114463. static long INVSQ_LOOKUP_I[64+1]={
  114464. 92682l, 91966l, 91267l, 90583l,
  114465. 89915l, 89261l, 88621l, 87995l,
  114466. 87381l, 86781l, 86192l, 85616l,
  114467. 85051l, 84497l, 83953l, 83420l,
  114468. 82897l, 82384l, 81880l, 81385l,
  114469. 80899l, 80422l, 79953l, 79492l,
  114470. 79039l, 78594l, 78156l, 77726l,
  114471. 77302l, 76885l, 76475l, 76072l,
  114472. 75674l, 75283l, 74898l, 74519l,
  114473. 74146l, 73778l, 73415l, 73058l,
  114474. 72706l, 72359l, 72016l, 71679l,
  114475. 71347l, 71019l, 70695l, 70376l,
  114476. 70061l, 69750l, 69444l, 69141l,
  114477. 68842l, 68548l, 68256l, 67969l,
  114478. 67685l, 67405l, 67128l, 66855l,
  114479. 66585l, 66318l, 66054l, 65794l,
  114480. 65536l,
  114481. };
  114482. #define COS_LOOKUP_I_SHIFT 9
  114483. #define COS_LOOKUP_I_MASK 511
  114484. #define COS_LOOKUP_I_SZ 128
  114485. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114486. 16384l, 16379l, 16364l, 16340l,
  114487. 16305l, 16261l, 16207l, 16143l,
  114488. 16069l, 15986l, 15893l, 15791l,
  114489. 15679l, 15557l, 15426l, 15286l,
  114490. 15137l, 14978l, 14811l, 14635l,
  114491. 14449l, 14256l, 14053l, 13842l,
  114492. 13623l, 13395l, 13160l, 12916l,
  114493. 12665l, 12406l, 12140l, 11866l,
  114494. 11585l, 11297l, 11003l, 10702l,
  114495. 10394l, 10080l, 9760l, 9434l,
  114496. 9102l, 8765l, 8423l, 8076l,
  114497. 7723l, 7366l, 7005l, 6639l,
  114498. 6270l, 5897l, 5520l, 5139l,
  114499. 4756l, 4370l, 3981l, 3590l,
  114500. 3196l, 2801l, 2404l, 2006l,
  114501. 1606l, 1205l, 804l, 402l,
  114502. 0l, -401l, -803l, -1204l,
  114503. -1605l, -2005l, -2403l, -2800l,
  114504. -3195l, -3589l, -3980l, -4369l,
  114505. -4755l, -5138l, -5519l, -5896l,
  114506. -6269l, -6638l, -7004l, -7365l,
  114507. -7722l, -8075l, -8422l, -8764l,
  114508. -9101l, -9433l, -9759l, -10079l,
  114509. -10393l, -10701l, -11002l, -11296l,
  114510. -11584l, -11865l, -12139l, -12405l,
  114511. -12664l, -12915l, -13159l, -13394l,
  114512. -13622l, -13841l, -14052l, -14255l,
  114513. -14448l, -14634l, -14810l, -14977l,
  114514. -15136l, -15285l, -15425l, -15556l,
  114515. -15678l, -15790l, -15892l, -15985l,
  114516. -16068l, -16142l, -16206l, -16260l,
  114517. -16304l, -16339l, -16363l, -16378l,
  114518. -16383l,
  114519. };
  114520. #endif
  114521. #endif
  114522. /*** End of inlined file: lookup_data.h ***/
  114523. #ifdef FLOAT_LOOKUP
  114524. /* interpolated lookup based cos function, domain 0 to PI only */
  114525. float vorbis_coslook(float a){
  114526. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114527. int i=vorbis_ftoi(d-.5);
  114528. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114529. }
  114530. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114531. float vorbis_invsqlook(float a){
  114532. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114533. int i=vorbis_ftoi(d-.5f);
  114534. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114535. }
  114536. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114537. float vorbis_invsq2explook(int a){
  114538. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114539. }
  114540. #include <stdio.h>
  114541. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114542. float vorbis_fromdBlook(float a){
  114543. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114544. return (i<0)?1.f:
  114545. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114546. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114547. }
  114548. #endif
  114549. #ifdef INT_LOOKUP
  114550. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114551. 16.16 format
  114552. returns in m.8 format */
  114553. long vorbis_invsqlook_i(long a,long e){
  114554. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114555. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114556. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114557. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114558. d)>>16); /* result 1.16 */
  114559. e+=32;
  114560. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114561. e=(e>>1)-8;
  114562. return(val>>e);
  114563. }
  114564. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114565. /* a is in n.12 format */
  114566. float vorbis_fromdBlook_i(long a){
  114567. int i=(-a)>>(12-FROMdB2_SHIFT);
  114568. return (i<0)?1.f:
  114569. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114570. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114571. }
  114572. /* interpolated lookup based cos function, domain 0 to PI only */
  114573. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114574. long vorbis_coslook_i(long a){
  114575. int i=a>>COS_LOOKUP_I_SHIFT;
  114576. int d=a&COS_LOOKUP_I_MASK;
  114577. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114578. COS_LOOKUP_I_SHIFT);
  114579. }
  114580. #endif
  114581. #endif
  114582. /*** End of inlined file: lookup.c ***/
  114583. /* catch this in the build system; we #include for
  114584. compilers (like gcc) that can't inline across
  114585. modules */
  114586. /* side effect: changes *lsp to cosines of lsp */
  114587. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114588. float amp,float ampoffset){
  114589. int i;
  114590. float wdel=M_PI/ln;
  114591. vorbis_fpu_control fpu;
  114592. (void) fpu; // to avoid an unused variable warning
  114593. vorbis_fpu_setround(&fpu);
  114594. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114595. i=0;
  114596. while(i<n){
  114597. int k=map[i];
  114598. int qexp;
  114599. float p=.7071067812f;
  114600. float q=.7071067812f;
  114601. float w=vorbis_coslook(wdel*k);
  114602. float *ftmp=lsp;
  114603. int c=m>>1;
  114604. do{
  114605. q*=ftmp[0]-w;
  114606. p*=ftmp[1]-w;
  114607. ftmp+=2;
  114608. }while(--c);
  114609. if(m&1){
  114610. /* odd order filter; slightly assymetric */
  114611. /* the last coefficient */
  114612. q*=ftmp[0]-w;
  114613. q*=q;
  114614. p*=p*(1.f-w*w);
  114615. }else{
  114616. /* even order filter; still symmetric */
  114617. q*=q*(1.f+w);
  114618. p*=p*(1.f-w);
  114619. }
  114620. q=frexp(p+q,&qexp);
  114621. q=vorbis_fromdBlook(amp*
  114622. vorbis_invsqlook(q)*
  114623. vorbis_invsq2explook(qexp+m)-
  114624. ampoffset);
  114625. do{
  114626. curve[i++]*=q;
  114627. }while(map[i]==k);
  114628. }
  114629. vorbis_fpu_restore(fpu);
  114630. }
  114631. #else
  114632. #ifdef INT_LOOKUP
  114633. /*** Start of inlined file: lookup.c ***/
  114634. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114635. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114636. // tasks..
  114637. #if JUCE_MSVC
  114638. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114639. #endif
  114640. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114641. #if JUCE_USE_OGGVORBIS
  114642. #include <math.h>
  114643. /*** Start of inlined file: lookup.h ***/
  114644. #ifndef _V_LOOKUP_H_
  114645. #ifdef FLOAT_LOOKUP
  114646. extern float vorbis_coslook(float a);
  114647. extern float vorbis_invsqlook(float a);
  114648. extern float vorbis_invsq2explook(int a);
  114649. extern float vorbis_fromdBlook(float a);
  114650. #endif
  114651. #ifdef INT_LOOKUP
  114652. extern long vorbis_invsqlook_i(long a,long e);
  114653. extern long vorbis_coslook_i(long a);
  114654. extern float vorbis_fromdBlook_i(long a);
  114655. #endif
  114656. #endif
  114657. /*** End of inlined file: lookup.h ***/
  114658. /*** Start of inlined file: lookup_data.h ***/
  114659. #ifndef _V_LOOKUP_DATA_H_
  114660. #ifdef FLOAT_LOOKUP
  114661. #define COS_LOOKUP_SZ 128
  114662. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114663. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114664. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114665. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114666. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114667. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114668. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114669. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114670. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114671. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114672. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114673. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114674. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114675. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114676. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114677. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114678. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114679. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114680. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114681. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114682. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114683. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114684. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114685. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114686. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114687. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114688. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114689. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114690. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114691. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114692. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114693. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114694. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114695. -1.0000000000000f,
  114696. };
  114697. #define INVSQ_LOOKUP_SZ 32
  114698. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114699. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114700. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114701. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114702. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114703. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114704. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114705. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114706. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114707. 1.000000000000f,
  114708. };
  114709. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114710. #define INVSQ2EXP_LOOKUP_MAX 32
  114711. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114712. INVSQ2EXP_LOOKUP_MIN+1]={
  114713. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114714. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114715. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114716. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114717. 256.f, 181.019336f, 128.f, 90.50966799f,
  114718. 64.f, 45.254834f, 32.f, 22.627417f,
  114719. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114720. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114721. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114722. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114723. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114724. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114725. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114726. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114727. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114728. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114729. 1.525878906e-05f,
  114730. };
  114731. #endif
  114732. #define FROMdB_LOOKUP_SZ 35
  114733. #define FROMdB2_LOOKUP_SZ 32
  114734. #define FROMdB_SHIFT 5
  114735. #define FROMdB2_SHIFT 3
  114736. #define FROMdB2_MASK 31
  114737. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114738. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114739. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114740. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114741. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114742. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114743. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114744. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114745. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114746. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114747. };
  114748. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114749. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114750. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114751. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114752. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114753. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114754. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114755. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114756. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114757. };
  114758. #ifdef INT_LOOKUP
  114759. #define INVSQ_LOOKUP_I_SHIFT 10
  114760. #define INVSQ_LOOKUP_I_MASK 1023
  114761. static long INVSQ_LOOKUP_I[64+1]={
  114762. 92682l, 91966l, 91267l, 90583l,
  114763. 89915l, 89261l, 88621l, 87995l,
  114764. 87381l, 86781l, 86192l, 85616l,
  114765. 85051l, 84497l, 83953l, 83420l,
  114766. 82897l, 82384l, 81880l, 81385l,
  114767. 80899l, 80422l, 79953l, 79492l,
  114768. 79039l, 78594l, 78156l, 77726l,
  114769. 77302l, 76885l, 76475l, 76072l,
  114770. 75674l, 75283l, 74898l, 74519l,
  114771. 74146l, 73778l, 73415l, 73058l,
  114772. 72706l, 72359l, 72016l, 71679l,
  114773. 71347l, 71019l, 70695l, 70376l,
  114774. 70061l, 69750l, 69444l, 69141l,
  114775. 68842l, 68548l, 68256l, 67969l,
  114776. 67685l, 67405l, 67128l, 66855l,
  114777. 66585l, 66318l, 66054l, 65794l,
  114778. 65536l,
  114779. };
  114780. #define COS_LOOKUP_I_SHIFT 9
  114781. #define COS_LOOKUP_I_MASK 511
  114782. #define COS_LOOKUP_I_SZ 128
  114783. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114784. 16384l, 16379l, 16364l, 16340l,
  114785. 16305l, 16261l, 16207l, 16143l,
  114786. 16069l, 15986l, 15893l, 15791l,
  114787. 15679l, 15557l, 15426l, 15286l,
  114788. 15137l, 14978l, 14811l, 14635l,
  114789. 14449l, 14256l, 14053l, 13842l,
  114790. 13623l, 13395l, 13160l, 12916l,
  114791. 12665l, 12406l, 12140l, 11866l,
  114792. 11585l, 11297l, 11003l, 10702l,
  114793. 10394l, 10080l, 9760l, 9434l,
  114794. 9102l, 8765l, 8423l, 8076l,
  114795. 7723l, 7366l, 7005l, 6639l,
  114796. 6270l, 5897l, 5520l, 5139l,
  114797. 4756l, 4370l, 3981l, 3590l,
  114798. 3196l, 2801l, 2404l, 2006l,
  114799. 1606l, 1205l, 804l, 402l,
  114800. 0l, -401l, -803l, -1204l,
  114801. -1605l, -2005l, -2403l, -2800l,
  114802. -3195l, -3589l, -3980l, -4369l,
  114803. -4755l, -5138l, -5519l, -5896l,
  114804. -6269l, -6638l, -7004l, -7365l,
  114805. -7722l, -8075l, -8422l, -8764l,
  114806. -9101l, -9433l, -9759l, -10079l,
  114807. -10393l, -10701l, -11002l, -11296l,
  114808. -11584l, -11865l, -12139l, -12405l,
  114809. -12664l, -12915l, -13159l, -13394l,
  114810. -13622l, -13841l, -14052l, -14255l,
  114811. -14448l, -14634l, -14810l, -14977l,
  114812. -15136l, -15285l, -15425l, -15556l,
  114813. -15678l, -15790l, -15892l, -15985l,
  114814. -16068l, -16142l, -16206l, -16260l,
  114815. -16304l, -16339l, -16363l, -16378l,
  114816. -16383l,
  114817. };
  114818. #endif
  114819. #endif
  114820. /*** End of inlined file: lookup_data.h ***/
  114821. #ifdef FLOAT_LOOKUP
  114822. /* interpolated lookup based cos function, domain 0 to PI only */
  114823. float vorbis_coslook(float a){
  114824. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114825. int i=vorbis_ftoi(d-.5);
  114826. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114827. }
  114828. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114829. float vorbis_invsqlook(float a){
  114830. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114831. int i=vorbis_ftoi(d-.5f);
  114832. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114833. }
  114834. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114835. float vorbis_invsq2explook(int a){
  114836. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114837. }
  114838. #include <stdio.h>
  114839. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114840. float vorbis_fromdBlook(float a){
  114841. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114842. return (i<0)?1.f:
  114843. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114844. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114845. }
  114846. #endif
  114847. #ifdef INT_LOOKUP
  114848. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114849. 16.16 format
  114850. returns in m.8 format */
  114851. long vorbis_invsqlook_i(long a,long e){
  114852. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114853. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114854. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114855. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114856. d)>>16); /* result 1.16 */
  114857. e+=32;
  114858. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114859. e=(e>>1)-8;
  114860. return(val>>e);
  114861. }
  114862. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114863. /* a is in n.12 format */
  114864. float vorbis_fromdBlook_i(long a){
  114865. int i=(-a)>>(12-FROMdB2_SHIFT);
  114866. return (i<0)?1.f:
  114867. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114868. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114869. }
  114870. /* interpolated lookup based cos function, domain 0 to PI only */
  114871. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114872. long vorbis_coslook_i(long a){
  114873. int i=a>>COS_LOOKUP_I_SHIFT;
  114874. int d=a&COS_LOOKUP_I_MASK;
  114875. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114876. COS_LOOKUP_I_SHIFT);
  114877. }
  114878. #endif
  114879. #endif
  114880. /*** End of inlined file: lookup.c ***/
  114881. /* catch this in the build system; we #include for
  114882. compilers (like gcc) that can't inline across
  114883. modules */
  114884. static int MLOOP_1[64]={
  114885. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114886. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114887. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114888. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114889. };
  114890. static int MLOOP_2[64]={
  114891. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114892. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114893. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114894. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114895. };
  114896. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114897. /* side effect: changes *lsp to cosines of lsp */
  114898. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114899. float amp,float ampoffset){
  114900. /* 0 <= m < 256 */
  114901. /* set up for using all int later */
  114902. int i;
  114903. int ampoffseti=rint(ampoffset*4096.f);
  114904. int ampi=rint(amp*16.f);
  114905. long *ilsp=alloca(m*sizeof(*ilsp));
  114906. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114907. i=0;
  114908. while(i<n){
  114909. int j,k=map[i];
  114910. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114911. unsigned long qi=46341;
  114912. int qexp=0,shift;
  114913. long wi=vorbis_coslook_i(k*65536/ln);
  114914. qi*=labs(ilsp[0]-wi);
  114915. pi*=labs(ilsp[1]-wi);
  114916. for(j=3;j<m;j+=2){
  114917. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114918. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114919. shift=MLOOP_3[(pi|qi)>>16];
  114920. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114921. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114922. qexp+=shift;
  114923. }
  114924. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114925. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114926. shift=MLOOP_3[(pi|qi)>>16];
  114927. /* pi,qi normalized collectively, both tracked using qexp */
  114928. if(m&1){
  114929. /* odd order filter; slightly assymetric */
  114930. /* the last coefficient */
  114931. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114932. pi=(pi>>shift)<<14;
  114933. qexp+=shift;
  114934. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114935. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114936. shift=MLOOP_3[(pi|qi)>>16];
  114937. pi>>=shift;
  114938. qi>>=shift;
  114939. qexp+=shift-14*((m+1)>>1);
  114940. pi=((pi*pi)>>16);
  114941. qi=((qi*qi)>>16);
  114942. qexp=qexp*2+m;
  114943. pi*=(1<<14)-((wi*wi)>>14);
  114944. qi+=pi>>14;
  114945. }else{
  114946. /* even order filter; still symmetric */
  114947. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114948. worth tracking step by step */
  114949. pi>>=shift;
  114950. qi>>=shift;
  114951. qexp+=shift-7*m;
  114952. pi=((pi*pi)>>16);
  114953. qi=((qi*qi)>>16);
  114954. qexp=qexp*2+m;
  114955. pi*=(1<<14)-wi;
  114956. qi*=(1<<14)+wi;
  114957. qi=(qi+pi)>>14;
  114958. }
  114959. /* we've let the normalization drift because it wasn't important;
  114960. however, for the lookup, things must be normalized again. We
  114961. need at most one right shift or a number of left shifts */
  114962. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114963. qi>>=1; qexp++;
  114964. }else
  114965. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114966. qi<<=1; qexp--;
  114967. }
  114968. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114969. vorbis_invsqlook_i(qi,qexp)-
  114970. /* m.8, m+n<=8 */
  114971. ampoffseti); /* 8.12[0] */
  114972. curve[i]*=amp;
  114973. while(map[++i]==k)curve[i]*=amp;
  114974. }
  114975. }
  114976. #else
  114977. /* old, nonoptimized but simple version for any poor sap who needs to
  114978. figure out what the hell this code does, or wants the other
  114979. fraction of a dB precision */
  114980. /* side effect: changes *lsp to cosines of lsp */
  114981. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114982. float amp,float ampoffset){
  114983. int i;
  114984. float wdel=M_PI/ln;
  114985. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114986. i=0;
  114987. while(i<n){
  114988. int j,k=map[i];
  114989. float p=.5f;
  114990. float q=.5f;
  114991. float w=2.f*cos(wdel*k);
  114992. for(j=1;j<m;j+=2){
  114993. q *= w-lsp[j-1];
  114994. p *= w-lsp[j];
  114995. }
  114996. if(j==m){
  114997. /* odd order filter; slightly assymetric */
  114998. /* the last coefficient */
  114999. q*=w-lsp[j-1];
  115000. p*=p*(4.f-w*w);
  115001. q*=q;
  115002. }else{
  115003. /* even order filter; still symmetric */
  115004. p*=p*(2.f-w);
  115005. q*=q*(2.f+w);
  115006. }
  115007. q=fromdB(amp/sqrt(p+q)-ampoffset);
  115008. curve[i]*=q;
  115009. while(map[++i]==k)curve[i]*=q;
  115010. }
  115011. }
  115012. #endif
  115013. #endif
  115014. static void cheby(float *g, int ord) {
  115015. int i, j;
  115016. g[0] *= .5f;
  115017. for(i=2; i<= ord; i++) {
  115018. for(j=ord; j >= i; j--) {
  115019. g[j-2] -= g[j];
  115020. g[j] += g[j];
  115021. }
  115022. }
  115023. }
  115024. static int comp(const void *a,const void *b){
  115025. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  115026. }
  115027. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  115028. but there are root sets for which it gets into limit cycles
  115029. (exacerbated by zero suppression) and fails. We can't afford to
  115030. fail, even if the failure is 1 in 100,000,000, so we now use
  115031. Laguerre and later polish with Newton-Raphson (which can then
  115032. afford to fail) */
  115033. #define EPSILON 10e-7
  115034. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  115035. int i,m;
  115036. double lastdelta=0.f;
  115037. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  115038. for(i=0;i<=ord;i++)defl[i]=a[i];
  115039. for(m=ord;m>0;m--){
  115040. double newx=0.f,delta;
  115041. /* iterate a root */
  115042. while(1){
  115043. double p=defl[m],pp=0.f,ppp=0.f,denom;
  115044. /* eval the polynomial and its first two derivatives */
  115045. for(i=m;i>0;i--){
  115046. ppp = newx*ppp + pp;
  115047. pp = newx*pp + p;
  115048. p = newx*p + defl[i-1];
  115049. }
  115050. /* Laguerre's method */
  115051. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  115052. if(denom<0)
  115053. return(-1); /* complex root! The LPC generator handed us a bad filter */
  115054. if(pp>0){
  115055. denom = pp + sqrt(denom);
  115056. if(denom<EPSILON)denom=EPSILON;
  115057. }else{
  115058. denom = pp - sqrt(denom);
  115059. if(denom>-(EPSILON))denom=-(EPSILON);
  115060. }
  115061. delta = m*p/denom;
  115062. newx -= delta;
  115063. if(delta<0.f)delta*=-1;
  115064. if(fabs(delta/newx)<10e-12)break;
  115065. lastdelta=delta;
  115066. }
  115067. r[m-1]=newx;
  115068. /* forward deflation */
  115069. for(i=m;i>0;i--)
  115070. defl[i-1]+=newx*defl[i];
  115071. defl++;
  115072. }
  115073. return(0);
  115074. }
  115075. /* for spit-and-polish only */
  115076. static int Newton_Raphson(float *a,int ord,float *r){
  115077. int i, k, count=0;
  115078. double error=1.f;
  115079. double *root=(double*)alloca(ord*sizeof(*root));
  115080. for(i=0; i<ord;i++) root[i] = r[i];
  115081. while(error>1e-20){
  115082. error=0;
  115083. for(i=0; i<ord; i++) { /* Update each point. */
  115084. double pp=0.,delta;
  115085. double rooti=root[i];
  115086. double p=a[ord];
  115087. for(k=ord-1; k>= 0; k--) {
  115088. pp= pp* rooti + p;
  115089. p = p * rooti + a[k];
  115090. }
  115091. delta = p/pp;
  115092. root[i] -= delta;
  115093. error+= delta*delta;
  115094. }
  115095. if(count>40)return(-1);
  115096. count++;
  115097. }
  115098. /* Replaced the original bubble sort with a real sort. With your
  115099. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115100. for(i=0; i<ord;i++) r[i] = root[i];
  115101. return(0);
  115102. }
  115103. /* Convert lpc coefficients to lsp coefficients */
  115104. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115105. int order2=(m+1)>>1;
  115106. int g1_order,g2_order;
  115107. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115108. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115109. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115110. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115111. int i;
  115112. /* even and odd are slightly different base cases */
  115113. g1_order=(m+1)>>1;
  115114. g2_order=(m) >>1;
  115115. /* Compute the lengths of the x polynomials. */
  115116. /* Compute the first half of K & R F1 & F2 polynomials. */
  115117. /* Compute half of the symmetric and antisymmetric polynomials. */
  115118. /* Remove the roots at +1 and -1. */
  115119. g1[g1_order] = 1.f;
  115120. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115121. g2[g2_order] = 1.f;
  115122. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115123. if(g1_order>g2_order){
  115124. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115125. }else{
  115126. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115127. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115128. }
  115129. /* Convert into polynomials in cos(alpha) */
  115130. cheby(g1,g1_order);
  115131. cheby(g2,g2_order);
  115132. /* Find the roots of the 2 even polynomials.*/
  115133. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115134. Laguerre_With_Deflation(g2,g2_order,g2r))
  115135. return(-1);
  115136. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115137. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115138. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115139. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115140. for(i=0;i<g1_order;i++)
  115141. lsp[i*2] = acos(g1r[i]);
  115142. for(i=0;i<g2_order;i++)
  115143. lsp[i*2+1] = acos(g2r[i]);
  115144. return(0);
  115145. }
  115146. #endif
  115147. /*** End of inlined file: lsp.c ***/
  115148. /*** Start of inlined file: mapping0.c ***/
  115149. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115150. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115151. // tasks..
  115152. #if JUCE_MSVC
  115153. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115154. #endif
  115155. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115156. #if JUCE_USE_OGGVORBIS
  115157. #include <stdlib.h>
  115158. #include <stdio.h>
  115159. #include <string.h>
  115160. #include <math.h>
  115161. /* simplistic, wasteful way of doing this (unique lookup for each
  115162. mode/submapping); there should be a central repository for
  115163. identical lookups. That will require minor work, so I'm putting it
  115164. off as low priority.
  115165. Why a lookup for each backend in a given mode? Because the
  115166. blocksize is set by the mode, and low backend lookups may require
  115167. parameters from other areas of the mode/mapping */
  115168. static void mapping0_free_info(vorbis_info_mapping *i){
  115169. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115170. if(info){
  115171. memset(info,0,sizeof(*info));
  115172. _ogg_free(info);
  115173. }
  115174. }
  115175. static int ilog3(unsigned int v){
  115176. int ret=0;
  115177. if(v)--v;
  115178. while(v){
  115179. ret++;
  115180. v>>=1;
  115181. }
  115182. return(ret);
  115183. }
  115184. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115185. oggpack_buffer *opb){
  115186. int i;
  115187. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115188. /* another 'we meant to do it this way' hack... up to beta 4, we
  115189. packed 4 binary zeros here to signify one submapping in use. We
  115190. now redefine that to mean four bitflags that indicate use of
  115191. deeper features; bit0:submappings, bit1:coupling,
  115192. bit2,3:reserved. This is backward compatable with all actual uses
  115193. of the beta code. */
  115194. if(info->submaps>1){
  115195. oggpack_write(opb,1,1);
  115196. oggpack_write(opb,info->submaps-1,4);
  115197. }else
  115198. oggpack_write(opb,0,1);
  115199. if(info->coupling_steps>0){
  115200. oggpack_write(opb,1,1);
  115201. oggpack_write(opb,info->coupling_steps-1,8);
  115202. for(i=0;i<info->coupling_steps;i++){
  115203. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115204. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115205. }
  115206. }else
  115207. oggpack_write(opb,0,1);
  115208. oggpack_write(opb,0,2); /* 2,3:reserved */
  115209. /* we don't write the channel submappings if we only have one... */
  115210. if(info->submaps>1){
  115211. for(i=0;i<vi->channels;i++)
  115212. oggpack_write(opb,info->chmuxlist[i],4);
  115213. }
  115214. for(i=0;i<info->submaps;i++){
  115215. oggpack_write(opb,0,8); /* time submap unused */
  115216. oggpack_write(opb,info->floorsubmap[i],8);
  115217. oggpack_write(opb,info->residuesubmap[i],8);
  115218. }
  115219. }
  115220. /* also responsible for range checking */
  115221. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115222. int i;
  115223. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115224. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115225. memset(info,0,sizeof(*info));
  115226. if(oggpack_read(opb,1))
  115227. info->submaps=oggpack_read(opb,4)+1;
  115228. else
  115229. info->submaps=1;
  115230. if(oggpack_read(opb,1)){
  115231. info->coupling_steps=oggpack_read(opb,8)+1;
  115232. for(i=0;i<info->coupling_steps;i++){
  115233. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115234. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115235. if(testM<0 ||
  115236. testA<0 ||
  115237. testM==testA ||
  115238. testM>=vi->channels ||
  115239. testA>=vi->channels) goto err_out;
  115240. }
  115241. }
  115242. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115243. if(info->submaps>1){
  115244. for(i=0;i<vi->channels;i++){
  115245. info->chmuxlist[i]=oggpack_read(opb,4);
  115246. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115247. }
  115248. }
  115249. for(i=0;i<info->submaps;i++){
  115250. oggpack_read(opb,8); /* time submap unused */
  115251. info->floorsubmap[i]=oggpack_read(opb,8);
  115252. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115253. info->residuesubmap[i]=oggpack_read(opb,8);
  115254. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115255. }
  115256. return info;
  115257. err_out:
  115258. mapping0_free_info(info);
  115259. return(NULL);
  115260. }
  115261. #if 0
  115262. static long seq=0;
  115263. static ogg_int64_t total=0;
  115264. static float FLOOR1_fromdB_LOOKUP[256]={
  115265. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115266. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115267. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115268. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115269. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115270. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115271. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115272. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115273. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115274. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115275. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115276. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115277. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115278. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115279. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115280. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115281. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115282. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115283. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115284. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115285. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115286. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115287. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115288. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115289. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115290. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115291. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115292. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115293. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115294. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115295. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115296. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115297. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115298. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115299. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115300. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115301. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115302. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115303. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115304. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115305. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115306. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115307. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115308. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115309. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115310. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115311. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115312. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115313. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115314. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115315. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115316. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115317. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115318. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115319. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115320. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115321. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115322. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115323. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115324. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115325. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115326. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115327. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115328. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115329. };
  115330. #endif
  115331. extern int *floor1_fit(vorbis_block *vb,void *look,
  115332. const float *logmdct, /* in */
  115333. const float *logmask);
  115334. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115335. int *A,int *B,
  115336. int del);
  115337. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115338. void*look,
  115339. int *post,int *ilogmask);
  115340. static int mapping0_forward(vorbis_block *vb){
  115341. vorbis_dsp_state *vd=vb->vd;
  115342. vorbis_info *vi=vd->vi;
  115343. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115344. private_state *b=(private_state*)vb->vd->backend_state;
  115345. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115346. int n=vb->pcmend;
  115347. int i,j,k;
  115348. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115349. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115350. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115351. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115352. float global_ampmax=vbi->ampmax;
  115353. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115354. int blocktype=vbi->blocktype;
  115355. int modenumber=vb->W;
  115356. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115357. vorbis_look_psy *psy_look=
  115358. b->psy+blocktype+(vb->W?2:0);
  115359. vb->mode=modenumber;
  115360. for(i=0;i<vi->channels;i++){
  115361. float scale=4.f/n;
  115362. float scale_dB;
  115363. float *pcm =vb->pcm[i];
  115364. float *logfft =pcm;
  115365. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115366. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115367. todB estimation used on IEEE 754
  115368. compliant machines had a bug that
  115369. returned dB values about a third
  115370. of a decibel too high. The bug
  115371. was harmless because tunings
  115372. implicitly took that into
  115373. account. However, fixing the bug
  115374. in the estimator requires
  115375. changing all the tunings as well.
  115376. For now, it's easier to sync
  115377. things back up here, and
  115378. recalibrate the tunings in the
  115379. next major model upgrade. */
  115380. #if 0
  115381. if(vi->channels==2)
  115382. if(i==0)
  115383. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115384. else
  115385. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115386. #endif
  115387. /* window the PCM data */
  115388. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115389. #if 0
  115390. if(vi->channels==2)
  115391. if(i==0)
  115392. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115393. else
  115394. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115395. #endif
  115396. /* transform the PCM data */
  115397. /* only MDCT right now.... */
  115398. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115399. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115400. drft_forward(&b->fft_look[vb->W],pcm);
  115401. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115402. original todB estimation used on
  115403. IEEE 754 compliant machines had a
  115404. bug that returned dB values about
  115405. a third of a decibel too high.
  115406. The bug was harmless because
  115407. tunings implicitly took that into
  115408. account. However, fixing the bug
  115409. in the estimator requires
  115410. changing all the tunings as well.
  115411. For now, it's easier to sync
  115412. things back up here, and
  115413. recalibrate the tunings in the
  115414. next major model upgrade. */
  115415. local_ampmax[i]=logfft[0];
  115416. for(j=1;j<n-1;j+=2){
  115417. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115418. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115419. .345 is a hack; the original todB
  115420. estimation used on IEEE 754
  115421. compliant machines had a bug that
  115422. returned dB values about a third
  115423. of a decibel too high. The bug
  115424. was harmless because tunings
  115425. implicitly took that into
  115426. account. However, fixing the bug
  115427. in the estimator requires
  115428. changing all the tunings as well.
  115429. For now, it's easier to sync
  115430. things back up here, and
  115431. recalibrate the tunings in the
  115432. next major model upgrade. */
  115433. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115434. }
  115435. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115436. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115437. #if 0
  115438. if(vi->channels==2){
  115439. if(i==0){
  115440. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115441. }else{
  115442. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115443. }
  115444. }
  115445. #endif
  115446. }
  115447. {
  115448. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115449. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115450. for(i=0;i<vi->channels;i++){
  115451. /* the encoder setup assumes that all the modes used by any
  115452. specific bitrate tweaking use the same floor */
  115453. int submap=info->chmuxlist[i];
  115454. /* the following makes things clearer to *me* anyway */
  115455. float *mdct =gmdct[i];
  115456. float *logfft =vb->pcm[i];
  115457. float *logmdct =logfft+n/2;
  115458. float *logmask =logfft;
  115459. vb->mode=modenumber;
  115460. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115461. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115462. for(j=0;j<n/2;j++)
  115463. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115464. todB estimation used on IEEE 754
  115465. compliant machines had a bug that
  115466. returned dB values about a third
  115467. of a decibel too high. The bug
  115468. was harmless because tunings
  115469. implicitly took that into
  115470. account. However, fixing the bug
  115471. in the estimator requires
  115472. changing all the tunings as well.
  115473. For now, it's easier to sync
  115474. things back up here, and
  115475. recalibrate the tunings in the
  115476. next major model upgrade. */
  115477. #if 0
  115478. if(vi->channels==2){
  115479. if(i==0)
  115480. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115481. else
  115482. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115483. }else{
  115484. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115485. }
  115486. #endif
  115487. /* first step; noise masking. Not only does 'noise masking'
  115488. give us curves from which we can decide how much resolution
  115489. to give noise parts of the spectrum, it also implicitly hands
  115490. us a tonality estimate (the larger the value in the
  115491. 'noise_depth' vector, the more tonal that area is) */
  115492. _vp_noisemask(psy_look,
  115493. logmdct,
  115494. noise); /* noise does not have by-frequency offset
  115495. bias applied yet */
  115496. #if 0
  115497. if(vi->channels==2){
  115498. if(i==0)
  115499. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115500. else
  115501. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115502. }
  115503. #endif
  115504. /* second step: 'all the other crap'; all the stuff that isn't
  115505. computed/fit for bitrate management goes in the second psy
  115506. vector. This includes tone masking, peak limiting and ATH */
  115507. _vp_tonemask(psy_look,
  115508. logfft,
  115509. tone,
  115510. global_ampmax,
  115511. local_ampmax[i]);
  115512. #if 0
  115513. if(vi->channels==2){
  115514. if(i==0)
  115515. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115516. else
  115517. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115518. }
  115519. #endif
  115520. /* third step; we offset the noise vectors, overlay tone
  115521. masking. We then do a floor1-specific line fit. If we're
  115522. performing bitrate management, the line fit is performed
  115523. multiple times for up/down tweakage on demand. */
  115524. #if 0
  115525. {
  115526. float aotuv[psy_look->n];
  115527. #endif
  115528. _vp_offset_and_mix(psy_look,
  115529. noise,
  115530. tone,
  115531. 1,
  115532. logmask,
  115533. mdct,
  115534. logmdct);
  115535. #if 0
  115536. if(vi->channels==2){
  115537. if(i==0)
  115538. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115539. else
  115540. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115541. }
  115542. }
  115543. #endif
  115544. #if 0
  115545. if(vi->channels==2){
  115546. if(i==0)
  115547. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115548. else
  115549. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115550. }
  115551. #endif
  115552. /* this algorithm is hardwired to floor 1 for now; abort out if
  115553. we're *not* floor1. This won't happen unless someone has
  115554. broken the encode setup lib. Guard it anyway. */
  115555. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115556. floor_posts[i][PACKETBLOBS/2]=
  115557. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115558. logmdct,
  115559. logmask);
  115560. /* are we managing bitrate? If so, perform two more fits for
  115561. later rate tweaking (fits represent hi/lo) */
  115562. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115563. /* higher rate by way of lower noise curve */
  115564. _vp_offset_and_mix(psy_look,
  115565. noise,
  115566. tone,
  115567. 2,
  115568. logmask,
  115569. mdct,
  115570. logmdct);
  115571. #if 0
  115572. if(vi->channels==2){
  115573. if(i==0)
  115574. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115575. else
  115576. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115577. }
  115578. #endif
  115579. floor_posts[i][PACKETBLOBS-1]=
  115580. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115581. logmdct,
  115582. logmask);
  115583. /* lower rate by way of higher noise curve */
  115584. _vp_offset_and_mix(psy_look,
  115585. noise,
  115586. tone,
  115587. 0,
  115588. logmask,
  115589. mdct,
  115590. logmdct);
  115591. #if 0
  115592. if(vi->channels==2)
  115593. if(i==0)
  115594. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115595. else
  115596. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115597. #endif
  115598. floor_posts[i][0]=
  115599. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115600. logmdct,
  115601. logmask);
  115602. /* we also interpolate a range of intermediate curves for
  115603. intermediate rates */
  115604. for(k=1;k<PACKETBLOBS/2;k++)
  115605. floor_posts[i][k]=
  115606. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115607. floor_posts[i][0],
  115608. floor_posts[i][PACKETBLOBS/2],
  115609. k*65536/(PACKETBLOBS/2));
  115610. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115611. floor_posts[i][k]=
  115612. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115613. floor_posts[i][PACKETBLOBS/2],
  115614. floor_posts[i][PACKETBLOBS-1],
  115615. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115616. }
  115617. }
  115618. }
  115619. vbi->ampmax=global_ampmax;
  115620. /*
  115621. the next phases are performed once for vbr-only and PACKETBLOB
  115622. times for bitrate managed modes.
  115623. 1) encode actual mode being used
  115624. 2) encode the floor for each channel, compute coded mask curve/res
  115625. 3) normalize and couple.
  115626. 4) encode residue
  115627. 5) save packet bytes to the packetblob vector
  115628. */
  115629. /* iterate over the many masking curve fits we've created */
  115630. {
  115631. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115632. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115633. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115634. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115635. float **mag_memo;
  115636. int **mag_sort;
  115637. if(info->coupling_steps){
  115638. mag_memo=_vp_quantize_couple_memo(vb,
  115639. &ci->psy_g_param,
  115640. psy_look,
  115641. info,
  115642. gmdct);
  115643. mag_sort=_vp_quantize_couple_sort(vb,
  115644. psy_look,
  115645. info,
  115646. mag_memo);
  115647. hf_reduction(&ci->psy_g_param,
  115648. psy_look,
  115649. info,
  115650. mag_memo);
  115651. }
  115652. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115653. if(psy_look->vi->normal_channel_p){
  115654. for(i=0;i<vi->channels;i++){
  115655. float *mdct =gmdct[i];
  115656. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115657. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115658. }
  115659. }
  115660. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115661. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115662. k++){
  115663. oggpack_buffer *opb=vbi->packetblob[k];
  115664. /* start out our new packet blob with packet type and mode */
  115665. /* Encode the packet type */
  115666. oggpack_write(opb,0,1);
  115667. /* Encode the modenumber */
  115668. /* Encode frame mode, pre,post windowsize, then dispatch */
  115669. oggpack_write(opb,modenumber,b->modebits);
  115670. if(vb->W){
  115671. oggpack_write(opb,vb->lW,1);
  115672. oggpack_write(opb,vb->nW,1);
  115673. }
  115674. /* encode floor, compute masking curve, sep out residue */
  115675. for(i=0;i<vi->channels;i++){
  115676. int submap=info->chmuxlist[i];
  115677. float *mdct =gmdct[i];
  115678. float *res =vb->pcm[i];
  115679. int *ilogmask=ilogmaskch[i]=
  115680. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115681. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115682. floor_posts[i][k],
  115683. ilogmask);
  115684. #if 0
  115685. {
  115686. char buf[80];
  115687. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115688. float work[n/2];
  115689. for(j=0;j<n/2;j++)
  115690. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115691. _analysis_output(buf,seq,work,n/2,1,1,0);
  115692. }
  115693. #endif
  115694. _vp_remove_floor(psy_look,
  115695. mdct,
  115696. ilogmask,
  115697. res,
  115698. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115699. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115700. #if 0
  115701. {
  115702. char buf[80];
  115703. float work[n/2];
  115704. for(j=0;j<n/2;j++)
  115705. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115706. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115707. _analysis_output(buf,seq,work,n/2,1,1,0);
  115708. }
  115709. #endif
  115710. }
  115711. /* our iteration is now based on masking curve, not prequant and
  115712. coupling. Only one prequant/coupling step */
  115713. /* quantize/couple */
  115714. /* incomplete implementation that assumes the tree is all depth
  115715. one, or no tree at all */
  115716. if(info->coupling_steps){
  115717. _vp_couple(k,
  115718. &ci->psy_g_param,
  115719. psy_look,
  115720. info,
  115721. vb->pcm,
  115722. mag_memo,
  115723. mag_sort,
  115724. ilogmaskch,
  115725. nonzero,
  115726. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115727. }
  115728. /* classify and encode by submap */
  115729. for(i=0;i<info->submaps;i++){
  115730. int ch_in_bundle=0;
  115731. long **classifications;
  115732. int resnum=info->residuesubmap[i];
  115733. for(j=0;j<vi->channels;j++){
  115734. if(info->chmuxlist[j]==i){
  115735. zerobundle[ch_in_bundle]=0;
  115736. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115737. res_bundle[ch_in_bundle]=vb->pcm[j];
  115738. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115739. }
  115740. }
  115741. classifications=_residue_P[ci->residue_type[resnum]]->
  115742. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115743. _residue_P[ci->residue_type[resnum]]->
  115744. forward(opb,vb,b->residue[resnum],
  115745. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115746. }
  115747. /* ok, done encoding. Next protopacket. */
  115748. }
  115749. }
  115750. #if 0
  115751. seq++;
  115752. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115753. #endif
  115754. return(0);
  115755. }
  115756. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115757. vorbis_dsp_state *vd=vb->vd;
  115758. vorbis_info *vi=vd->vi;
  115759. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115760. private_state *b=(private_state*)vd->backend_state;
  115761. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115762. int i,j;
  115763. long n=vb->pcmend=ci->blocksizes[vb->W];
  115764. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115765. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115766. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115767. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115768. /* recover the spectral envelope; store it in the PCM vector for now */
  115769. for(i=0;i<vi->channels;i++){
  115770. int submap=info->chmuxlist[i];
  115771. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115772. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115773. if(floormemo[i])
  115774. nonzero[i]=1;
  115775. else
  115776. nonzero[i]=0;
  115777. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115778. }
  115779. /* channel coupling can 'dirty' the nonzero listing */
  115780. for(i=0;i<info->coupling_steps;i++){
  115781. if(nonzero[info->coupling_mag[i]] ||
  115782. nonzero[info->coupling_ang[i]]){
  115783. nonzero[info->coupling_mag[i]]=1;
  115784. nonzero[info->coupling_ang[i]]=1;
  115785. }
  115786. }
  115787. /* recover the residue into our working vectors */
  115788. for(i=0;i<info->submaps;i++){
  115789. int ch_in_bundle=0;
  115790. for(j=0;j<vi->channels;j++){
  115791. if(info->chmuxlist[j]==i){
  115792. if(nonzero[j])
  115793. zerobundle[ch_in_bundle]=1;
  115794. else
  115795. zerobundle[ch_in_bundle]=0;
  115796. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115797. }
  115798. }
  115799. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115800. inverse(vb,b->residue[info->residuesubmap[i]],
  115801. pcmbundle,zerobundle,ch_in_bundle);
  115802. }
  115803. /* channel coupling */
  115804. for(i=info->coupling_steps-1;i>=0;i--){
  115805. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115806. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115807. for(j=0;j<n/2;j++){
  115808. float mag=pcmM[j];
  115809. float ang=pcmA[j];
  115810. if(mag>0)
  115811. if(ang>0){
  115812. pcmM[j]=mag;
  115813. pcmA[j]=mag-ang;
  115814. }else{
  115815. pcmA[j]=mag;
  115816. pcmM[j]=mag+ang;
  115817. }
  115818. else
  115819. if(ang>0){
  115820. pcmM[j]=mag;
  115821. pcmA[j]=mag+ang;
  115822. }else{
  115823. pcmA[j]=mag;
  115824. pcmM[j]=mag-ang;
  115825. }
  115826. }
  115827. }
  115828. /* compute and apply spectral envelope */
  115829. for(i=0;i<vi->channels;i++){
  115830. float *pcm=vb->pcm[i];
  115831. int submap=info->chmuxlist[i];
  115832. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115833. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115834. floormemo[i],pcm);
  115835. }
  115836. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115837. /* only MDCT right now.... */
  115838. for(i=0;i<vi->channels;i++){
  115839. float *pcm=vb->pcm[i];
  115840. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115841. }
  115842. /* all done! */
  115843. return(0);
  115844. }
  115845. /* export hooks */
  115846. vorbis_func_mapping mapping0_exportbundle={
  115847. &mapping0_pack,
  115848. &mapping0_unpack,
  115849. &mapping0_free_info,
  115850. &mapping0_forward,
  115851. &mapping0_inverse
  115852. };
  115853. #endif
  115854. /*** End of inlined file: mapping0.c ***/
  115855. /*** Start of inlined file: mdct.c ***/
  115856. /* this can also be run as an integer transform by uncommenting a
  115857. define in mdct.h; the integerization is a first pass and although
  115858. it's likely stable for Vorbis, the dynamic range is constrained and
  115859. roundoff isn't done (so it's noisy). Consider it functional, but
  115860. only a starting point. There's no point on a machine with an FPU */
  115861. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115862. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115863. // tasks..
  115864. #if JUCE_MSVC
  115865. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115866. #endif
  115867. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115868. #if JUCE_USE_OGGVORBIS
  115869. #include <stdio.h>
  115870. #include <stdlib.h>
  115871. #include <string.h>
  115872. #include <math.h>
  115873. /* build lookups for trig functions; also pre-figure scaling and
  115874. some window function algebra. */
  115875. void mdct_init(mdct_lookup *lookup,int n){
  115876. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115877. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115878. int i;
  115879. int n2=n>>1;
  115880. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115881. lookup->n=n;
  115882. lookup->trig=T;
  115883. lookup->bitrev=bitrev;
  115884. /* trig lookups... */
  115885. for(i=0;i<n/4;i++){
  115886. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115887. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115888. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115889. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115890. }
  115891. for(i=0;i<n/8;i++){
  115892. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115893. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115894. }
  115895. /* bitreverse lookup... */
  115896. {
  115897. int mask=(1<<(log2n-1))-1,i,j;
  115898. int msb=1<<(log2n-2);
  115899. for(i=0;i<n/8;i++){
  115900. int acc=0;
  115901. for(j=0;msb>>j;j++)
  115902. if((msb>>j)&i)acc|=1<<j;
  115903. bitrev[i*2]=((~acc)&mask)-1;
  115904. bitrev[i*2+1]=acc;
  115905. }
  115906. }
  115907. lookup->scale=FLOAT_CONV(4.f/n);
  115908. }
  115909. /* 8 point butterfly (in place, 4 register) */
  115910. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115911. REG_TYPE r0 = x[6] + x[2];
  115912. REG_TYPE r1 = x[6] - x[2];
  115913. REG_TYPE r2 = x[4] + x[0];
  115914. REG_TYPE r3 = x[4] - x[0];
  115915. x[6] = r0 + r2;
  115916. x[4] = r0 - r2;
  115917. r0 = x[5] - x[1];
  115918. r2 = x[7] - x[3];
  115919. x[0] = r1 + r0;
  115920. x[2] = r1 - r0;
  115921. r0 = x[5] + x[1];
  115922. r1 = x[7] + x[3];
  115923. x[3] = r2 + r3;
  115924. x[1] = r2 - r3;
  115925. x[7] = r1 + r0;
  115926. x[5] = r1 - r0;
  115927. }
  115928. /* 16 point butterfly (in place, 4 register) */
  115929. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115930. REG_TYPE r0 = x[1] - x[9];
  115931. REG_TYPE r1 = x[0] - x[8];
  115932. x[8] += x[0];
  115933. x[9] += x[1];
  115934. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115935. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115936. r0 = x[3] - x[11];
  115937. r1 = x[10] - x[2];
  115938. x[10] += x[2];
  115939. x[11] += x[3];
  115940. x[2] = r0;
  115941. x[3] = r1;
  115942. r0 = x[12] - x[4];
  115943. r1 = x[13] - x[5];
  115944. x[12] += x[4];
  115945. x[13] += x[5];
  115946. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115947. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115948. r0 = x[14] - x[6];
  115949. r1 = x[15] - x[7];
  115950. x[14] += x[6];
  115951. x[15] += x[7];
  115952. x[6] = r0;
  115953. x[7] = r1;
  115954. mdct_butterfly_8(x);
  115955. mdct_butterfly_8(x+8);
  115956. }
  115957. /* 32 point butterfly (in place, 4 register) */
  115958. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115959. REG_TYPE r0 = x[30] - x[14];
  115960. REG_TYPE r1 = x[31] - x[15];
  115961. x[30] += x[14];
  115962. x[31] += x[15];
  115963. x[14] = r0;
  115964. x[15] = r1;
  115965. r0 = x[28] - x[12];
  115966. r1 = x[29] - x[13];
  115967. x[28] += x[12];
  115968. x[29] += x[13];
  115969. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115970. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115971. r0 = x[26] - x[10];
  115972. r1 = x[27] - x[11];
  115973. x[26] += x[10];
  115974. x[27] += x[11];
  115975. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115976. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115977. r0 = x[24] - x[8];
  115978. r1 = x[25] - x[9];
  115979. x[24] += x[8];
  115980. x[25] += x[9];
  115981. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115982. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115983. r0 = x[22] - x[6];
  115984. r1 = x[7] - x[23];
  115985. x[22] += x[6];
  115986. x[23] += x[7];
  115987. x[6] = r1;
  115988. x[7] = r0;
  115989. r0 = x[4] - x[20];
  115990. r1 = x[5] - x[21];
  115991. x[20] += x[4];
  115992. x[21] += x[5];
  115993. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115994. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115995. r0 = x[2] - x[18];
  115996. r1 = x[3] - x[19];
  115997. x[18] += x[2];
  115998. x[19] += x[3];
  115999. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  116000. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  116001. r0 = x[0] - x[16];
  116002. r1 = x[1] - x[17];
  116003. x[16] += x[0];
  116004. x[17] += x[1];
  116005. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116006. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  116007. mdct_butterfly_16(x);
  116008. mdct_butterfly_16(x+16);
  116009. }
  116010. /* N point first stage butterfly (in place, 2 register) */
  116011. STIN void mdct_butterfly_first(DATA_TYPE *T,
  116012. DATA_TYPE *x,
  116013. int points){
  116014. DATA_TYPE *x1 = x + points - 8;
  116015. DATA_TYPE *x2 = x + (points>>1) - 8;
  116016. REG_TYPE r0;
  116017. REG_TYPE r1;
  116018. do{
  116019. r0 = x1[6] - x2[6];
  116020. r1 = x1[7] - x2[7];
  116021. x1[6] += x2[6];
  116022. x1[7] += x2[7];
  116023. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116024. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116025. r0 = x1[4] - x2[4];
  116026. r1 = x1[5] - x2[5];
  116027. x1[4] += x2[4];
  116028. x1[5] += x2[5];
  116029. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  116030. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  116031. r0 = x1[2] - x2[2];
  116032. r1 = x1[3] - x2[3];
  116033. x1[2] += x2[2];
  116034. x1[3] += x2[3];
  116035. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  116036. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  116037. r0 = x1[0] - x2[0];
  116038. r1 = x1[1] - x2[1];
  116039. x1[0] += x2[0];
  116040. x1[1] += x2[1];
  116041. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  116042. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  116043. x1-=8;
  116044. x2-=8;
  116045. T+=16;
  116046. }while(x2>=x);
  116047. }
  116048. /* N/stage point generic N stage butterfly (in place, 2 register) */
  116049. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  116050. DATA_TYPE *x,
  116051. int points,
  116052. int trigint){
  116053. DATA_TYPE *x1 = x + points - 8;
  116054. DATA_TYPE *x2 = x + (points>>1) - 8;
  116055. REG_TYPE r0;
  116056. REG_TYPE r1;
  116057. do{
  116058. r0 = x1[6] - x2[6];
  116059. r1 = x1[7] - x2[7];
  116060. x1[6] += x2[6];
  116061. x1[7] += x2[7];
  116062. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116063. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116064. T+=trigint;
  116065. r0 = x1[4] - x2[4];
  116066. r1 = x1[5] - x2[5];
  116067. x1[4] += x2[4];
  116068. x1[5] += x2[5];
  116069. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116070. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116071. T+=trigint;
  116072. r0 = x1[2] - x2[2];
  116073. r1 = x1[3] - x2[3];
  116074. x1[2] += x2[2];
  116075. x1[3] += x2[3];
  116076. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116077. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116078. T+=trigint;
  116079. r0 = x1[0] - x2[0];
  116080. r1 = x1[1] - x2[1];
  116081. x1[0] += x2[0];
  116082. x1[1] += x2[1];
  116083. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116084. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116085. T+=trigint;
  116086. x1-=8;
  116087. x2-=8;
  116088. }while(x2>=x);
  116089. }
  116090. STIN void mdct_butterflies(mdct_lookup *init,
  116091. DATA_TYPE *x,
  116092. int points){
  116093. DATA_TYPE *T=init->trig;
  116094. int stages=init->log2n-5;
  116095. int i,j;
  116096. if(--stages>0){
  116097. mdct_butterfly_first(T,x,points);
  116098. }
  116099. for(i=1;--stages>0;i++){
  116100. for(j=0;j<(1<<i);j++)
  116101. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116102. }
  116103. for(j=0;j<points;j+=32)
  116104. mdct_butterfly_32(x+j);
  116105. }
  116106. void mdct_clear(mdct_lookup *l){
  116107. if(l){
  116108. if(l->trig)_ogg_free(l->trig);
  116109. if(l->bitrev)_ogg_free(l->bitrev);
  116110. memset(l,0,sizeof(*l));
  116111. }
  116112. }
  116113. STIN void mdct_bitreverse(mdct_lookup *init,
  116114. DATA_TYPE *x){
  116115. int n = init->n;
  116116. int *bit = init->bitrev;
  116117. DATA_TYPE *w0 = x;
  116118. DATA_TYPE *w1 = x = w0+(n>>1);
  116119. DATA_TYPE *T = init->trig+n;
  116120. do{
  116121. DATA_TYPE *x0 = x+bit[0];
  116122. DATA_TYPE *x1 = x+bit[1];
  116123. REG_TYPE r0 = x0[1] - x1[1];
  116124. REG_TYPE r1 = x0[0] + x1[0];
  116125. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116126. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116127. w1 -= 4;
  116128. r0 = HALVE(x0[1] + x1[1]);
  116129. r1 = HALVE(x0[0] - x1[0]);
  116130. w0[0] = r0 + r2;
  116131. w1[2] = r0 - r2;
  116132. w0[1] = r1 + r3;
  116133. w1[3] = r3 - r1;
  116134. x0 = x+bit[2];
  116135. x1 = x+bit[3];
  116136. r0 = x0[1] - x1[1];
  116137. r1 = x0[0] + x1[0];
  116138. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116139. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116140. r0 = HALVE(x0[1] + x1[1]);
  116141. r1 = HALVE(x0[0] - x1[0]);
  116142. w0[2] = r0 + r2;
  116143. w1[0] = r0 - r2;
  116144. w0[3] = r1 + r3;
  116145. w1[1] = r3 - r1;
  116146. T += 4;
  116147. bit += 4;
  116148. w0 += 4;
  116149. }while(w0<w1);
  116150. }
  116151. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116152. int n=init->n;
  116153. int n2=n>>1;
  116154. int n4=n>>2;
  116155. /* rotate */
  116156. DATA_TYPE *iX = in+n2-7;
  116157. DATA_TYPE *oX = out+n2+n4;
  116158. DATA_TYPE *T = init->trig+n4;
  116159. do{
  116160. oX -= 4;
  116161. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116162. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116163. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116164. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116165. iX -= 8;
  116166. T += 4;
  116167. }while(iX>=in);
  116168. iX = in+n2-8;
  116169. oX = out+n2+n4;
  116170. T = init->trig+n4;
  116171. do{
  116172. T -= 4;
  116173. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116174. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116175. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116176. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116177. iX -= 8;
  116178. oX += 4;
  116179. }while(iX>=in);
  116180. mdct_butterflies(init,out+n2,n2);
  116181. mdct_bitreverse(init,out);
  116182. /* roatate + window */
  116183. {
  116184. DATA_TYPE *oX1=out+n2+n4;
  116185. DATA_TYPE *oX2=out+n2+n4;
  116186. DATA_TYPE *iX =out;
  116187. T =init->trig+n2;
  116188. do{
  116189. oX1-=4;
  116190. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116191. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116192. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116193. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116194. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116195. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116196. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116197. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116198. oX2+=4;
  116199. iX += 8;
  116200. T += 8;
  116201. }while(iX<oX1);
  116202. iX=out+n2+n4;
  116203. oX1=out+n4;
  116204. oX2=oX1;
  116205. do{
  116206. oX1-=4;
  116207. iX-=4;
  116208. oX2[0] = -(oX1[3] = iX[3]);
  116209. oX2[1] = -(oX1[2] = iX[2]);
  116210. oX2[2] = -(oX1[1] = iX[1]);
  116211. oX2[3] = -(oX1[0] = iX[0]);
  116212. oX2+=4;
  116213. }while(oX2<iX);
  116214. iX=out+n2+n4;
  116215. oX1=out+n2+n4;
  116216. oX2=out+n2;
  116217. do{
  116218. oX1-=4;
  116219. oX1[0]= iX[3];
  116220. oX1[1]= iX[2];
  116221. oX1[2]= iX[1];
  116222. oX1[3]= iX[0];
  116223. iX+=4;
  116224. }while(oX1>oX2);
  116225. }
  116226. }
  116227. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116228. int n=init->n;
  116229. int n2=n>>1;
  116230. int n4=n>>2;
  116231. int n8=n>>3;
  116232. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116233. DATA_TYPE *w2=w+n2;
  116234. /* rotate */
  116235. /* window + rotate + step 1 */
  116236. REG_TYPE r0;
  116237. REG_TYPE r1;
  116238. DATA_TYPE *x0=in+n2+n4;
  116239. DATA_TYPE *x1=x0+1;
  116240. DATA_TYPE *T=init->trig+n2;
  116241. int i=0;
  116242. for(i=0;i<n8;i+=2){
  116243. x0 -=4;
  116244. T-=2;
  116245. r0= x0[2] + x1[0];
  116246. r1= x0[0] + x1[2];
  116247. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116248. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116249. x1 +=4;
  116250. }
  116251. x1=in+1;
  116252. for(;i<n2-n8;i+=2){
  116253. T-=2;
  116254. x0 -=4;
  116255. r0= x0[2] - x1[0];
  116256. r1= x0[0] - x1[2];
  116257. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116258. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116259. x1 +=4;
  116260. }
  116261. x0=in+n;
  116262. for(;i<n2;i+=2){
  116263. T-=2;
  116264. x0 -=4;
  116265. r0= -x0[2] - x1[0];
  116266. r1= -x0[0] - x1[2];
  116267. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116268. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116269. x1 +=4;
  116270. }
  116271. mdct_butterflies(init,w+n2,n2);
  116272. mdct_bitreverse(init,w);
  116273. /* roatate + window */
  116274. T=init->trig+n2;
  116275. x0=out+n2;
  116276. for(i=0;i<n4;i++){
  116277. x0--;
  116278. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116279. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116280. w+=2;
  116281. T+=2;
  116282. }
  116283. }
  116284. #endif
  116285. /*** End of inlined file: mdct.c ***/
  116286. /*** Start of inlined file: psy.c ***/
  116287. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116288. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116289. // tasks..
  116290. #if JUCE_MSVC
  116291. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116292. #endif
  116293. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116294. #if JUCE_USE_OGGVORBIS
  116295. #include <stdlib.h>
  116296. #include <math.h>
  116297. #include <string.h>
  116298. /*** Start of inlined file: masking.h ***/
  116299. #ifndef _V_MASKING_H_
  116300. #define _V_MASKING_H_
  116301. /* more detailed ATH; the bass if flat to save stressing the floor
  116302. overly for only a bin or two of savings. */
  116303. #define MAX_ATH 88
  116304. static float ATH[]={
  116305. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116306. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116307. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116308. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116309. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116310. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116311. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116312. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116313. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116314. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116315. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116316. };
  116317. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116318. replaced by an empirically collected data set. The previously
  116319. published values were, far too often, simply on crack. */
  116320. #define EHMER_OFFSET 16
  116321. #define EHMER_MAX 56
  116322. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116323. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116324. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116325. for collection of these curves) */
  116326. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116327. /* 62.5 Hz */
  116328. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116329. -60, -60, -60, -60, -62, -62, -65, -73,
  116330. -69, -68, -68, -67, -70, -70, -72, -74,
  116331. -75, -79, -79, -80, -83, -88, -93, -100,
  116332. -110, -999, -999, -999, -999, -999, -999, -999,
  116333. -999, -999, -999, -999, -999, -999, -999, -999,
  116334. -999, -999, -999, -999, -999, -999, -999, -999},
  116335. { -48, -48, -48, -48, -48, -48, -48, -48,
  116336. -48, -48, -48, -48, -48, -53, -61, -66,
  116337. -66, -68, -67, -70, -76, -76, -72, -73,
  116338. -75, -76, -78, -79, -83, -88, -93, -100,
  116339. -110, -999, -999, -999, -999, -999, -999, -999,
  116340. -999, -999, -999, -999, -999, -999, -999, -999,
  116341. -999, -999, -999, -999, -999, -999, -999, -999},
  116342. { -37, -37, -37, -37, -37, -37, -37, -37,
  116343. -38, -40, -42, -46, -48, -53, -55, -62,
  116344. -65, -58, -56, -56, -61, -60, -65, -67,
  116345. -69, -71, -77, -77, -78, -80, -82, -84,
  116346. -88, -93, -98, -106, -112, -999, -999, -999,
  116347. -999, -999, -999, -999, -999, -999, -999, -999,
  116348. -999, -999, -999, -999, -999, -999, -999, -999},
  116349. { -25, -25, -25, -25, -25, -25, -25, -25,
  116350. -25, -26, -27, -29, -32, -38, -48, -52,
  116351. -52, -50, -48, -48, -51, -52, -54, -60,
  116352. -67, -67, -66, -68, -69, -73, -73, -76,
  116353. -80, -81, -81, -85, -85, -86, -88, -93,
  116354. -100, -110, -999, -999, -999, -999, -999, -999,
  116355. -999, -999, -999, -999, -999, -999, -999, -999},
  116356. { -16, -16, -16, -16, -16, -16, -16, -16,
  116357. -17, -19, -20, -22, -26, -28, -31, -40,
  116358. -47, -39, -39, -40, -42, -43, -47, -51,
  116359. -57, -52, -55, -55, -60, -58, -62, -63,
  116360. -70, -67, -69, -72, -73, -77, -80, -82,
  116361. -83, -87, -90, -94, -98, -104, -115, -999,
  116362. -999, -999, -999, -999, -999, -999, -999, -999},
  116363. { -8, -8, -8, -8, -8, -8, -8, -8,
  116364. -8, -8, -10, -11, -15, -19, -25, -30,
  116365. -34, -31, -30, -31, -29, -32, -35, -42,
  116366. -48, -42, -44, -46, -50, -50, -51, -52,
  116367. -59, -54, -55, -55, -58, -62, -63, -66,
  116368. -72, -73, -76, -75, -78, -80, -80, -81,
  116369. -84, -88, -90, -94, -98, -101, -106, -110}},
  116370. /* 88Hz */
  116371. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116372. -66, -66, -66, -66, -66, -67, -67, -67,
  116373. -76, -72, -71, -74, -76, -76, -75, -78,
  116374. -79, -79, -81, -83, -86, -89, -93, -97,
  116375. -100, -105, -110, -999, -999, -999, -999, -999,
  116376. -999, -999, -999, -999, -999, -999, -999, -999,
  116377. -999, -999, -999, -999, -999, -999, -999, -999},
  116378. { -47, -47, -47, -47, -47, -47, -47, -47,
  116379. -47, -47, -47, -48, -51, -55, -59, -66,
  116380. -66, -66, -67, -66, -68, -69, -70, -74,
  116381. -79, -77, -77, -78, -80, -81, -82, -84,
  116382. -86, -88, -91, -95, -100, -108, -116, -999,
  116383. -999, -999, -999, -999, -999, -999, -999, -999,
  116384. -999, -999, -999, -999, -999, -999, -999, -999},
  116385. { -36, -36, -36, -36, -36, -36, -36, -36,
  116386. -36, -37, -37, -41, -44, -48, -51, -58,
  116387. -62, -60, -57, -59, -59, -60, -63, -65,
  116388. -72, -71, -70, -72, -74, -77, -76, -78,
  116389. -81, -81, -80, -83, -86, -91, -96, -100,
  116390. -105, -110, -999, -999, -999, -999, -999, -999,
  116391. -999, -999, -999, -999, -999, -999, -999, -999},
  116392. { -28, -28, -28, -28, -28, -28, -28, -28,
  116393. -28, -30, -32, -32, -33, -35, -41, -49,
  116394. -50, -49, -47, -48, -48, -52, -51, -57,
  116395. -65, -61, -59, -61, -64, -69, -70, -74,
  116396. -77, -77, -78, -81, -84, -85, -87, -90,
  116397. -92, -96, -100, -107, -112, -999, -999, -999,
  116398. -999, -999, -999, -999, -999, -999, -999, -999},
  116399. { -19, -19, -19, -19, -19, -19, -19, -19,
  116400. -20, -21, -23, -27, -30, -35, -36, -41,
  116401. -46, -44, -42, -40, -41, -41, -43, -48,
  116402. -55, -53, -52, -53, -56, -59, -58, -60,
  116403. -67, -66, -69, -71, -72, -75, -79, -81,
  116404. -84, -87, -90, -93, -97, -101, -107, -114,
  116405. -999, -999, -999, -999, -999, -999, -999, -999},
  116406. { -9, -9, -9, -9, -9, -9, -9, -9,
  116407. -11, -12, -12, -15, -16, -20, -23, -30,
  116408. -37, -34, -33, -34, -31, -32, -32, -38,
  116409. -47, -44, -41, -40, -47, -49, -46, -46,
  116410. -58, -50, -50, -54, -58, -62, -64, -67,
  116411. -67, -70, -72, -76, -79, -83, -87, -91,
  116412. -96, -100, -104, -110, -999, -999, -999, -999}},
  116413. /* 125 Hz */
  116414. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116415. -62, -62, -63, -64, -66, -67, -66, -68,
  116416. -75, -72, -76, -75, -76, -78, -79, -82,
  116417. -84, -85, -90, -94, -101, -110, -999, -999,
  116418. -999, -999, -999, -999, -999, -999, -999, -999,
  116419. -999, -999, -999, -999, -999, -999, -999, -999,
  116420. -999, -999, -999, -999, -999, -999, -999, -999},
  116421. { -59, -59, -59, -59, -59, -59, -59, -59,
  116422. -59, -59, -59, -60, -60, -61, -63, -66,
  116423. -71, -68, -70, -70, -71, -72, -72, -75,
  116424. -81, -78, -79, -82, -83, -86, -90, -97,
  116425. -103, -113, -999, -999, -999, -999, -999, -999,
  116426. -999, -999, -999, -999, -999, -999, -999, -999,
  116427. -999, -999, -999, -999, -999, -999, -999, -999},
  116428. { -53, -53, -53, -53, -53, -53, -53, -53,
  116429. -53, -54, -55, -57, -56, -57, -55, -61,
  116430. -65, -60, -60, -62, -63, -63, -66, -68,
  116431. -74, -73, -75, -75, -78, -80, -80, -82,
  116432. -85, -90, -96, -101, -108, -999, -999, -999,
  116433. -999, -999, -999, -999, -999, -999, -999, -999,
  116434. -999, -999, -999, -999, -999, -999, -999, -999},
  116435. { -46, -46, -46, -46, -46, -46, -46, -46,
  116436. -46, -46, -47, -47, -47, -47, -48, -51,
  116437. -57, -51, -49, -50, -51, -53, -54, -59,
  116438. -66, -60, -62, -67, -67, -70, -72, -75,
  116439. -76, -78, -81, -85, -88, -94, -97, -104,
  116440. -112, -999, -999, -999, -999, -999, -999, -999,
  116441. -999, -999, -999, -999, -999, -999, -999, -999},
  116442. { -36, -36, -36, -36, -36, -36, -36, -36,
  116443. -39, -41, -42, -42, -39, -38, -41, -43,
  116444. -52, -44, -40, -39, -37, -37, -40, -47,
  116445. -54, -50, -48, -50, -55, -61, -59, -62,
  116446. -66, -66, -66, -69, -69, -73, -74, -74,
  116447. -75, -77, -79, -82, -87, -91, -95, -100,
  116448. -108, -115, -999, -999, -999, -999, -999, -999},
  116449. { -28, -26, -24, -22, -20, -20, -23, -29,
  116450. -30, -31, -28, -27, -28, -28, -28, -35,
  116451. -40, -33, -32, -29, -30, -30, -30, -37,
  116452. -45, -41, -37, -38, -45, -47, -47, -48,
  116453. -53, -49, -48, -50, -49, -49, -51, -52,
  116454. -58, -56, -57, -56, -60, -61, -62, -70,
  116455. -72, -74, -78, -83, -88, -93, -100, -106}},
  116456. /* 177 Hz */
  116457. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116458. -999, -110, -105, -100, -95, -91, -87, -83,
  116459. -80, -78, -76, -78, -78, -81, -83, -85,
  116460. -86, -85, -86, -87, -90, -97, -107, -999,
  116461. -999, -999, -999, -999, -999, -999, -999, -999,
  116462. -999, -999, -999, -999, -999, -999, -999, -999,
  116463. -999, -999, -999, -999, -999, -999, -999, -999},
  116464. {-999, -999, -999, -110, -105, -100, -95, -90,
  116465. -85, -81, -77, -73, -70, -67, -67, -68,
  116466. -75, -73, -70, -69, -70, -72, -75, -79,
  116467. -84, -83, -84, -86, -88, -89, -89, -93,
  116468. -98, -105, -112, -999, -999, -999, -999, -999,
  116469. -999, -999, -999, -999, -999, -999, -999, -999,
  116470. -999, -999, -999, -999, -999, -999, -999, -999},
  116471. {-105, -100, -95, -90, -85, -80, -76, -71,
  116472. -68, -68, -65, -63, -63, -62, -62, -64,
  116473. -65, -64, -61, -62, -63, -64, -66, -68,
  116474. -73, -73, -74, -75, -76, -81, -83, -85,
  116475. -88, -89, -92, -95, -100, -108, -999, -999,
  116476. -999, -999, -999, -999, -999, -999, -999, -999,
  116477. -999, -999, -999, -999, -999, -999, -999, -999},
  116478. { -80, -75, -71, -68, -65, -63, -62, -61,
  116479. -61, -61, -61, -59, -56, -57, -53, -50,
  116480. -58, -52, -50, -50, -52, -53, -54, -58,
  116481. -67, -63, -67, -68, -72, -75, -78, -80,
  116482. -81, -81, -82, -85, -89, -90, -93, -97,
  116483. -101, -107, -114, -999, -999, -999, -999, -999,
  116484. -999, -999, -999, -999, -999, -999, -999, -999},
  116485. { -65, -61, -59, -57, -56, -55, -55, -56,
  116486. -56, -57, -55, -53, -52, -47, -44, -44,
  116487. -50, -44, -41, -39, -39, -42, -40, -46,
  116488. -51, -49, -50, -53, -54, -63, -60, -61,
  116489. -62, -66, -66, -66, -70, -73, -74, -75,
  116490. -76, -75, -79, -85, -89, -91, -96, -102,
  116491. -110, -999, -999, -999, -999, -999, -999, -999},
  116492. { -52, -50, -49, -49, -48, -48, -48, -49,
  116493. -50, -50, -49, -46, -43, -39, -35, -33,
  116494. -38, -36, -32, -29, -32, -32, -32, -35,
  116495. -44, -39, -38, -38, -46, -50, -45, -46,
  116496. -53, -50, -50, -50, -54, -54, -53, -53,
  116497. -56, -57, -59, -66, -70, -72, -74, -79,
  116498. -83, -85, -90, -97, -114, -999, -999, -999}},
  116499. /* 250 Hz */
  116500. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116501. -100, -95, -90, -86, -80, -75, -75, -79,
  116502. -80, -79, -80, -81, -82, -88, -95, -103,
  116503. -110, -999, -999, -999, -999, -999, -999, -999,
  116504. -999, -999, -999, -999, -999, -999, -999, -999,
  116505. -999, -999, -999, -999, -999, -999, -999, -999,
  116506. -999, -999, -999, -999, -999, -999, -999, -999},
  116507. {-999, -999, -999, -999, -108, -103, -98, -93,
  116508. -88, -83, -79, -78, -75, -71, -67, -68,
  116509. -73, -73, -72, -73, -75, -77, -80, -82,
  116510. -88, -93, -100, -107, -114, -999, -999, -999,
  116511. -999, -999, -999, -999, -999, -999, -999, -999,
  116512. -999, -999, -999, -999, -999, -999, -999, -999,
  116513. -999, -999, -999, -999, -999, -999, -999, -999},
  116514. {-999, -999, -999, -110, -105, -101, -96, -90,
  116515. -86, -81, -77, -73, -69, -66, -61, -62,
  116516. -66, -64, -62, -65, -66, -70, -72, -76,
  116517. -81, -80, -84, -90, -95, -102, -110, -999,
  116518. -999, -999, -999, -999, -999, -999, -999, -999,
  116519. -999, -999, -999, -999, -999, -999, -999, -999,
  116520. -999, -999, -999, -999, -999, -999, -999, -999},
  116521. {-999, -999, -999, -107, -103, -97, -92, -88,
  116522. -83, -79, -74, -70, -66, -59, -53, -58,
  116523. -62, -55, -54, -54, -54, -58, -61, -62,
  116524. -72, -70, -72, -75, -78, -80, -81, -80,
  116525. -83, -83, -88, -93, -100, -107, -115, -999,
  116526. -999, -999, -999, -999, -999, -999, -999, -999,
  116527. -999, -999, -999, -999, -999, -999, -999, -999},
  116528. {-999, -999, -999, -105, -100, -95, -90, -85,
  116529. -80, -75, -70, -66, -62, -56, -48, -44,
  116530. -48, -46, -46, -43, -46, -48, -48, -51,
  116531. -58, -58, -59, -60, -62, -62, -61, -61,
  116532. -65, -64, -65, -68, -70, -74, -75, -78,
  116533. -81, -86, -95, -110, -999, -999, -999, -999,
  116534. -999, -999, -999, -999, -999, -999, -999, -999},
  116535. {-999, -999, -105, -100, -95, -90, -85, -80,
  116536. -75, -70, -65, -61, -55, -49, -39, -33,
  116537. -40, -35, -32, -38, -40, -33, -35, -37,
  116538. -46, -41, -45, -44, -46, -42, -45, -46,
  116539. -52, -50, -50, -50, -54, -54, -55, -57,
  116540. -62, -64, -66, -68, -70, -76, -81, -90,
  116541. -100, -110, -999, -999, -999, -999, -999, -999}},
  116542. /* 354 hz */
  116543. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116544. -105, -98, -90, -85, -82, -83, -80, -78,
  116545. -84, -79, -80, -83, -87, -89, -91, -93,
  116546. -99, -106, -117, -999, -999, -999, -999, -999,
  116547. -999, -999, -999, -999, -999, -999, -999, -999,
  116548. -999, -999, -999, -999, -999, -999, -999, -999,
  116549. -999, -999, -999, -999, -999, -999, -999, -999},
  116550. {-999, -999, -999, -999, -999, -999, -999, -999,
  116551. -105, -98, -90, -85, -80, -75, -70, -68,
  116552. -74, -72, -74, -77, -80, -82, -85, -87,
  116553. -92, -89, -91, -95, -100, -106, -112, -999,
  116554. -999, -999, -999, -999, -999, -999, -999, -999,
  116555. -999, -999, -999, -999, -999, -999, -999, -999,
  116556. -999, -999, -999, -999, -999, -999, -999, -999},
  116557. {-999, -999, -999, -999, -999, -999, -999, -999,
  116558. -105, -98, -90, -83, -75, -71, -63, -64,
  116559. -67, -62, -64, -67, -70, -73, -77, -81,
  116560. -84, -83, -85, -89, -90, -93, -98, -104,
  116561. -109, -114, -999, -999, -999, -999, -999, -999,
  116562. -999, -999, -999, -999, -999, -999, -999, -999,
  116563. -999, -999, -999, -999, -999, -999, -999, -999},
  116564. {-999, -999, -999, -999, -999, -999, -999, -999,
  116565. -103, -96, -88, -81, -75, -68, -58, -54,
  116566. -56, -54, -56, -56, -58, -60, -63, -66,
  116567. -74, -69, -72, -72, -75, -74, -77, -81,
  116568. -81, -82, -84, -87, -93, -96, -99, -104,
  116569. -110, -999, -999, -999, -999, -999, -999, -999,
  116570. -999, -999, -999, -999, -999, -999, -999, -999},
  116571. {-999, -999, -999, -999, -999, -108, -102, -96,
  116572. -91, -85, -80, -74, -68, -60, -51, -46,
  116573. -48, -46, -43, -45, -47, -47, -49, -48,
  116574. -56, -53, -55, -58, -57, -63, -58, -60,
  116575. -66, -64, -67, -70, -70, -74, -77, -84,
  116576. -86, -89, -91, -93, -94, -101, -109, -118,
  116577. -999, -999, -999, -999, -999, -999, -999, -999},
  116578. {-999, -999, -999, -108, -103, -98, -93, -88,
  116579. -83, -78, -73, -68, -60, -53, -44, -35,
  116580. -38, -38, -34, -34, -36, -40, -41, -44,
  116581. -51, -45, -46, -47, -46, -54, -50, -49,
  116582. -50, -50, -50, -51, -54, -57, -58, -60,
  116583. -66, -66, -66, -64, -65, -68, -77, -82,
  116584. -87, -95, -110, -999, -999, -999, -999, -999}},
  116585. /* 500 Hz */
  116586. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116587. -107, -102, -97, -92, -87, -83, -78, -75,
  116588. -82, -79, -83, -85, -89, -92, -95, -98,
  116589. -101, -105, -109, -113, -999, -999, -999, -999,
  116590. -999, -999, -999, -999, -999, -999, -999, -999,
  116591. -999, -999, -999, -999, -999, -999, -999, -999,
  116592. -999, -999, -999, -999, -999, -999, -999, -999},
  116593. {-999, -999, -999, -999, -999, -999, -999, -106,
  116594. -100, -95, -90, -86, -81, -78, -74, -69,
  116595. -74, -74, -76, -79, -83, -84, -86, -89,
  116596. -92, -97, -93, -100, -103, -107, -110, -999,
  116597. -999, -999, -999, -999, -999, -999, -999, -999,
  116598. -999, -999, -999, -999, -999, -999, -999, -999,
  116599. -999, -999, -999, -999, -999, -999, -999, -999},
  116600. {-999, -999, -999, -999, -999, -999, -106, -100,
  116601. -95, -90, -87, -83, -80, -75, -69, -60,
  116602. -66, -66, -68, -70, -74, -78, -79, -81,
  116603. -81, -83, -84, -87, -93, -96, -99, -103,
  116604. -107, -110, -999, -999, -999, -999, -999, -999,
  116605. -999, -999, -999, -999, -999, -999, -999, -999,
  116606. -999, -999, -999, -999, -999, -999, -999, -999},
  116607. {-999, -999, -999, -999, -999, -108, -103, -98,
  116608. -93, -89, -85, -82, -78, -71, -62, -55,
  116609. -58, -58, -54, -54, -55, -59, -61, -62,
  116610. -70, -66, -66, -67, -70, -72, -75, -78,
  116611. -84, -84, -84, -88, -91, -90, -95, -98,
  116612. -102, -103, -106, -110, -999, -999, -999, -999,
  116613. -999, -999, -999, -999, -999, -999, -999, -999},
  116614. {-999, -999, -999, -999, -108, -103, -98, -94,
  116615. -90, -87, -82, -79, -73, -67, -58, -47,
  116616. -50, -45, -41, -45, -48, -44, -44, -49,
  116617. -54, -51, -48, -47, -49, -50, -51, -57,
  116618. -58, -60, -63, -69, -70, -69, -71, -74,
  116619. -78, -82, -90, -95, -101, -105, -110, -999,
  116620. -999, -999, -999, -999, -999, -999, -999, -999},
  116621. {-999, -999, -999, -105, -101, -97, -93, -90,
  116622. -85, -80, -77, -72, -65, -56, -48, -37,
  116623. -40, -36, -34, -40, -50, -47, -38, -41,
  116624. -47, -38, -35, -39, -38, -43, -40, -45,
  116625. -50, -45, -44, -47, -50, -55, -48, -48,
  116626. -52, -66, -70, -76, -82, -90, -97, -105,
  116627. -110, -999, -999, -999, -999, -999, -999, -999}},
  116628. /* 707 Hz */
  116629. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116630. -999, -108, -103, -98, -93, -86, -79, -76,
  116631. -83, -81, -85, -87, -89, -93, -98, -102,
  116632. -107, -112, -999, -999, -999, -999, -999, -999,
  116633. -999, -999, -999, -999, -999, -999, -999, -999,
  116634. -999, -999, -999, -999, -999, -999, -999, -999,
  116635. -999, -999, -999, -999, -999, -999, -999, -999},
  116636. {-999, -999, -999, -999, -999, -999, -999, -999,
  116637. -999, -108, -103, -98, -93, -86, -79, -71,
  116638. -77, -74, -77, -79, -81, -84, -85, -90,
  116639. -92, -93, -92, -98, -101, -108, -112, -999,
  116640. -999, -999, -999, -999, -999, -999, -999, -999,
  116641. -999, -999, -999, -999, -999, -999, -999, -999,
  116642. -999, -999, -999, -999, -999, -999, -999, -999},
  116643. {-999, -999, -999, -999, -999, -999, -999, -999,
  116644. -108, -103, -98, -93, -87, -78, -68, -65,
  116645. -66, -62, -65, -67, -70, -73, -75, -78,
  116646. -82, -82, -83, -84, -91, -93, -98, -102,
  116647. -106, -110, -999, -999, -999, -999, -999, -999,
  116648. -999, -999, -999, -999, -999, -999, -999, -999,
  116649. -999, -999, -999, -999, -999, -999, -999, -999},
  116650. {-999, -999, -999, -999, -999, -999, -999, -999,
  116651. -105, -100, -95, -90, -82, -74, -62, -57,
  116652. -58, -56, -51, -52, -52, -54, -54, -58,
  116653. -66, -59, -60, -63, -66, -69, -73, -79,
  116654. -83, -84, -80, -81, -81, -82, -88, -92,
  116655. -98, -105, -113, -999, -999, -999, -999, -999,
  116656. -999, -999, -999, -999, -999, -999, -999, -999},
  116657. {-999, -999, -999, -999, -999, -999, -999, -107,
  116658. -102, -97, -92, -84, -79, -69, -57, -47,
  116659. -52, -47, -44, -45, -50, -52, -42, -42,
  116660. -53, -43, -43, -48, -51, -56, -55, -52,
  116661. -57, -59, -61, -62, -67, -71, -78, -83,
  116662. -86, -94, -98, -103, -110, -999, -999, -999,
  116663. -999, -999, -999, -999, -999, -999, -999, -999},
  116664. {-999, -999, -999, -999, -999, -999, -105, -100,
  116665. -95, -90, -84, -78, -70, -61, -51, -41,
  116666. -40, -38, -40, -46, -52, -51, -41, -40,
  116667. -46, -40, -38, -38, -41, -46, -41, -46,
  116668. -47, -43, -43, -45, -41, -45, -56, -67,
  116669. -68, -83, -87, -90, -95, -102, -107, -113,
  116670. -999, -999, -999, -999, -999, -999, -999, -999}},
  116671. /* 1000 Hz */
  116672. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116673. -999, -109, -105, -101, -96, -91, -84, -77,
  116674. -82, -82, -85, -89, -94, -100, -106, -110,
  116675. -999, -999, -999, -999, -999, -999, -999, -999,
  116676. -999, -999, -999, -999, -999, -999, -999, -999,
  116677. -999, -999, -999, -999, -999, -999, -999, -999,
  116678. -999, -999, -999, -999, -999, -999, -999, -999},
  116679. {-999, -999, -999, -999, -999, -999, -999, -999,
  116680. -999, -106, -103, -98, -92, -85, -80, -71,
  116681. -75, -72, -76, -80, -84, -86, -89, -93,
  116682. -100, -107, -113, -999, -999, -999, -999, -999,
  116683. -999, -999, -999, -999, -999, -999, -999, -999,
  116684. -999, -999, -999, -999, -999, -999, -999, -999,
  116685. -999, -999, -999, -999, -999, -999, -999, -999},
  116686. {-999, -999, -999, -999, -999, -999, -999, -107,
  116687. -104, -101, -97, -92, -88, -84, -80, -64,
  116688. -66, -63, -64, -66, -69, -73, -77, -83,
  116689. -83, -86, -91, -98, -104, -111, -999, -999,
  116690. -999, -999, -999, -999, -999, -999, -999, -999,
  116691. -999, -999, -999, -999, -999, -999, -999, -999,
  116692. -999, -999, -999, -999, -999, -999, -999, -999},
  116693. {-999, -999, -999, -999, -999, -999, -999, -107,
  116694. -104, -101, -97, -92, -90, -84, -74, -57,
  116695. -58, -52, -55, -54, -50, -52, -50, -52,
  116696. -63, -62, -69, -76, -77, -78, -78, -79,
  116697. -82, -88, -94, -100, -106, -111, -999, -999,
  116698. -999, -999, -999, -999, -999, -999, -999, -999,
  116699. -999, -999, -999, -999, -999, -999, -999, -999},
  116700. {-999, -999, -999, -999, -999, -999, -106, -102,
  116701. -98, -95, -90, -85, -83, -78, -70, -50,
  116702. -50, -41, -44, -49, -47, -50, -50, -44,
  116703. -55, -46, -47, -48, -48, -54, -49, -49,
  116704. -58, -62, -71, -81, -87, -92, -97, -102,
  116705. -108, -114, -999, -999, -999, -999, -999, -999,
  116706. -999, -999, -999, -999, -999, -999, -999, -999},
  116707. {-999, -999, -999, -999, -999, -999, -106, -102,
  116708. -98, -95, -90, -85, -83, -78, -70, -45,
  116709. -43, -41, -47, -50, -51, -50, -49, -45,
  116710. -47, -41, -44, -41, -39, -43, -38, -37,
  116711. -40, -41, -44, -50, -58, -65, -73, -79,
  116712. -85, -92, -97, -101, -105, -109, -113, -999,
  116713. -999, -999, -999, -999, -999, -999, -999, -999}},
  116714. /* 1414 Hz */
  116715. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116716. -999, -999, -999, -107, -100, -95, -87, -81,
  116717. -85, -83, -88, -93, -100, -107, -114, -999,
  116718. -999, -999, -999, -999, -999, -999, -999, -999,
  116719. -999, -999, -999, -999, -999, -999, -999, -999,
  116720. -999, -999, -999, -999, -999, -999, -999, -999,
  116721. -999, -999, -999, -999, -999, -999, -999, -999},
  116722. {-999, -999, -999, -999, -999, -999, -999, -999,
  116723. -999, -999, -107, -101, -95, -88, -83, -76,
  116724. -73, -72, -79, -84, -90, -95, -100, -105,
  116725. -110, -115, -999, -999, -999, -999, -999, -999,
  116726. -999, -999, -999, -999, -999, -999, -999, -999,
  116727. -999, -999, -999, -999, -999, -999, -999, -999,
  116728. -999, -999, -999, -999, -999, -999, -999, -999},
  116729. {-999, -999, -999, -999, -999, -999, -999, -999,
  116730. -999, -999, -104, -98, -92, -87, -81, -70,
  116731. -65, -62, -67, -71, -74, -80, -85, -91,
  116732. -95, -99, -103, -108, -111, -114, -999, -999,
  116733. -999, -999, -999, -999, -999, -999, -999, -999,
  116734. -999, -999, -999, -999, -999, -999, -999, -999,
  116735. -999, -999, -999, -999, -999, -999, -999, -999},
  116736. {-999, -999, -999, -999, -999, -999, -999, -999,
  116737. -999, -999, -103, -97, -90, -85, -76, -60,
  116738. -56, -54, -60, -62, -61, -56, -63, -65,
  116739. -73, -74, -77, -75, -78, -81, -86, -87,
  116740. -88, -91, -94, -98, -103, -110, -999, -999,
  116741. -999, -999, -999, -999, -999, -999, -999, -999,
  116742. -999, -999, -999, -999, -999, -999, -999, -999},
  116743. {-999, -999, -999, -999, -999, -999, -999, -105,
  116744. -100, -97, -92, -86, -81, -79, -70, -57,
  116745. -51, -47, -51, -58, -60, -56, -53, -50,
  116746. -58, -52, -50, -50, -53, -55, -64, -69,
  116747. -71, -85, -82, -78, -81, -85, -95, -102,
  116748. -112, -999, -999, -999, -999, -999, -999, -999,
  116749. -999, -999, -999, -999, -999, -999, -999, -999},
  116750. {-999, -999, -999, -999, -999, -999, -999, -105,
  116751. -100, -97, -92, -85, -83, -79, -72, -49,
  116752. -40, -43, -43, -54, -56, -51, -50, -40,
  116753. -43, -38, -36, -35, -37, -38, -37, -44,
  116754. -54, -60, -57, -60, -70, -75, -84, -92,
  116755. -103, -112, -999, -999, -999, -999, -999, -999,
  116756. -999, -999, -999, -999, -999, -999, -999, -999}},
  116757. /* 2000 Hz */
  116758. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116759. -999, -999, -999, -110, -102, -95, -89, -82,
  116760. -83, -84, -90, -92, -99, -107, -113, -999,
  116761. -999, -999, -999, -999, -999, -999, -999, -999,
  116762. -999, -999, -999, -999, -999, -999, -999, -999,
  116763. -999, -999, -999, -999, -999, -999, -999, -999,
  116764. -999, -999, -999, -999, -999, -999, -999, -999},
  116765. {-999, -999, -999, -999, -999, -999, -999, -999,
  116766. -999, -999, -107, -101, -95, -89, -83, -72,
  116767. -74, -78, -85, -88, -88, -90, -92, -98,
  116768. -105, -111, -999, -999, -999, -999, -999, -999,
  116769. -999, -999, -999, -999, -999, -999, -999, -999,
  116770. -999, -999, -999, -999, -999, -999, -999, -999,
  116771. -999, -999, -999, -999, -999, -999, -999, -999},
  116772. {-999, -999, -999, -999, -999, -999, -999, -999,
  116773. -999, -109, -103, -97, -93, -87, -81, -70,
  116774. -70, -67, -75, -73, -76, -79, -81, -83,
  116775. -88, -89, -97, -103, -110, -999, -999, -999,
  116776. -999, -999, -999, -999, -999, -999, -999, -999,
  116777. -999, -999, -999, -999, -999, -999, -999, -999,
  116778. -999, -999, -999, -999, -999, -999, -999, -999},
  116779. {-999, -999, -999, -999, -999, -999, -999, -999,
  116780. -999, -107, -100, -94, -88, -83, -75, -63,
  116781. -59, -59, -63, -66, -60, -62, -67, -67,
  116782. -77, -76, -81, -88, -86, -92, -96, -102,
  116783. -109, -116, -999, -999, -999, -999, -999, -999,
  116784. -999, -999, -999, -999, -999, -999, -999, -999,
  116785. -999, -999, -999, -999, -999, -999, -999, -999},
  116786. {-999, -999, -999, -999, -999, -999, -999, -999,
  116787. -999, -105, -98, -92, -86, -81, -73, -56,
  116788. -52, -47, -55, -60, -58, -52, -51, -45,
  116789. -49, -50, -53, -54, -61, -71, -70, -69,
  116790. -78, -79, -87, -90, -96, -104, -112, -999,
  116791. -999, -999, -999, -999, -999, -999, -999, -999,
  116792. -999, -999, -999, -999, -999, -999, -999, -999},
  116793. {-999, -999, -999, -999, -999, -999, -999, -999,
  116794. -999, -103, -96, -90, -86, -78, -70, -51,
  116795. -42, -47, -48, -55, -54, -54, -53, -42,
  116796. -35, -28, -33, -38, -37, -44, -47, -49,
  116797. -54, -63, -68, -78, -82, -89, -94, -99,
  116798. -104, -109, -114, -999, -999, -999, -999, -999,
  116799. -999, -999, -999, -999, -999, -999, -999, -999}},
  116800. /* 2828 Hz */
  116801. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116802. -999, -999, -999, -999, -110, -100, -90, -79,
  116803. -85, -81, -82, -82, -89, -94, -99, -103,
  116804. -109, -115, -999, -999, -999, -999, -999, -999,
  116805. -999, -999, -999, -999, -999, -999, -999, -999,
  116806. -999, -999, -999, -999, -999, -999, -999, -999,
  116807. -999, -999, -999, -999, -999, -999, -999, -999},
  116808. {-999, -999, -999, -999, -999, -999, -999, -999,
  116809. -999, -999, -999, -999, -105, -97, -85, -72,
  116810. -74, -70, -70, -70, -76, -85, -91, -93,
  116811. -97, -103, -109, -115, -999, -999, -999, -999,
  116812. -999, -999, -999, -999, -999, -999, -999, -999,
  116813. -999, -999, -999, -999, -999, -999, -999, -999,
  116814. -999, -999, -999, -999, -999, -999, -999, -999},
  116815. {-999, -999, -999, -999, -999, -999, -999, -999,
  116816. -999, -999, -999, -999, -112, -93, -81, -68,
  116817. -62, -60, -60, -57, -63, -70, -77, -82,
  116818. -90, -93, -98, -104, -109, -113, -999, -999,
  116819. -999, -999, -999, -999, -999, -999, -999, -999,
  116820. -999, -999, -999, -999, -999, -999, -999, -999,
  116821. -999, -999, -999, -999, -999, -999, -999, -999},
  116822. {-999, -999, -999, -999, -999, -999, -999, -999,
  116823. -999, -999, -999, -113, -100, -93, -84, -63,
  116824. -58, -48, -53, -54, -52, -52, -57, -64,
  116825. -66, -76, -83, -81, -85, -85, -90, -95,
  116826. -98, -101, -103, -106, -108, -111, -999, -999,
  116827. -999, -999, -999, -999, -999, -999, -999, -999,
  116828. -999, -999, -999, -999, -999, -999, -999, -999},
  116829. {-999, -999, -999, -999, -999, -999, -999, -999,
  116830. -999, -999, -999, -105, -95, -86, -74, -53,
  116831. -50, -38, -43, -49, -43, -42, -39, -39,
  116832. -46, -52, -57, -56, -72, -69, -74, -81,
  116833. -87, -92, -94, -97, -99, -102, -105, -108,
  116834. -999, -999, -999, -999, -999, -999, -999, -999,
  116835. -999, -999, -999, -999, -999, -999, -999, -999},
  116836. {-999, -999, -999, -999, -999, -999, -999, -999,
  116837. -999, -999, -108, -99, -90, -76, -66, -45,
  116838. -43, -41, -44, -47, -43, -47, -40, -30,
  116839. -31, -31, -39, -33, -40, -41, -43, -53,
  116840. -59, -70, -73, -77, -79, -82, -84, -87,
  116841. -999, -999, -999, -999, -999, -999, -999, -999,
  116842. -999, -999, -999, -999, -999, -999, -999, -999}},
  116843. /* 4000 Hz */
  116844. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116845. -999, -999, -999, -999, -999, -110, -91, -76,
  116846. -75, -85, -93, -98, -104, -110, -999, -999,
  116847. -999, -999, -999, -999, -999, -999, -999, -999,
  116848. -999, -999, -999, -999, -999, -999, -999, -999,
  116849. -999, -999, -999, -999, -999, -999, -999, -999,
  116850. -999, -999, -999, -999, -999, -999, -999, -999},
  116851. {-999, -999, -999, -999, -999, -999, -999, -999,
  116852. -999, -999, -999, -999, -999, -110, -91, -70,
  116853. -70, -75, -86, -89, -94, -98, -101, -106,
  116854. -110, -999, -999, -999, -999, -999, -999, -999,
  116855. -999, -999, -999, -999, -999, -999, -999, -999,
  116856. -999, -999, -999, -999, -999, -999, -999, -999,
  116857. -999, -999, -999, -999, -999, -999, -999, -999},
  116858. {-999, -999, -999, -999, -999, -999, -999, -999,
  116859. -999, -999, -999, -999, -110, -95, -80, -60,
  116860. -65, -64, -74, -83, -88, -91, -95, -99,
  116861. -103, -107, -110, -999, -999, -999, -999, -999,
  116862. -999, -999, -999, -999, -999, -999, -999, -999,
  116863. -999, -999, -999, -999, -999, -999, -999, -999,
  116864. -999, -999, -999, -999, -999, -999, -999, -999},
  116865. {-999, -999, -999, -999, -999, -999, -999, -999,
  116866. -999, -999, -999, -999, -110, -95, -80, -58,
  116867. -55, -49, -66, -68, -71, -78, -78, -80,
  116868. -88, -85, -89, -97, -100, -105, -110, -999,
  116869. -999, -999, -999, -999, -999, -999, -999, -999,
  116870. -999, -999, -999, -999, -999, -999, -999, -999,
  116871. -999, -999, -999, -999, -999, -999, -999, -999},
  116872. {-999, -999, -999, -999, -999, -999, -999, -999,
  116873. -999, -999, -999, -999, -110, -95, -80, -53,
  116874. -52, -41, -59, -59, -49, -58, -56, -63,
  116875. -86, -79, -90, -93, -98, -103, -107, -112,
  116876. -999, -999, -999, -999, -999, -999, -999, -999,
  116877. -999, -999, -999, -999, -999, -999, -999, -999,
  116878. -999, -999, -999, -999, -999, -999, -999, -999},
  116879. {-999, -999, -999, -999, -999, -999, -999, -999,
  116880. -999, -999, -999, -110, -97, -91, -73, -45,
  116881. -40, -33, -53, -61, -49, -54, -50, -50,
  116882. -60, -52, -67, -74, -81, -92, -96, -100,
  116883. -105, -110, -999, -999, -999, -999, -999, -999,
  116884. -999, -999, -999, -999, -999, -999, -999, -999,
  116885. -999, -999, -999, -999, -999, -999, -999, -999}},
  116886. /* 5657 Hz */
  116887. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116888. -999, -999, -999, -113, -106, -99, -92, -77,
  116889. -80, -88, -97, -106, -115, -999, -999, -999,
  116890. -999, -999, -999, -999, -999, -999, -999, -999,
  116891. -999, -999, -999, -999, -999, -999, -999, -999,
  116892. -999, -999, -999, -999, -999, -999, -999, -999,
  116893. -999, -999, -999, -999, -999, -999, -999, -999},
  116894. {-999, -999, -999, -999, -999, -999, -999, -999,
  116895. -999, -999, -116, -109, -102, -95, -89, -74,
  116896. -72, -88, -87, -95, -102, -109, -116, -999,
  116897. -999, -999, -999, -999, -999, -999, -999, -999,
  116898. -999, -999, -999, -999, -999, -999, -999, -999,
  116899. -999, -999, -999, -999, -999, -999, -999, -999,
  116900. -999, -999, -999, -999, -999, -999, -999, -999},
  116901. {-999, -999, -999, -999, -999, -999, -999, -999,
  116902. -999, -999, -116, -109, -102, -95, -89, -75,
  116903. -66, -74, -77, -78, -86, -87, -90, -96,
  116904. -105, -115, -999, -999, -999, -999, -999, -999,
  116905. -999, -999, -999, -999, -999, -999, -999, -999,
  116906. -999, -999, -999, -999, -999, -999, -999, -999,
  116907. -999, -999, -999, -999, -999, -999, -999, -999},
  116908. {-999, -999, -999, -999, -999, -999, -999, -999,
  116909. -999, -999, -115, -108, -101, -94, -88, -66,
  116910. -56, -61, -70, -65, -78, -72, -83, -84,
  116911. -93, -98, -105, -110, -999, -999, -999, -999,
  116912. -999, -999, -999, -999, -999, -999, -999, -999,
  116913. -999, -999, -999, -999, -999, -999, -999, -999,
  116914. -999, -999, -999, -999, -999, -999, -999, -999},
  116915. {-999, -999, -999, -999, -999, -999, -999, -999,
  116916. -999, -999, -110, -105, -95, -89, -82, -57,
  116917. -52, -52, -59, -56, -59, -58, -69, -67,
  116918. -88, -82, -82, -89, -94, -100, -108, -999,
  116919. -999, -999, -999, -999, -999, -999, -999, -999,
  116920. -999, -999, -999, -999, -999, -999, -999, -999,
  116921. -999, -999, -999, -999, -999, -999, -999, -999},
  116922. {-999, -999, -999, -999, -999, -999, -999, -999,
  116923. -999, -110, -101, -96, -90, -83, -77, -54,
  116924. -43, -38, -50, -48, -52, -48, -42, -42,
  116925. -51, -52, -53, -59, -65, -71, -78, -85,
  116926. -95, -999, -999, -999, -999, -999, -999, -999,
  116927. -999, -999, -999, -999, -999, -999, -999, -999,
  116928. -999, -999, -999, -999, -999, -999, -999, -999}},
  116929. /* 8000 Hz */
  116930. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116931. -999, -999, -999, -999, -120, -105, -86, -68,
  116932. -78, -79, -90, -100, -110, -999, -999, -999,
  116933. -999, -999, -999, -999, -999, -999, -999, -999,
  116934. -999, -999, -999, -999, -999, -999, -999, -999,
  116935. -999, -999, -999, -999, -999, -999, -999, -999,
  116936. -999, -999, -999, -999, -999, -999, -999, -999},
  116937. {-999, -999, -999, -999, -999, -999, -999, -999,
  116938. -999, -999, -999, -999, -120, -105, -86, -66,
  116939. -73, -77, -88, -96, -105, -115, -999, -999,
  116940. -999, -999, -999, -999, -999, -999, -999, -999,
  116941. -999, -999, -999, -999, -999, -999, -999, -999,
  116942. -999, -999, -999, -999, -999, -999, -999, -999,
  116943. -999, -999, -999, -999, -999, -999, -999, -999},
  116944. {-999, -999, -999, -999, -999, -999, -999, -999,
  116945. -999, -999, -999, -120, -105, -92, -80, -61,
  116946. -64, -68, -80, -87, -92, -100, -110, -999,
  116947. -999, -999, -999, -999, -999, -999, -999, -999,
  116948. -999, -999, -999, -999, -999, -999, -999, -999,
  116949. -999, -999, -999, -999, -999, -999, -999, -999,
  116950. -999, -999, -999, -999, -999, -999, -999, -999},
  116951. {-999, -999, -999, -999, -999, -999, -999, -999,
  116952. -999, -999, -999, -120, -104, -91, -79, -52,
  116953. -60, -54, -64, -69, -77, -80, -82, -84,
  116954. -85, -87, -88, -90, -999, -999, -999, -999,
  116955. -999, -999, -999, -999, -999, -999, -999, -999,
  116956. -999, -999, -999, -999, -999, -999, -999, -999,
  116957. -999, -999, -999, -999, -999, -999, -999, -999},
  116958. {-999, -999, -999, -999, -999, -999, -999, -999,
  116959. -999, -999, -999, -118, -100, -87, -77, -49,
  116960. -50, -44, -58, -61, -61, -67, -65, -62,
  116961. -62, -62, -65, -68, -999, -999, -999, -999,
  116962. -999, -999, -999, -999, -999, -999, -999, -999,
  116963. -999, -999, -999, -999, -999, -999, -999, -999,
  116964. -999, -999, -999, -999, -999, -999, -999, -999},
  116965. {-999, -999, -999, -999, -999, -999, -999, -999,
  116966. -999, -999, -999, -115, -98, -84, -62, -49,
  116967. -44, -38, -46, -49, -49, -46, -39, -37,
  116968. -39, -40, -42, -43, -999, -999, -999, -999,
  116969. -999, -999, -999, -999, -999, -999, -999, -999,
  116970. -999, -999, -999, -999, -999, -999, -999, -999,
  116971. -999, -999, -999, -999, -999, -999, -999, -999}},
  116972. /* 11314 Hz */
  116973. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116974. -999, -999, -999, -999, -999, -110, -88, -74,
  116975. -77, -82, -82, -85, -90, -94, -99, -104,
  116976. -999, -999, -999, -999, -999, -999, -999, -999,
  116977. -999, -999, -999, -999, -999, -999, -999, -999,
  116978. -999, -999, -999, -999, -999, -999, -999, -999,
  116979. -999, -999, -999, -999, -999, -999, -999, -999},
  116980. {-999, -999, -999, -999, -999, -999, -999, -999,
  116981. -999, -999, -999, -999, -999, -110, -88, -66,
  116982. -70, -81, -80, -81, -84, -88, -91, -93,
  116983. -999, -999, -999, -999, -999, -999, -999, -999,
  116984. -999, -999, -999, -999, -999, -999, -999, -999,
  116985. -999, -999, -999, -999, -999, -999, -999, -999,
  116986. -999, -999, -999, -999, -999, -999, -999, -999},
  116987. {-999, -999, -999, -999, -999, -999, -999, -999,
  116988. -999, -999, -999, -999, -999, -110, -88, -61,
  116989. -63, -70, -71, -74, -77, -80, -83, -85,
  116990. -999, -999, -999, -999, -999, -999, -999, -999,
  116991. -999, -999, -999, -999, -999, -999, -999, -999,
  116992. -999, -999, -999, -999, -999, -999, -999, -999,
  116993. -999, -999, -999, -999, -999, -999, -999, -999},
  116994. {-999, -999, -999, -999, -999, -999, -999, -999,
  116995. -999, -999, -999, -999, -999, -110, -86, -62,
  116996. -63, -62, -62, -58, -52, -50, -50, -52,
  116997. -54, -999, -999, -999, -999, -999, -999, -999,
  116998. -999, -999, -999, -999, -999, -999, -999, -999,
  116999. -999, -999, -999, -999, -999, -999, -999, -999,
  117000. -999, -999, -999, -999, -999, -999, -999, -999},
  117001. {-999, -999, -999, -999, -999, -999, -999, -999,
  117002. -999, -999, -999, -999, -118, -108, -84, -53,
  117003. -50, -50, -50, -55, -47, -45, -40, -40,
  117004. -40, -999, -999, -999, -999, -999, -999, -999,
  117005. -999, -999, -999, -999, -999, -999, -999, -999,
  117006. -999, -999, -999, -999, -999, -999, -999, -999,
  117007. -999, -999, -999, -999, -999, -999, -999, -999},
  117008. {-999, -999, -999, -999, -999, -999, -999, -999,
  117009. -999, -999, -999, -999, -118, -100, -73, -43,
  117010. -37, -42, -43, -53, -38, -37, -35, -35,
  117011. -38, -999, -999, -999, -999, -999, -999, -999,
  117012. -999, -999, -999, -999, -999, -999, -999, -999,
  117013. -999, -999, -999, -999, -999, -999, -999, -999,
  117014. -999, -999, -999, -999, -999, -999, -999, -999}},
  117015. /* 16000 Hz */
  117016. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117017. -999, -999, -999, -110, -100, -91, -84, -74,
  117018. -80, -80, -80, -80, -80, -999, -999, -999,
  117019. -999, -999, -999, -999, -999, -999, -999, -999,
  117020. -999, -999, -999, -999, -999, -999, -999, -999,
  117021. -999, -999, -999, -999, -999, -999, -999, -999,
  117022. -999, -999, -999, -999, -999, -999, -999, -999},
  117023. {-999, -999, -999, -999, -999, -999, -999, -999,
  117024. -999, -999, -999, -110, -100, -91, -84, -74,
  117025. -68, -68, -68, -68, -68, -999, -999, -999,
  117026. -999, -999, -999, -999, -999, -999, -999, -999,
  117027. -999, -999, -999, -999, -999, -999, -999, -999,
  117028. -999, -999, -999, -999, -999, -999, -999, -999,
  117029. -999, -999, -999, -999, -999, -999, -999, -999},
  117030. {-999, -999, -999, -999, -999, -999, -999, -999,
  117031. -999, -999, -999, -110, -100, -86, -78, -70,
  117032. -60, -45, -30, -21, -999, -999, -999, -999,
  117033. -999, -999, -999, -999, -999, -999, -999, -999,
  117034. -999, -999, -999, -999, -999, -999, -999, -999,
  117035. -999, -999, -999, -999, -999, -999, -999, -999,
  117036. -999, -999, -999, -999, -999, -999, -999, -999},
  117037. {-999, -999, -999, -999, -999, -999, -999, -999,
  117038. -999, -999, -999, -110, -100, -87, -78, -67,
  117039. -48, -38, -29, -21, -999, -999, -999, -999,
  117040. -999, -999, -999, -999, -999, -999, -999, -999,
  117041. -999, -999, -999, -999, -999, -999, -999, -999,
  117042. -999, -999, -999, -999, -999, -999, -999, -999,
  117043. -999, -999, -999, -999, -999, -999, -999, -999},
  117044. {-999, -999, -999, -999, -999, -999, -999, -999,
  117045. -999, -999, -999, -110, -100, -86, -69, -56,
  117046. -45, -35, -33, -29, -999, -999, -999, -999,
  117047. -999, -999, -999, -999, -999, -999, -999, -999,
  117048. -999, -999, -999, -999, -999, -999, -999, -999,
  117049. -999, -999, -999, -999, -999, -999, -999, -999,
  117050. -999, -999, -999, -999, -999, -999, -999, -999},
  117051. {-999, -999, -999, -999, -999, -999, -999, -999,
  117052. -999, -999, -999, -110, -100, -83, -71, -48,
  117053. -27, -38, -37, -34, -999, -999, -999, -999,
  117054. -999, -999, -999, -999, -999, -999, -999, -999,
  117055. -999, -999, -999, -999, -999, -999, -999, -999,
  117056. -999, -999, -999, -999, -999, -999, -999, -999,
  117057. -999, -999, -999, -999, -999, -999, -999, -999}}
  117058. };
  117059. #endif
  117060. /*** End of inlined file: masking.h ***/
  117061. #define NEGINF -9999.f
  117062. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  117063. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  117064. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  117065. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117066. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117067. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  117068. look->channels=vi->channels;
  117069. look->ampmax=-9999.;
  117070. look->gi=gi;
  117071. return(look);
  117072. }
  117073. void _vp_global_free(vorbis_look_psy_global *look){
  117074. if(look){
  117075. memset(look,0,sizeof(*look));
  117076. _ogg_free(look);
  117077. }
  117078. }
  117079. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117080. if(i){
  117081. memset(i,0,sizeof(*i));
  117082. _ogg_free(i);
  117083. }
  117084. }
  117085. void _vi_psy_free(vorbis_info_psy *i){
  117086. if(i){
  117087. memset(i,0,sizeof(*i));
  117088. _ogg_free(i);
  117089. }
  117090. }
  117091. static void min_curve(float *c,
  117092. float *c2){
  117093. int i;
  117094. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117095. }
  117096. static void max_curve(float *c,
  117097. float *c2){
  117098. int i;
  117099. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117100. }
  117101. static void attenuate_curve(float *c,float att){
  117102. int i;
  117103. for(i=0;i<EHMER_MAX;i++)
  117104. c[i]+=att;
  117105. }
  117106. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117107. float center_boost, float center_decay_rate){
  117108. int i,j,k,m;
  117109. float ath[EHMER_MAX];
  117110. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117111. float athc[P_LEVELS][EHMER_MAX];
  117112. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117113. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117114. memset(workc,0,sizeof(workc));
  117115. for(i=0;i<P_BANDS;i++){
  117116. /* we add back in the ATH to avoid low level curves falling off to
  117117. -infinity and unnecessarily cutting off high level curves in the
  117118. curve limiting (last step). */
  117119. /* A half-band's settings must be valid over the whole band, and
  117120. it's better to mask too little than too much */
  117121. int ath_offset=i*4;
  117122. for(j=0;j<EHMER_MAX;j++){
  117123. float min=999.;
  117124. for(k=0;k<4;k++)
  117125. if(j+k+ath_offset<MAX_ATH){
  117126. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117127. }else{
  117128. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117129. }
  117130. ath[j]=min;
  117131. }
  117132. /* copy curves into working space, replicate the 50dB curve to 30
  117133. and 40, replicate the 100dB curve to 110 */
  117134. for(j=0;j<6;j++)
  117135. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117136. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117137. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117138. /* apply centered curve boost/decay */
  117139. for(j=0;j<P_LEVELS;j++){
  117140. for(k=0;k<EHMER_MAX;k++){
  117141. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117142. if(adj<0. && center_boost>0)adj=0.;
  117143. if(adj>0. && center_boost<0)adj=0.;
  117144. workc[i][j][k]+=adj;
  117145. }
  117146. }
  117147. /* normalize curves so the driving amplitude is 0dB */
  117148. /* make temp curves with the ATH overlayed */
  117149. for(j=0;j<P_LEVELS;j++){
  117150. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117151. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117152. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117153. max_curve(athc[j],workc[i][j]);
  117154. }
  117155. /* Now limit the louder curves.
  117156. the idea is this: We don't know what the playback attenuation
  117157. will be; 0dB SL moves every time the user twiddles the volume
  117158. knob. So that means we have to use a single 'most pessimal' curve
  117159. for all masking amplitudes, right? Wrong. The *loudest* sound
  117160. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117161. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117162. etc... */
  117163. for(j=1;j<P_LEVELS;j++){
  117164. min_curve(athc[j],athc[j-1]);
  117165. min_curve(workc[i][j],athc[j]);
  117166. }
  117167. }
  117168. for(i=0;i<P_BANDS;i++){
  117169. int hi_curve,lo_curve,bin;
  117170. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117171. /* low frequency curves are measured with greater resolution than
  117172. the MDCT/FFT will actually give us; we want the curve applied
  117173. to the tone data to be pessimistic and thus apply the minimum
  117174. masking possible for a given bin. That means that a single bin
  117175. could span more than one octave and that the curve will be a
  117176. composite of multiple octaves. It also may mean that a single
  117177. bin may span > an eighth of an octave and that the eighth
  117178. octave values may also be composited. */
  117179. /* which octave curves will we be compositing? */
  117180. bin=floor(fromOC(i*.5)/binHz);
  117181. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117182. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117183. if(lo_curve>i)lo_curve=i;
  117184. if(lo_curve<0)lo_curve=0;
  117185. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117186. for(m=0;m<P_LEVELS;m++){
  117187. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117188. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117189. /* render the curve into bins, then pull values back into curve.
  117190. The point is that any inherent subsampling aliasing results in
  117191. a safe minimum */
  117192. for(k=lo_curve;k<=hi_curve;k++){
  117193. int l=0;
  117194. for(j=0;j<EHMER_MAX;j++){
  117195. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117196. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117197. if(lo_bin<0)lo_bin=0;
  117198. if(lo_bin>n)lo_bin=n;
  117199. if(lo_bin<l)l=lo_bin;
  117200. if(hi_bin<0)hi_bin=0;
  117201. if(hi_bin>n)hi_bin=n;
  117202. for(;l<hi_bin && l<n;l++)
  117203. if(brute_buffer[l]>workc[k][m][j])
  117204. brute_buffer[l]=workc[k][m][j];
  117205. }
  117206. for(;l<n;l++)
  117207. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117208. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117209. }
  117210. /* be equally paranoid about being valid up to next half ocatve */
  117211. if(i+1<P_BANDS){
  117212. int l=0;
  117213. k=i+1;
  117214. for(j=0;j<EHMER_MAX;j++){
  117215. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117216. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117217. if(lo_bin<0)lo_bin=0;
  117218. if(lo_bin>n)lo_bin=n;
  117219. if(lo_bin<l)l=lo_bin;
  117220. if(hi_bin<0)hi_bin=0;
  117221. if(hi_bin>n)hi_bin=n;
  117222. for(;l<hi_bin && l<n;l++)
  117223. if(brute_buffer[l]>workc[k][m][j])
  117224. brute_buffer[l]=workc[k][m][j];
  117225. }
  117226. for(;l<n;l++)
  117227. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117228. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117229. }
  117230. for(j=0;j<EHMER_MAX;j++){
  117231. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117232. if(bin<0){
  117233. ret[i][m][j+2]=-999.;
  117234. }else{
  117235. if(bin>=n){
  117236. ret[i][m][j+2]=-999.;
  117237. }else{
  117238. ret[i][m][j+2]=brute_buffer[bin];
  117239. }
  117240. }
  117241. }
  117242. /* add fenceposts */
  117243. for(j=0;j<EHMER_OFFSET;j++)
  117244. if(ret[i][m][j+2]>-200.f)break;
  117245. ret[i][m][0]=j;
  117246. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117247. if(ret[i][m][j+2]>-200.f)
  117248. break;
  117249. ret[i][m][1]=j;
  117250. }
  117251. }
  117252. return(ret);
  117253. }
  117254. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117255. vorbis_info_psy_global *gi,int n,long rate){
  117256. long i,j,lo=-99,hi=1;
  117257. long maxoc;
  117258. memset(p,0,sizeof(*p));
  117259. p->eighth_octave_lines=gi->eighth_octave_lines;
  117260. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117261. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117262. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117263. p->total_octave_lines=maxoc-p->firstoc+1;
  117264. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117265. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117266. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117267. p->vi=vi;
  117268. p->n=n;
  117269. p->rate=rate;
  117270. /* AoTuV HF weighting */
  117271. p->m_val = 1.;
  117272. if(rate < 26000) p->m_val = 0;
  117273. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117274. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117275. /* set up the lookups for a given blocksize and sample rate */
  117276. for(i=0,j=0;i<MAX_ATH-1;i++){
  117277. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117278. float base=ATH[i];
  117279. if(j<endpos){
  117280. float delta=(ATH[i+1]-base)/(endpos-j);
  117281. for(;j<endpos && j<n;j++){
  117282. p->ath[j]=base+100.;
  117283. base+=delta;
  117284. }
  117285. }
  117286. }
  117287. for(i=0;i<n;i++){
  117288. float bark=toBARK(rate/(2*n)*i);
  117289. for(;lo+vi->noisewindowlomin<i &&
  117290. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117291. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117292. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117293. p->bark[i]=((lo-1)<<16)+(hi-1);
  117294. }
  117295. for(i=0;i<n;i++)
  117296. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117297. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117298. vi->tone_centerboost,vi->tone_decay);
  117299. /* set up rolling noise median */
  117300. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117301. for(i=0;i<P_NOISECURVES;i++)
  117302. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117303. for(i=0;i<n;i++){
  117304. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117305. int inthalfoc;
  117306. float del;
  117307. if(halfoc<0)halfoc=0;
  117308. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117309. inthalfoc=(int)halfoc;
  117310. del=halfoc-inthalfoc;
  117311. for(j=0;j<P_NOISECURVES;j++)
  117312. p->noiseoffset[j][i]=
  117313. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117314. p->vi->noiseoff[j][inthalfoc+1]*del;
  117315. }
  117316. #if 0
  117317. {
  117318. static int ls=0;
  117319. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117320. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117321. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117322. }
  117323. #endif
  117324. }
  117325. void _vp_psy_clear(vorbis_look_psy *p){
  117326. int i,j;
  117327. if(p){
  117328. if(p->ath)_ogg_free(p->ath);
  117329. if(p->octave)_ogg_free(p->octave);
  117330. if(p->bark)_ogg_free(p->bark);
  117331. if(p->tonecurves){
  117332. for(i=0;i<P_BANDS;i++){
  117333. for(j=0;j<P_LEVELS;j++){
  117334. _ogg_free(p->tonecurves[i][j]);
  117335. }
  117336. _ogg_free(p->tonecurves[i]);
  117337. }
  117338. _ogg_free(p->tonecurves);
  117339. }
  117340. if(p->noiseoffset){
  117341. for(i=0;i<P_NOISECURVES;i++){
  117342. _ogg_free(p->noiseoffset[i]);
  117343. }
  117344. _ogg_free(p->noiseoffset);
  117345. }
  117346. memset(p,0,sizeof(*p));
  117347. }
  117348. }
  117349. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117350. static void seed_curve(float *seed,
  117351. const float **curves,
  117352. float amp,
  117353. int oc, int n,
  117354. int linesper,float dBoffset){
  117355. int i,post1;
  117356. int seedptr;
  117357. const float *posts,*curve;
  117358. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117359. choice=max(choice,0);
  117360. choice=min(choice,P_LEVELS-1);
  117361. posts=curves[choice];
  117362. curve=posts+2;
  117363. post1=(int)posts[1];
  117364. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117365. for(i=posts[0];i<post1;i++){
  117366. if(seedptr>0){
  117367. float lin=amp+curve[i];
  117368. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117369. }
  117370. seedptr+=linesper;
  117371. if(seedptr>=n)break;
  117372. }
  117373. }
  117374. static void seed_loop(vorbis_look_psy *p,
  117375. const float ***curves,
  117376. const float *f,
  117377. const float *flr,
  117378. float *seed,
  117379. float specmax){
  117380. vorbis_info_psy *vi=p->vi;
  117381. long n=p->n,i;
  117382. float dBoffset=vi->max_curve_dB-specmax;
  117383. /* prime the working vector with peak values */
  117384. for(i=0;i<n;i++){
  117385. float max=f[i];
  117386. long oc=p->octave[i];
  117387. while(i+1<n && p->octave[i+1]==oc){
  117388. i++;
  117389. if(f[i]>max)max=f[i];
  117390. }
  117391. if(max+6.f>flr[i]){
  117392. oc=oc>>p->shiftoc;
  117393. if(oc>=P_BANDS)oc=P_BANDS-1;
  117394. if(oc<0)oc=0;
  117395. seed_curve(seed,
  117396. curves[oc],
  117397. max,
  117398. p->octave[i]-p->firstoc,
  117399. p->total_octave_lines,
  117400. p->eighth_octave_lines,
  117401. dBoffset);
  117402. }
  117403. }
  117404. }
  117405. static void seed_chase(float *seeds, int linesper, long n){
  117406. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117407. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117408. long stack=0;
  117409. long pos=0;
  117410. long i;
  117411. for(i=0;i<n;i++){
  117412. if(stack<2){
  117413. posstack[stack]=i;
  117414. ampstack[stack++]=seeds[i];
  117415. }else{
  117416. while(1){
  117417. if(seeds[i]<ampstack[stack-1]){
  117418. posstack[stack]=i;
  117419. ampstack[stack++]=seeds[i];
  117420. break;
  117421. }else{
  117422. if(i<posstack[stack-1]+linesper){
  117423. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117424. i<posstack[stack-2]+linesper){
  117425. /* we completely overlap, making stack-1 irrelevant. pop it */
  117426. stack--;
  117427. continue;
  117428. }
  117429. }
  117430. posstack[stack]=i;
  117431. ampstack[stack++]=seeds[i];
  117432. break;
  117433. }
  117434. }
  117435. }
  117436. }
  117437. /* the stack now contains only the positions that are relevant. Scan
  117438. 'em straight through */
  117439. for(i=0;i<stack;i++){
  117440. long endpos;
  117441. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117442. endpos=posstack[i+1];
  117443. }else{
  117444. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117445. discarded in short frames */
  117446. }
  117447. if(endpos>n)endpos=n;
  117448. for(;pos<endpos;pos++)
  117449. seeds[pos]=ampstack[i];
  117450. }
  117451. /* there. Linear time. I now remember this was on a problem set I
  117452. had in Grad Skool... I didn't solve it at the time ;-) */
  117453. }
  117454. /* bleaugh, this is more complicated than it needs to be */
  117455. #include<stdio.h>
  117456. static void max_seeds(vorbis_look_psy *p,
  117457. float *seed,
  117458. float *flr){
  117459. long n=p->total_octave_lines;
  117460. int linesper=p->eighth_octave_lines;
  117461. long linpos=0;
  117462. long pos;
  117463. seed_chase(seed,linesper,n); /* for masking */
  117464. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117465. while(linpos+1<p->n){
  117466. float minV=seed[pos];
  117467. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117468. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117469. while(pos+1<=end){
  117470. pos++;
  117471. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117472. minV=seed[pos];
  117473. }
  117474. end=pos+p->firstoc;
  117475. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117476. if(flr[linpos]<minV)flr[linpos]=minV;
  117477. }
  117478. {
  117479. float minV=seed[p->total_octave_lines-1];
  117480. for(;linpos<p->n;linpos++)
  117481. if(flr[linpos]<minV)flr[linpos]=minV;
  117482. }
  117483. }
  117484. static void bark_noise_hybridmp(int n,const long *b,
  117485. const float *f,
  117486. float *noise,
  117487. const float offset,
  117488. const int fixed){
  117489. float *N=(float*) alloca(n*sizeof(*N));
  117490. float *X=(float*) alloca(n*sizeof(*N));
  117491. float *XX=(float*) alloca(n*sizeof(*N));
  117492. float *Y=(float*) alloca(n*sizeof(*N));
  117493. float *XY=(float*) alloca(n*sizeof(*N));
  117494. float tN, tX, tXX, tY, tXY;
  117495. int i;
  117496. int lo, hi;
  117497. float R, A, B, D;
  117498. float w, x, y;
  117499. tN = tX = tXX = tY = tXY = 0.f;
  117500. y = f[0] + offset;
  117501. if (y < 1.f) y = 1.f;
  117502. w = y * y * .5;
  117503. tN += w;
  117504. tX += w;
  117505. tY += w * y;
  117506. N[0] = tN;
  117507. X[0] = tX;
  117508. XX[0] = tXX;
  117509. Y[0] = tY;
  117510. XY[0] = tXY;
  117511. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117512. y = f[i] + offset;
  117513. if (y < 1.f) y = 1.f;
  117514. w = y * y;
  117515. tN += w;
  117516. tX += w * x;
  117517. tXX += w * x * x;
  117518. tY += w * y;
  117519. tXY += w * x * y;
  117520. N[i] = tN;
  117521. X[i] = tX;
  117522. XX[i] = tXX;
  117523. Y[i] = tY;
  117524. XY[i] = tXY;
  117525. }
  117526. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117527. lo = b[i] >> 16;
  117528. if( lo>=0 ) break;
  117529. hi = b[i] & 0xffff;
  117530. tN = N[hi] + N[-lo];
  117531. tX = X[hi] - X[-lo];
  117532. tXX = XX[hi] + XX[-lo];
  117533. tY = Y[hi] + Y[-lo];
  117534. tXY = XY[hi] - XY[-lo];
  117535. A = tY * tXX - tX * tXY;
  117536. B = tN * tXY - tX * tY;
  117537. D = tN * tXX - tX * tX;
  117538. R = (A + x * B) / D;
  117539. if (R < 0.f)
  117540. R = 0.f;
  117541. noise[i] = R - offset;
  117542. }
  117543. for ( ;; i++, x += 1.f) {
  117544. lo = b[i] >> 16;
  117545. hi = b[i] & 0xffff;
  117546. if(hi>=n)break;
  117547. tN = N[hi] - N[lo];
  117548. tX = X[hi] - X[lo];
  117549. tXX = XX[hi] - XX[lo];
  117550. tY = Y[hi] - Y[lo];
  117551. tXY = XY[hi] - XY[lo];
  117552. A = tY * tXX - tX * tXY;
  117553. B = tN * tXY - tX * tY;
  117554. D = tN * tXX - tX * tX;
  117555. R = (A + x * B) / D;
  117556. if (R < 0.f) R = 0.f;
  117557. noise[i] = R - offset;
  117558. }
  117559. for ( ; i < n; i++, x += 1.f) {
  117560. R = (A + x * B) / D;
  117561. if (R < 0.f) R = 0.f;
  117562. noise[i] = R - offset;
  117563. }
  117564. if (fixed <= 0) return;
  117565. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117566. hi = i + fixed / 2;
  117567. lo = hi - fixed;
  117568. if(lo>=0)break;
  117569. tN = N[hi] + N[-lo];
  117570. tX = X[hi] - X[-lo];
  117571. tXX = XX[hi] + XX[-lo];
  117572. tY = Y[hi] + Y[-lo];
  117573. tXY = XY[hi] - XY[-lo];
  117574. A = tY * tXX - tX * tXY;
  117575. B = tN * tXY - tX * tY;
  117576. D = tN * tXX - tX * tX;
  117577. R = (A + x * B) / D;
  117578. if (R - offset < noise[i]) noise[i] = R - offset;
  117579. }
  117580. for ( ;; i++, x += 1.f) {
  117581. hi = i + fixed / 2;
  117582. lo = hi - fixed;
  117583. if(hi>=n)break;
  117584. tN = N[hi] - N[lo];
  117585. tX = X[hi] - X[lo];
  117586. tXX = XX[hi] - XX[lo];
  117587. tY = Y[hi] - Y[lo];
  117588. tXY = XY[hi] - XY[lo];
  117589. A = tY * tXX - tX * tXY;
  117590. B = tN * tXY - tX * tY;
  117591. D = tN * tXX - tX * tX;
  117592. R = (A + x * B) / D;
  117593. if (R - offset < noise[i]) noise[i] = R - offset;
  117594. }
  117595. for ( ; i < n; i++, x += 1.f) {
  117596. R = (A + x * B) / D;
  117597. if (R - offset < noise[i]) noise[i] = R - offset;
  117598. }
  117599. }
  117600. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117601. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117602. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117603. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117604. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117605. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117606. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117607. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117608. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117609. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117610. 973377.F, 913981.F, 858210.F, 805842.F,
  117611. 756669.F, 710497.F, 667142.F, 626433.F,
  117612. 588208.F, 552316.F, 518613.F, 486967.F,
  117613. 457252.F, 429351.F, 403152.F, 378551.F,
  117614. 355452.F, 333762.F, 313396.F, 294273.F,
  117615. 276316.F, 259455.F, 243623.F, 228757.F,
  117616. 214798.F, 201691.F, 189384.F, 177828.F,
  117617. 166977.F, 156788.F, 147221.F, 138237.F,
  117618. 129802.F, 121881.F, 114444.F, 107461.F,
  117619. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117620. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117621. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117622. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117623. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117624. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117625. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117626. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117627. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117628. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117629. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117630. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117631. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117632. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117633. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117634. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117635. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117636. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117637. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117638. 842.910F, 791.475F, 743.179F, 697.830F,
  117639. 655.249F, 615.265F, 577.722F, 542.469F,
  117640. 509.367F, 478.286F, 449.101F, 421.696F,
  117641. 395.964F, 371.803F, 349.115F, 327.812F,
  117642. 307.809F, 289.026F, 271.390F, 254.830F,
  117643. 239.280F, 224.679F, 210.969F, 198.096F,
  117644. 186.008F, 174.658F, 164.000F, 153.993F,
  117645. 144.596F, 135.773F, 127.488F, 119.708F,
  117646. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117647. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117648. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117649. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117650. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117651. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117652. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117653. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117654. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117655. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117656. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117657. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117658. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117659. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117660. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117661. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117662. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117663. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117664. 1.20790F, 1.13419F, 1.06499F, 1.F
  117665. };
  117666. void _vp_remove_floor(vorbis_look_psy *p,
  117667. float *mdct,
  117668. int *codedflr,
  117669. float *residue,
  117670. int sliding_lowpass){
  117671. int i,n=p->n;
  117672. if(sliding_lowpass>n)sliding_lowpass=n;
  117673. for(i=0;i<sliding_lowpass;i++){
  117674. residue[i]=
  117675. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117676. }
  117677. for(;i<n;i++)
  117678. residue[i]=0.;
  117679. }
  117680. void _vp_noisemask(vorbis_look_psy *p,
  117681. float *logmdct,
  117682. float *logmask){
  117683. int i,n=p->n;
  117684. float *work=(float*) alloca(n*sizeof(*work));
  117685. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117686. 140.,-1);
  117687. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117688. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117689. p->vi->noisewindowfixed);
  117690. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117691. #if 0
  117692. {
  117693. static int seq=0;
  117694. float work2[n];
  117695. for(i=0;i<n;i++){
  117696. work2[i]=logmask[i]+work[i];
  117697. }
  117698. if(seq&1)
  117699. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117700. else
  117701. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117702. if(seq&1)
  117703. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117704. else
  117705. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117706. seq++;
  117707. }
  117708. #endif
  117709. for(i=0;i<n;i++){
  117710. int dB=logmask[i]+.5;
  117711. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117712. if(dB<0)dB=0;
  117713. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117714. }
  117715. }
  117716. void _vp_tonemask(vorbis_look_psy *p,
  117717. float *logfft,
  117718. float *logmask,
  117719. float global_specmax,
  117720. float local_specmax){
  117721. int i,n=p->n;
  117722. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117723. float att=local_specmax+p->vi->ath_adjatt;
  117724. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117725. /* set the ATH (floating below localmax, not global max by a
  117726. specified att) */
  117727. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117728. for(i=0;i<n;i++)
  117729. logmask[i]=p->ath[i]+att;
  117730. /* tone masking */
  117731. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117732. max_seeds(p,seed,logmask);
  117733. }
  117734. void _vp_offset_and_mix(vorbis_look_psy *p,
  117735. float *noise,
  117736. float *tone,
  117737. int offset_select,
  117738. float *logmask,
  117739. float *mdct,
  117740. float *logmdct){
  117741. int i,n=p->n;
  117742. float de, coeffi, cx;/* AoTuV */
  117743. float toneatt=p->vi->tone_masteratt[offset_select];
  117744. cx = p->m_val;
  117745. for(i=0;i<n;i++){
  117746. float val= noise[i]+p->noiseoffset[offset_select][i];
  117747. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117748. logmask[i]=max(val,tone[i]+toneatt);
  117749. /* AoTuV */
  117750. /** @ M1 **
  117751. The following codes improve a noise problem.
  117752. A fundamental idea uses the value of masking and carries out
  117753. the relative compensation of the MDCT.
  117754. However, this code is not perfect and all noise problems cannot be solved.
  117755. by Aoyumi @ 2004/04/18
  117756. */
  117757. if(offset_select == 1) {
  117758. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117759. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117760. if(val > coeffi){
  117761. /* mdct value is > -17.2 dB below floor */
  117762. de = 1.0-((val-coeffi)*0.005*cx);
  117763. /* pro-rated attenuation:
  117764. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117765. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117766. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117767. etc... */
  117768. if(de < 0) de = 0.0001;
  117769. }else
  117770. /* mdct value is <= -17.2 dB below floor */
  117771. de = 1.0-((val-coeffi)*0.0003*cx);
  117772. /* pro-rated attenuation:
  117773. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117774. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117775. etc... */
  117776. mdct[i] *= de;
  117777. }
  117778. }
  117779. }
  117780. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117781. vorbis_info *vi=vd->vi;
  117782. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117783. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117784. int n=ci->blocksizes[vd->W]/2;
  117785. float secs=(float)n/vi->rate;
  117786. amp+=secs*gi->ampmax_att_per_sec;
  117787. if(amp<-9999)amp=-9999;
  117788. return(amp);
  117789. }
  117790. static void couple_lossless(float A, float B,
  117791. float *qA, float *qB){
  117792. int test1=fabs(*qA)>fabs(*qB);
  117793. test1-= fabs(*qA)<fabs(*qB);
  117794. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117795. if(test1==1){
  117796. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117797. }else{
  117798. float temp=*qB;
  117799. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117800. *qA=temp;
  117801. }
  117802. if(*qB>fabs(*qA)*1.9999f){
  117803. *qB= -fabs(*qA)*2.f;
  117804. *qA= -*qA;
  117805. }
  117806. }
  117807. static float hypot_lookup[32]={
  117808. -0.009935, -0.011245, -0.012726, -0.014397,
  117809. -0.016282, -0.018407, -0.020800, -0.023494,
  117810. -0.026522, -0.029923, -0.033737, -0.038010,
  117811. -0.042787, -0.048121, -0.054064, -0.060671,
  117812. -0.068000, -0.076109, -0.085054, -0.094892,
  117813. -0.105675, -0.117451, -0.130260, -0.144134,
  117814. -0.159093, -0.175146, -0.192286, -0.210490,
  117815. -0.229718, -0.249913, -0.271001, -0.292893};
  117816. static void precomputed_couple_point(float premag,
  117817. int floorA,int floorB,
  117818. float *mag, float *ang){
  117819. int test=(floorA>floorB)-1;
  117820. int offset=31-abs(floorA-floorB);
  117821. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117822. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117823. *mag=premag*floormag;
  117824. *ang=0.f;
  117825. }
  117826. /* just like below, this is currently set up to only do
  117827. single-step-depth coupling. Otherwise, we'd have to do more
  117828. copying (which will be inevitable later) */
  117829. /* doing the real circular magnitude calculation is audibly superior
  117830. to (A+B)/sqrt(2) */
  117831. static float dipole_hypot(float a, float b){
  117832. if(a>0.){
  117833. if(b>0.)return sqrt(a*a+b*b);
  117834. if(a>-b)return sqrt(a*a-b*b);
  117835. return -sqrt(b*b-a*a);
  117836. }
  117837. if(b<0.)return -sqrt(a*a+b*b);
  117838. if(-a>b)return -sqrt(a*a-b*b);
  117839. return sqrt(b*b-a*a);
  117840. }
  117841. static float round_hypot(float a, float b){
  117842. if(a>0.){
  117843. if(b>0.)return sqrt(a*a+b*b);
  117844. if(a>-b)return sqrt(a*a+b*b);
  117845. return -sqrt(b*b+a*a);
  117846. }
  117847. if(b<0.)return -sqrt(a*a+b*b);
  117848. if(-a>b)return -sqrt(a*a+b*b);
  117849. return sqrt(b*b+a*a);
  117850. }
  117851. /* revert to round hypot for now */
  117852. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117853. vorbis_info_psy_global *g,
  117854. vorbis_look_psy *p,
  117855. vorbis_info_mapping0 *vi,
  117856. float **mdct){
  117857. int i,j,n=p->n;
  117858. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117859. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117860. for(i=0;i<vi->coupling_steps;i++){
  117861. float *mdctM=mdct[vi->coupling_mag[i]];
  117862. float *mdctA=mdct[vi->coupling_ang[i]];
  117863. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117864. for(j=0;j<limit;j++)
  117865. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117866. for(;j<n;j++)
  117867. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117868. }
  117869. return(ret);
  117870. }
  117871. /* this is for per-channel noise normalization */
  117872. static int apsort(const void *a, const void *b){
  117873. float f1=fabs(**(float**)a);
  117874. float f2=fabs(**(float**)b);
  117875. return (f1<f2)-(f1>f2);
  117876. }
  117877. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117878. vorbis_look_psy *p,
  117879. vorbis_info_mapping0 *vi,
  117880. float **mags){
  117881. if(p->vi->normal_point_p){
  117882. int i,j,k,n=p->n;
  117883. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117884. int partition=p->vi->normal_partition;
  117885. float **work=(float**) alloca(sizeof(*work)*partition);
  117886. for(i=0;i<vi->coupling_steps;i++){
  117887. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117888. for(j=0;j<n;j+=partition){
  117889. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117890. qsort(work,partition,sizeof(*work),apsort);
  117891. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117892. }
  117893. }
  117894. return(ret);
  117895. }
  117896. return(NULL);
  117897. }
  117898. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117899. float *magnitudes,int *sortedindex){
  117900. int i,j,n=p->n;
  117901. vorbis_info_psy *vi=p->vi;
  117902. int partition=vi->normal_partition;
  117903. float **work=(float**) alloca(sizeof(*work)*partition);
  117904. int start=vi->normal_start;
  117905. for(j=start;j<n;j+=partition){
  117906. if(j+partition>n)partition=n-j;
  117907. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117908. qsort(work,partition,sizeof(*work),apsort);
  117909. for(i=0;i<partition;i++){
  117910. sortedindex[i+j-start]=work[i]-magnitudes;
  117911. }
  117912. }
  117913. }
  117914. void _vp_noise_normalize(vorbis_look_psy *p,
  117915. float *in,float *out,int *sortedindex){
  117916. int flag=0,i,j=0,n=p->n;
  117917. vorbis_info_psy *vi=p->vi;
  117918. int partition=vi->normal_partition;
  117919. int start=vi->normal_start;
  117920. if(start>n)start=n;
  117921. if(vi->normal_channel_p){
  117922. for(;j<start;j++)
  117923. out[j]=rint(in[j]);
  117924. for(;j+partition<=n;j+=partition){
  117925. float acc=0.;
  117926. int k;
  117927. for(i=j;i<j+partition;i++)
  117928. acc+=in[i]*in[i];
  117929. for(i=0;i<partition;i++){
  117930. k=sortedindex[i+j-start];
  117931. if(in[k]*in[k]>=.25f){
  117932. out[k]=rint(in[k]);
  117933. acc-=in[k]*in[k];
  117934. flag=1;
  117935. }else{
  117936. if(acc<vi->normal_thresh)break;
  117937. out[k]=unitnorm(in[k]);
  117938. acc-=1.;
  117939. }
  117940. }
  117941. for(;i<partition;i++){
  117942. k=sortedindex[i+j-start];
  117943. out[k]=0.;
  117944. }
  117945. }
  117946. }
  117947. for(;j<n;j++)
  117948. out[j]=rint(in[j]);
  117949. }
  117950. void _vp_couple(int blobno,
  117951. vorbis_info_psy_global *g,
  117952. vorbis_look_psy *p,
  117953. vorbis_info_mapping0 *vi,
  117954. float **res,
  117955. float **mag_memo,
  117956. int **mag_sort,
  117957. int **ifloor,
  117958. int *nonzero,
  117959. int sliding_lowpass){
  117960. int i,j,k,n=p->n;
  117961. /* perform any requested channel coupling */
  117962. /* point stereo can only be used in a first stage (in this encoder)
  117963. because of the dependency on floor lookups */
  117964. for(i=0;i<vi->coupling_steps;i++){
  117965. /* once we're doing multistage coupling in which a channel goes
  117966. through more than one coupling step, the floor vector
  117967. magnitudes will also have to be recalculated an propogated
  117968. along with PCM. Right now, we're not (that will wait until 5.1
  117969. most likely), so the code isn't here yet. The memory management
  117970. here is all assuming single depth couplings anyway. */
  117971. /* make sure coupling a zero and a nonzero channel results in two
  117972. nonzero channels. */
  117973. if(nonzero[vi->coupling_mag[i]] ||
  117974. nonzero[vi->coupling_ang[i]]){
  117975. float *rM=res[vi->coupling_mag[i]];
  117976. float *rA=res[vi->coupling_ang[i]];
  117977. float *qM=rM+n;
  117978. float *qA=rA+n;
  117979. int *floorM=ifloor[vi->coupling_mag[i]];
  117980. int *floorA=ifloor[vi->coupling_ang[i]];
  117981. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117982. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117983. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117984. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117985. int pointlimit=limit;
  117986. nonzero[vi->coupling_mag[i]]=1;
  117987. nonzero[vi->coupling_ang[i]]=1;
  117988. /* The threshold of a stereo is changed with the size of n */
  117989. if(n > 1000)
  117990. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117991. for(j=0;j<p->n;j+=partition){
  117992. float acc=0.f;
  117993. for(k=0;k<partition;k++){
  117994. int l=k+j;
  117995. if(l<sliding_lowpass){
  117996. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117997. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117998. precomputed_couple_point(mag_memo[i][l],
  117999. floorM[l],floorA[l],
  118000. qM+l,qA+l);
  118001. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  118002. }else{
  118003. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  118004. }
  118005. }else{
  118006. qM[l]=0.;
  118007. qA[l]=0.;
  118008. }
  118009. }
  118010. if(p->vi->normal_point_p){
  118011. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  118012. int l=mag_sort[i][j+k];
  118013. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  118014. qM[l]=unitnorm(qM[l]);
  118015. acc-=1.f;
  118016. }
  118017. }
  118018. }
  118019. }
  118020. }
  118021. }
  118022. }
  118023. /* AoTuV */
  118024. /** @ M2 **
  118025. The boost problem by the combination of noise normalization and point stereo is eased.
  118026. However, this is a temporary patch.
  118027. by Aoyumi @ 2004/04/18
  118028. */
  118029. void hf_reduction(vorbis_info_psy_global *g,
  118030. vorbis_look_psy *p,
  118031. vorbis_info_mapping0 *vi,
  118032. float **mdct){
  118033. int i,j,n=p->n, de=0.3*p->m_val;
  118034. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118035. for(i=0; i<vi->coupling_steps; i++){
  118036. /* for(j=start; j<limit; j++){} // ???*/
  118037. for(j=limit; j<n; j++)
  118038. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  118039. }
  118040. }
  118041. #endif
  118042. /*** End of inlined file: psy.c ***/
  118043. /*** Start of inlined file: registry.c ***/
  118044. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118045. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118046. // tasks..
  118047. #if JUCE_MSVC
  118048. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118049. #endif
  118050. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118051. #if JUCE_USE_OGGVORBIS
  118052. /* seems like major overkill now; the backend numbers will grow into
  118053. the infrastructure soon enough */
  118054. extern vorbis_func_floor floor0_exportbundle;
  118055. extern vorbis_func_floor floor1_exportbundle;
  118056. extern vorbis_func_residue residue0_exportbundle;
  118057. extern vorbis_func_residue residue1_exportbundle;
  118058. extern vorbis_func_residue residue2_exportbundle;
  118059. extern vorbis_func_mapping mapping0_exportbundle;
  118060. vorbis_func_floor *_floor_P[]={
  118061. &floor0_exportbundle,
  118062. &floor1_exportbundle,
  118063. };
  118064. vorbis_func_residue *_residue_P[]={
  118065. &residue0_exportbundle,
  118066. &residue1_exportbundle,
  118067. &residue2_exportbundle,
  118068. };
  118069. vorbis_func_mapping *_mapping_P[]={
  118070. &mapping0_exportbundle,
  118071. };
  118072. #endif
  118073. /*** End of inlined file: registry.c ***/
  118074. /*** Start of inlined file: res0.c ***/
  118075. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118076. encode/decode loops are coded for clarity and performance is not
  118077. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118078. it's slow. */
  118079. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118080. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118081. // tasks..
  118082. #if JUCE_MSVC
  118083. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118084. #endif
  118085. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118086. #if JUCE_USE_OGGVORBIS
  118087. #include <stdlib.h>
  118088. #include <string.h>
  118089. #include <math.h>
  118090. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118091. #include <stdio.h>
  118092. #endif
  118093. typedef struct {
  118094. vorbis_info_residue0 *info;
  118095. int parts;
  118096. int stages;
  118097. codebook *fullbooks;
  118098. codebook *phrasebook;
  118099. codebook ***partbooks;
  118100. int partvals;
  118101. int **decodemap;
  118102. long postbits;
  118103. long phrasebits;
  118104. long frames;
  118105. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118106. int train_seq;
  118107. long *training_data[8][64];
  118108. float training_max[8][64];
  118109. float training_min[8][64];
  118110. float tmin;
  118111. float tmax;
  118112. #endif
  118113. } vorbis_look_residue0;
  118114. void res0_free_info(vorbis_info_residue *i){
  118115. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118116. if(info){
  118117. memset(info,0,sizeof(*info));
  118118. _ogg_free(info);
  118119. }
  118120. }
  118121. void res0_free_look(vorbis_look_residue *i){
  118122. int j;
  118123. if(i){
  118124. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118125. #ifdef TRAIN_RES
  118126. {
  118127. int j,k,l;
  118128. for(j=0;j<look->parts;j++){
  118129. /*fprintf(stderr,"partition %d: ",j);*/
  118130. for(k=0;k<8;k++)
  118131. if(look->training_data[k][j]){
  118132. char buffer[80];
  118133. FILE *of;
  118134. codebook *statebook=look->partbooks[j][k];
  118135. /* long and short into the same bucket by current convention */
  118136. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118137. of=fopen(buffer,"a");
  118138. for(l=0;l<statebook->entries;l++)
  118139. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118140. fclose(of);
  118141. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118142. look->training_min[k][j],look->training_max[k][j]);*/
  118143. _ogg_free(look->training_data[k][j]);
  118144. look->training_data[k][j]=NULL;
  118145. }
  118146. /*fprintf(stderr,"\n");*/
  118147. }
  118148. }
  118149. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118150. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118151. (float)look->phrasebits/look->frames,
  118152. (float)look->postbits/look->frames,
  118153. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118154. #endif
  118155. /*vorbis_info_residue0 *info=look->info;
  118156. fprintf(stderr,
  118157. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118158. "(%g/frame) \n",look->frames,look->phrasebits,
  118159. look->resbitsflat,
  118160. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118161. for(j=0;j<look->parts;j++){
  118162. long acc=0;
  118163. fprintf(stderr,"\t[%d] == ",j);
  118164. for(k=0;k<look->stages;k++)
  118165. if((info->secondstages[j]>>k)&1){
  118166. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118167. acc+=look->resbits[j][k];
  118168. }
  118169. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118170. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118171. }
  118172. fprintf(stderr,"\n");*/
  118173. for(j=0;j<look->parts;j++)
  118174. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118175. _ogg_free(look->partbooks);
  118176. for(j=0;j<look->partvals;j++)
  118177. _ogg_free(look->decodemap[j]);
  118178. _ogg_free(look->decodemap);
  118179. memset(look,0,sizeof(*look));
  118180. _ogg_free(look);
  118181. }
  118182. }
  118183. static int icount(unsigned int v){
  118184. int ret=0;
  118185. while(v){
  118186. ret+=v&1;
  118187. v>>=1;
  118188. }
  118189. return(ret);
  118190. }
  118191. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118192. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118193. int j,acc=0;
  118194. oggpack_write(opb,info->begin,24);
  118195. oggpack_write(opb,info->end,24);
  118196. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118197. code with a partitioned book */
  118198. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118199. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118200. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118201. bitmask of one indicates this partition class has bits to write
  118202. this pass */
  118203. for(j=0;j<info->partitions;j++){
  118204. if(ilog(info->secondstages[j])>3){
  118205. /* yes, this is a minor hack due to not thinking ahead */
  118206. oggpack_write(opb,info->secondstages[j],3);
  118207. oggpack_write(opb,1,1);
  118208. oggpack_write(opb,info->secondstages[j]>>3,5);
  118209. }else
  118210. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118211. acc+=icount(info->secondstages[j]);
  118212. }
  118213. for(j=0;j<acc;j++)
  118214. oggpack_write(opb,info->booklist[j],8);
  118215. }
  118216. /* vorbis_info is for range checking */
  118217. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118218. int j,acc=0;
  118219. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118220. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118221. info->begin=oggpack_read(opb,24);
  118222. info->end=oggpack_read(opb,24);
  118223. info->grouping=oggpack_read(opb,24)+1;
  118224. info->partitions=oggpack_read(opb,6)+1;
  118225. info->groupbook=oggpack_read(opb,8);
  118226. for(j=0;j<info->partitions;j++){
  118227. int cascade=oggpack_read(opb,3);
  118228. if(oggpack_read(opb,1))
  118229. cascade|=(oggpack_read(opb,5)<<3);
  118230. info->secondstages[j]=cascade;
  118231. acc+=icount(cascade);
  118232. }
  118233. for(j=0;j<acc;j++)
  118234. info->booklist[j]=oggpack_read(opb,8);
  118235. if(info->groupbook>=ci->books)goto errout;
  118236. for(j=0;j<acc;j++)
  118237. if(info->booklist[j]>=ci->books)goto errout;
  118238. return(info);
  118239. errout:
  118240. res0_free_info(info);
  118241. return(NULL);
  118242. }
  118243. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118244. vorbis_info_residue *vr){
  118245. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118246. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118247. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118248. int j,k,acc=0;
  118249. int dim;
  118250. int maxstage=0;
  118251. look->info=info;
  118252. look->parts=info->partitions;
  118253. look->fullbooks=ci->fullbooks;
  118254. look->phrasebook=ci->fullbooks+info->groupbook;
  118255. dim=look->phrasebook->dim;
  118256. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118257. for(j=0;j<look->parts;j++){
  118258. int stages=ilog(info->secondstages[j]);
  118259. if(stages){
  118260. if(stages>maxstage)maxstage=stages;
  118261. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118262. for(k=0;k<stages;k++)
  118263. if(info->secondstages[j]&(1<<k)){
  118264. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118265. #ifdef TRAIN_RES
  118266. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118267. sizeof(***look->training_data));
  118268. #endif
  118269. }
  118270. }
  118271. }
  118272. look->partvals=rint(pow((float)look->parts,(float)dim));
  118273. look->stages=maxstage;
  118274. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118275. for(j=0;j<look->partvals;j++){
  118276. long val=j;
  118277. long mult=look->partvals/look->parts;
  118278. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118279. for(k=0;k<dim;k++){
  118280. long deco=val/mult;
  118281. val-=deco*mult;
  118282. mult/=look->parts;
  118283. look->decodemap[j][k]=deco;
  118284. }
  118285. }
  118286. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118287. {
  118288. static int train_seq=0;
  118289. look->train_seq=train_seq++;
  118290. }
  118291. #endif
  118292. return(look);
  118293. }
  118294. /* break an abstraction and copy some code for performance purposes */
  118295. static int local_book_besterror(codebook *book,float *a){
  118296. int dim=book->dim,i,k,o;
  118297. int best=0;
  118298. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118299. /* find the quant val of each scalar */
  118300. for(k=0,o=dim;k<dim;++k){
  118301. float val=a[--o];
  118302. i=tt->threshvals>>1;
  118303. if(val<tt->quantthresh[i]){
  118304. if(val<tt->quantthresh[i-1]){
  118305. for(--i;i>0;--i)
  118306. if(val>=tt->quantthresh[i-1])
  118307. break;
  118308. }
  118309. }else{
  118310. for(++i;i<tt->threshvals-1;++i)
  118311. if(val<tt->quantthresh[i])break;
  118312. }
  118313. best=(best*tt->quantvals)+tt->quantmap[i];
  118314. }
  118315. /* regular lattices are easy :-) */
  118316. if(book->c->lengthlist[best]<=0){
  118317. const static_codebook *c=book->c;
  118318. int i,j;
  118319. float bestf=0.f;
  118320. float *e=book->valuelist;
  118321. best=-1;
  118322. for(i=0;i<book->entries;i++){
  118323. if(c->lengthlist[i]>0){
  118324. float thisx=0.f;
  118325. for(j=0;j<dim;j++){
  118326. float val=(e[j]-a[j]);
  118327. thisx+=val*val;
  118328. }
  118329. if(best==-1 || thisx<bestf){
  118330. bestf=thisx;
  118331. best=i;
  118332. }
  118333. }
  118334. e+=dim;
  118335. }
  118336. }
  118337. {
  118338. float *ptr=book->valuelist+best*dim;
  118339. for(i=0;i<dim;i++)
  118340. *a++ -= *ptr++;
  118341. }
  118342. return(best);
  118343. }
  118344. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118345. codebook *book,long *acc){
  118346. int i,bits=0;
  118347. int dim=book->dim;
  118348. int step=n/dim;
  118349. for(i=0;i<step;i++){
  118350. int entry=local_book_besterror(book,vec+i*dim);
  118351. #ifdef TRAIN_RES
  118352. acc[entry]++;
  118353. #endif
  118354. bits+=vorbis_book_encode(book,entry,opb);
  118355. }
  118356. return(bits);
  118357. }
  118358. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118359. float **in,int ch){
  118360. long i,j,k;
  118361. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118362. vorbis_info_residue0 *info=look->info;
  118363. /* move all this setup out later */
  118364. int samples_per_partition=info->grouping;
  118365. int possible_partitions=info->partitions;
  118366. int n=info->end-info->begin;
  118367. int partvals=n/samples_per_partition;
  118368. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118369. float scale=100./samples_per_partition;
  118370. /* we find the partition type for each partition of each
  118371. channel. We'll go back and do the interleaved encoding in a
  118372. bit. For now, clarity */
  118373. for(i=0;i<ch;i++){
  118374. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118375. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118376. }
  118377. for(i=0;i<partvals;i++){
  118378. int offset=i*samples_per_partition+info->begin;
  118379. for(j=0;j<ch;j++){
  118380. float max=0.;
  118381. float ent=0.;
  118382. for(k=0;k<samples_per_partition;k++){
  118383. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118384. ent+=fabs(rint(in[j][offset+k]));
  118385. }
  118386. ent*=scale;
  118387. for(k=0;k<possible_partitions-1;k++)
  118388. if(max<=info->classmetric1[k] &&
  118389. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118390. break;
  118391. partword[j][i]=k;
  118392. }
  118393. }
  118394. #ifdef TRAIN_RESAUX
  118395. {
  118396. FILE *of;
  118397. char buffer[80];
  118398. for(i=0;i<ch;i++){
  118399. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118400. of=fopen(buffer,"a");
  118401. for(j=0;j<partvals;j++)
  118402. fprintf(of,"%ld, ",partword[i][j]);
  118403. fprintf(of,"\n");
  118404. fclose(of);
  118405. }
  118406. }
  118407. #endif
  118408. look->frames++;
  118409. return(partword);
  118410. }
  118411. /* designed for stereo or other modes where the partition size is an
  118412. integer multiple of the number of channels encoded in the current
  118413. submap */
  118414. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118415. int ch){
  118416. long i,j,k,l;
  118417. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118418. vorbis_info_residue0 *info=look->info;
  118419. /* move all this setup out later */
  118420. int samples_per_partition=info->grouping;
  118421. int possible_partitions=info->partitions;
  118422. int n=info->end-info->begin;
  118423. int partvals=n/samples_per_partition;
  118424. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118425. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118426. FILE *of;
  118427. char buffer[80];
  118428. #endif
  118429. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118430. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118431. for(i=0,l=info->begin/ch;i<partvals;i++){
  118432. float magmax=0.f;
  118433. float angmax=0.f;
  118434. for(j=0;j<samples_per_partition;j+=ch){
  118435. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118436. for(k=1;k<ch;k++)
  118437. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118438. l++;
  118439. }
  118440. for(j=0;j<possible_partitions-1;j++)
  118441. if(magmax<=info->classmetric1[j] &&
  118442. angmax<=info->classmetric2[j])
  118443. break;
  118444. partword[0][i]=j;
  118445. }
  118446. #ifdef TRAIN_RESAUX
  118447. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118448. of=fopen(buffer,"a");
  118449. for(i=0;i<partvals;i++)
  118450. fprintf(of,"%ld, ",partword[0][i]);
  118451. fprintf(of,"\n");
  118452. fclose(of);
  118453. #endif
  118454. look->frames++;
  118455. return(partword);
  118456. }
  118457. static int _01forward(oggpack_buffer *opb,
  118458. vorbis_block *vb,vorbis_look_residue *vl,
  118459. float **in,int ch,
  118460. long **partword,
  118461. int (*encode)(oggpack_buffer *,float *,int,
  118462. codebook *,long *)){
  118463. long i,j,k,s;
  118464. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118465. vorbis_info_residue0 *info=look->info;
  118466. /* move all this setup out later */
  118467. int samples_per_partition=info->grouping;
  118468. int possible_partitions=info->partitions;
  118469. int partitions_per_word=look->phrasebook->dim;
  118470. int n=info->end-info->begin;
  118471. int partvals=n/samples_per_partition;
  118472. long resbits[128];
  118473. long resvals[128];
  118474. #ifdef TRAIN_RES
  118475. for(i=0;i<ch;i++)
  118476. for(j=info->begin;j<info->end;j++){
  118477. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118478. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118479. }
  118480. #endif
  118481. memset(resbits,0,sizeof(resbits));
  118482. memset(resvals,0,sizeof(resvals));
  118483. /* we code the partition words for each channel, then the residual
  118484. words for a partition per channel until we've written all the
  118485. residual words for that partition word. Then write the next
  118486. partition channel words... */
  118487. for(s=0;s<look->stages;s++){
  118488. for(i=0;i<partvals;){
  118489. /* first we encode a partition codeword for each channel */
  118490. if(s==0){
  118491. for(j=0;j<ch;j++){
  118492. long val=partword[j][i];
  118493. for(k=1;k<partitions_per_word;k++){
  118494. val*=possible_partitions;
  118495. if(i+k<partvals)
  118496. val+=partword[j][i+k];
  118497. }
  118498. /* training hack */
  118499. if(val<look->phrasebook->entries)
  118500. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118501. #if 0 /*def TRAIN_RES*/
  118502. else
  118503. fprintf(stderr,"!");
  118504. #endif
  118505. }
  118506. }
  118507. /* now we encode interleaved residual values for the partitions */
  118508. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118509. long offset=i*samples_per_partition+info->begin;
  118510. for(j=0;j<ch;j++){
  118511. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118512. if(info->secondstages[partword[j][i]]&(1<<s)){
  118513. codebook *statebook=look->partbooks[partword[j][i]][s];
  118514. if(statebook){
  118515. int ret;
  118516. long *accumulator=NULL;
  118517. #ifdef TRAIN_RES
  118518. accumulator=look->training_data[s][partword[j][i]];
  118519. {
  118520. int l;
  118521. float *samples=in[j]+offset;
  118522. for(l=0;l<samples_per_partition;l++){
  118523. if(samples[l]<look->training_min[s][partword[j][i]])
  118524. look->training_min[s][partword[j][i]]=samples[l];
  118525. if(samples[l]>look->training_max[s][partword[j][i]])
  118526. look->training_max[s][partword[j][i]]=samples[l];
  118527. }
  118528. }
  118529. #endif
  118530. ret=encode(opb,in[j]+offset,samples_per_partition,
  118531. statebook,accumulator);
  118532. look->postbits+=ret;
  118533. resbits[partword[j][i]]+=ret;
  118534. }
  118535. }
  118536. }
  118537. }
  118538. }
  118539. }
  118540. /*{
  118541. long total=0;
  118542. long totalbits=0;
  118543. fprintf(stderr,"%d :: ",vb->mode);
  118544. for(k=0;k<possible_partitions;k++){
  118545. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118546. total+=resvals[k];
  118547. totalbits+=resbits[k];
  118548. }
  118549. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118550. }*/
  118551. return(0);
  118552. }
  118553. /* a truncated packet here just means 'stop working'; it's not an error */
  118554. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118555. float **in,int ch,
  118556. long (*decodepart)(codebook *, float *,
  118557. oggpack_buffer *,int)){
  118558. long i,j,k,l,s;
  118559. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118560. vorbis_info_residue0 *info=look->info;
  118561. /* move all this setup out later */
  118562. int samples_per_partition=info->grouping;
  118563. int partitions_per_word=look->phrasebook->dim;
  118564. int n=info->end-info->begin;
  118565. int partvals=n/samples_per_partition;
  118566. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118567. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118568. for(j=0;j<ch;j++)
  118569. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118570. for(s=0;s<look->stages;s++){
  118571. /* each loop decodes on partition codeword containing
  118572. partitions_pre_word partitions */
  118573. for(i=0,l=0;i<partvals;l++){
  118574. if(s==0){
  118575. /* fetch the partition word for each channel */
  118576. for(j=0;j<ch;j++){
  118577. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118578. if(temp==-1)goto eopbreak;
  118579. partword[j][l]=look->decodemap[temp];
  118580. if(partword[j][l]==NULL)goto errout;
  118581. }
  118582. }
  118583. /* now we decode residual values for the partitions */
  118584. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118585. for(j=0;j<ch;j++){
  118586. long offset=info->begin+i*samples_per_partition;
  118587. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118588. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118589. if(stagebook){
  118590. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118591. samples_per_partition)==-1)goto eopbreak;
  118592. }
  118593. }
  118594. }
  118595. }
  118596. }
  118597. errout:
  118598. eopbreak:
  118599. return(0);
  118600. }
  118601. #if 0
  118602. /* residue 0 and 1 are just slight variants of one another. 0 is
  118603. interleaved, 1 is not */
  118604. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118605. float **in,int *nonzero,int ch){
  118606. /* we encode only the nonzero parts of a bundle */
  118607. int i,used=0;
  118608. for(i=0;i<ch;i++)
  118609. if(nonzero[i])
  118610. in[used++]=in[i];
  118611. if(used)
  118612. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118613. return(_01class(vb,vl,in,used));
  118614. else
  118615. return(0);
  118616. }
  118617. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118618. float **in,float **out,int *nonzero,int ch,
  118619. long **partword){
  118620. /* we encode only the nonzero parts of a bundle */
  118621. int i,j,used=0,n=vb->pcmend/2;
  118622. for(i=0;i<ch;i++)
  118623. if(nonzero[i]){
  118624. if(out)
  118625. for(j=0;j<n;j++)
  118626. out[i][j]+=in[i][j];
  118627. in[used++]=in[i];
  118628. }
  118629. if(used){
  118630. int ret=_01forward(vb,vl,in,used,partword,
  118631. _interleaved_encodepart);
  118632. if(out){
  118633. used=0;
  118634. for(i=0;i<ch;i++)
  118635. if(nonzero[i]){
  118636. for(j=0;j<n;j++)
  118637. out[i][j]-=in[used][j];
  118638. used++;
  118639. }
  118640. }
  118641. return(ret);
  118642. }else{
  118643. return(0);
  118644. }
  118645. }
  118646. #endif
  118647. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118648. float **in,int *nonzero,int ch){
  118649. int i,used=0;
  118650. for(i=0;i<ch;i++)
  118651. if(nonzero[i])
  118652. in[used++]=in[i];
  118653. if(used)
  118654. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118655. else
  118656. return(0);
  118657. }
  118658. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118659. float **in,float **out,int *nonzero,int ch,
  118660. long **partword){
  118661. int i,j,used=0,n=vb->pcmend/2;
  118662. for(i=0;i<ch;i++)
  118663. if(nonzero[i]){
  118664. if(out)
  118665. for(j=0;j<n;j++)
  118666. out[i][j]+=in[i][j];
  118667. in[used++]=in[i];
  118668. }
  118669. if(used){
  118670. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118671. if(out){
  118672. used=0;
  118673. for(i=0;i<ch;i++)
  118674. if(nonzero[i]){
  118675. for(j=0;j<n;j++)
  118676. out[i][j]-=in[used][j];
  118677. used++;
  118678. }
  118679. }
  118680. return(ret);
  118681. }else{
  118682. return(0);
  118683. }
  118684. }
  118685. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118686. float **in,int *nonzero,int ch){
  118687. int i,used=0;
  118688. for(i=0;i<ch;i++)
  118689. if(nonzero[i])
  118690. in[used++]=in[i];
  118691. if(used)
  118692. return(_01class(vb,vl,in,used));
  118693. else
  118694. return(0);
  118695. }
  118696. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118697. float **in,int *nonzero,int ch){
  118698. int i,used=0;
  118699. for(i=0;i<ch;i++)
  118700. if(nonzero[i])
  118701. in[used++]=in[i];
  118702. if(used)
  118703. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118704. else
  118705. return(0);
  118706. }
  118707. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118708. float **in,int *nonzero,int ch){
  118709. int i,used=0;
  118710. for(i=0;i<ch;i++)
  118711. if(nonzero[i])used++;
  118712. if(used)
  118713. return(_2class(vb,vl,in,ch));
  118714. else
  118715. return(0);
  118716. }
  118717. /* res2 is slightly more different; all the channels are interleaved
  118718. into a single vector and encoded. */
  118719. int res2_forward(oggpack_buffer *opb,
  118720. vorbis_block *vb,vorbis_look_residue *vl,
  118721. float **in,float **out,int *nonzero,int ch,
  118722. long **partword){
  118723. long i,j,k,n=vb->pcmend/2,used=0;
  118724. /* don't duplicate the code; use a working vector hack for now and
  118725. reshape ourselves into a single channel res1 */
  118726. /* ugly; reallocs for each coupling pass :-( */
  118727. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118728. for(i=0;i<ch;i++){
  118729. float *pcm=in[i];
  118730. if(nonzero[i])used++;
  118731. for(j=0,k=i;j<n;j++,k+=ch)
  118732. work[k]=pcm[j];
  118733. }
  118734. if(used){
  118735. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118736. /* update the sofar vector */
  118737. if(out){
  118738. for(i=0;i<ch;i++){
  118739. float *pcm=in[i];
  118740. float *sofar=out[i];
  118741. for(j=0,k=i;j<n;j++,k+=ch)
  118742. sofar[j]+=pcm[j]-work[k];
  118743. }
  118744. }
  118745. return(ret);
  118746. }else{
  118747. return(0);
  118748. }
  118749. }
  118750. /* duplicate code here as speed is somewhat more important */
  118751. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118752. float **in,int *nonzero,int ch){
  118753. long i,k,l,s;
  118754. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118755. vorbis_info_residue0 *info=look->info;
  118756. /* move all this setup out later */
  118757. int samples_per_partition=info->grouping;
  118758. int partitions_per_word=look->phrasebook->dim;
  118759. int n=info->end-info->begin;
  118760. int partvals=n/samples_per_partition;
  118761. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118762. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118763. for(i=0;i<ch;i++)if(nonzero[i])break;
  118764. if(i==ch)return(0); /* no nonzero vectors */
  118765. for(s=0;s<look->stages;s++){
  118766. for(i=0,l=0;i<partvals;l++){
  118767. if(s==0){
  118768. /* fetch the partition word */
  118769. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118770. if(temp==-1)goto eopbreak;
  118771. partword[l]=look->decodemap[temp];
  118772. if(partword[l]==NULL)goto errout;
  118773. }
  118774. /* now we decode residual values for the partitions */
  118775. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118776. if(info->secondstages[partword[l][k]]&(1<<s)){
  118777. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118778. if(stagebook){
  118779. if(vorbis_book_decodevv_add(stagebook,in,
  118780. i*samples_per_partition+info->begin,ch,
  118781. &vb->opb,samples_per_partition)==-1)
  118782. goto eopbreak;
  118783. }
  118784. }
  118785. }
  118786. }
  118787. errout:
  118788. eopbreak:
  118789. return(0);
  118790. }
  118791. vorbis_func_residue residue0_exportbundle={
  118792. NULL,
  118793. &res0_unpack,
  118794. &res0_look,
  118795. &res0_free_info,
  118796. &res0_free_look,
  118797. NULL,
  118798. NULL,
  118799. &res0_inverse
  118800. };
  118801. vorbis_func_residue residue1_exportbundle={
  118802. &res0_pack,
  118803. &res0_unpack,
  118804. &res0_look,
  118805. &res0_free_info,
  118806. &res0_free_look,
  118807. &res1_class,
  118808. &res1_forward,
  118809. &res1_inverse
  118810. };
  118811. vorbis_func_residue residue2_exportbundle={
  118812. &res0_pack,
  118813. &res0_unpack,
  118814. &res0_look,
  118815. &res0_free_info,
  118816. &res0_free_look,
  118817. &res2_class,
  118818. &res2_forward,
  118819. &res2_inverse
  118820. };
  118821. #endif
  118822. /*** End of inlined file: res0.c ***/
  118823. /*** Start of inlined file: sharedbook.c ***/
  118824. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118825. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118826. // tasks..
  118827. #if JUCE_MSVC
  118828. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118829. #endif
  118830. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118831. #if JUCE_USE_OGGVORBIS
  118832. #include <stdlib.h>
  118833. #include <math.h>
  118834. #include <string.h>
  118835. /**** pack/unpack helpers ******************************************/
  118836. int _ilog(unsigned int v){
  118837. int ret=0;
  118838. while(v){
  118839. ret++;
  118840. v>>=1;
  118841. }
  118842. return(ret);
  118843. }
  118844. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118845. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118846. Why not IEEE? It's just not that important here. */
  118847. #define VQ_FEXP 10
  118848. #define VQ_FMAN 21
  118849. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118850. /* doesn't currently guard under/overflow */
  118851. long _float32_pack(float val){
  118852. int sign=0;
  118853. long exp;
  118854. long mant;
  118855. if(val<0){
  118856. sign=0x80000000;
  118857. val= -val;
  118858. }
  118859. exp= floor(log(val)/log(2.f));
  118860. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118861. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118862. return(sign|exp|mant);
  118863. }
  118864. float _float32_unpack(long val){
  118865. double mant=val&0x1fffff;
  118866. int sign=val&0x80000000;
  118867. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118868. if(sign)mant= -mant;
  118869. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118870. }
  118871. /* given a list of word lengths, generate a list of codewords. Works
  118872. for length ordered or unordered, always assigns the lowest valued
  118873. codewords first. Extended to handle unused entries (length 0) */
  118874. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118875. long i,j,count=0;
  118876. ogg_uint32_t marker[33];
  118877. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118878. memset(marker,0,sizeof(marker));
  118879. for(i=0;i<n;i++){
  118880. long length=l[i];
  118881. if(length>0){
  118882. ogg_uint32_t entry=marker[length];
  118883. /* when we claim a node for an entry, we also claim the nodes
  118884. below it (pruning off the imagined tree that may have dangled
  118885. from it) as well as blocking the use of any nodes directly
  118886. above for leaves */
  118887. /* update ourself */
  118888. if(length<32 && (entry>>length)){
  118889. /* error condition; the lengths must specify an overpopulated tree */
  118890. _ogg_free(r);
  118891. return(NULL);
  118892. }
  118893. r[count++]=entry;
  118894. /* Look to see if the next shorter marker points to the node
  118895. above. if so, update it and repeat. */
  118896. {
  118897. for(j=length;j>0;j--){
  118898. if(marker[j]&1){
  118899. /* have to jump branches */
  118900. if(j==1)
  118901. marker[1]++;
  118902. else
  118903. marker[j]=marker[j-1]<<1;
  118904. break; /* invariant says next upper marker would already
  118905. have been moved if it was on the same path */
  118906. }
  118907. marker[j]++;
  118908. }
  118909. }
  118910. /* prune the tree; the implicit invariant says all the longer
  118911. markers were dangling from our just-taken node. Dangle them
  118912. from our *new* node. */
  118913. for(j=length+1;j<33;j++)
  118914. if((marker[j]>>1) == entry){
  118915. entry=marker[j];
  118916. marker[j]=marker[j-1]<<1;
  118917. }else
  118918. break;
  118919. }else
  118920. if(sparsecount==0)count++;
  118921. }
  118922. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118923. endian */
  118924. for(i=0,count=0;i<n;i++){
  118925. ogg_uint32_t temp=0;
  118926. for(j=0;j<l[i];j++){
  118927. temp<<=1;
  118928. temp|=(r[count]>>j)&1;
  118929. }
  118930. if(sparsecount){
  118931. if(l[i])
  118932. r[count++]=temp;
  118933. }else
  118934. r[count++]=temp;
  118935. }
  118936. return(r);
  118937. }
  118938. /* there might be a straightforward one-line way to do the below
  118939. that's portable and totally safe against roundoff, but I haven't
  118940. thought of it. Therefore, we opt on the side of caution */
  118941. long _book_maptype1_quantvals(const static_codebook *b){
  118942. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118943. /* the above *should* be reliable, but we'll not assume that FP is
  118944. ever reliable when bitstream sync is at stake; verify via integer
  118945. means that vals really is the greatest value of dim for which
  118946. vals^b->bim <= b->entries */
  118947. /* treat the above as an initial guess */
  118948. while(1){
  118949. long acc=1;
  118950. long acc1=1;
  118951. int i;
  118952. for(i=0;i<b->dim;i++){
  118953. acc*=vals;
  118954. acc1*=vals+1;
  118955. }
  118956. if(acc<=b->entries && acc1>b->entries){
  118957. return(vals);
  118958. }else{
  118959. if(acc>b->entries){
  118960. vals--;
  118961. }else{
  118962. vals++;
  118963. }
  118964. }
  118965. }
  118966. }
  118967. /* unpack the quantized list of values for encode/decode ***********/
  118968. /* we need to deal with two map types: in map type 1, the values are
  118969. generated algorithmically (each column of the vector counts through
  118970. the values in the quant vector). in map type 2, all the values came
  118971. in in an explicit list. Both value lists must be unpacked */
  118972. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118973. long j,k,count=0;
  118974. if(b->maptype==1 || b->maptype==2){
  118975. int quantvals;
  118976. float mindel=_float32_unpack(b->q_min);
  118977. float delta=_float32_unpack(b->q_delta);
  118978. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118979. /* maptype 1 and 2 both use a quantized value vector, but
  118980. different sizes */
  118981. switch(b->maptype){
  118982. case 1:
  118983. /* most of the time, entries%dimensions == 0, but we need to be
  118984. well defined. We define that the possible vales at each
  118985. scalar is values == entries/dim. If entries%dim != 0, we'll
  118986. have 'too few' values (values*dim<entries), which means that
  118987. we'll have 'left over' entries; left over entries use zeroed
  118988. values (and are wasted). So don't generate codebooks like
  118989. that */
  118990. quantvals=_book_maptype1_quantvals(b);
  118991. for(j=0;j<b->entries;j++){
  118992. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118993. float last=0.f;
  118994. int indexdiv=1;
  118995. for(k=0;k<b->dim;k++){
  118996. int index= (j/indexdiv)%quantvals;
  118997. float val=b->quantlist[index];
  118998. val=fabs(val)*delta+mindel+last;
  118999. if(b->q_sequencep)last=val;
  119000. if(sparsemap)
  119001. r[sparsemap[count]*b->dim+k]=val;
  119002. else
  119003. r[count*b->dim+k]=val;
  119004. indexdiv*=quantvals;
  119005. }
  119006. count++;
  119007. }
  119008. }
  119009. break;
  119010. case 2:
  119011. for(j=0;j<b->entries;j++){
  119012. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119013. float last=0.f;
  119014. for(k=0;k<b->dim;k++){
  119015. float val=b->quantlist[j*b->dim+k];
  119016. val=fabs(val)*delta+mindel+last;
  119017. if(b->q_sequencep)last=val;
  119018. if(sparsemap)
  119019. r[sparsemap[count]*b->dim+k]=val;
  119020. else
  119021. r[count*b->dim+k]=val;
  119022. }
  119023. count++;
  119024. }
  119025. }
  119026. break;
  119027. }
  119028. return(r);
  119029. }
  119030. return(NULL);
  119031. }
  119032. void vorbis_staticbook_clear(static_codebook *b){
  119033. if(b->allocedp){
  119034. if(b->quantlist)_ogg_free(b->quantlist);
  119035. if(b->lengthlist)_ogg_free(b->lengthlist);
  119036. if(b->nearest_tree){
  119037. _ogg_free(b->nearest_tree->ptr0);
  119038. _ogg_free(b->nearest_tree->ptr1);
  119039. _ogg_free(b->nearest_tree->p);
  119040. _ogg_free(b->nearest_tree->q);
  119041. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  119042. _ogg_free(b->nearest_tree);
  119043. }
  119044. if(b->thresh_tree){
  119045. _ogg_free(b->thresh_tree->quantthresh);
  119046. _ogg_free(b->thresh_tree->quantmap);
  119047. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119048. _ogg_free(b->thresh_tree);
  119049. }
  119050. memset(b,0,sizeof(*b));
  119051. }
  119052. }
  119053. void vorbis_staticbook_destroy(static_codebook *b){
  119054. if(b->allocedp){
  119055. vorbis_staticbook_clear(b);
  119056. _ogg_free(b);
  119057. }
  119058. }
  119059. void vorbis_book_clear(codebook *b){
  119060. /* static book is not cleared; we're likely called on the lookup and
  119061. the static codebook belongs to the info struct */
  119062. if(b->valuelist)_ogg_free(b->valuelist);
  119063. if(b->codelist)_ogg_free(b->codelist);
  119064. if(b->dec_index)_ogg_free(b->dec_index);
  119065. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119066. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119067. memset(b,0,sizeof(*b));
  119068. }
  119069. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119070. memset(c,0,sizeof(*c));
  119071. c->c=s;
  119072. c->entries=s->entries;
  119073. c->used_entries=s->entries;
  119074. c->dim=s->dim;
  119075. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119076. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119077. return(0);
  119078. }
  119079. static int sort32a(const void *a,const void *b){
  119080. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119081. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119082. }
  119083. /* decode codebook arrangement is more heavily optimized than encode */
  119084. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119085. int i,j,n=0,tabn;
  119086. int *sortindex;
  119087. memset(c,0,sizeof(*c));
  119088. /* count actually used entries */
  119089. for(i=0;i<s->entries;i++)
  119090. if(s->lengthlist[i]>0)
  119091. n++;
  119092. c->entries=s->entries;
  119093. c->used_entries=n;
  119094. c->dim=s->dim;
  119095. /* two different remappings go on here.
  119096. First, we collapse the likely sparse codebook down only to
  119097. actually represented values/words. This collapsing needs to be
  119098. indexed as map-valueless books are used to encode original entry
  119099. positions as integers.
  119100. Second, we reorder all vectors, including the entry index above,
  119101. by sorted bitreversed codeword to allow treeless decode. */
  119102. {
  119103. /* perform sort */
  119104. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119105. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119106. if(codes==NULL)goto err_out;
  119107. for(i=0;i<n;i++){
  119108. codes[i]=ogg_bitreverse(codes[i]);
  119109. codep[i]=codes+i;
  119110. }
  119111. qsort(codep,n,sizeof(*codep),sort32a);
  119112. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119113. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119114. /* the index is a reverse index */
  119115. for(i=0;i<n;i++){
  119116. int position=codep[i]-codes;
  119117. sortindex[position]=i;
  119118. }
  119119. for(i=0;i<n;i++)
  119120. c->codelist[sortindex[i]]=codes[i];
  119121. _ogg_free(codes);
  119122. }
  119123. c->valuelist=_book_unquantize(s,n,sortindex);
  119124. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119125. for(n=0,i=0;i<s->entries;i++)
  119126. if(s->lengthlist[i]>0)
  119127. c->dec_index[sortindex[n++]]=i;
  119128. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119129. for(n=0,i=0;i<s->entries;i++)
  119130. if(s->lengthlist[i]>0)
  119131. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119132. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119133. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119134. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119135. tabn=1<<c->dec_firsttablen;
  119136. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119137. c->dec_maxlength=0;
  119138. for(i=0;i<n;i++){
  119139. if(c->dec_maxlength<c->dec_codelengths[i])
  119140. c->dec_maxlength=c->dec_codelengths[i];
  119141. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119142. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119143. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119144. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119145. }
  119146. }
  119147. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119148. hints for the non-direct-hits */
  119149. {
  119150. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119151. long lo=0,hi=0;
  119152. for(i=0;i<tabn;i++){
  119153. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119154. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119155. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119156. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119157. /* we only actually have 15 bits per hint to play with here.
  119158. In order to overflow gracefully (nothing breaks, efficiency
  119159. just drops), encode as the difference from the extremes. */
  119160. {
  119161. unsigned long loval=lo;
  119162. unsigned long hival=n-hi;
  119163. if(loval>0x7fff)loval=0x7fff;
  119164. if(hival>0x7fff)hival=0x7fff;
  119165. c->dec_firsttable[ogg_bitreverse(word)]=
  119166. 0x80000000UL | (loval<<15) | hival;
  119167. }
  119168. }
  119169. }
  119170. }
  119171. return(0);
  119172. err_out:
  119173. vorbis_book_clear(c);
  119174. return(-1);
  119175. }
  119176. static float _dist(int el,float *ref, float *b,int step){
  119177. int i;
  119178. float acc=0.f;
  119179. for(i=0;i<el;i++){
  119180. float val=(ref[i]-b[i*step]);
  119181. acc+=val*val;
  119182. }
  119183. return(acc);
  119184. }
  119185. int _best(codebook *book, float *a, int step){
  119186. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119187. #if 0
  119188. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119189. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119190. #endif
  119191. int dim=book->dim;
  119192. int k,o;
  119193. /*int savebest=-1;
  119194. float saverr;*/
  119195. /* do we have a threshhold encode hint? */
  119196. if(tt){
  119197. int index=0,i;
  119198. /* find the quant val of each scalar */
  119199. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119200. i=tt->threshvals>>1;
  119201. if(a[o]<tt->quantthresh[i]){
  119202. for(;i>0;i--)
  119203. if(a[o]>=tt->quantthresh[i-1])
  119204. break;
  119205. }else{
  119206. for(i++;i<tt->threshvals-1;i++)
  119207. if(a[o]<tt->quantthresh[i])break;
  119208. }
  119209. index=(index*tt->quantvals)+tt->quantmap[i];
  119210. }
  119211. /* regular lattices are easy :-) */
  119212. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119213. use a decision tree after all
  119214. and fall through*/
  119215. return(index);
  119216. }
  119217. #if 0
  119218. /* do we have a pigeonhole encode hint? */
  119219. if(pt){
  119220. const static_codebook *c=book->c;
  119221. int i,besti=-1;
  119222. float best=0.f;
  119223. int entry=0;
  119224. /* dealing with sequentialness is a pain in the ass */
  119225. if(c->q_sequencep){
  119226. int pv;
  119227. long mul=1;
  119228. float qlast=0;
  119229. for(k=0,o=0;k<dim;k++,o+=step){
  119230. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119231. if(pv<0 || pv>=pt->mapentries)break;
  119232. entry+=pt->pigeonmap[pv]*mul;
  119233. mul*=pt->quantvals;
  119234. qlast+=pv*pt->del+pt->min;
  119235. }
  119236. }else{
  119237. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119238. int pv=(int)((a[o]-pt->min)/pt->del);
  119239. if(pv<0 || pv>=pt->mapentries)break;
  119240. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119241. }
  119242. }
  119243. /* must be within the pigeonholable range; if we quant outside (or
  119244. in an entry that we define no list for), brute force it */
  119245. if(k==dim && pt->fitlength[entry]){
  119246. /* search the abbreviated list */
  119247. long *list=pt->fitlist+pt->fitmap[entry];
  119248. for(i=0;i<pt->fitlength[entry];i++){
  119249. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119250. if(besti==-1 || this<best){
  119251. best=this;
  119252. besti=list[i];
  119253. }
  119254. }
  119255. return(besti);
  119256. }
  119257. }
  119258. if(nt){
  119259. /* optimized using the decision tree */
  119260. while(1){
  119261. float c=0.f;
  119262. float *p=book->valuelist+nt->p[ptr];
  119263. float *q=book->valuelist+nt->q[ptr];
  119264. for(k=0,o=0;k<dim;k++,o+=step)
  119265. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119266. if(c>0.f) /* in A */
  119267. ptr= -nt->ptr0[ptr];
  119268. else /* in B */
  119269. ptr= -nt->ptr1[ptr];
  119270. if(ptr<=0)break;
  119271. }
  119272. return(-ptr);
  119273. }
  119274. #endif
  119275. /* brute force it! */
  119276. {
  119277. const static_codebook *c=book->c;
  119278. int i,besti=-1;
  119279. float best=0.f;
  119280. float *e=book->valuelist;
  119281. for(i=0;i<book->entries;i++){
  119282. if(c->lengthlist[i]>0){
  119283. float thisx=_dist(dim,e,a,step);
  119284. if(besti==-1 || thisx<best){
  119285. best=thisx;
  119286. besti=i;
  119287. }
  119288. }
  119289. e+=dim;
  119290. }
  119291. /*if(savebest!=-1 && savebest!=besti){
  119292. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119293. "original:");
  119294. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119295. fprintf(stderr,"\n"
  119296. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119297. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119298. (book->valuelist+savebest*dim)[i]);
  119299. fprintf(stderr,"\n"
  119300. "bruteforce (entry %d, err %g):",besti,best);
  119301. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119302. (book->valuelist+besti*dim)[i]);
  119303. fprintf(stderr,"\n");
  119304. }*/
  119305. return(besti);
  119306. }
  119307. }
  119308. long vorbis_book_codeword(codebook *book,int entry){
  119309. if(book->c) /* only use with encode; decode optimizations are
  119310. allowed to break this */
  119311. return book->codelist[entry];
  119312. return -1;
  119313. }
  119314. long vorbis_book_codelen(codebook *book,int entry){
  119315. if(book->c) /* only use with encode; decode optimizations are
  119316. allowed to break this */
  119317. return book->c->lengthlist[entry];
  119318. return -1;
  119319. }
  119320. #ifdef _V_SELFTEST
  119321. /* Unit tests of the dequantizer; this stuff will be OK
  119322. cross-platform, I simply want to be sure that special mapping cases
  119323. actually work properly; a bug could go unnoticed for a while */
  119324. #include <stdio.h>
  119325. /* cases:
  119326. no mapping
  119327. full, explicit mapping
  119328. algorithmic mapping
  119329. nonsequential
  119330. sequential
  119331. */
  119332. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119333. static long partial_quantlist1[]={0,7,2};
  119334. /* no mapping */
  119335. static_codebook test1={
  119336. 4,16,
  119337. NULL,
  119338. 0,
  119339. 0,0,0,0,
  119340. NULL,
  119341. NULL,NULL
  119342. };
  119343. static float *test1_result=NULL;
  119344. /* linear, full mapping, nonsequential */
  119345. static_codebook test2={
  119346. 4,3,
  119347. NULL,
  119348. 2,
  119349. -533200896,1611661312,4,0,
  119350. full_quantlist1,
  119351. NULL,NULL
  119352. };
  119353. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119354. /* linear, full mapping, sequential */
  119355. static_codebook test3={
  119356. 4,3,
  119357. NULL,
  119358. 2,
  119359. -533200896,1611661312,4,1,
  119360. full_quantlist1,
  119361. NULL,NULL
  119362. };
  119363. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119364. /* linear, algorithmic mapping, nonsequential */
  119365. static_codebook test4={
  119366. 3,27,
  119367. NULL,
  119368. 1,
  119369. -533200896,1611661312,4,0,
  119370. partial_quantlist1,
  119371. NULL,NULL
  119372. };
  119373. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119374. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119375. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119376. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119377. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119378. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119379. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119380. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119381. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119382. /* linear, algorithmic mapping, sequential */
  119383. static_codebook test5={
  119384. 3,27,
  119385. NULL,
  119386. 1,
  119387. -533200896,1611661312,4,1,
  119388. partial_quantlist1,
  119389. NULL,NULL
  119390. };
  119391. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119392. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119393. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119394. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119395. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119396. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119397. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119398. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119399. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119400. void run_test(static_codebook *b,float *comp){
  119401. float *out=_book_unquantize(b,b->entries,NULL);
  119402. int i;
  119403. if(comp){
  119404. if(!out){
  119405. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119406. exit(1);
  119407. }
  119408. for(i=0;i<b->entries*b->dim;i++)
  119409. if(fabs(out[i]-comp[i])>.0001){
  119410. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119411. "position %d, %g != %g\n",i,out[i],comp[i]);
  119412. exit(1);
  119413. }
  119414. }else{
  119415. if(out){
  119416. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119417. " correct result should have been NULL\n");
  119418. exit(1);
  119419. }
  119420. }
  119421. }
  119422. int main(){
  119423. /* run the nine dequant tests, and compare to the hand-rolled results */
  119424. fprintf(stderr,"Dequant test 1... ");
  119425. run_test(&test1,test1_result);
  119426. fprintf(stderr,"OK\nDequant test 2... ");
  119427. run_test(&test2,test2_result);
  119428. fprintf(stderr,"OK\nDequant test 3... ");
  119429. run_test(&test3,test3_result);
  119430. fprintf(stderr,"OK\nDequant test 4... ");
  119431. run_test(&test4,test4_result);
  119432. fprintf(stderr,"OK\nDequant test 5... ");
  119433. run_test(&test5,test5_result);
  119434. fprintf(stderr,"OK\n\n");
  119435. return(0);
  119436. }
  119437. #endif
  119438. #endif
  119439. /*** End of inlined file: sharedbook.c ***/
  119440. /*** Start of inlined file: smallft.c ***/
  119441. /* FFT implementation from OggSquish, minus cosine transforms,
  119442. * minus all but radix 2/4 case. In Vorbis we only need this
  119443. * cut-down version.
  119444. *
  119445. * To do more than just power-of-two sized vectors, see the full
  119446. * version I wrote for NetLib.
  119447. *
  119448. * Note that the packing is a little strange; rather than the FFT r/i
  119449. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119450. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119451. * FORTRAN version
  119452. */
  119453. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119454. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119455. // tasks..
  119456. #if JUCE_MSVC
  119457. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119458. #endif
  119459. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119460. #if JUCE_USE_OGGVORBIS
  119461. #include <stdlib.h>
  119462. #include <string.h>
  119463. #include <math.h>
  119464. static void drfti1(int n, float *wa, int *ifac){
  119465. static int ntryh[4] = { 4,2,3,5 };
  119466. static float tpi = 6.28318530717958648f;
  119467. float arg,argh,argld,fi;
  119468. int ntry=0,i,j=-1;
  119469. int k1, l1, l2, ib;
  119470. int ld, ii, ip, is, nq, nr;
  119471. int ido, ipm, nfm1;
  119472. int nl=n;
  119473. int nf=0;
  119474. L101:
  119475. j++;
  119476. if (j < 4)
  119477. ntry=ntryh[j];
  119478. else
  119479. ntry+=2;
  119480. L104:
  119481. nq=nl/ntry;
  119482. nr=nl-ntry*nq;
  119483. if (nr!=0) goto L101;
  119484. nf++;
  119485. ifac[nf+1]=ntry;
  119486. nl=nq;
  119487. if(ntry!=2)goto L107;
  119488. if(nf==1)goto L107;
  119489. for (i=1;i<nf;i++){
  119490. ib=nf-i+1;
  119491. ifac[ib+1]=ifac[ib];
  119492. }
  119493. ifac[2] = 2;
  119494. L107:
  119495. if(nl!=1)goto L104;
  119496. ifac[0]=n;
  119497. ifac[1]=nf;
  119498. argh=tpi/n;
  119499. is=0;
  119500. nfm1=nf-1;
  119501. l1=1;
  119502. if(nfm1==0)return;
  119503. for (k1=0;k1<nfm1;k1++){
  119504. ip=ifac[k1+2];
  119505. ld=0;
  119506. l2=l1*ip;
  119507. ido=n/l2;
  119508. ipm=ip-1;
  119509. for (j=0;j<ipm;j++){
  119510. ld+=l1;
  119511. i=is;
  119512. argld=(float)ld*argh;
  119513. fi=0.f;
  119514. for (ii=2;ii<ido;ii+=2){
  119515. fi+=1.f;
  119516. arg=fi*argld;
  119517. wa[i++]=cos(arg);
  119518. wa[i++]=sin(arg);
  119519. }
  119520. is+=ido;
  119521. }
  119522. l1=l2;
  119523. }
  119524. }
  119525. static void fdrffti(int n, float *wsave, int *ifac){
  119526. if (n == 1) return;
  119527. drfti1(n, wsave+n, ifac);
  119528. }
  119529. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119530. int i,k;
  119531. float ti2,tr2;
  119532. int t0,t1,t2,t3,t4,t5,t6;
  119533. t1=0;
  119534. t0=(t2=l1*ido);
  119535. t3=ido<<1;
  119536. for(k=0;k<l1;k++){
  119537. ch[t1<<1]=cc[t1]+cc[t2];
  119538. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119539. t1+=ido;
  119540. t2+=ido;
  119541. }
  119542. if(ido<2)return;
  119543. if(ido==2)goto L105;
  119544. t1=0;
  119545. t2=t0;
  119546. for(k=0;k<l1;k++){
  119547. t3=t2;
  119548. t4=(t1<<1)+(ido<<1);
  119549. t5=t1;
  119550. t6=t1+t1;
  119551. for(i=2;i<ido;i+=2){
  119552. t3+=2;
  119553. t4-=2;
  119554. t5+=2;
  119555. t6+=2;
  119556. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119557. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119558. ch[t6]=cc[t5]+ti2;
  119559. ch[t4]=ti2-cc[t5];
  119560. ch[t6-1]=cc[t5-1]+tr2;
  119561. ch[t4-1]=cc[t5-1]-tr2;
  119562. }
  119563. t1+=ido;
  119564. t2+=ido;
  119565. }
  119566. if(ido%2==1)return;
  119567. L105:
  119568. t3=(t2=(t1=ido)-1);
  119569. t2+=t0;
  119570. for(k=0;k<l1;k++){
  119571. ch[t1]=-cc[t2];
  119572. ch[t1-1]=cc[t3];
  119573. t1+=ido<<1;
  119574. t2+=ido;
  119575. t3+=ido;
  119576. }
  119577. }
  119578. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119579. float *wa2,float *wa3){
  119580. static float hsqt2 = .70710678118654752f;
  119581. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119582. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119583. t0=l1*ido;
  119584. t1=t0;
  119585. t4=t1<<1;
  119586. t2=t1+(t1<<1);
  119587. t3=0;
  119588. for(k=0;k<l1;k++){
  119589. tr1=cc[t1]+cc[t2];
  119590. tr2=cc[t3]+cc[t4];
  119591. ch[t5=t3<<2]=tr1+tr2;
  119592. ch[(ido<<2)+t5-1]=tr2-tr1;
  119593. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119594. ch[t5]=cc[t2]-cc[t1];
  119595. t1+=ido;
  119596. t2+=ido;
  119597. t3+=ido;
  119598. t4+=ido;
  119599. }
  119600. if(ido<2)return;
  119601. if(ido==2)goto L105;
  119602. t1=0;
  119603. for(k=0;k<l1;k++){
  119604. t2=t1;
  119605. t4=t1<<2;
  119606. t5=(t6=ido<<1)+t4;
  119607. for(i=2;i<ido;i+=2){
  119608. t3=(t2+=2);
  119609. t4+=2;
  119610. t5-=2;
  119611. t3+=t0;
  119612. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119613. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119614. t3+=t0;
  119615. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119616. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119617. t3+=t0;
  119618. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119619. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119620. tr1=cr2+cr4;
  119621. tr4=cr4-cr2;
  119622. ti1=ci2+ci4;
  119623. ti4=ci2-ci4;
  119624. ti2=cc[t2]+ci3;
  119625. ti3=cc[t2]-ci3;
  119626. tr2=cc[t2-1]+cr3;
  119627. tr3=cc[t2-1]-cr3;
  119628. ch[t4-1]=tr1+tr2;
  119629. ch[t4]=ti1+ti2;
  119630. ch[t5-1]=tr3-ti4;
  119631. ch[t5]=tr4-ti3;
  119632. ch[t4+t6-1]=ti4+tr3;
  119633. ch[t4+t6]=tr4+ti3;
  119634. ch[t5+t6-1]=tr2-tr1;
  119635. ch[t5+t6]=ti1-ti2;
  119636. }
  119637. t1+=ido;
  119638. }
  119639. if(ido&1)return;
  119640. L105:
  119641. t2=(t1=t0+ido-1)+(t0<<1);
  119642. t3=ido<<2;
  119643. t4=ido;
  119644. t5=ido<<1;
  119645. t6=ido;
  119646. for(k=0;k<l1;k++){
  119647. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119648. tr1=hsqt2*(cc[t1]-cc[t2]);
  119649. ch[t4-1]=tr1+cc[t6-1];
  119650. ch[t4+t5-1]=cc[t6-1]-tr1;
  119651. ch[t4]=ti1-cc[t1+t0];
  119652. ch[t4+t5]=ti1+cc[t1+t0];
  119653. t1+=ido;
  119654. t2+=ido;
  119655. t4+=t3;
  119656. t6+=ido;
  119657. }
  119658. }
  119659. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119660. float *c2,float *ch,float *ch2,float *wa){
  119661. static float tpi=6.283185307179586f;
  119662. int idij,ipph,i,j,k,l,ic,ik,is;
  119663. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119664. float dc2,ai1,ai2,ar1,ar2,ds2;
  119665. int nbd;
  119666. float dcp,arg,dsp,ar1h,ar2h;
  119667. int idp2,ipp2;
  119668. arg=tpi/(float)ip;
  119669. dcp=cos(arg);
  119670. dsp=sin(arg);
  119671. ipph=(ip+1)>>1;
  119672. ipp2=ip;
  119673. idp2=ido;
  119674. nbd=(ido-1)>>1;
  119675. t0=l1*ido;
  119676. t10=ip*ido;
  119677. if(ido==1)goto L119;
  119678. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119679. t1=0;
  119680. for(j=1;j<ip;j++){
  119681. t1+=t0;
  119682. t2=t1;
  119683. for(k=0;k<l1;k++){
  119684. ch[t2]=c1[t2];
  119685. t2+=ido;
  119686. }
  119687. }
  119688. is=-ido;
  119689. t1=0;
  119690. if(nbd>l1){
  119691. for(j=1;j<ip;j++){
  119692. t1+=t0;
  119693. is+=ido;
  119694. t2= -ido+t1;
  119695. for(k=0;k<l1;k++){
  119696. idij=is-1;
  119697. t2+=ido;
  119698. t3=t2;
  119699. for(i=2;i<ido;i+=2){
  119700. idij+=2;
  119701. t3+=2;
  119702. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119703. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119704. }
  119705. }
  119706. }
  119707. }else{
  119708. for(j=1;j<ip;j++){
  119709. is+=ido;
  119710. idij=is-1;
  119711. t1+=t0;
  119712. t2=t1;
  119713. for(i=2;i<ido;i+=2){
  119714. idij+=2;
  119715. t2+=2;
  119716. t3=t2;
  119717. for(k=0;k<l1;k++){
  119718. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119719. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119720. t3+=ido;
  119721. }
  119722. }
  119723. }
  119724. }
  119725. t1=0;
  119726. t2=ipp2*t0;
  119727. if(nbd<l1){
  119728. for(j=1;j<ipph;j++){
  119729. t1+=t0;
  119730. t2-=t0;
  119731. t3=t1;
  119732. t4=t2;
  119733. for(i=2;i<ido;i+=2){
  119734. t3+=2;
  119735. t4+=2;
  119736. t5=t3-ido;
  119737. t6=t4-ido;
  119738. for(k=0;k<l1;k++){
  119739. t5+=ido;
  119740. t6+=ido;
  119741. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119742. c1[t6-1]=ch[t5]-ch[t6];
  119743. c1[t5]=ch[t5]+ch[t6];
  119744. c1[t6]=ch[t6-1]-ch[t5-1];
  119745. }
  119746. }
  119747. }
  119748. }else{
  119749. for(j=1;j<ipph;j++){
  119750. t1+=t0;
  119751. t2-=t0;
  119752. t3=t1;
  119753. t4=t2;
  119754. for(k=0;k<l1;k++){
  119755. t5=t3;
  119756. t6=t4;
  119757. for(i=2;i<ido;i+=2){
  119758. t5+=2;
  119759. t6+=2;
  119760. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119761. c1[t6-1]=ch[t5]-ch[t6];
  119762. c1[t5]=ch[t5]+ch[t6];
  119763. c1[t6]=ch[t6-1]-ch[t5-1];
  119764. }
  119765. t3+=ido;
  119766. t4+=ido;
  119767. }
  119768. }
  119769. }
  119770. L119:
  119771. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119772. t1=0;
  119773. t2=ipp2*idl1;
  119774. for(j=1;j<ipph;j++){
  119775. t1+=t0;
  119776. t2-=t0;
  119777. t3=t1-ido;
  119778. t4=t2-ido;
  119779. for(k=0;k<l1;k++){
  119780. t3+=ido;
  119781. t4+=ido;
  119782. c1[t3]=ch[t3]+ch[t4];
  119783. c1[t4]=ch[t4]-ch[t3];
  119784. }
  119785. }
  119786. ar1=1.f;
  119787. ai1=0.f;
  119788. t1=0;
  119789. t2=ipp2*idl1;
  119790. t3=(ip-1)*idl1;
  119791. for(l=1;l<ipph;l++){
  119792. t1+=idl1;
  119793. t2-=idl1;
  119794. ar1h=dcp*ar1-dsp*ai1;
  119795. ai1=dcp*ai1+dsp*ar1;
  119796. ar1=ar1h;
  119797. t4=t1;
  119798. t5=t2;
  119799. t6=t3;
  119800. t7=idl1;
  119801. for(ik=0;ik<idl1;ik++){
  119802. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119803. ch2[t5++]=ai1*c2[t6++];
  119804. }
  119805. dc2=ar1;
  119806. ds2=ai1;
  119807. ar2=ar1;
  119808. ai2=ai1;
  119809. t4=idl1;
  119810. t5=(ipp2-1)*idl1;
  119811. for(j=2;j<ipph;j++){
  119812. t4+=idl1;
  119813. t5-=idl1;
  119814. ar2h=dc2*ar2-ds2*ai2;
  119815. ai2=dc2*ai2+ds2*ar2;
  119816. ar2=ar2h;
  119817. t6=t1;
  119818. t7=t2;
  119819. t8=t4;
  119820. t9=t5;
  119821. for(ik=0;ik<idl1;ik++){
  119822. ch2[t6++]+=ar2*c2[t8++];
  119823. ch2[t7++]+=ai2*c2[t9++];
  119824. }
  119825. }
  119826. }
  119827. t1=0;
  119828. for(j=1;j<ipph;j++){
  119829. t1+=idl1;
  119830. t2=t1;
  119831. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119832. }
  119833. if(ido<l1)goto L132;
  119834. t1=0;
  119835. t2=0;
  119836. for(k=0;k<l1;k++){
  119837. t3=t1;
  119838. t4=t2;
  119839. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119840. t1+=ido;
  119841. t2+=t10;
  119842. }
  119843. goto L135;
  119844. L132:
  119845. for(i=0;i<ido;i++){
  119846. t1=i;
  119847. t2=i;
  119848. for(k=0;k<l1;k++){
  119849. cc[t2]=ch[t1];
  119850. t1+=ido;
  119851. t2+=t10;
  119852. }
  119853. }
  119854. L135:
  119855. t1=0;
  119856. t2=ido<<1;
  119857. t3=0;
  119858. t4=ipp2*t0;
  119859. for(j=1;j<ipph;j++){
  119860. t1+=t2;
  119861. t3+=t0;
  119862. t4-=t0;
  119863. t5=t1;
  119864. t6=t3;
  119865. t7=t4;
  119866. for(k=0;k<l1;k++){
  119867. cc[t5-1]=ch[t6];
  119868. cc[t5]=ch[t7];
  119869. t5+=t10;
  119870. t6+=ido;
  119871. t7+=ido;
  119872. }
  119873. }
  119874. if(ido==1)return;
  119875. if(nbd<l1)goto L141;
  119876. t1=-ido;
  119877. t3=0;
  119878. t4=0;
  119879. t5=ipp2*t0;
  119880. for(j=1;j<ipph;j++){
  119881. t1+=t2;
  119882. t3+=t2;
  119883. t4+=t0;
  119884. t5-=t0;
  119885. t6=t1;
  119886. t7=t3;
  119887. t8=t4;
  119888. t9=t5;
  119889. for(k=0;k<l1;k++){
  119890. for(i=2;i<ido;i+=2){
  119891. ic=idp2-i;
  119892. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119893. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119894. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119895. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119896. }
  119897. t6+=t10;
  119898. t7+=t10;
  119899. t8+=ido;
  119900. t9+=ido;
  119901. }
  119902. }
  119903. return;
  119904. L141:
  119905. t1=-ido;
  119906. t3=0;
  119907. t4=0;
  119908. t5=ipp2*t0;
  119909. for(j=1;j<ipph;j++){
  119910. t1+=t2;
  119911. t3+=t2;
  119912. t4+=t0;
  119913. t5-=t0;
  119914. for(i=2;i<ido;i+=2){
  119915. t6=idp2+t1-i;
  119916. t7=i+t3;
  119917. t8=i+t4;
  119918. t9=i+t5;
  119919. for(k=0;k<l1;k++){
  119920. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119921. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119922. cc[t7]=ch[t8]+ch[t9];
  119923. cc[t6]=ch[t9]-ch[t8];
  119924. t6+=t10;
  119925. t7+=t10;
  119926. t8+=ido;
  119927. t9+=ido;
  119928. }
  119929. }
  119930. }
  119931. }
  119932. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119933. int i,k1,l1,l2;
  119934. int na,kh,nf;
  119935. int ip,iw,ido,idl1,ix2,ix3;
  119936. nf=ifac[1];
  119937. na=1;
  119938. l2=n;
  119939. iw=n;
  119940. for(k1=0;k1<nf;k1++){
  119941. kh=nf-k1;
  119942. ip=ifac[kh+1];
  119943. l1=l2/ip;
  119944. ido=n/l2;
  119945. idl1=ido*l1;
  119946. iw-=(ip-1)*ido;
  119947. na=1-na;
  119948. if(ip!=4)goto L102;
  119949. ix2=iw+ido;
  119950. ix3=ix2+ido;
  119951. if(na!=0)
  119952. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119953. else
  119954. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119955. goto L110;
  119956. L102:
  119957. if(ip!=2)goto L104;
  119958. if(na!=0)goto L103;
  119959. dradf2(ido,l1,c,ch,wa+iw-1);
  119960. goto L110;
  119961. L103:
  119962. dradf2(ido,l1,ch,c,wa+iw-1);
  119963. goto L110;
  119964. L104:
  119965. if(ido==1)na=1-na;
  119966. if(na!=0)goto L109;
  119967. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119968. na=1;
  119969. goto L110;
  119970. L109:
  119971. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119972. na=0;
  119973. L110:
  119974. l2=l1;
  119975. }
  119976. if(na==1)return;
  119977. for(i=0;i<n;i++)c[i]=ch[i];
  119978. }
  119979. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119980. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119981. float ti2,tr2;
  119982. t0=l1*ido;
  119983. t1=0;
  119984. t2=0;
  119985. t3=(ido<<1)-1;
  119986. for(k=0;k<l1;k++){
  119987. ch[t1]=cc[t2]+cc[t3+t2];
  119988. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119989. t2=(t1+=ido)<<1;
  119990. }
  119991. if(ido<2)return;
  119992. if(ido==2)goto L105;
  119993. t1=0;
  119994. t2=0;
  119995. for(k=0;k<l1;k++){
  119996. t3=t1;
  119997. t5=(t4=t2)+(ido<<1);
  119998. t6=t0+t1;
  119999. for(i=2;i<ido;i+=2){
  120000. t3+=2;
  120001. t4+=2;
  120002. t5-=2;
  120003. t6+=2;
  120004. ch[t3-1]=cc[t4-1]+cc[t5-1];
  120005. tr2=cc[t4-1]-cc[t5-1];
  120006. ch[t3]=cc[t4]-cc[t5];
  120007. ti2=cc[t4]+cc[t5];
  120008. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  120009. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  120010. }
  120011. t2=(t1+=ido)<<1;
  120012. }
  120013. if(ido%2==1)return;
  120014. L105:
  120015. t1=ido-1;
  120016. t2=ido-1;
  120017. for(k=0;k<l1;k++){
  120018. ch[t1]=cc[t2]+cc[t2];
  120019. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  120020. t1+=ido;
  120021. t2+=ido<<1;
  120022. }
  120023. }
  120024. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  120025. float *wa2){
  120026. static float taur = -.5f;
  120027. static float taui = .8660254037844386f;
  120028. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120029. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  120030. t0=l1*ido;
  120031. t1=0;
  120032. t2=t0<<1;
  120033. t3=ido<<1;
  120034. t4=ido+(ido<<1);
  120035. t5=0;
  120036. for(k=0;k<l1;k++){
  120037. tr2=cc[t3-1]+cc[t3-1];
  120038. cr2=cc[t5]+(taur*tr2);
  120039. ch[t1]=cc[t5]+tr2;
  120040. ci3=taui*(cc[t3]+cc[t3]);
  120041. ch[t1+t0]=cr2-ci3;
  120042. ch[t1+t2]=cr2+ci3;
  120043. t1+=ido;
  120044. t3+=t4;
  120045. t5+=t4;
  120046. }
  120047. if(ido==1)return;
  120048. t1=0;
  120049. t3=ido<<1;
  120050. for(k=0;k<l1;k++){
  120051. t7=t1+(t1<<1);
  120052. t6=(t5=t7+t3);
  120053. t8=t1;
  120054. t10=(t9=t1+t0)+t0;
  120055. for(i=2;i<ido;i+=2){
  120056. t5+=2;
  120057. t6-=2;
  120058. t7+=2;
  120059. t8+=2;
  120060. t9+=2;
  120061. t10+=2;
  120062. tr2=cc[t5-1]+cc[t6-1];
  120063. cr2=cc[t7-1]+(taur*tr2);
  120064. ch[t8-1]=cc[t7-1]+tr2;
  120065. ti2=cc[t5]-cc[t6];
  120066. ci2=cc[t7]+(taur*ti2);
  120067. ch[t8]=cc[t7]+ti2;
  120068. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120069. ci3=taui*(cc[t5]+cc[t6]);
  120070. dr2=cr2-ci3;
  120071. dr3=cr2+ci3;
  120072. di2=ci2+cr3;
  120073. di3=ci2-cr3;
  120074. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120075. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120076. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120077. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120078. }
  120079. t1+=ido;
  120080. }
  120081. }
  120082. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120083. float *wa2,float *wa3){
  120084. static float sqrt2=1.414213562373095f;
  120085. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120086. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120087. t0=l1*ido;
  120088. t1=0;
  120089. t2=ido<<2;
  120090. t3=0;
  120091. t6=ido<<1;
  120092. for(k=0;k<l1;k++){
  120093. t4=t3+t6;
  120094. t5=t1;
  120095. tr3=cc[t4-1]+cc[t4-1];
  120096. tr4=cc[t4]+cc[t4];
  120097. tr1=cc[t3]-cc[(t4+=t6)-1];
  120098. tr2=cc[t3]+cc[t4-1];
  120099. ch[t5]=tr2+tr3;
  120100. ch[t5+=t0]=tr1-tr4;
  120101. ch[t5+=t0]=tr2-tr3;
  120102. ch[t5+=t0]=tr1+tr4;
  120103. t1+=ido;
  120104. t3+=t2;
  120105. }
  120106. if(ido<2)return;
  120107. if(ido==2)goto L105;
  120108. t1=0;
  120109. for(k=0;k<l1;k++){
  120110. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120111. t7=t1;
  120112. for(i=2;i<ido;i+=2){
  120113. t2+=2;
  120114. t3+=2;
  120115. t4-=2;
  120116. t5-=2;
  120117. t7+=2;
  120118. ti1=cc[t2]+cc[t5];
  120119. ti2=cc[t2]-cc[t5];
  120120. ti3=cc[t3]-cc[t4];
  120121. tr4=cc[t3]+cc[t4];
  120122. tr1=cc[t2-1]-cc[t5-1];
  120123. tr2=cc[t2-1]+cc[t5-1];
  120124. ti4=cc[t3-1]-cc[t4-1];
  120125. tr3=cc[t3-1]+cc[t4-1];
  120126. ch[t7-1]=tr2+tr3;
  120127. cr3=tr2-tr3;
  120128. ch[t7]=ti2+ti3;
  120129. ci3=ti2-ti3;
  120130. cr2=tr1-tr4;
  120131. cr4=tr1+tr4;
  120132. ci2=ti1+ti4;
  120133. ci4=ti1-ti4;
  120134. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120135. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120136. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120137. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120138. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120139. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120140. }
  120141. t1+=ido;
  120142. }
  120143. if(ido%2 == 1)return;
  120144. L105:
  120145. t1=ido;
  120146. t2=ido<<2;
  120147. t3=ido-1;
  120148. t4=ido+(ido<<1);
  120149. for(k=0;k<l1;k++){
  120150. t5=t3;
  120151. ti1=cc[t1]+cc[t4];
  120152. ti2=cc[t4]-cc[t1];
  120153. tr1=cc[t1-1]-cc[t4-1];
  120154. tr2=cc[t1-1]+cc[t4-1];
  120155. ch[t5]=tr2+tr2;
  120156. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120157. ch[t5+=t0]=ti2+ti2;
  120158. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120159. t3+=ido;
  120160. t1+=t2;
  120161. t4+=t2;
  120162. }
  120163. }
  120164. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120165. float *c2,float *ch,float *ch2,float *wa){
  120166. static float tpi=6.283185307179586f;
  120167. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120168. t11,t12;
  120169. float dc2,ai1,ai2,ar1,ar2,ds2;
  120170. int nbd;
  120171. float dcp,arg,dsp,ar1h,ar2h;
  120172. int ipp2;
  120173. t10=ip*ido;
  120174. t0=l1*ido;
  120175. arg=tpi/(float)ip;
  120176. dcp=cos(arg);
  120177. dsp=sin(arg);
  120178. nbd=(ido-1)>>1;
  120179. ipp2=ip;
  120180. ipph=(ip+1)>>1;
  120181. if(ido<l1)goto L103;
  120182. t1=0;
  120183. t2=0;
  120184. for(k=0;k<l1;k++){
  120185. t3=t1;
  120186. t4=t2;
  120187. for(i=0;i<ido;i++){
  120188. ch[t3]=cc[t4];
  120189. t3++;
  120190. t4++;
  120191. }
  120192. t1+=ido;
  120193. t2+=t10;
  120194. }
  120195. goto L106;
  120196. L103:
  120197. t1=0;
  120198. for(i=0;i<ido;i++){
  120199. t2=t1;
  120200. t3=t1;
  120201. for(k=0;k<l1;k++){
  120202. ch[t2]=cc[t3];
  120203. t2+=ido;
  120204. t3+=t10;
  120205. }
  120206. t1++;
  120207. }
  120208. L106:
  120209. t1=0;
  120210. t2=ipp2*t0;
  120211. t7=(t5=ido<<1);
  120212. for(j=1;j<ipph;j++){
  120213. t1+=t0;
  120214. t2-=t0;
  120215. t3=t1;
  120216. t4=t2;
  120217. t6=t5;
  120218. for(k=0;k<l1;k++){
  120219. ch[t3]=cc[t6-1]+cc[t6-1];
  120220. ch[t4]=cc[t6]+cc[t6];
  120221. t3+=ido;
  120222. t4+=ido;
  120223. t6+=t10;
  120224. }
  120225. t5+=t7;
  120226. }
  120227. if (ido == 1)goto L116;
  120228. if(nbd<l1)goto L112;
  120229. t1=0;
  120230. t2=ipp2*t0;
  120231. t7=0;
  120232. for(j=1;j<ipph;j++){
  120233. t1+=t0;
  120234. t2-=t0;
  120235. t3=t1;
  120236. t4=t2;
  120237. t7+=(ido<<1);
  120238. t8=t7;
  120239. for(k=0;k<l1;k++){
  120240. t5=t3;
  120241. t6=t4;
  120242. t9=t8;
  120243. t11=t8;
  120244. for(i=2;i<ido;i+=2){
  120245. t5+=2;
  120246. t6+=2;
  120247. t9+=2;
  120248. t11-=2;
  120249. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120250. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120251. ch[t5]=cc[t9]-cc[t11];
  120252. ch[t6]=cc[t9]+cc[t11];
  120253. }
  120254. t3+=ido;
  120255. t4+=ido;
  120256. t8+=t10;
  120257. }
  120258. }
  120259. goto L116;
  120260. L112:
  120261. t1=0;
  120262. t2=ipp2*t0;
  120263. t7=0;
  120264. for(j=1;j<ipph;j++){
  120265. t1+=t0;
  120266. t2-=t0;
  120267. t3=t1;
  120268. t4=t2;
  120269. t7+=(ido<<1);
  120270. t8=t7;
  120271. t9=t7;
  120272. for(i=2;i<ido;i+=2){
  120273. t3+=2;
  120274. t4+=2;
  120275. t8+=2;
  120276. t9-=2;
  120277. t5=t3;
  120278. t6=t4;
  120279. t11=t8;
  120280. t12=t9;
  120281. for(k=0;k<l1;k++){
  120282. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120283. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120284. ch[t5]=cc[t11]-cc[t12];
  120285. ch[t6]=cc[t11]+cc[t12];
  120286. t5+=ido;
  120287. t6+=ido;
  120288. t11+=t10;
  120289. t12+=t10;
  120290. }
  120291. }
  120292. }
  120293. L116:
  120294. ar1=1.f;
  120295. ai1=0.f;
  120296. t1=0;
  120297. t9=(t2=ipp2*idl1);
  120298. t3=(ip-1)*idl1;
  120299. for(l=1;l<ipph;l++){
  120300. t1+=idl1;
  120301. t2-=idl1;
  120302. ar1h=dcp*ar1-dsp*ai1;
  120303. ai1=dcp*ai1+dsp*ar1;
  120304. ar1=ar1h;
  120305. t4=t1;
  120306. t5=t2;
  120307. t6=0;
  120308. t7=idl1;
  120309. t8=t3;
  120310. for(ik=0;ik<idl1;ik++){
  120311. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120312. c2[t5++]=ai1*ch2[t8++];
  120313. }
  120314. dc2=ar1;
  120315. ds2=ai1;
  120316. ar2=ar1;
  120317. ai2=ai1;
  120318. t6=idl1;
  120319. t7=t9-idl1;
  120320. for(j=2;j<ipph;j++){
  120321. t6+=idl1;
  120322. t7-=idl1;
  120323. ar2h=dc2*ar2-ds2*ai2;
  120324. ai2=dc2*ai2+ds2*ar2;
  120325. ar2=ar2h;
  120326. t4=t1;
  120327. t5=t2;
  120328. t11=t6;
  120329. t12=t7;
  120330. for(ik=0;ik<idl1;ik++){
  120331. c2[t4++]+=ar2*ch2[t11++];
  120332. c2[t5++]+=ai2*ch2[t12++];
  120333. }
  120334. }
  120335. }
  120336. t1=0;
  120337. for(j=1;j<ipph;j++){
  120338. t1+=idl1;
  120339. t2=t1;
  120340. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120341. }
  120342. t1=0;
  120343. t2=ipp2*t0;
  120344. for(j=1;j<ipph;j++){
  120345. t1+=t0;
  120346. t2-=t0;
  120347. t3=t1;
  120348. t4=t2;
  120349. for(k=0;k<l1;k++){
  120350. ch[t3]=c1[t3]-c1[t4];
  120351. ch[t4]=c1[t3]+c1[t4];
  120352. t3+=ido;
  120353. t4+=ido;
  120354. }
  120355. }
  120356. if(ido==1)goto L132;
  120357. if(nbd<l1)goto L128;
  120358. t1=0;
  120359. t2=ipp2*t0;
  120360. for(j=1;j<ipph;j++){
  120361. t1+=t0;
  120362. t2-=t0;
  120363. t3=t1;
  120364. t4=t2;
  120365. for(k=0;k<l1;k++){
  120366. t5=t3;
  120367. t6=t4;
  120368. for(i=2;i<ido;i+=2){
  120369. t5+=2;
  120370. t6+=2;
  120371. ch[t5-1]=c1[t5-1]-c1[t6];
  120372. ch[t6-1]=c1[t5-1]+c1[t6];
  120373. ch[t5]=c1[t5]+c1[t6-1];
  120374. ch[t6]=c1[t5]-c1[t6-1];
  120375. }
  120376. t3+=ido;
  120377. t4+=ido;
  120378. }
  120379. }
  120380. goto L132;
  120381. L128:
  120382. t1=0;
  120383. t2=ipp2*t0;
  120384. for(j=1;j<ipph;j++){
  120385. t1+=t0;
  120386. t2-=t0;
  120387. t3=t1;
  120388. t4=t2;
  120389. for(i=2;i<ido;i+=2){
  120390. t3+=2;
  120391. t4+=2;
  120392. t5=t3;
  120393. t6=t4;
  120394. for(k=0;k<l1;k++){
  120395. ch[t5-1]=c1[t5-1]-c1[t6];
  120396. ch[t6-1]=c1[t5-1]+c1[t6];
  120397. ch[t5]=c1[t5]+c1[t6-1];
  120398. ch[t6]=c1[t5]-c1[t6-1];
  120399. t5+=ido;
  120400. t6+=ido;
  120401. }
  120402. }
  120403. }
  120404. L132:
  120405. if(ido==1)return;
  120406. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120407. t1=0;
  120408. for(j=1;j<ip;j++){
  120409. t2=(t1+=t0);
  120410. for(k=0;k<l1;k++){
  120411. c1[t2]=ch[t2];
  120412. t2+=ido;
  120413. }
  120414. }
  120415. if(nbd>l1)goto L139;
  120416. is= -ido-1;
  120417. t1=0;
  120418. for(j=1;j<ip;j++){
  120419. is+=ido;
  120420. t1+=t0;
  120421. idij=is;
  120422. t2=t1;
  120423. for(i=2;i<ido;i+=2){
  120424. t2+=2;
  120425. idij+=2;
  120426. t3=t2;
  120427. for(k=0;k<l1;k++){
  120428. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120429. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120430. t3+=ido;
  120431. }
  120432. }
  120433. }
  120434. return;
  120435. L139:
  120436. is= -ido-1;
  120437. t1=0;
  120438. for(j=1;j<ip;j++){
  120439. is+=ido;
  120440. t1+=t0;
  120441. t2=t1;
  120442. for(k=0;k<l1;k++){
  120443. idij=is;
  120444. t3=t2;
  120445. for(i=2;i<ido;i+=2){
  120446. idij+=2;
  120447. t3+=2;
  120448. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120449. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120450. }
  120451. t2+=ido;
  120452. }
  120453. }
  120454. }
  120455. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120456. int i,k1,l1,l2;
  120457. int na;
  120458. int nf,ip,iw,ix2,ix3,ido,idl1;
  120459. nf=ifac[1];
  120460. na=0;
  120461. l1=1;
  120462. iw=1;
  120463. for(k1=0;k1<nf;k1++){
  120464. ip=ifac[k1 + 2];
  120465. l2=ip*l1;
  120466. ido=n/l2;
  120467. idl1=ido*l1;
  120468. if(ip!=4)goto L103;
  120469. ix2=iw+ido;
  120470. ix3=ix2+ido;
  120471. if(na!=0)
  120472. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120473. else
  120474. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120475. na=1-na;
  120476. goto L115;
  120477. L103:
  120478. if(ip!=2)goto L106;
  120479. if(na!=0)
  120480. dradb2(ido,l1,ch,c,wa+iw-1);
  120481. else
  120482. dradb2(ido,l1,c,ch,wa+iw-1);
  120483. na=1-na;
  120484. goto L115;
  120485. L106:
  120486. if(ip!=3)goto L109;
  120487. ix2=iw+ido;
  120488. if(na!=0)
  120489. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120490. else
  120491. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120492. na=1-na;
  120493. goto L115;
  120494. L109:
  120495. /* The radix five case can be translated later..... */
  120496. /* if(ip!=5)goto L112;
  120497. ix2=iw+ido;
  120498. ix3=ix2+ido;
  120499. ix4=ix3+ido;
  120500. if(na!=0)
  120501. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120502. else
  120503. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120504. na=1-na;
  120505. goto L115;
  120506. L112:*/
  120507. if(na!=0)
  120508. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120509. else
  120510. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120511. if(ido==1)na=1-na;
  120512. L115:
  120513. l1=l2;
  120514. iw+=(ip-1)*ido;
  120515. }
  120516. if(na==0)return;
  120517. for(i=0;i<n;i++)c[i]=ch[i];
  120518. }
  120519. void drft_forward(drft_lookup *l,float *data){
  120520. if(l->n==1)return;
  120521. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120522. }
  120523. void drft_backward(drft_lookup *l,float *data){
  120524. if (l->n==1)return;
  120525. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120526. }
  120527. void drft_init(drft_lookup *l,int n){
  120528. l->n=n;
  120529. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120530. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120531. fdrffti(n, l->trigcache, l->splitcache);
  120532. }
  120533. void drft_clear(drft_lookup *l){
  120534. if(l){
  120535. if(l->trigcache)_ogg_free(l->trigcache);
  120536. if(l->splitcache)_ogg_free(l->splitcache);
  120537. memset(l,0,sizeof(*l));
  120538. }
  120539. }
  120540. #endif
  120541. /*** End of inlined file: smallft.c ***/
  120542. /*** Start of inlined file: synthesis.c ***/
  120543. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120544. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120545. // tasks..
  120546. #if JUCE_MSVC
  120547. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120548. #endif
  120549. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120550. #if JUCE_USE_OGGVORBIS
  120551. #include <stdio.h>
  120552. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120553. vorbis_dsp_state *vd=vb->vd;
  120554. private_state *b=(private_state*)vd->backend_state;
  120555. vorbis_info *vi=vd->vi;
  120556. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120557. oggpack_buffer *opb=&vb->opb;
  120558. int type,mode,i;
  120559. /* first things first. Make sure decode is ready */
  120560. _vorbis_block_ripcord(vb);
  120561. oggpack_readinit(opb,op->packet,op->bytes);
  120562. /* Check the packet type */
  120563. if(oggpack_read(opb,1)!=0){
  120564. /* Oops. This is not an audio data packet */
  120565. return(OV_ENOTAUDIO);
  120566. }
  120567. /* read our mode and pre/post windowsize */
  120568. mode=oggpack_read(opb,b->modebits);
  120569. if(mode==-1)return(OV_EBADPACKET);
  120570. vb->mode=mode;
  120571. vb->W=ci->mode_param[mode]->blockflag;
  120572. if(vb->W){
  120573. /* this doesn;t get mapped through mode selection as it's used
  120574. only for window selection */
  120575. vb->lW=oggpack_read(opb,1);
  120576. vb->nW=oggpack_read(opb,1);
  120577. if(vb->nW==-1) return(OV_EBADPACKET);
  120578. }else{
  120579. vb->lW=0;
  120580. vb->nW=0;
  120581. }
  120582. /* more setup */
  120583. vb->granulepos=op->granulepos;
  120584. vb->sequence=op->packetno;
  120585. vb->eofflag=op->e_o_s;
  120586. /* alloc pcm passback storage */
  120587. vb->pcmend=ci->blocksizes[vb->W];
  120588. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120589. for(i=0;i<vi->channels;i++)
  120590. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120591. /* unpack_header enforces range checking */
  120592. type=ci->map_type[ci->mode_param[mode]->mapping];
  120593. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120594. mapping]));
  120595. }
  120596. /* used to track pcm position without actually performing decode.
  120597. Useful for sequential 'fast forward' */
  120598. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120599. vorbis_dsp_state *vd=vb->vd;
  120600. private_state *b=(private_state*)vd->backend_state;
  120601. vorbis_info *vi=vd->vi;
  120602. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120603. oggpack_buffer *opb=&vb->opb;
  120604. int mode;
  120605. /* first things first. Make sure decode is ready */
  120606. _vorbis_block_ripcord(vb);
  120607. oggpack_readinit(opb,op->packet,op->bytes);
  120608. /* Check the packet type */
  120609. if(oggpack_read(opb,1)!=0){
  120610. /* Oops. This is not an audio data packet */
  120611. return(OV_ENOTAUDIO);
  120612. }
  120613. /* read our mode and pre/post windowsize */
  120614. mode=oggpack_read(opb,b->modebits);
  120615. if(mode==-1)return(OV_EBADPACKET);
  120616. vb->mode=mode;
  120617. vb->W=ci->mode_param[mode]->blockflag;
  120618. if(vb->W){
  120619. vb->lW=oggpack_read(opb,1);
  120620. vb->nW=oggpack_read(opb,1);
  120621. if(vb->nW==-1) return(OV_EBADPACKET);
  120622. }else{
  120623. vb->lW=0;
  120624. vb->nW=0;
  120625. }
  120626. /* more setup */
  120627. vb->granulepos=op->granulepos;
  120628. vb->sequence=op->packetno;
  120629. vb->eofflag=op->e_o_s;
  120630. /* no pcm */
  120631. vb->pcmend=0;
  120632. vb->pcm=NULL;
  120633. return(0);
  120634. }
  120635. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120636. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120637. oggpack_buffer opb;
  120638. int mode;
  120639. oggpack_readinit(&opb,op->packet,op->bytes);
  120640. /* Check the packet type */
  120641. if(oggpack_read(&opb,1)!=0){
  120642. /* Oops. This is not an audio data packet */
  120643. return(OV_ENOTAUDIO);
  120644. }
  120645. {
  120646. int modebits=0;
  120647. int v=ci->modes;
  120648. while(v>1){
  120649. modebits++;
  120650. v>>=1;
  120651. }
  120652. /* read our mode and pre/post windowsize */
  120653. mode=oggpack_read(&opb,modebits);
  120654. }
  120655. if(mode==-1)return(OV_EBADPACKET);
  120656. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120657. }
  120658. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120659. /* set / clear half-sample-rate mode */
  120660. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120661. /* right now, our MDCT can't handle < 64 sample windows. */
  120662. if(ci->blocksizes[0]<=64 && flag)return -1;
  120663. ci->halfrate_flag=(flag?1:0);
  120664. return 0;
  120665. }
  120666. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120667. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120668. return ci->halfrate_flag;
  120669. }
  120670. #endif
  120671. /*** End of inlined file: synthesis.c ***/
  120672. /*** Start of inlined file: vorbisenc.c ***/
  120673. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120674. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120675. // tasks..
  120676. #if JUCE_MSVC
  120677. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120678. #endif
  120679. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120680. #if JUCE_USE_OGGVORBIS
  120681. #include <stdlib.h>
  120682. #include <string.h>
  120683. #include <math.h>
  120684. /* careful with this; it's using static array sizing to make managing
  120685. all the modes a little less annoying. If we use a residue backend
  120686. with > 12 partition types, or a different division of iteration,
  120687. this needs to be updated. */
  120688. typedef struct {
  120689. static_codebook *books[12][3];
  120690. } static_bookblock;
  120691. typedef struct {
  120692. int res_type;
  120693. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120694. vorbis_info_residue0 *res;
  120695. static_codebook *book_aux;
  120696. static_codebook *book_aux_managed;
  120697. static_bookblock *books_base;
  120698. static_bookblock *books_base_managed;
  120699. } vorbis_residue_template;
  120700. typedef struct {
  120701. vorbis_info_mapping0 *map;
  120702. vorbis_residue_template *res;
  120703. } vorbis_mapping_template;
  120704. typedef struct vp_adjblock{
  120705. int block[P_BANDS];
  120706. } vp_adjblock;
  120707. typedef struct {
  120708. int data[NOISE_COMPAND_LEVELS];
  120709. } compandblock;
  120710. /* high level configuration information for setting things up
  120711. step-by-step with the detailed vorbis_encode_ctl interface.
  120712. There's a fair amount of redundancy such that interactive setup
  120713. does not directly deal with any vorbis_info or codec_setup_info
  120714. initialization; it's all stored (until full init) in this highlevel
  120715. setup, then flushed out to the real codec setup structs later. */
  120716. typedef struct {
  120717. int att[P_NOISECURVES];
  120718. float boost;
  120719. float decay;
  120720. } att3;
  120721. typedef struct { int data[P_NOISECURVES]; } adj3;
  120722. typedef struct {
  120723. int pre[PACKETBLOBS];
  120724. int post[PACKETBLOBS];
  120725. float kHz[PACKETBLOBS];
  120726. float lowpasskHz[PACKETBLOBS];
  120727. } adj_stereo;
  120728. typedef struct {
  120729. int lo;
  120730. int hi;
  120731. int fixed;
  120732. } noiseguard;
  120733. typedef struct {
  120734. int data[P_NOISECURVES][17];
  120735. } noise3;
  120736. typedef struct {
  120737. int mappings;
  120738. double *rate_mapping;
  120739. double *quality_mapping;
  120740. int coupling_restriction;
  120741. long samplerate_min_restriction;
  120742. long samplerate_max_restriction;
  120743. int *blocksize_short;
  120744. int *blocksize_long;
  120745. att3 *psy_tone_masteratt;
  120746. int *psy_tone_0dB;
  120747. int *psy_tone_dBsuppress;
  120748. vp_adjblock *psy_tone_adj_impulse;
  120749. vp_adjblock *psy_tone_adj_long;
  120750. vp_adjblock *psy_tone_adj_other;
  120751. noiseguard *psy_noiseguards;
  120752. noise3 *psy_noise_bias_impulse;
  120753. noise3 *psy_noise_bias_padding;
  120754. noise3 *psy_noise_bias_trans;
  120755. noise3 *psy_noise_bias_long;
  120756. int *psy_noise_dBsuppress;
  120757. compandblock *psy_noise_compand;
  120758. double *psy_noise_compand_short_mapping;
  120759. double *psy_noise_compand_long_mapping;
  120760. int *psy_noise_normal_start[2];
  120761. int *psy_noise_normal_partition[2];
  120762. double *psy_noise_normal_thresh;
  120763. int *psy_ath_float;
  120764. int *psy_ath_abs;
  120765. double *psy_lowpass;
  120766. vorbis_info_psy_global *global_params;
  120767. double *global_mapping;
  120768. adj_stereo *stereo_modes;
  120769. static_codebook ***floor_books;
  120770. vorbis_info_floor1 *floor_params;
  120771. int *floor_short_mapping;
  120772. int *floor_long_mapping;
  120773. vorbis_mapping_template *maps;
  120774. } ve_setup_data_template;
  120775. /* a few static coder conventions */
  120776. static vorbis_info_mode _mode_template[2]={
  120777. {0,0,0,0},
  120778. {1,0,0,1}
  120779. };
  120780. static vorbis_info_mapping0 _map_nominal[2]={
  120781. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120782. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120783. };
  120784. /*** Start of inlined file: setup_44.h ***/
  120785. /*** Start of inlined file: floor_all.h ***/
  120786. /*** Start of inlined file: floor_books.h ***/
  120787. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120788. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120789. };
  120790. static static_codebook _huff_book_line_256x7_0sub1 = {
  120791. 1, 9,
  120792. _huff_lengthlist_line_256x7_0sub1,
  120793. 0, 0, 0, 0, 0,
  120794. NULL,
  120795. NULL,
  120796. NULL,
  120797. NULL,
  120798. 0
  120799. };
  120800. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120802. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120803. };
  120804. static static_codebook _huff_book_line_256x7_0sub2 = {
  120805. 1, 25,
  120806. _huff_lengthlist_line_256x7_0sub2,
  120807. 0, 0, 0, 0, 0,
  120808. NULL,
  120809. NULL,
  120810. NULL,
  120811. NULL,
  120812. 0
  120813. };
  120814. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120817. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120818. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120819. };
  120820. static static_codebook _huff_book_line_256x7_0sub3 = {
  120821. 1, 64,
  120822. _huff_lengthlist_line_256x7_0sub3,
  120823. 0, 0, 0, 0, 0,
  120824. NULL,
  120825. NULL,
  120826. NULL,
  120827. NULL,
  120828. 0
  120829. };
  120830. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120831. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120832. };
  120833. static static_codebook _huff_book_line_256x7_1sub1 = {
  120834. 1, 9,
  120835. _huff_lengthlist_line_256x7_1sub1,
  120836. 0, 0, 0, 0, 0,
  120837. NULL,
  120838. NULL,
  120839. NULL,
  120840. NULL,
  120841. 0
  120842. };
  120843. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120845. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120846. };
  120847. static static_codebook _huff_book_line_256x7_1sub2 = {
  120848. 1, 25,
  120849. _huff_lengthlist_line_256x7_1sub2,
  120850. 0, 0, 0, 0, 0,
  120851. NULL,
  120852. NULL,
  120853. NULL,
  120854. NULL,
  120855. 0
  120856. };
  120857. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120860. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120861. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120862. };
  120863. static static_codebook _huff_book_line_256x7_1sub3 = {
  120864. 1, 64,
  120865. _huff_lengthlist_line_256x7_1sub3,
  120866. 0, 0, 0, 0, 0,
  120867. NULL,
  120868. NULL,
  120869. NULL,
  120870. NULL,
  120871. 0
  120872. };
  120873. static long _huff_lengthlist_line_256x7_class0[] = {
  120874. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120875. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120876. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120877. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120878. };
  120879. static static_codebook _huff_book_line_256x7_class0 = {
  120880. 1, 64,
  120881. _huff_lengthlist_line_256x7_class0,
  120882. 0, 0, 0, 0, 0,
  120883. NULL,
  120884. NULL,
  120885. NULL,
  120886. NULL,
  120887. 0
  120888. };
  120889. static long _huff_lengthlist_line_256x7_class1[] = {
  120890. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120891. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120892. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120893. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120894. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120895. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120896. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120897. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120898. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120899. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120900. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120901. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120902. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120903. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120904. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120905. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120906. };
  120907. static static_codebook _huff_book_line_256x7_class1 = {
  120908. 1, 256,
  120909. _huff_lengthlist_line_256x7_class1,
  120910. 0, 0, 0, 0, 0,
  120911. NULL,
  120912. NULL,
  120913. NULL,
  120914. NULL,
  120915. 0
  120916. };
  120917. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120918. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120919. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120920. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120921. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120922. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120923. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120924. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120925. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120926. };
  120927. static static_codebook _huff_book_line_512x17_0sub0 = {
  120928. 1, 128,
  120929. _huff_lengthlist_line_512x17_0sub0,
  120930. 0, 0, 0, 0, 0,
  120931. NULL,
  120932. NULL,
  120933. NULL,
  120934. NULL,
  120935. 0
  120936. };
  120937. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120938. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120939. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120940. };
  120941. static static_codebook _huff_book_line_512x17_1sub0 = {
  120942. 1, 32,
  120943. _huff_lengthlist_line_512x17_1sub0,
  120944. 0, 0, 0, 0, 0,
  120945. NULL,
  120946. NULL,
  120947. NULL,
  120948. NULL,
  120949. 0
  120950. };
  120951. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120954. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120955. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120956. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120957. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120958. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120959. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120960. };
  120961. static static_codebook _huff_book_line_512x17_1sub1 = {
  120962. 1, 128,
  120963. _huff_lengthlist_line_512x17_1sub1,
  120964. 0, 0, 0, 0, 0,
  120965. NULL,
  120966. NULL,
  120967. NULL,
  120968. NULL,
  120969. 0
  120970. };
  120971. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120972. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120973. 5, 3,
  120974. };
  120975. static static_codebook _huff_book_line_512x17_2sub1 = {
  120976. 1, 18,
  120977. _huff_lengthlist_line_512x17_2sub1,
  120978. 0, 0, 0, 0, 0,
  120979. NULL,
  120980. NULL,
  120981. NULL,
  120982. NULL,
  120983. 0
  120984. };
  120985. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120987. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120988. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120989. 9, 8,
  120990. };
  120991. static static_codebook _huff_book_line_512x17_2sub2 = {
  120992. 1, 50,
  120993. _huff_lengthlist_line_512x17_2sub2,
  120994. 0, 0, 0, 0, 0,
  120995. NULL,
  120996. NULL,
  120997. NULL,
  120998. NULL,
  120999. 0
  121000. };
  121001. static long _huff_lengthlist_line_512x17_2sub3[] = {
  121002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121005. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  121006. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  121007. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121008. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121009. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121010. };
  121011. static static_codebook _huff_book_line_512x17_2sub3 = {
  121012. 1, 128,
  121013. _huff_lengthlist_line_512x17_2sub3,
  121014. 0, 0, 0, 0, 0,
  121015. NULL,
  121016. NULL,
  121017. NULL,
  121018. NULL,
  121019. 0
  121020. };
  121021. static long _huff_lengthlist_line_512x17_3sub1[] = {
  121022. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  121023. 5, 5,
  121024. };
  121025. static static_codebook _huff_book_line_512x17_3sub1 = {
  121026. 1, 18,
  121027. _huff_lengthlist_line_512x17_3sub1,
  121028. 0, 0, 0, 0, 0,
  121029. NULL,
  121030. NULL,
  121031. NULL,
  121032. NULL,
  121033. 0
  121034. };
  121035. static long _huff_lengthlist_line_512x17_3sub2[] = {
  121036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121037. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  121038. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  121039. 11,14,
  121040. };
  121041. static static_codebook _huff_book_line_512x17_3sub2 = {
  121042. 1, 50,
  121043. _huff_lengthlist_line_512x17_3sub2,
  121044. 0, 0, 0, 0, 0,
  121045. NULL,
  121046. NULL,
  121047. NULL,
  121048. NULL,
  121049. 0
  121050. };
  121051. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121055. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121056. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121057. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121058. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121059. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121060. };
  121061. static static_codebook _huff_book_line_512x17_3sub3 = {
  121062. 1, 128,
  121063. _huff_lengthlist_line_512x17_3sub3,
  121064. 0, 0, 0, 0, 0,
  121065. NULL,
  121066. NULL,
  121067. NULL,
  121068. NULL,
  121069. 0
  121070. };
  121071. static long _huff_lengthlist_line_512x17_class1[] = {
  121072. 1, 2, 3, 6, 5, 4, 7, 7,
  121073. };
  121074. static static_codebook _huff_book_line_512x17_class1 = {
  121075. 1, 8,
  121076. _huff_lengthlist_line_512x17_class1,
  121077. 0, 0, 0, 0, 0,
  121078. NULL,
  121079. NULL,
  121080. NULL,
  121081. NULL,
  121082. 0
  121083. };
  121084. static long _huff_lengthlist_line_512x17_class2[] = {
  121085. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121086. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121087. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121088. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121089. };
  121090. static static_codebook _huff_book_line_512x17_class2 = {
  121091. 1, 64,
  121092. _huff_lengthlist_line_512x17_class2,
  121093. 0, 0, 0, 0, 0,
  121094. NULL,
  121095. NULL,
  121096. NULL,
  121097. NULL,
  121098. 0
  121099. };
  121100. static long _huff_lengthlist_line_512x17_class3[] = {
  121101. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121102. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121103. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121104. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121105. };
  121106. static static_codebook _huff_book_line_512x17_class3 = {
  121107. 1, 64,
  121108. _huff_lengthlist_line_512x17_class3,
  121109. 0, 0, 0, 0, 0,
  121110. NULL,
  121111. NULL,
  121112. NULL,
  121113. NULL,
  121114. 0
  121115. };
  121116. static long _huff_lengthlist_line_128x4_class0[] = {
  121117. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121118. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121119. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121120. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121121. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121122. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121123. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121124. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121125. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121126. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121127. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121128. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121129. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121130. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121131. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121132. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121133. };
  121134. static static_codebook _huff_book_line_128x4_class0 = {
  121135. 1, 256,
  121136. _huff_lengthlist_line_128x4_class0,
  121137. 0, 0, 0, 0, 0,
  121138. NULL,
  121139. NULL,
  121140. NULL,
  121141. NULL,
  121142. 0
  121143. };
  121144. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121145. 2, 2, 2, 2,
  121146. };
  121147. static static_codebook _huff_book_line_128x4_0sub0 = {
  121148. 1, 4,
  121149. _huff_lengthlist_line_128x4_0sub0,
  121150. 0, 0, 0, 0, 0,
  121151. NULL,
  121152. NULL,
  121153. NULL,
  121154. NULL,
  121155. 0
  121156. };
  121157. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121158. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121159. };
  121160. static static_codebook _huff_book_line_128x4_0sub1 = {
  121161. 1, 10,
  121162. _huff_lengthlist_line_128x4_0sub1,
  121163. 0, 0, 0, 0, 0,
  121164. NULL,
  121165. NULL,
  121166. NULL,
  121167. NULL,
  121168. 0
  121169. };
  121170. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121172. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121173. };
  121174. static static_codebook _huff_book_line_128x4_0sub2 = {
  121175. 1, 25,
  121176. _huff_lengthlist_line_128x4_0sub2,
  121177. 0, 0, 0, 0, 0,
  121178. NULL,
  121179. NULL,
  121180. NULL,
  121181. NULL,
  121182. 0
  121183. };
  121184. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121187. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121188. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121189. };
  121190. static static_codebook _huff_book_line_128x4_0sub3 = {
  121191. 1, 64,
  121192. _huff_lengthlist_line_128x4_0sub3,
  121193. 0, 0, 0, 0, 0,
  121194. NULL,
  121195. NULL,
  121196. NULL,
  121197. NULL,
  121198. 0
  121199. };
  121200. static long _huff_lengthlist_line_256x4_class0[] = {
  121201. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121202. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121203. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121204. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121205. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121206. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121207. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121208. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121209. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121210. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121211. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121212. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121213. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121214. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121215. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121216. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121217. };
  121218. static static_codebook _huff_book_line_256x4_class0 = {
  121219. 1, 256,
  121220. _huff_lengthlist_line_256x4_class0,
  121221. 0, 0, 0, 0, 0,
  121222. NULL,
  121223. NULL,
  121224. NULL,
  121225. NULL,
  121226. 0
  121227. };
  121228. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121229. 2, 2, 2, 2,
  121230. };
  121231. static static_codebook _huff_book_line_256x4_0sub0 = {
  121232. 1, 4,
  121233. _huff_lengthlist_line_256x4_0sub0,
  121234. 0, 0, 0, 0, 0,
  121235. NULL,
  121236. NULL,
  121237. NULL,
  121238. NULL,
  121239. 0
  121240. };
  121241. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121242. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121243. };
  121244. static static_codebook _huff_book_line_256x4_0sub1 = {
  121245. 1, 10,
  121246. _huff_lengthlist_line_256x4_0sub1,
  121247. 0, 0, 0, 0, 0,
  121248. NULL,
  121249. NULL,
  121250. NULL,
  121251. NULL,
  121252. 0
  121253. };
  121254. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121256. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121257. };
  121258. static static_codebook _huff_book_line_256x4_0sub2 = {
  121259. 1, 25,
  121260. _huff_lengthlist_line_256x4_0sub2,
  121261. 0, 0, 0, 0, 0,
  121262. NULL,
  121263. NULL,
  121264. NULL,
  121265. NULL,
  121266. 0
  121267. };
  121268. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121271. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121272. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121273. };
  121274. static static_codebook _huff_book_line_256x4_0sub3 = {
  121275. 1, 64,
  121276. _huff_lengthlist_line_256x4_0sub3,
  121277. 0, 0, 0, 0, 0,
  121278. NULL,
  121279. NULL,
  121280. NULL,
  121281. NULL,
  121282. 0
  121283. };
  121284. static long _huff_lengthlist_line_128x7_class0[] = {
  121285. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121286. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121287. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121288. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121289. };
  121290. static static_codebook _huff_book_line_128x7_class0 = {
  121291. 1, 64,
  121292. _huff_lengthlist_line_128x7_class0,
  121293. 0, 0, 0, 0, 0,
  121294. NULL,
  121295. NULL,
  121296. NULL,
  121297. NULL,
  121298. 0
  121299. };
  121300. static long _huff_lengthlist_line_128x7_class1[] = {
  121301. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121302. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121303. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121304. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121305. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121306. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121307. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121308. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121309. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121310. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121311. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121312. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121313. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121314. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121315. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121316. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121317. };
  121318. static static_codebook _huff_book_line_128x7_class1 = {
  121319. 1, 256,
  121320. _huff_lengthlist_line_128x7_class1,
  121321. 0, 0, 0, 0, 0,
  121322. NULL,
  121323. NULL,
  121324. NULL,
  121325. NULL,
  121326. 0
  121327. };
  121328. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121329. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121330. };
  121331. static static_codebook _huff_book_line_128x7_0sub1 = {
  121332. 1, 9,
  121333. _huff_lengthlist_line_128x7_0sub1,
  121334. 0, 0, 0, 0, 0,
  121335. NULL,
  121336. NULL,
  121337. NULL,
  121338. NULL,
  121339. 0
  121340. };
  121341. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121343. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121344. };
  121345. static static_codebook _huff_book_line_128x7_0sub2 = {
  121346. 1, 25,
  121347. _huff_lengthlist_line_128x7_0sub2,
  121348. 0, 0, 0, 0, 0,
  121349. NULL,
  121350. NULL,
  121351. NULL,
  121352. NULL,
  121353. 0
  121354. };
  121355. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121358. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121359. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121360. };
  121361. static static_codebook _huff_book_line_128x7_0sub3 = {
  121362. 1, 64,
  121363. _huff_lengthlist_line_128x7_0sub3,
  121364. 0, 0, 0, 0, 0,
  121365. NULL,
  121366. NULL,
  121367. NULL,
  121368. NULL,
  121369. 0
  121370. };
  121371. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121372. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121373. };
  121374. static static_codebook _huff_book_line_128x7_1sub1 = {
  121375. 1, 9,
  121376. _huff_lengthlist_line_128x7_1sub1,
  121377. 0, 0, 0, 0, 0,
  121378. NULL,
  121379. NULL,
  121380. NULL,
  121381. NULL,
  121382. 0
  121383. };
  121384. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121386. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121387. };
  121388. static static_codebook _huff_book_line_128x7_1sub2 = {
  121389. 1, 25,
  121390. _huff_lengthlist_line_128x7_1sub2,
  121391. 0, 0, 0, 0, 0,
  121392. NULL,
  121393. NULL,
  121394. NULL,
  121395. NULL,
  121396. 0
  121397. };
  121398. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121401. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121402. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121403. };
  121404. static static_codebook _huff_book_line_128x7_1sub3 = {
  121405. 1, 64,
  121406. _huff_lengthlist_line_128x7_1sub3,
  121407. 0, 0, 0, 0, 0,
  121408. NULL,
  121409. NULL,
  121410. NULL,
  121411. NULL,
  121412. 0
  121413. };
  121414. static long _huff_lengthlist_line_128x11_class1[] = {
  121415. 1, 6, 3, 7, 2, 4, 5, 7,
  121416. };
  121417. static static_codebook _huff_book_line_128x11_class1 = {
  121418. 1, 8,
  121419. _huff_lengthlist_line_128x11_class1,
  121420. 0, 0, 0, 0, 0,
  121421. NULL,
  121422. NULL,
  121423. NULL,
  121424. NULL,
  121425. 0
  121426. };
  121427. static long _huff_lengthlist_line_128x11_class2[] = {
  121428. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121429. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121430. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121431. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121432. };
  121433. static static_codebook _huff_book_line_128x11_class2 = {
  121434. 1, 64,
  121435. _huff_lengthlist_line_128x11_class2,
  121436. 0, 0, 0, 0, 0,
  121437. NULL,
  121438. NULL,
  121439. NULL,
  121440. NULL,
  121441. 0
  121442. };
  121443. static long _huff_lengthlist_line_128x11_class3[] = {
  121444. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121445. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121446. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121447. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121448. };
  121449. static static_codebook _huff_book_line_128x11_class3 = {
  121450. 1, 64,
  121451. _huff_lengthlist_line_128x11_class3,
  121452. 0, 0, 0, 0, 0,
  121453. NULL,
  121454. NULL,
  121455. NULL,
  121456. NULL,
  121457. 0
  121458. };
  121459. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121460. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121461. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121462. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121463. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121464. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121465. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121466. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121467. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121468. };
  121469. static static_codebook _huff_book_line_128x11_0sub0 = {
  121470. 1, 128,
  121471. _huff_lengthlist_line_128x11_0sub0,
  121472. 0, 0, 0, 0, 0,
  121473. NULL,
  121474. NULL,
  121475. NULL,
  121476. NULL,
  121477. 0
  121478. };
  121479. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121480. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121481. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121482. };
  121483. static static_codebook _huff_book_line_128x11_1sub0 = {
  121484. 1, 32,
  121485. _huff_lengthlist_line_128x11_1sub0,
  121486. 0, 0, 0, 0, 0,
  121487. NULL,
  121488. NULL,
  121489. NULL,
  121490. NULL,
  121491. 0
  121492. };
  121493. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121496. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121497. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121498. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121499. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121500. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121501. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121502. };
  121503. static static_codebook _huff_book_line_128x11_1sub1 = {
  121504. 1, 128,
  121505. _huff_lengthlist_line_128x11_1sub1,
  121506. 0, 0, 0, 0, 0,
  121507. NULL,
  121508. NULL,
  121509. NULL,
  121510. NULL,
  121511. 0
  121512. };
  121513. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121514. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121515. 5, 5,
  121516. };
  121517. static static_codebook _huff_book_line_128x11_2sub1 = {
  121518. 1, 18,
  121519. _huff_lengthlist_line_128x11_2sub1,
  121520. 0, 0, 0, 0, 0,
  121521. NULL,
  121522. NULL,
  121523. NULL,
  121524. NULL,
  121525. 0
  121526. };
  121527. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121529. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121530. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121531. 8,11,
  121532. };
  121533. static static_codebook _huff_book_line_128x11_2sub2 = {
  121534. 1, 50,
  121535. _huff_lengthlist_line_128x11_2sub2,
  121536. 0, 0, 0, 0, 0,
  121537. NULL,
  121538. NULL,
  121539. NULL,
  121540. NULL,
  121541. 0
  121542. };
  121543. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121547. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121548. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121549. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121550. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121551. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121552. };
  121553. static static_codebook _huff_book_line_128x11_2sub3 = {
  121554. 1, 128,
  121555. _huff_lengthlist_line_128x11_2sub3,
  121556. 0, 0, 0, 0, 0,
  121557. NULL,
  121558. NULL,
  121559. NULL,
  121560. NULL,
  121561. 0
  121562. };
  121563. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121564. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121565. 5, 4,
  121566. };
  121567. static static_codebook _huff_book_line_128x11_3sub1 = {
  121568. 1, 18,
  121569. _huff_lengthlist_line_128x11_3sub1,
  121570. 0, 0, 0, 0, 0,
  121571. NULL,
  121572. NULL,
  121573. NULL,
  121574. NULL,
  121575. 0
  121576. };
  121577. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121579. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121580. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121581. 12, 6,
  121582. };
  121583. static static_codebook _huff_book_line_128x11_3sub2 = {
  121584. 1, 50,
  121585. _huff_lengthlist_line_128x11_3sub2,
  121586. 0, 0, 0, 0, 0,
  121587. NULL,
  121588. NULL,
  121589. NULL,
  121590. NULL,
  121591. 0
  121592. };
  121593. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121597. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121598. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121599. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121600. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121601. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121602. };
  121603. static static_codebook _huff_book_line_128x11_3sub3 = {
  121604. 1, 128,
  121605. _huff_lengthlist_line_128x11_3sub3,
  121606. 0, 0, 0, 0, 0,
  121607. NULL,
  121608. NULL,
  121609. NULL,
  121610. NULL,
  121611. 0
  121612. };
  121613. static long _huff_lengthlist_line_128x17_class1[] = {
  121614. 1, 3, 4, 7, 2, 5, 6, 7,
  121615. };
  121616. static static_codebook _huff_book_line_128x17_class1 = {
  121617. 1, 8,
  121618. _huff_lengthlist_line_128x17_class1,
  121619. 0, 0, 0, 0, 0,
  121620. NULL,
  121621. NULL,
  121622. NULL,
  121623. NULL,
  121624. 0
  121625. };
  121626. static long _huff_lengthlist_line_128x17_class2[] = {
  121627. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121628. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121629. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121630. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121631. };
  121632. static static_codebook _huff_book_line_128x17_class2 = {
  121633. 1, 64,
  121634. _huff_lengthlist_line_128x17_class2,
  121635. 0, 0, 0, 0, 0,
  121636. NULL,
  121637. NULL,
  121638. NULL,
  121639. NULL,
  121640. 0
  121641. };
  121642. static long _huff_lengthlist_line_128x17_class3[] = {
  121643. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121644. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121645. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121646. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121647. };
  121648. static static_codebook _huff_book_line_128x17_class3 = {
  121649. 1, 64,
  121650. _huff_lengthlist_line_128x17_class3,
  121651. 0, 0, 0, 0, 0,
  121652. NULL,
  121653. NULL,
  121654. NULL,
  121655. NULL,
  121656. 0
  121657. };
  121658. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121659. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121660. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121661. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121662. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121663. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121664. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121665. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121666. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121667. };
  121668. static static_codebook _huff_book_line_128x17_0sub0 = {
  121669. 1, 128,
  121670. _huff_lengthlist_line_128x17_0sub0,
  121671. 0, 0, 0, 0, 0,
  121672. NULL,
  121673. NULL,
  121674. NULL,
  121675. NULL,
  121676. 0
  121677. };
  121678. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121679. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121680. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121681. };
  121682. static static_codebook _huff_book_line_128x17_1sub0 = {
  121683. 1, 32,
  121684. _huff_lengthlist_line_128x17_1sub0,
  121685. 0, 0, 0, 0, 0,
  121686. NULL,
  121687. NULL,
  121688. NULL,
  121689. NULL,
  121690. 0
  121691. };
  121692. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121695. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121696. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121697. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121698. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121699. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121700. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121701. };
  121702. static static_codebook _huff_book_line_128x17_1sub1 = {
  121703. 1, 128,
  121704. _huff_lengthlist_line_128x17_1sub1,
  121705. 0, 0, 0, 0, 0,
  121706. NULL,
  121707. NULL,
  121708. NULL,
  121709. NULL,
  121710. 0
  121711. };
  121712. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121713. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121714. 9, 4,
  121715. };
  121716. static static_codebook _huff_book_line_128x17_2sub1 = {
  121717. 1, 18,
  121718. _huff_lengthlist_line_128x17_2sub1,
  121719. 0, 0, 0, 0, 0,
  121720. NULL,
  121721. NULL,
  121722. NULL,
  121723. NULL,
  121724. 0
  121725. };
  121726. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121728. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121729. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121730. 13,13,
  121731. };
  121732. static static_codebook _huff_book_line_128x17_2sub2 = {
  121733. 1, 50,
  121734. _huff_lengthlist_line_128x17_2sub2,
  121735. 0, 0, 0, 0, 0,
  121736. NULL,
  121737. NULL,
  121738. NULL,
  121739. NULL,
  121740. 0
  121741. };
  121742. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121746. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121747. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121748. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121749. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121750. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121751. };
  121752. static static_codebook _huff_book_line_128x17_2sub3 = {
  121753. 1, 128,
  121754. _huff_lengthlist_line_128x17_2sub3,
  121755. 0, 0, 0, 0, 0,
  121756. NULL,
  121757. NULL,
  121758. NULL,
  121759. NULL,
  121760. 0
  121761. };
  121762. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121763. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121764. 6, 4,
  121765. };
  121766. static static_codebook _huff_book_line_128x17_3sub1 = {
  121767. 1, 18,
  121768. _huff_lengthlist_line_128x17_3sub1,
  121769. 0, 0, 0, 0, 0,
  121770. NULL,
  121771. NULL,
  121772. NULL,
  121773. NULL,
  121774. 0
  121775. };
  121776. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121778. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121779. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121780. 10, 8,
  121781. };
  121782. static static_codebook _huff_book_line_128x17_3sub2 = {
  121783. 1, 50,
  121784. _huff_lengthlist_line_128x17_3sub2,
  121785. 0, 0, 0, 0, 0,
  121786. NULL,
  121787. NULL,
  121788. NULL,
  121789. NULL,
  121790. 0
  121791. };
  121792. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121796. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121797. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121798. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121799. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121800. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121801. };
  121802. static static_codebook _huff_book_line_128x17_3sub3 = {
  121803. 1, 128,
  121804. _huff_lengthlist_line_128x17_3sub3,
  121805. 0, 0, 0, 0, 0,
  121806. NULL,
  121807. NULL,
  121808. NULL,
  121809. NULL,
  121810. 0
  121811. };
  121812. static long _huff_lengthlist_line_1024x27_class1[] = {
  121813. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121814. };
  121815. static static_codebook _huff_book_line_1024x27_class1 = {
  121816. 1, 16,
  121817. _huff_lengthlist_line_1024x27_class1,
  121818. 0, 0, 0, 0, 0,
  121819. NULL,
  121820. NULL,
  121821. NULL,
  121822. NULL,
  121823. 0
  121824. };
  121825. static long _huff_lengthlist_line_1024x27_class2[] = {
  121826. 1, 4, 2, 6, 3, 7, 5, 7,
  121827. };
  121828. static static_codebook _huff_book_line_1024x27_class2 = {
  121829. 1, 8,
  121830. _huff_lengthlist_line_1024x27_class2,
  121831. 0, 0, 0, 0, 0,
  121832. NULL,
  121833. NULL,
  121834. NULL,
  121835. NULL,
  121836. 0
  121837. };
  121838. static long _huff_lengthlist_line_1024x27_class3[] = {
  121839. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121840. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121841. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121842. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121843. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121844. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121845. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121846. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121847. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121848. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121849. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121850. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121851. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121852. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121853. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121854. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121855. };
  121856. static static_codebook _huff_book_line_1024x27_class3 = {
  121857. 1, 256,
  121858. _huff_lengthlist_line_1024x27_class3,
  121859. 0, 0, 0, 0, 0,
  121860. NULL,
  121861. NULL,
  121862. NULL,
  121863. NULL,
  121864. 0
  121865. };
  121866. static long _huff_lengthlist_line_1024x27_class4[] = {
  121867. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121868. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121869. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121870. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121871. };
  121872. static static_codebook _huff_book_line_1024x27_class4 = {
  121873. 1, 64,
  121874. _huff_lengthlist_line_1024x27_class4,
  121875. 0, 0, 0, 0, 0,
  121876. NULL,
  121877. NULL,
  121878. NULL,
  121879. NULL,
  121880. 0
  121881. };
  121882. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121883. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121884. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121885. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121886. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121887. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121888. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121889. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121890. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121891. };
  121892. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121893. 1, 128,
  121894. _huff_lengthlist_line_1024x27_0sub0,
  121895. 0, 0, 0, 0, 0,
  121896. NULL,
  121897. NULL,
  121898. NULL,
  121899. NULL,
  121900. 0
  121901. };
  121902. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121903. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121904. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121905. };
  121906. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121907. 1, 32,
  121908. _huff_lengthlist_line_1024x27_1sub0,
  121909. 0, 0, 0, 0, 0,
  121910. NULL,
  121911. NULL,
  121912. NULL,
  121913. NULL,
  121914. 0
  121915. };
  121916. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121919. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121920. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121921. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121922. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121923. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121924. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121925. };
  121926. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121927. 1, 128,
  121928. _huff_lengthlist_line_1024x27_1sub1,
  121929. 0, 0, 0, 0, 0,
  121930. NULL,
  121931. NULL,
  121932. NULL,
  121933. NULL,
  121934. 0
  121935. };
  121936. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121937. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121938. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121939. };
  121940. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121941. 1, 32,
  121942. _huff_lengthlist_line_1024x27_2sub0,
  121943. 0, 0, 0, 0, 0,
  121944. NULL,
  121945. NULL,
  121946. NULL,
  121947. NULL,
  121948. 0
  121949. };
  121950. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121953. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121954. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121955. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121956. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121957. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121958. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121959. };
  121960. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121961. 1, 128,
  121962. _huff_lengthlist_line_1024x27_2sub1,
  121963. 0, 0, 0, 0, 0,
  121964. NULL,
  121965. NULL,
  121966. NULL,
  121967. NULL,
  121968. 0
  121969. };
  121970. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121971. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121972. 5, 5,
  121973. };
  121974. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121975. 1, 18,
  121976. _huff_lengthlist_line_1024x27_3sub1,
  121977. 0, 0, 0, 0, 0,
  121978. NULL,
  121979. NULL,
  121980. NULL,
  121981. NULL,
  121982. 0
  121983. };
  121984. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121986. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121987. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121988. 9,11,
  121989. };
  121990. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121991. 1, 50,
  121992. _huff_lengthlist_line_1024x27_3sub2,
  121993. 0, 0, 0, 0, 0,
  121994. NULL,
  121995. NULL,
  121996. NULL,
  121997. NULL,
  121998. 0
  121999. };
  122000. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  122001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122004. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  122005. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  122006. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122007. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122008. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122009. };
  122010. static static_codebook _huff_book_line_1024x27_3sub3 = {
  122011. 1, 128,
  122012. _huff_lengthlist_line_1024x27_3sub3,
  122013. 0, 0, 0, 0, 0,
  122014. NULL,
  122015. NULL,
  122016. NULL,
  122017. NULL,
  122018. 0
  122019. };
  122020. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  122021. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  122022. 5, 4,
  122023. };
  122024. static static_codebook _huff_book_line_1024x27_4sub1 = {
  122025. 1, 18,
  122026. _huff_lengthlist_line_1024x27_4sub1,
  122027. 0, 0, 0, 0, 0,
  122028. NULL,
  122029. NULL,
  122030. NULL,
  122031. NULL,
  122032. 0
  122033. };
  122034. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  122035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122036. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  122037. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  122038. 9,12,
  122039. };
  122040. static static_codebook _huff_book_line_1024x27_4sub2 = {
  122041. 1, 50,
  122042. _huff_lengthlist_line_1024x27_4sub2,
  122043. 0, 0, 0, 0, 0,
  122044. NULL,
  122045. NULL,
  122046. NULL,
  122047. NULL,
  122048. 0
  122049. };
  122050. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122054. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122055. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122056. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122057. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122058. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122059. };
  122060. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122061. 1, 128,
  122062. _huff_lengthlist_line_1024x27_4sub3,
  122063. 0, 0, 0, 0, 0,
  122064. NULL,
  122065. NULL,
  122066. NULL,
  122067. NULL,
  122068. 0
  122069. };
  122070. static long _huff_lengthlist_line_2048x27_class1[] = {
  122071. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122072. };
  122073. static static_codebook _huff_book_line_2048x27_class1 = {
  122074. 1, 16,
  122075. _huff_lengthlist_line_2048x27_class1,
  122076. 0, 0, 0, 0, 0,
  122077. NULL,
  122078. NULL,
  122079. NULL,
  122080. NULL,
  122081. 0
  122082. };
  122083. static long _huff_lengthlist_line_2048x27_class2[] = {
  122084. 1, 2, 3, 6, 4, 7, 5, 7,
  122085. };
  122086. static static_codebook _huff_book_line_2048x27_class2 = {
  122087. 1, 8,
  122088. _huff_lengthlist_line_2048x27_class2,
  122089. 0, 0, 0, 0, 0,
  122090. NULL,
  122091. NULL,
  122092. NULL,
  122093. NULL,
  122094. 0
  122095. };
  122096. static long _huff_lengthlist_line_2048x27_class3[] = {
  122097. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122098. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122099. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122100. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122101. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122102. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122103. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122104. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122105. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122106. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122107. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122108. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122109. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122110. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122111. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122112. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122113. };
  122114. static static_codebook _huff_book_line_2048x27_class3 = {
  122115. 1, 256,
  122116. _huff_lengthlist_line_2048x27_class3,
  122117. 0, 0, 0, 0, 0,
  122118. NULL,
  122119. NULL,
  122120. NULL,
  122121. NULL,
  122122. 0
  122123. };
  122124. static long _huff_lengthlist_line_2048x27_class4[] = {
  122125. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122126. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122127. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122128. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122129. };
  122130. static static_codebook _huff_book_line_2048x27_class4 = {
  122131. 1, 64,
  122132. _huff_lengthlist_line_2048x27_class4,
  122133. 0, 0, 0, 0, 0,
  122134. NULL,
  122135. NULL,
  122136. NULL,
  122137. NULL,
  122138. 0
  122139. };
  122140. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122141. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122142. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122143. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122144. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122145. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122146. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122147. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122148. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122149. };
  122150. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122151. 1, 128,
  122152. _huff_lengthlist_line_2048x27_0sub0,
  122153. 0, 0, 0, 0, 0,
  122154. NULL,
  122155. NULL,
  122156. NULL,
  122157. NULL,
  122158. 0
  122159. };
  122160. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122161. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122162. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122163. };
  122164. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122165. 1, 32,
  122166. _huff_lengthlist_line_2048x27_1sub0,
  122167. 0, 0, 0, 0, 0,
  122168. NULL,
  122169. NULL,
  122170. NULL,
  122171. NULL,
  122172. 0
  122173. };
  122174. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122177. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122178. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122179. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122180. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122181. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122182. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122183. };
  122184. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122185. 1, 128,
  122186. _huff_lengthlist_line_2048x27_1sub1,
  122187. 0, 0, 0, 0, 0,
  122188. NULL,
  122189. NULL,
  122190. NULL,
  122191. NULL,
  122192. 0
  122193. };
  122194. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122195. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122196. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122197. };
  122198. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122199. 1, 32,
  122200. _huff_lengthlist_line_2048x27_2sub0,
  122201. 0, 0, 0, 0, 0,
  122202. NULL,
  122203. NULL,
  122204. NULL,
  122205. NULL,
  122206. 0
  122207. };
  122208. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122211. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122212. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122213. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122214. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122215. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122216. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122217. };
  122218. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122219. 1, 128,
  122220. _huff_lengthlist_line_2048x27_2sub1,
  122221. 0, 0, 0, 0, 0,
  122222. NULL,
  122223. NULL,
  122224. NULL,
  122225. NULL,
  122226. 0
  122227. };
  122228. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122229. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122230. 5, 5,
  122231. };
  122232. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122233. 1, 18,
  122234. _huff_lengthlist_line_2048x27_3sub1,
  122235. 0, 0, 0, 0, 0,
  122236. NULL,
  122237. NULL,
  122238. NULL,
  122239. NULL,
  122240. 0
  122241. };
  122242. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122244. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122245. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122246. 10,12,
  122247. };
  122248. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122249. 1, 50,
  122250. _huff_lengthlist_line_2048x27_3sub2,
  122251. 0, 0, 0, 0, 0,
  122252. NULL,
  122253. NULL,
  122254. NULL,
  122255. NULL,
  122256. 0
  122257. };
  122258. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122262. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122263. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122264. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122265. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122266. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122267. };
  122268. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122269. 1, 128,
  122270. _huff_lengthlist_line_2048x27_3sub3,
  122271. 0, 0, 0, 0, 0,
  122272. NULL,
  122273. NULL,
  122274. NULL,
  122275. NULL,
  122276. 0
  122277. };
  122278. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122279. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122280. 4, 5,
  122281. };
  122282. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122283. 1, 18,
  122284. _huff_lengthlist_line_2048x27_4sub1,
  122285. 0, 0, 0, 0, 0,
  122286. NULL,
  122287. NULL,
  122288. NULL,
  122289. NULL,
  122290. 0
  122291. };
  122292. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122294. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122295. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122296. 10,10,
  122297. };
  122298. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122299. 1, 50,
  122300. _huff_lengthlist_line_2048x27_4sub2,
  122301. 0, 0, 0, 0, 0,
  122302. NULL,
  122303. NULL,
  122304. NULL,
  122305. NULL,
  122306. 0
  122307. };
  122308. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122312. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122313. 5, 7, 5, 7, 7, 7, 7, 7, 4, 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. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122316. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122317. };
  122318. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122319. 1, 128,
  122320. _huff_lengthlist_line_2048x27_4sub3,
  122321. 0, 0, 0, 0, 0,
  122322. NULL,
  122323. NULL,
  122324. NULL,
  122325. NULL,
  122326. 0
  122327. };
  122328. static long _huff_lengthlist_line_256x4low_class0[] = {
  122329. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122330. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122331. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122332. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122333. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122334. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122335. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122336. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122337. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122338. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122339. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122340. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122341. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122342. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122343. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122344. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122345. };
  122346. static static_codebook _huff_book_line_256x4low_class0 = {
  122347. 1, 256,
  122348. _huff_lengthlist_line_256x4low_class0,
  122349. 0, 0, 0, 0, 0,
  122350. NULL,
  122351. NULL,
  122352. NULL,
  122353. NULL,
  122354. 0
  122355. };
  122356. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122357. 1, 3, 2, 3,
  122358. };
  122359. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122360. 1, 4,
  122361. _huff_lengthlist_line_256x4low_0sub0,
  122362. 0, 0, 0, 0, 0,
  122363. NULL,
  122364. NULL,
  122365. NULL,
  122366. NULL,
  122367. 0
  122368. };
  122369. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122370. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122371. };
  122372. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122373. 1, 10,
  122374. _huff_lengthlist_line_256x4low_0sub1,
  122375. 0, 0, 0, 0, 0,
  122376. NULL,
  122377. NULL,
  122378. NULL,
  122379. NULL,
  122380. 0
  122381. };
  122382. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122384. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122385. };
  122386. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122387. 1, 25,
  122388. _huff_lengthlist_line_256x4low_0sub2,
  122389. 0, 0, 0, 0, 0,
  122390. NULL,
  122391. NULL,
  122392. NULL,
  122393. NULL,
  122394. 0
  122395. };
  122396. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122399. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122400. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122401. };
  122402. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122403. 1, 64,
  122404. _huff_lengthlist_line_256x4low_0sub3,
  122405. 0, 0, 0, 0, 0,
  122406. NULL,
  122407. NULL,
  122408. NULL,
  122409. NULL,
  122410. 0
  122411. };
  122412. /*** End of inlined file: floor_books.h ***/
  122413. static static_codebook *_floor_128x4_books[]={
  122414. &_huff_book_line_128x4_class0,
  122415. &_huff_book_line_128x4_0sub0,
  122416. &_huff_book_line_128x4_0sub1,
  122417. &_huff_book_line_128x4_0sub2,
  122418. &_huff_book_line_128x4_0sub3,
  122419. };
  122420. static static_codebook *_floor_256x4_books[]={
  122421. &_huff_book_line_256x4_class0,
  122422. &_huff_book_line_256x4_0sub0,
  122423. &_huff_book_line_256x4_0sub1,
  122424. &_huff_book_line_256x4_0sub2,
  122425. &_huff_book_line_256x4_0sub3,
  122426. };
  122427. static static_codebook *_floor_128x7_books[]={
  122428. &_huff_book_line_128x7_class0,
  122429. &_huff_book_line_128x7_class1,
  122430. &_huff_book_line_128x7_0sub1,
  122431. &_huff_book_line_128x7_0sub2,
  122432. &_huff_book_line_128x7_0sub3,
  122433. &_huff_book_line_128x7_1sub1,
  122434. &_huff_book_line_128x7_1sub2,
  122435. &_huff_book_line_128x7_1sub3,
  122436. };
  122437. static static_codebook *_floor_256x7_books[]={
  122438. &_huff_book_line_256x7_class0,
  122439. &_huff_book_line_256x7_class1,
  122440. &_huff_book_line_256x7_0sub1,
  122441. &_huff_book_line_256x7_0sub2,
  122442. &_huff_book_line_256x7_0sub3,
  122443. &_huff_book_line_256x7_1sub1,
  122444. &_huff_book_line_256x7_1sub2,
  122445. &_huff_book_line_256x7_1sub3,
  122446. };
  122447. static static_codebook *_floor_128x11_books[]={
  122448. &_huff_book_line_128x11_class1,
  122449. &_huff_book_line_128x11_class2,
  122450. &_huff_book_line_128x11_class3,
  122451. &_huff_book_line_128x11_0sub0,
  122452. &_huff_book_line_128x11_1sub0,
  122453. &_huff_book_line_128x11_1sub1,
  122454. &_huff_book_line_128x11_2sub1,
  122455. &_huff_book_line_128x11_2sub2,
  122456. &_huff_book_line_128x11_2sub3,
  122457. &_huff_book_line_128x11_3sub1,
  122458. &_huff_book_line_128x11_3sub2,
  122459. &_huff_book_line_128x11_3sub3,
  122460. };
  122461. static static_codebook *_floor_128x17_books[]={
  122462. &_huff_book_line_128x17_class1,
  122463. &_huff_book_line_128x17_class2,
  122464. &_huff_book_line_128x17_class3,
  122465. &_huff_book_line_128x17_0sub0,
  122466. &_huff_book_line_128x17_1sub0,
  122467. &_huff_book_line_128x17_1sub1,
  122468. &_huff_book_line_128x17_2sub1,
  122469. &_huff_book_line_128x17_2sub2,
  122470. &_huff_book_line_128x17_2sub3,
  122471. &_huff_book_line_128x17_3sub1,
  122472. &_huff_book_line_128x17_3sub2,
  122473. &_huff_book_line_128x17_3sub3,
  122474. };
  122475. static static_codebook *_floor_256x4low_books[]={
  122476. &_huff_book_line_256x4low_class0,
  122477. &_huff_book_line_256x4low_0sub0,
  122478. &_huff_book_line_256x4low_0sub1,
  122479. &_huff_book_line_256x4low_0sub2,
  122480. &_huff_book_line_256x4low_0sub3,
  122481. };
  122482. static static_codebook *_floor_1024x27_books[]={
  122483. &_huff_book_line_1024x27_class1,
  122484. &_huff_book_line_1024x27_class2,
  122485. &_huff_book_line_1024x27_class3,
  122486. &_huff_book_line_1024x27_class4,
  122487. &_huff_book_line_1024x27_0sub0,
  122488. &_huff_book_line_1024x27_1sub0,
  122489. &_huff_book_line_1024x27_1sub1,
  122490. &_huff_book_line_1024x27_2sub0,
  122491. &_huff_book_line_1024x27_2sub1,
  122492. &_huff_book_line_1024x27_3sub1,
  122493. &_huff_book_line_1024x27_3sub2,
  122494. &_huff_book_line_1024x27_3sub3,
  122495. &_huff_book_line_1024x27_4sub1,
  122496. &_huff_book_line_1024x27_4sub2,
  122497. &_huff_book_line_1024x27_4sub3,
  122498. };
  122499. static static_codebook *_floor_2048x27_books[]={
  122500. &_huff_book_line_2048x27_class1,
  122501. &_huff_book_line_2048x27_class2,
  122502. &_huff_book_line_2048x27_class3,
  122503. &_huff_book_line_2048x27_class4,
  122504. &_huff_book_line_2048x27_0sub0,
  122505. &_huff_book_line_2048x27_1sub0,
  122506. &_huff_book_line_2048x27_1sub1,
  122507. &_huff_book_line_2048x27_2sub0,
  122508. &_huff_book_line_2048x27_2sub1,
  122509. &_huff_book_line_2048x27_3sub1,
  122510. &_huff_book_line_2048x27_3sub2,
  122511. &_huff_book_line_2048x27_3sub3,
  122512. &_huff_book_line_2048x27_4sub1,
  122513. &_huff_book_line_2048x27_4sub2,
  122514. &_huff_book_line_2048x27_4sub3,
  122515. };
  122516. static static_codebook *_floor_512x17_books[]={
  122517. &_huff_book_line_512x17_class1,
  122518. &_huff_book_line_512x17_class2,
  122519. &_huff_book_line_512x17_class3,
  122520. &_huff_book_line_512x17_0sub0,
  122521. &_huff_book_line_512x17_1sub0,
  122522. &_huff_book_line_512x17_1sub1,
  122523. &_huff_book_line_512x17_2sub1,
  122524. &_huff_book_line_512x17_2sub2,
  122525. &_huff_book_line_512x17_2sub3,
  122526. &_huff_book_line_512x17_3sub1,
  122527. &_huff_book_line_512x17_3sub2,
  122528. &_huff_book_line_512x17_3sub3,
  122529. };
  122530. static static_codebook **_floor_books[10]={
  122531. _floor_128x4_books,
  122532. _floor_256x4_books,
  122533. _floor_128x7_books,
  122534. _floor_256x7_books,
  122535. _floor_128x11_books,
  122536. _floor_128x17_books,
  122537. _floor_256x4low_books,
  122538. _floor_1024x27_books,
  122539. _floor_2048x27_books,
  122540. _floor_512x17_books,
  122541. };
  122542. static vorbis_info_floor1 _floor[10]={
  122543. /* 128 x 4 */
  122544. {
  122545. 1,{0},{4},{2},{0},
  122546. {{1,2,3,4}},
  122547. 4,{0,128, 33,8,16,70},
  122548. 60,30,500, 1.,18., -1
  122549. },
  122550. /* 256 x 4 */
  122551. {
  122552. 1,{0},{4},{2},{0},
  122553. {{1,2,3,4}},
  122554. 4,{0,256, 66,16,32,140},
  122555. 60,30,500, 1.,18., -1
  122556. },
  122557. /* 128 x 7 */
  122558. {
  122559. 2,{0,1},{3,4},{2,2},{0,1},
  122560. {{-1,2,3,4},{-1,5,6,7}},
  122561. 4,{0,128, 14,4,58, 2,8,28,90},
  122562. 60,30,500, 1.,18., -1
  122563. },
  122564. /* 256 x 7 */
  122565. {
  122566. 2,{0,1},{3,4},{2,2},{0,1},
  122567. {{-1,2,3,4},{-1,5,6,7}},
  122568. 4,{0,256, 28,8,116, 4,16,56,180},
  122569. 60,30,500, 1.,18., -1
  122570. },
  122571. /* 128 x 11 */
  122572. {
  122573. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122574. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122575. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122576. 60,30,500, 1,18., -1
  122577. },
  122578. /* 128 x 17 */
  122579. {
  122580. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122581. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122582. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122583. 60,30,500, 1,18., -1
  122584. },
  122585. /* 256 x 4 (low bitrate version) */
  122586. {
  122587. 1,{0},{4},{2},{0},
  122588. {{1,2,3,4}},
  122589. 4,{0,256, 66,16,32,140},
  122590. 60,30,500, 1.,18., -1
  122591. },
  122592. /* 1024 x 27 */
  122593. {
  122594. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122595. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122596. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122597. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122598. 60,30,500, 3,18., -1 /* lowpass */
  122599. },
  122600. /* 2048 x 27 */
  122601. {
  122602. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122603. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122604. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122605. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122606. 60,30,500, 3,18., -1 /* lowpass */
  122607. },
  122608. /* 512 x 17 */
  122609. {
  122610. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122611. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122612. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122613. 7,23,39, 55,79,110, 156,232,360},
  122614. 60,30,500, 1,18., -1 /* lowpass! */
  122615. },
  122616. };
  122617. /*** End of inlined file: floor_all.h ***/
  122618. /*** Start of inlined file: residue_44.h ***/
  122619. /*** Start of inlined file: res_books_stereo.h ***/
  122620. static long _vq_quantlist__16c0_s_p1_0[] = {
  122621. 1,
  122622. 0,
  122623. 2,
  122624. };
  122625. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122626. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122627. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122631. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122632. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122636. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122637. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122672. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122677. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122682. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122718. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122723. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122728. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0,
  123037. };
  123038. static float _vq_quantthresh__16c0_s_p1_0[] = {
  123039. -0.5, 0.5,
  123040. };
  123041. static long _vq_quantmap__16c0_s_p1_0[] = {
  123042. 1, 0, 2,
  123043. };
  123044. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  123045. _vq_quantthresh__16c0_s_p1_0,
  123046. _vq_quantmap__16c0_s_p1_0,
  123047. 3,
  123048. 3
  123049. };
  123050. static static_codebook _16c0_s_p1_0 = {
  123051. 8, 6561,
  123052. _vq_lengthlist__16c0_s_p1_0,
  123053. 1, -535822336, 1611661312, 2, 0,
  123054. _vq_quantlist__16c0_s_p1_0,
  123055. NULL,
  123056. &_vq_auxt__16c0_s_p1_0,
  123057. NULL,
  123058. 0
  123059. };
  123060. static long _vq_quantlist__16c0_s_p2_0[] = {
  123061. 2,
  123062. 1,
  123063. 3,
  123064. 0,
  123065. 4,
  123066. };
  123067. static long _vq_lengthlist__16c0_s_p2_0[] = {
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123107. 0,
  123108. };
  123109. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123110. -1.5, -0.5, 0.5, 1.5,
  123111. };
  123112. static long _vq_quantmap__16c0_s_p2_0[] = {
  123113. 3, 1, 0, 2, 4,
  123114. };
  123115. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123116. _vq_quantthresh__16c0_s_p2_0,
  123117. _vq_quantmap__16c0_s_p2_0,
  123118. 5,
  123119. 5
  123120. };
  123121. static static_codebook _16c0_s_p2_0 = {
  123122. 4, 625,
  123123. _vq_lengthlist__16c0_s_p2_0,
  123124. 1, -533725184, 1611661312, 3, 0,
  123125. _vq_quantlist__16c0_s_p2_0,
  123126. NULL,
  123127. &_vq_auxt__16c0_s_p2_0,
  123128. NULL,
  123129. 0
  123130. };
  123131. static long _vq_quantlist__16c0_s_p3_0[] = {
  123132. 2,
  123133. 1,
  123134. 3,
  123135. 0,
  123136. 4,
  123137. };
  123138. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123139. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123142. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123145. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123178. 0,
  123179. };
  123180. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123181. -1.5, -0.5, 0.5, 1.5,
  123182. };
  123183. static long _vq_quantmap__16c0_s_p3_0[] = {
  123184. 3, 1, 0, 2, 4,
  123185. };
  123186. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123187. _vq_quantthresh__16c0_s_p3_0,
  123188. _vq_quantmap__16c0_s_p3_0,
  123189. 5,
  123190. 5
  123191. };
  123192. static static_codebook _16c0_s_p3_0 = {
  123193. 4, 625,
  123194. _vq_lengthlist__16c0_s_p3_0,
  123195. 1, -533725184, 1611661312, 3, 0,
  123196. _vq_quantlist__16c0_s_p3_0,
  123197. NULL,
  123198. &_vq_auxt__16c0_s_p3_0,
  123199. NULL,
  123200. 0
  123201. };
  123202. static long _vq_quantlist__16c0_s_p4_0[] = {
  123203. 4,
  123204. 3,
  123205. 5,
  123206. 2,
  123207. 6,
  123208. 1,
  123209. 7,
  123210. 0,
  123211. 8,
  123212. };
  123213. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123214. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123215. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123216. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123217. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123218. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123219. 0,
  123220. };
  123221. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123222. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123223. };
  123224. static long _vq_quantmap__16c0_s_p4_0[] = {
  123225. 7, 5, 3, 1, 0, 2, 4, 6,
  123226. 8,
  123227. };
  123228. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123229. _vq_quantthresh__16c0_s_p4_0,
  123230. _vq_quantmap__16c0_s_p4_0,
  123231. 9,
  123232. 9
  123233. };
  123234. static static_codebook _16c0_s_p4_0 = {
  123235. 2, 81,
  123236. _vq_lengthlist__16c0_s_p4_0,
  123237. 1, -531628032, 1611661312, 4, 0,
  123238. _vq_quantlist__16c0_s_p4_0,
  123239. NULL,
  123240. &_vq_auxt__16c0_s_p4_0,
  123241. NULL,
  123242. 0
  123243. };
  123244. static long _vq_quantlist__16c0_s_p5_0[] = {
  123245. 4,
  123246. 3,
  123247. 5,
  123248. 2,
  123249. 6,
  123250. 1,
  123251. 7,
  123252. 0,
  123253. 8,
  123254. };
  123255. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123256. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123257. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123258. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123259. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123260. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123261. 10,
  123262. };
  123263. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123264. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123265. };
  123266. static long _vq_quantmap__16c0_s_p5_0[] = {
  123267. 7, 5, 3, 1, 0, 2, 4, 6,
  123268. 8,
  123269. };
  123270. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123271. _vq_quantthresh__16c0_s_p5_0,
  123272. _vq_quantmap__16c0_s_p5_0,
  123273. 9,
  123274. 9
  123275. };
  123276. static static_codebook _16c0_s_p5_0 = {
  123277. 2, 81,
  123278. _vq_lengthlist__16c0_s_p5_0,
  123279. 1, -531628032, 1611661312, 4, 0,
  123280. _vq_quantlist__16c0_s_p5_0,
  123281. NULL,
  123282. &_vq_auxt__16c0_s_p5_0,
  123283. NULL,
  123284. 0
  123285. };
  123286. static long _vq_quantlist__16c0_s_p6_0[] = {
  123287. 8,
  123288. 7,
  123289. 9,
  123290. 6,
  123291. 10,
  123292. 5,
  123293. 11,
  123294. 4,
  123295. 12,
  123296. 3,
  123297. 13,
  123298. 2,
  123299. 14,
  123300. 1,
  123301. 15,
  123302. 0,
  123303. 16,
  123304. };
  123305. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123306. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123307. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123308. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123309. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123310. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123311. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123312. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123313. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123314. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123315. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123316. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123317. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123318. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123319. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123320. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123321. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123322. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123323. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123324. 14,
  123325. };
  123326. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123327. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123328. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123329. };
  123330. static long _vq_quantmap__16c0_s_p6_0[] = {
  123331. 15, 13, 11, 9, 7, 5, 3, 1,
  123332. 0, 2, 4, 6, 8, 10, 12, 14,
  123333. 16,
  123334. };
  123335. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123336. _vq_quantthresh__16c0_s_p6_0,
  123337. _vq_quantmap__16c0_s_p6_0,
  123338. 17,
  123339. 17
  123340. };
  123341. static static_codebook _16c0_s_p6_0 = {
  123342. 2, 289,
  123343. _vq_lengthlist__16c0_s_p6_0,
  123344. 1, -529530880, 1611661312, 5, 0,
  123345. _vq_quantlist__16c0_s_p6_0,
  123346. NULL,
  123347. &_vq_auxt__16c0_s_p6_0,
  123348. NULL,
  123349. 0
  123350. };
  123351. static long _vq_quantlist__16c0_s_p7_0[] = {
  123352. 1,
  123353. 0,
  123354. 2,
  123355. };
  123356. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123357. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123358. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123359. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123360. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123361. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123362. 13,
  123363. };
  123364. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123365. -5.5, 5.5,
  123366. };
  123367. static long _vq_quantmap__16c0_s_p7_0[] = {
  123368. 1, 0, 2,
  123369. };
  123370. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123371. _vq_quantthresh__16c0_s_p7_0,
  123372. _vq_quantmap__16c0_s_p7_0,
  123373. 3,
  123374. 3
  123375. };
  123376. static static_codebook _16c0_s_p7_0 = {
  123377. 4, 81,
  123378. _vq_lengthlist__16c0_s_p7_0,
  123379. 1, -529137664, 1618345984, 2, 0,
  123380. _vq_quantlist__16c0_s_p7_0,
  123381. NULL,
  123382. &_vq_auxt__16c0_s_p7_0,
  123383. NULL,
  123384. 0
  123385. };
  123386. static long _vq_quantlist__16c0_s_p7_1[] = {
  123387. 5,
  123388. 4,
  123389. 6,
  123390. 3,
  123391. 7,
  123392. 2,
  123393. 8,
  123394. 1,
  123395. 9,
  123396. 0,
  123397. 10,
  123398. };
  123399. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123400. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123401. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123402. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123403. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123404. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123405. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123406. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123407. 11,11,11, 9, 9, 9, 9,10,10,
  123408. };
  123409. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123410. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123411. 3.5, 4.5,
  123412. };
  123413. static long _vq_quantmap__16c0_s_p7_1[] = {
  123414. 9, 7, 5, 3, 1, 0, 2, 4,
  123415. 6, 8, 10,
  123416. };
  123417. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123418. _vq_quantthresh__16c0_s_p7_1,
  123419. _vq_quantmap__16c0_s_p7_1,
  123420. 11,
  123421. 11
  123422. };
  123423. static static_codebook _16c0_s_p7_1 = {
  123424. 2, 121,
  123425. _vq_lengthlist__16c0_s_p7_1,
  123426. 1, -531365888, 1611661312, 4, 0,
  123427. _vq_quantlist__16c0_s_p7_1,
  123428. NULL,
  123429. &_vq_auxt__16c0_s_p7_1,
  123430. NULL,
  123431. 0
  123432. };
  123433. static long _vq_quantlist__16c0_s_p8_0[] = {
  123434. 6,
  123435. 5,
  123436. 7,
  123437. 4,
  123438. 8,
  123439. 3,
  123440. 9,
  123441. 2,
  123442. 10,
  123443. 1,
  123444. 11,
  123445. 0,
  123446. 12,
  123447. };
  123448. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123449. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123450. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123451. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123452. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123453. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123454. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123455. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123456. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123457. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123458. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123459. 0,12,13,13,12,13,14,14,14,
  123460. };
  123461. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123462. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123463. 12.5, 17.5, 22.5, 27.5,
  123464. };
  123465. static long _vq_quantmap__16c0_s_p8_0[] = {
  123466. 11, 9, 7, 5, 3, 1, 0, 2,
  123467. 4, 6, 8, 10, 12,
  123468. };
  123469. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123470. _vq_quantthresh__16c0_s_p8_0,
  123471. _vq_quantmap__16c0_s_p8_0,
  123472. 13,
  123473. 13
  123474. };
  123475. static static_codebook _16c0_s_p8_0 = {
  123476. 2, 169,
  123477. _vq_lengthlist__16c0_s_p8_0,
  123478. 1, -526516224, 1616117760, 4, 0,
  123479. _vq_quantlist__16c0_s_p8_0,
  123480. NULL,
  123481. &_vq_auxt__16c0_s_p8_0,
  123482. NULL,
  123483. 0
  123484. };
  123485. static long _vq_quantlist__16c0_s_p8_1[] = {
  123486. 2,
  123487. 1,
  123488. 3,
  123489. 0,
  123490. 4,
  123491. };
  123492. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123493. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123494. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123495. };
  123496. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123497. -1.5, -0.5, 0.5, 1.5,
  123498. };
  123499. static long _vq_quantmap__16c0_s_p8_1[] = {
  123500. 3, 1, 0, 2, 4,
  123501. };
  123502. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123503. _vq_quantthresh__16c0_s_p8_1,
  123504. _vq_quantmap__16c0_s_p8_1,
  123505. 5,
  123506. 5
  123507. };
  123508. static static_codebook _16c0_s_p8_1 = {
  123509. 2, 25,
  123510. _vq_lengthlist__16c0_s_p8_1,
  123511. 1, -533725184, 1611661312, 3, 0,
  123512. _vq_quantlist__16c0_s_p8_1,
  123513. NULL,
  123514. &_vq_auxt__16c0_s_p8_1,
  123515. NULL,
  123516. 0
  123517. };
  123518. static long _vq_quantlist__16c0_s_p9_0[] = {
  123519. 1,
  123520. 0,
  123521. 2,
  123522. };
  123523. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123524. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123525. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123526. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123527. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123528. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123529. 7,
  123530. };
  123531. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123532. -157.5, 157.5,
  123533. };
  123534. static long _vq_quantmap__16c0_s_p9_0[] = {
  123535. 1, 0, 2,
  123536. };
  123537. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123538. _vq_quantthresh__16c0_s_p9_0,
  123539. _vq_quantmap__16c0_s_p9_0,
  123540. 3,
  123541. 3
  123542. };
  123543. static static_codebook _16c0_s_p9_0 = {
  123544. 4, 81,
  123545. _vq_lengthlist__16c0_s_p9_0,
  123546. 1, -518803456, 1628680192, 2, 0,
  123547. _vq_quantlist__16c0_s_p9_0,
  123548. NULL,
  123549. &_vq_auxt__16c0_s_p9_0,
  123550. NULL,
  123551. 0
  123552. };
  123553. static long _vq_quantlist__16c0_s_p9_1[] = {
  123554. 7,
  123555. 6,
  123556. 8,
  123557. 5,
  123558. 9,
  123559. 4,
  123560. 10,
  123561. 3,
  123562. 11,
  123563. 2,
  123564. 12,
  123565. 1,
  123566. 13,
  123567. 0,
  123568. 14,
  123569. };
  123570. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123571. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123572. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123573. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123574. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123575. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123576. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123577. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123578. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123579. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123580. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123581. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123582. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123583. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123584. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123585. 10,
  123586. };
  123587. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123588. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123589. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123590. };
  123591. static long _vq_quantmap__16c0_s_p9_1[] = {
  123592. 13, 11, 9, 7, 5, 3, 1, 0,
  123593. 2, 4, 6, 8, 10, 12, 14,
  123594. };
  123595. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123596. _vq_quantthresh__16c0_s_p9_1,
  123597. _vq_quantmap__16c0_s_p9_1,
  123598. 15,
  123599. 15
  123600. };
  123601. static static_codebook _16c0_s_p9_1 = {
  123602. 2, 225,
  123603. _vq_lengthlist__16c0_s_p9_1,
  123604. 1, -520986624, 1620377600, 4, 0,
  123605. _vq_quantlist__16c0_s_p9_1,
  123606. NULL,
  123607. &_vq_auxt__16c0_s_p9_1,
  123608. NULL,
  123609. 0
  123610. };
  123611. static long _vq_quantlist__16c0_s_p9_2[] = {
  123612. 10,
  123613. 9,
  123614. 11,
  123615. 8,
  123616. 12,
  123617. 7,
  123618. 13,
  123619. 6,
  123620. 14,
  123621. 5,
  123622. 15,
  123623. 4,
  123624. 16,
  123625. 3,
  123626. 17,
  123627. 2,
  123628. 18,
  123629. 1,
  123630. 19,
  123631. 0,
  123632. 20,
  123633. };
  123634. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123635. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123636. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123637. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123638. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123639. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123640. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123641. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123642. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123643. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123644. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123645. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123646. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123647. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123648. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123649. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123650. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123651. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123652. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123653. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123654. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123655. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123656. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123657. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123658. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123659. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123660. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123661. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123662. 10,11,10,10,11, 9,10,10,10,
  123663. };
  123664. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123665. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123666. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123667. 6.5, 7.5, 8.5, 9.5,
  123668. };
  123669. static long _vq_quantmap__16c0_s_p9_2[] = {
  123670. 19, 17, 15, 13, 11, 9, 7, 5,
  123671. 3, 1, 0, 2, 4, 6, 8, 10,
  123672. 12, 14, 16, 18, 20,
  123673. };
  123674. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123675. _vq_quantthresh__16c0_s_p9_2,
  123676. _vq_quantmap__16c0_s_p9_2,
  123677. 21,
  123678. 21
  123679. };
  123680. static static_codebook _16c0_s_p9_2 = {
  123681. 2, 441,
  123682. _vq_lengthlist__16c0_s_p9_2,
  123683. 1, -529268736, 1611661312, 5, 0,
  123684. _vq_quantlist__16c0_s_p9_2,
  123685. NULL,
  123686. &_vq_auxt__16c0_s_p9_2,
  123687. NULL,
  123688. 0
  123689. };
  123690. static long _huff_lengthlist__16c0_s_single[] = {
  123691. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123692. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123693. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123694. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123695. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123696. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123697. 16,16,18,18,
  123698. };
  123699. static static_codebook _huff_book__16c0_s_single = {
  123700. 2, 100,
  123701. _huff_lengthlist__16c0_s_single,
  123702. 0, 0, 0, 0, 0,
  123703. NULL,
  123704. NULL,
  123705. NULL,
  123706. NULL,
  123707. 0
  123708. };
  123709. static long _huff_lengthlist__16c1_s_long[] = {
  123710. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123711. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123712. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123713. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123714. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123715. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123716. 12,11,11,13,
  123717. };
  123718. static static_codebook _huff_book__16c1_s_long = {
  123719. 2, 100,
  123720. _huff_lengthlist__16c1_s_long,
  123721. 0, 0, 0, 0, 0,
  123722. NULL,
  123723. NULL,
  123724. NULL,
  123725. NULL,
  123726. 0
  123727. };
  123728. static long _vq_quantlist__16c1_s_p1_0[] = {
  123729. 1,
  123730. 0,
  123731. 2,
  123732. };
  123733. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123734. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123735. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123739. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123740. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123744. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123745. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123780. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123785. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123790. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123826. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123830. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123831. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  123832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123835. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123836. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0,
  124145. };
  124146. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124147. -0.5, 0.5,
  124148. };
  124149. static long _vq_quantmap__16c1_s_p1_0[] = {
  124150. 1, 0, 2,
  124151. };
  124152. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124153. _vq_quantthresh__16c1_s_p1_0,
  124154. _vq_quantmap__16c1_s_p1_0,
  124155. 3,
  124156. 3
  124157. };
  124158. static static_codebook _16c1_s_p1_0 = {
  124159. 8, 6561,
  124160. _vq_lengthlist__16c1_s_p1_0,
  124161. 1, -535822336, 1611661312, 2, 0,
  124162. _vq_quantlist__16c1_s_p1_0,
  124163. NULL,
  124164. &_vq_auxt__16c1_s_p1_0,
  124165. NULL,
  124166. 0
  124167. };
  124168. static long _vq_quantlist__16c1_s_p2_0[] = {
  124169. 2,
  124170. 1,
  124171. 3,
  124172. 0,
  124173. 4,
  124174. };
  124175. static long _vq_lengthlist__16c1_s_p2_0[] = {
  124176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124215. 0,
  124216. };
  124217. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124218. -1.5, -0.5, 0.5, 1.5,
  124219. };
  124220. static long _vq_quantmap__16c1_s_p2_0[] = {
  124221. 3, 1, 0, 2, 4,
  124222. };
  124223. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124224. _vq_quantthresh__16c1_s_p2_0,
  124225. _vq_quantmap__16c1_s_p2_0,
  124226. 5,
  124227. 5
  124228. };
  124229. static static_codebook _16c1_s_p2_0 = {
  124230. 4, 625,
  124231. _vq_lengthlist__16c1_s_p2_0,
  124232. 1, -533725184, 1611661312, 3, 0,
  124233. _vq_quantlist__16c1_s_p2_0,
  124234. NULL,
  124235. &_vq_auxt__16c1_s_p2_0,
  124236. NULL,
  124237. 0
  124238. };
  124239. static long _vq_quantlist__16c1_s_p3_0[] = {
  124240. 2,
  124241. 1,
  124242. 3,
  124243. 0,
  124244. 4,
  124245. };
  124246. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124247. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124250. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124253. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124286. 0,
  124287. };
  124288. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124289. -1.5, -0.5, 0.5, 1.5,
  124290. };
  124291. static long _vq_quantmap__16c1_s_p3_0[] = {
  124292. 3, 1, 0, 2, 4,
  124293. };
  124294. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124295. _vq_quantthresh__16c1_s_p3_0,
  124296. _vq_quantmap__16c1_s_p3_0,
  124297. 5,
  124298. 5
  124299. };
  124300. static static_codebook _16c1_s_p3_0 = {
  124301. 4, 625,
  124302. _vq_lengthlist__16c1_s_p3_0,
  124303. 1, -533725184, 1611661312, 3, 0,
  124304. _vq_quantlist__16c1_s_p3_0,
  124305. NULL,
  124306. &_vq_auxt__16c1_s_p3_0,
  124307. NULL,
  124308. 0
  124309. };
  124310. static long _vq_quantlist__16c1_s_p4_0[] = {
  124311. 4,
  124312. 3,
  124313. 5,
  124314. 2,
  124315. 6,
  124316. 1,
  124317. 7,
  124318. 0,
  124319. 8,
  124320. };
  124321. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124322. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124323. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124324. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124325. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124326. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124327. 0,
  124328. };
  124329. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124330. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124331. };
  124332. static long _vq_quantmap__16c1_s_p4_0[] = {
  124333. 7, 5, 3, 1, 0, 2, 4, 6,
  124334. 8,
  124335. };
  124336. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124337. _vq_quantthresh__16c1_s_p4_0,
  124338. _vq_quantmap__16c1_s_p4_0,
  124339. 9,
  124340. 9
  124341. };
  124342. static static_codebook _16c1_s_p4_0 = {
  124343. 2, 81,
  124344. _vq_lengthlist__16c1_s_p4_0,
  124345. 1, -531628032, 1611661312, 4, 0,
  124346. _vq_quantlist__16c1_s_p4_0,
  124347. NULL,
  124348. &_vq_auxt__16c1_s_p4_0,
  124349. NULL,
  124350. 0
  124351. };
  124352. static long _vq_quantlist__16c1_s_p5_0[] = {
  124353. 4,
  124354. 3,
  124355. 5,
  124356. 2,
  124357. 6,
  124358. 1,
  124359. 7,
  124360. 0,
  124361. 8,
  124362. };
  124363. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124364. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124365. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124366. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124367. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124368. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124369. 10,
  124370. };
  124371. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124372. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124373. };
  124374. static long _vq_quantmap__16c1_s_p5_0[] = {
  124375. 7, 5, 3, 1, 0, 2, 4, 6,
  124376. 8,
  124377. };
  124378. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124379. _vq_quantthresh__16c1_s_p5_0,
  124380. _vq_quantmap__16c1_s_p5_0,
  124381. 9,
  124382. 9
  124383. };
  124384. static static_codebook _16c1_s_p5_0 = {
  124385. 2, 81,
  124386. _vq_lengthlist__16c1_s_p5_0,
  124387. 1, -531628032, 1611661312, 4, 0,
  124388. _vq_quantlist__16c1_s_p5_0,
  124389. NULL,
  124390. &_vq_auxt__16c1_s_p5_0,
  124391. NULL,
  124392. 0
  124393. };
  124394. static long _vq_quantlist__16c1_s_p6_0[] = {
  124395. 8,
  124396. 7,
  124397. 9,
  124398. 6,
  124399. 10,
  124400. 5,
  124401. 11,
  124402. 4,
  124403. 12,
  124404. 3,
  124405. 13,
  124406. 2,
  124407. 14,
  124408. 1,
  124409. 15,
  124410. 0,
  124411. 16,
  124412. };
  124413. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124414. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124415. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124416. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124417. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124418. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124419. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124420. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124421. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124422. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124423. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124424. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124425. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124426. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124427. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124428. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124429. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124430. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124431. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124432. 14,
  124433. };
  124434. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124435. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124436. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124437. };
  124438. static long _vq_quantmap__16c1_s_p6_0[] = {
  124439. 15, 13, 11, 9, 7, 5, 3, 1,
  124440. 0, 2, 4, 6, 8, 10, 12, 14,
  124441. 16,
  124442. };
  124443. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124444. _vq_quantthresh__16c1_s_p6_0,
  124445. _vq_quantmap__16c1_s_p6_0,
  124446. 17,
  124447. 17
  124448. };
  124449. static static_codebook _16c1_s_p6_0 = {
  124450. 2, 289,
  124451. _vq_lengthlist__16c1_s_p6_0,
  124452. 1, -529530880, 1611661312, 5, 0,
  124453. _vq_quantlist__16c1_s_p6_0,
  124454. NULL,
  124455. &_vq_auxt__16c1_s_p6_0,
  124456. NULL,
  124457. 0
  124458. };
  124459. static long _vq_quantlist__16c1_s_p7_0[] = {
  124460. 1,
  124461. 0,
  124462. 2,
  124463. };
  124464. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124465. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124466. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124467. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124468. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124469. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124470. 11,
  124471. };
  124472. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124473. -5.5, 5.5,
  124474. };
  124475. static long _vq_quantmap__16c1_s_p7_0[] = {
  124476. 1, 0, 2,
  124477. };
  124478. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124479. _vq_quantthresh__16c1_s_p7_0,
  124480. _vq_quantmap__16c1_s_p7_0,
  124481. 3,
  124482. 3
  124483. };
  124484. static static_codebook _16c1_s_p7_0 = {
  124485. 4, 81,
  124486. _vq_lengthlist__16c1_s_p7_0,
  124487. 1, -529137664, 1618345984, 2, 0,
  124488. _vq_quantlist__16c1_s_p7_0,
  124489. NULL,
  124490. &_vq_auxt__16c1_s_p7_0,
  124491. NULL,
  124492. 0
  124493. };
  124494. static long _vq_quantlist__16c1_s_p7_1[] = {
  124495. 5,
  124496. 4,
  124497. 6,
  124498. 3,
  124499. 7,
  124500. 2,
  124501. 8,
  124502. 1,
  124503. 9,
  124504. 0,
  124505. 10,
  124506. };
  124507. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124508. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124509. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124510. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124511. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124512. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124513. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124514. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124515. 10,10,10, 8, 8, 8, 8, 9, 9,
  124516. };
  124517. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124518. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124519. 3.5, 4.5,
  124520. };
  124521. static long _vq_quantmap__16c1_s_p7_1[] = {
  124522. 9, 7, 5, 3, 1, 0, 2, 4,
  124523. 6, 8, 10,
  124524. };
  124525. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124526. _vq_quantthresh__16c1_s_p7_1,
  124527. _vq_quantmap__16c1_s_p7_1,
  124528. 11,
  124529. 11
  124530. };
  124531. static static_codebook _16c1_s_p7_1 = {
  124532. 2, 121,
  124533. _vq_lengthlist__16c1_s_p7_1,
  124534. 1, -531365888, 1611661312, 4, 0,
  124535. _vq_quantlist__16c1_s_p7_1,
  124536. NULL,
  124537. &_vq_auxt__16c1_s_p7_1,
  124538. NULL,
  124539. 0
  124540. };
  124541. static long _vq_quantlist__16c1_s_p8_0[] = {
  124542. 6,
  124543. 5,
  124544. 7,
  124545. 4,
  124546. 8,
  124547. 3,
  124548. 9,
  124549. 2,
  124550. 10,
  124551. 1,
  124552. 11,
  124553. 0,
  124554. 12,
  124555. };
  124556. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124557. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124558. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124559. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124560. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124561. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124562. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124563. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124564. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124565. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124566. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124567. 0,12,12,12,12,13,13,14,15,
  124568. };
  124569. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124570. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124571. 12.5, 17.5, 22.5, 27.5,
  124572. };
  124573. static long _vq_quantmap__16c1_s_p8_0[] = {
  124574. 11, 9, 7, 5, 3, 1, 0, 2,
  124575. 4, 6, 8, 10, 12,
  124576. };
  124577. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124578. _vq_quantthresh__16c1_s_p8_0,
  124579. _vq_quantmap__16c1_s_p8_0,
  124580. 13,
  124581. 13
  124582. };
  124583. static static_codebook _16c1_s_p8_0 = {
  124584. 2, 169,
  124585. _vq_lengthlist__16c1_s_p8_0,
  124586. 1, -526516224, 1616117760, 4, 0,
  124587. _vq_quantlist__16c1_s_p8_0,
  124588. NULL,
  124589. &_vq_auxt__16c1_s_p8_0,
  124590. NULL,
  124591. 0
  124592. };
  124593. static long _vq_quantlist__16c1_s_p8_1[] = {
  124594. 2,
  124595. 1,
  124596. 3,
  124597. 0,
  124598. 4,
  124599. };
  124600. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124601. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124602. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124603. };
  124604. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124605. -1.5, -0.5, 0.5, 1.5,
  124606. };
  124607. static long _vq_quantmap__16c1_s_p8_1[] = {
  124608. 3, 1, 0, 2, 4,
  124609. };
  124610. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124611. _vq_quantthresh__16c1_s_p8_1,
  124612. _vq_quantmap__16c1_s_p8_1,
  124613. 5,
  124614. 5
  124615. };
  124616. static static_codebook _16c1_s_p8_1 = {
  124617. 2, 25,
  124618. _vq_lengthlist__16c1_s_p8_1,
  124619. 1, -533725184, 1611661312, 3, 0,
  124620. _vq_quantlist__16c1_s_p8_1,
  124621. NULL,
  124622. &_vq_auxt__16c1_s_p8_1,
  124623. NULL,
  124624. 0
  124625. };
  124626. static long _vq_quantlist__16c1_s_p9_0[] = {
  124627. 6,
  124628. 5,
  124629. 7,
  124630. 4,
  124631. 8,
  124632. 3,
  124633. 9,
  124634. 2,
  124635. 10,
  124636. 1,
  124637. 11,
  124638. 0,
  124639. 12,
  124640. };
  124641. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124642. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124643. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124644. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124645. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124646. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124647. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124648. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124649. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124650. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124651. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124652. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124653. };
  124654. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124655. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124656. 787.5, 1102.5, 1417.5, 1732.5,
  124657. };
  124658. static long _vq_quantmap__16c1_s_p9_0[] = {
  124659. 11, 9, 7, 5, 3, 1, 0, 2,
  124660. 4, 6, 8, 10, 12,
  124661. };
  124662. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124663. _vq_quantthresh__16c1_s_p9_0,
  124664. _vq_quantmap__16c1_s_p9_0,
  124665. 13,
  124666. 13
  124667. };
  124668. static static_codebook _16c1_s_p9_0 = {
  124669. 2, 169,
  124670. _vq_lengthlist__16c1_s_p9_0,
  124671. 1, -513964032, 1628680192, 4, 0,
  124672. _vq_quantlist__16c1_s_p9_0,
  124673. NULL,
  124674. &_vq_auxt__16c1_s_p9_0,
  124675. NULL,
  124676. 0
  124677. };
  124678. static long _vq_quantlist__16c1_s_p9_1[] = {
  124679. 7,
  124680. 6,
  124681. 8,
  124682. 5,
  124683. 9,
  124684. 4,
  124685. 10,
  124686. 3,
  124687. 11,
  124688. 2,
  124689. 12,
  124690. 1,
  124691. 13,
  124692. 0,
  124693. 14,
  124694. };
  124695. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124696. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124697. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124698. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124699. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124700. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124701. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124702. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124703. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124704. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124705. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124706. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124707. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124708. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124709. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124710. 13,
  124711. };
  124712. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124713. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124714. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124715. };
  124716. static long _vq_quantmap__16c1_s_p9_1[] = {
  124717. 13, 11, 9, 7, 5, 3, 1, 0,
  124718. 2, 4, 6, 8, 10, 12, 14,
  124719. };
  124720. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124721. _vq_quantthresh__16c1_s_p9_1,
  124722. _vq_quantmap__16c1_s_p9_1,
  124723. 15,
  124724. 15
  124725. };
  124726. static static_codebook _16c1_s_p9_1 = {
  124727. 2, 225,
  124728. _vq_lengthlist__16c1_s_p9_1,
  124729. 1, -520986624, 1620377600, 4, 0,
  124730. _vq_quantlist__16c1_s_p9_1,
  124731. NULL,
  124732. &_vq_auxt__16c1_s_p9_1,
  124733. NULL,
  124734. 0
  124735. };
  124736. static long _vq_quantlist__16c1_s_p9_2[] = {
  124737. 10,
  124738. 9,
  124739. 11,
  124740. 8,
  124741. 12,
  124742. 7,
  124743. 13,
  124744. 6,
  124745. 14,
  124746. 5,
  124747. 15,
  124748. 4,
  124749. 16,
  124750. 3,
  124751. 17,
  124752. 2,
  124753. 18,
  124754. 1,
  124755. 19,
  124756. 0,
  124757. 20,
  124758. };
  124759. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124760. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124761. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124762. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124763. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124764. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124765. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124766. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124767. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124768. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124769. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124770. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124771. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124772. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124773. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124774. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124775. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124776. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124777. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124778. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124779. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124780. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124781. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124782. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124783. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124784. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124785. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124786. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124787. 11,11,11,11,12,11,11,12,11,
  124788. };
  124789. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124790. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124791. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124792. 6.5, 7.5, 8.5, 9.5,
  124793. };
  124794. static long _vq_quantmap__16c1_s_p9_2[] = {
  124795. 19, 17, 15, 13, 11, 9, 7, 5,
  124796. 3, 1, 0, 2, 4, 6, 8, 10,
  124797. 12, 14, 16, 18, 20,
  124798. };
  124799. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124800. _vq_quantthresh__16c1_s_p9_2,
  124801. _vq_quantmap__16c1_s_p9_2,
  124802. 21,
  124803. 21
  124804. };
  124805. static static_codebook _16c1_s_p9_2 = {
  124806. 2, 441,
  124807. _vq_lengthlist__16c1_s_p9_2,
  124808. 1, -529268736, 1611661312, 5, 0,
  124809. _vq_quantlist__16c1_s_p9_2,
  124810. NULL,
  124811. &_vq_auxt__16c1_s_p9_2,
  124812. NULL,
  124813. 0
  124814. };
  124815. static long _huff_lengthlist__16c1_s_short[] = {
  124816. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124817. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124818. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124819. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124820. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124821. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124822. 9, 9,10,13,
  124823. };
  124824. static static_codebook _huff_book__16c1_s_short = {
  124825. 2, 100,
  124826. _huff_lengthlist__16c1_s_short,
  124827. 0, 0, 0, 0, 0,
  124828. NULL,
  124829. NULL,
  124830. NULL,
  124831. NULL,
  124832. 0
  124833. };
  124834. static long _huff_lengthlist__16c2_s_long[] = {
  124835. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124836. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124837. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124838. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124839. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124840. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124841. 14,14,16,18,
  124842. };
  124843. static static_codebook _huff_book__16c2_s_long = {
  124844. 2, 100,
  124845. _huff_lengthlist__16c2_s_long,
  124846. 0, 0, 0, 0, 0,
  124847. NULL,
  124848. NULL,
  124849. NULL,
  124850. NULL,
  124851. 0
  124852. };
  124853. static long _vq_quantlist__16c2_s_p1_0[] = {
  124854. 1,
  124855. 0,
  124856. 2,
  124857. };
  124858. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124859. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124860. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124864. 0,
  124865. };
  124866. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124867. -0.5, 0.5,
  124868. };
  124869. static long _vq_quantmap__16c2_s_p1_0[] = {
  124870. 1, 0, 2,
  124871. };
  124872. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124873. _vq_quantthresh__16c2_s_p1_0,
  124874. _vq_quantmap__16c2_s_p1_0,
  124875. 3,
  124876. 3
  124877. };
  124878. static static_codebook _16c2_s_p1_0 = {
  124879. 4, 81,
  124880. _vq_lengthlist__16c2_s_p1_0,
  124881. 1, -535822336, 1611661312, 2, 0,
  124882. _vq_quantlist__16c2_s_p1_0,
  124883. NULL,
  124884. &_vq_auxt__16c2_s_p1_0,
  124885. NULL,
  124886. 0
  124887. };
  124888. static long _vq_quantlist__16c2_s_p2_0[] = {
  124889. 2,
  124890. 1,
  124891. 3,
  124892. 0,
  124893. 4,
  124894. };
  124895. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124896. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124897. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124898. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124899. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124900. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124901. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124902. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124903. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124908. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124909. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124910. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124911. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124916. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124917. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124918. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124919. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124924. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124925. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124926. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124927. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124932. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124933. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124934. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124935. 13,
  124936. };
  124937. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124938. -1.5, -0.5, 0.5, 1.5,
  124939. };
  124940. static long _vq_quantmap__16c2_s_p2_0[] = {
  124941. 3, 1, 0, 2, 4,
  124942. };
  124943. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124944. _vq_quantthresh__16c2_s_p2_0,
  124945. _vq_quantmap__16c2_s_p2_0,
  124946. 5,
  124947. 5
  124948. };
  124949. static static_codebook _16c2_s_p2_0 = {
  124950. 4, 625,
  124951. _vq_lengthlist__16c2_s_p2_0,
  124952. 1, -533725184, 1611661312, 3, 0,
  124953. _vq_quantlist__16c2_s_p2_0,
  124954. NULL,
  124955. &_vq_auxt__16c2_s_p2_0,
  124956. NULL,
  124957. 0
  124958. };
  124959. static long _vq_quantlist__16c2_s_p3_0[] = {
  124960. 4,
  124961. 3,
  124962. 5,
  124963. 2,
  124964. 6,
  124965. 1,
  124966. 7,
  124967. 0,
  124968. 8,
  124969. };
  124970. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124971. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124972. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124973. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124974. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124976. 0,
  124977. };
  124978. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124979. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124980. };
  124981. static long _vq_quantmap__16c2_s_p3_0[] = {
  124982. 7, 5, 3, 1, 0, 2, 4, 6,
  124983. 8,
  124984. };
  124985. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124986. _vq_quantthresh__16c2_s_p3_0,
  124987. _vq_quantmap__16c2_s_p3_0,
  124988. 9,
  124989. 9
  124990. };
  124991. static static_codebook _16c2_s_p3_0 = {
  124992. 2, 81,
  124993. _vq_lengthlist__16c2_s_p3_0,
  124994. 1, -531628032, 1611661312, 4, 0,
  124995. _vq_quantlist__16c2_s_p3_0,
  124996. NULL,
  124997. &_vq_auxt__16c2_s_p3_0,
  124998. NULL,
  124999. 0
  125000. };
  125001. static long _vq_quantlist__16c2_s_p4_0[] = {
  125002. 8,
  125003. 7,
  125004. 9,
  125005. 6,
  125006. 10,
  125007. 5,
  125008. 11,
  125009. 4,
  125010. 12,
  125011. 3,
  125012. 13,
  125013. 2,
  125014. 14,
  125015. 1,
  125016. 15,
  125017. 0,
  125018. 16,
  125019. };
  125020. static long _vq_lengthlist__16c2_s_p4_0[] = {
  125021. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  125022. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  125023. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  125024. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  125025. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  125026. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  125027. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  125028. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125029. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125030. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  125031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125039. 0,
  125040. };
  125041. static float _vq_quantthresh__16c2_s_p4_0[] = {
  125042. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125043. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125044. };
  125045. static long _vq_quantmap__16c2_s_p4_0[] = {
  125046. 15, 13, 11, 9, 7, 5, 3, 1,
  125047. 0, 2, 4, 6, 8, 10, 12, 14,
  125048. 16,
  125049. };
  125050. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125051. _vq_quantthresh__16c2_s_p4_0,
  125052. _vq_quantmap__16c2_s_p4_0,
  125053. 17,
  125054. 17
  125055. };
  125056. static static_codebook _16c2_s_p4_0 = {
  125057. 2, 289,
  125058. _vq_lengthlist__16c2_s_p4_0,
  125059. 1, -529530880, 1611661312, 5, 0,
  125060. _vq_quantlist__16c2_s_p4_0,
  125061. NULL,
  125062. &_vq_auxt__16c2_s_p4_0,
  125063. NULL,
  125064. 0
  125065. };
  125066. static long _vq_quantlist__16c2_s_p5_0[] = {
  125067. 1,
  125068. 0,
  125069. 2,
  125070. };
  125071. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125072. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125073. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125074. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125075. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125076. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125077. 12,
  125078. };
  125079. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125080. -5.5, 5.5,
  125081. };
  125082. static long _vq_quantmap__16c2_s_p5_0[] = {
  125083. 1, 0, 2,
  125084. };
  125085. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125086. _vq_quantthresh__16c2_s_p5_0,
  125087. _vq_quantmap__16c2_s_p5_0,
  125088. 3,
  125089. 3
  125090. };
  125091. static static_codebook _16c2_s_p5_0 = {
  125092. 4, 81,
  125093. _vq_lengthlist__16c2_s_p5_0,
  125094. 1, -529137664, 1618345984, 2, 0,
  125095. _vq_quantlist__16c2_s_p5_0,
  125096. NULL,
  125097. &_vq_auxt__16c2_s_p5_0,
  125098. NULL,
  125099. 0
  125100. };
  125101. static long _vq_quantlist__16c2_s_p5_1[] = {
  125102. 5,
  125103. 4,
  125104. 6,
  125105. 3,
  125106. 7,
  125107. 2,
  125108. 8,
  125109. 1,
  125110. 9,
  125111. 0,
  125112. 10,
  125113. };
  125114. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125115. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125116. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125117. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125118. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125119. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125120. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125121. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125122. 11,11,11, 7, 7, 8, 8, 8, 8,
  125123. };
  125124. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125125. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125126. 3.5, 4.5,
  125127. };
  125128. static long _vq_quantmap__16c2_s_p5_1[] = {
  125129. 9, 7, 5, 3, 1, 0, 2, 4,
  125130. 6, 8, 10,
  125131. };
  125132. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125133. _vq_quantthresh__16c2_s_p5_1,
  125134. _vq_quantmap__16c2_s_p5_1,
  125135. 11,
  125136. 11
  125137. };
  125138. static static_codebook _16c2_s_p5_1 = {
  125139. 2, 121,
  125140. _vq_lengthlist__16c2_s_p5_1,
  125141. 1, -531365888, 1611661312, 4, 0,
  125142. _vq_quantlist__16c2_s_p5_1,
  125143. NULL,
  125144. &_vq_auxt__16c2_s_p5_1,
  125145. NULL,
  125146. 0
  125147. };
  125148. static long _vq_quantlist__16c2_s_p6_0[] = {
  125149. 6,
  125150. 5,
  125151. 7,
  125152. 4,
  125153. 8,
  125154. 3,
  125155. 9,
  125156. 2,
  125157. 10,
  125158. 1,
  125159. 11,
  125160. 0,
  125161. 12,
  125162. };
  125163. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125164. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125165. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125166. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125167. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125168. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125169. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125174. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125175. };
  125176. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125177. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125178. 12.5, 17.5, 22.5, 27.5,
  125179. };
  125180. static long _vq_quantmap__16c2_s_p6_0[] = {
  125181. 11, 9, 7, 5, 3, 1, 0, 2,
  125182. 4, 6, 8, 10, 12,
  125183. };
  125184. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125185. _vq_quantthresh__16c2_s_p6_0,
  125186. _vq_quantmap__16c2_s_p6_0,
  125187. 13,
  125188. 13
  125189. };
  125190. static static_codebook _16c2_s_p6_0 = {
  125191. 2, 169,
  125192. _vq_lengthlist__16c2_s_p6_0,
  125193. 1, -526516224, 1616117760, 4, 0,
  125194. _vq_quantlist__16c2_s_p6_0,
  125195. NULL,
  125196. &_vq_auxt__16c2_s_p6_0,
  125197. NULL,
  125198. 0
  125199. };
  125200. static long _vq_quantlist__16c2_s_p6_1[] = {
  125201. 2,
  125202. 1,
  125203. 3,
  125204. 0,
  125205. 4,
  125206. };
  125207. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125208. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125209. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125210. };
  125211. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125212. -1.5, -0.5, 0.5, 1.5,
  125213. };
  125214. static long _vq_quantmap__16c2_s_p6_1[] = {
  125215. 3, 1, 0, 2, 4,
  125216. };
  125217. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125218. _vq_quantthresh__16c2_s_p6_1,
  125219. _vq_quantmap__16c2_s_p6_1,
  125220. 5,
  125221. 5
  125222. };
  125223. static static_codebook _16c2_s_p6_1 = {
  125224. 2, 25,
  125225. _vq_lengthlist__16c2_s_p6_1,
  125226. 1, -533725184, 1611661312, 3, 0,
  125227. _vq_quantlist__16c2_s_p6_1,
  125228. NULL,
  125229. &_vq_auxt__16c2_s_p6_1,
  125230. NULL,
  125231. 0
  125232. };
  125233. static long _vq_quantlist__16c2_s_p7_0[] = {
  125234. 6,
  125235. 5,
  125236. 7,
  125237. 4,
  125238. 8,
  125239. 3,
  125240. 9,
  125241. 2,
  125242. 10,
  125243. 1,
  125244. 11,
  125245. 0,
  125246. 12,
  125247. };
  125248. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125249. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125250. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125251. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125252. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125253. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125254. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125255. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125256. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125257. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125258. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125259. 18,13,14,13,13,14,13,15,14,
  125260. };
  125261. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125262. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125263. 27.5, 38.5, 49.5, 60.5,
  125264. };
  125265. static long _vq_quantmap__16c2_s_p7_0[] = {
  125266. 11, 9, 7, 5, 3, 1, 0, 2,
  125267. 4, 6, 8, 10, 12,
  125268. };
  125269. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125270. _vq_quantthresh__16c2_s_p7_0,
  125271. _vq_quantmap__16c2_s_p7_0,
  125272. 13,
  125273. 13
  125274. };
  125275. static static_codebook _16c2_s_p7_0 = {
  125276. 2, 169,
  125277. _vq_lengthlist__16c2_s_p7_0,
  125278. 1, -523206656, 1618345984, 4, 0,
  125279. _vq_quantlist__16c2_s_p7_0,
  125280. NULL,
  125281. &_vq_auxt__16c2_s_p7_0,
  125282. NULL,
  125283. 0
  125284. };
  125285. static long _vq_quantlist__16c2_s_p7_1[] = {
  125286. 5,
  125287. 4,
  125288. 6,
  125289. 3,
  125290. 7,
  125291. 2,
  125292. 8,
  125293. 1,
  125294. 9,
  125295. 0,
  125296. 10,
  125297. };
  125298. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125299. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125300. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125301. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125302. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125303. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125304. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125305. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125306. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125307. };
  125308. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125309. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125310. 3.5, 4.5,
  125311. };
  125312. static long _vq_quantmap__16c2_s_p7_1[] = {
  125313. 9, 7, 5, 3, 1, 0, 2, 4,
  125314. 6, 8, 10,
  125315. };
  125316. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125317. _vq_quantthresh__16c2_s_p7_1,
  125318. _vq_quantmap__16c2_s_p7_1,
  125319. 11,
  125320. 11
  125321. };
  125322. static static_codebook _16c2_s_p7_1 = {
  125323. 2, 121,
  125324. _vq_lengthlist__16c2_s_p7_1,
  125325. 1, -531365888, 1611661312, 4, 0,
  125326. _vq_quantlist__16c2_s_p7_1,
  125327. NULL,
  125328. &_vq_auxt__16c2_s_p7_1,
  125329. NULL,
  125330. 0
  125331. };
  125332. static long _vq_quantlist__16c2_s_p8_0[] = {
  125333. 7,
  125334. 6,
  125335. 8,
  125336. 5,
  125337. 9,
  125338. 4,
  125339. 10,
  125340. 3,
  125341. 11,
  125342. 2,
  125343. 12,
  125344. 1,
  125345. 13,
  125346. 0,
  125347. 14,
  125348. };
  125349. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125350. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125351. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125352. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125353. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125354. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125355. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125356. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125357. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125358. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125359. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125360. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125361. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125362. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125363. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125364. 13,
  125365. };
  125366. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125367. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125368. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125369. };
  125370. static long _vq_quantmap__16c2_s_p8_0[] = {
  125371. 13, 11, 9, 7, 5, 3, 1, 0,
  125372. 2, 4, 6, 8, 10, 12, 14,
  125373. };
  125374. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125375. _vq_quantthresh__16c2_s_p8_0,
  125376. _vq_quantmap__16c2_s_p8_0,
  125377. 15,
  125378. 15
  125379. };
  125380. static static_codebook _16c2_s_p8_0 = {
  125381. 2, 225,
  125382. _vq_lengthlist__16c2_s_p8_0,
  125383. 1, -520986624, 1620377600, 4, 0,
  125384. _vq_quantlist__16c2_s_p8_0,
  125385. NULL,
  125386. &_vq_auxt__16c2_s_p8_0,
  125387. NULL,
  125388. 0
  125389. };
  125390. static long _vq_quantlist__16c2_s_p8_1[] = {
  125391. 10,
  125392. 9,
  125393. 11,
  125394. 8,
  125395. 12,
  125396. 7,
  125397. 13,
  125398. 6,
  125399. 14,
  125400. 5,
  125401. 15,
  125402. 4,
  125403. 16,
  125404. 3,
  125405. 17,
  125406. 2,
  125407. 18,
  125408. 1,
  125409. 19,
  125410. 0,
  125411. 20,
  125412. };
  125413. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125414. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125415. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125416. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125417. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125418. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125419. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125420. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125421. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125422. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125423. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125424. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125425. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125426. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125427. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125428. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125429. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125430. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125431. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125432. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125433. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125434. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125435. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125436. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125437. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125438. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125439. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125440. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125441. 10,11,10,10,10,10,10,10,10,
  125442. };
  125443. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125444. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125445. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125446. 6.5, 7.5, 8.5, 9.5,
  125447. };
  125448. static long _vq_quantmap__16c2_s_p8_1[] = {
  125449. 19, 17, 15, 13, 11, 9, 7, 5,
  125450. 3, 1, 0, 2, 4, 6, 8, 10,
  125451. 12, 14, 16, 18, 20,
  125452. };
  125453. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125454. _vq_quantthresh__16c2_s_p8_1,
  125455. _vq_quantmap__16c2_s_p8_1,
  125456. 21,
  125457. 21
  125458. };
  125459. static static_codebook _16c2_s_p8_1 = {
  125460. 2, 441,
  125461. _vq_lengthlist__16c2_s_p8_1,
  125462. 1, -529268736, 1611661312, 5, 0,
  125463. _vq_quantlist__16c2_s_p8_1,
  125464. NULL,
  125465. &_vq_auxt__16c2_s_p8_1,
  125466. NULL,
  125467. 0
  125468. };
  125469. static long _vq_quantlist__16c2_s_p9_0[] = {
  125470. 6,
  125471. 5,
  125472. 7,
  125473. 4,
  125474. 8,
  125475. 3,
  125476. 9,
  125477. 2,
  125478. 10,
  125479. 1,
  125480. 11,
  125481. 0,
  125482. 12,
  125483. };
  125484. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125485. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125486. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125487. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125488. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125489. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125490. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125491. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125492. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125493. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125494. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125495. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125496. };
  125497. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125498. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125499. 2327.5, 3258.5, 4189.5, 5120.5,
  125500. };
  125501. static long _vq_quantmap__16c2_s_p9_0[] = {
  125502. 11, 9, 7, 5, 3, 1, 0, 2,
  125503. 4, 6, 8, 10, 12,
  125504. };
  125505. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125506. _vq_quantthresh__16c2_s_p9_0,
  125507. _vq_quantmap__16c2_s_p9_0,
  125508. 13,
  125509. 13
  125510. };
  125511. static static_codebook _16c2_s_p9_0 = {
  125512. 2, 169,
  125513. _vq_lengthlist__16c2_s_p9_0,
  125514. 1, -510275072, 1631393792, 4, 0,
  125515. _vq_quantlist__16c2_s_p9_0,
  125516. NULL,
  125517. &_vq_auxt__16c2_s_p9_0,
  125518. NULL,
  125519. 0
  125520. };
  125521. static long _vq_quantlist__16c2_s_p9_1[] = {
  125522. 8,
  125523. 7,
  125524. 9,
  125525. 6,
  125526. 10,
  125527. 5,
  125528. 11,
  125529. 4,
  125530. 12,
  125531. 3,
  125532. 13,
  125533. 2,
  125534. 14,
  125535. 1,
  125536. 15,
  125537. 0,
  125538. 16,
  125539. };
  125540. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125541. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125542. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125543. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125544. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125545. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125546. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125547. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125548. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125549. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125550. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125551. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125552. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125553. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125554. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125555. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125556. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125557. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125558. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125559. 10,
  125560. };
  125561. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125562. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125563. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125564. };
  125565. static long _vq_quantmap__16c2_s_p9_1[] = {
  125566. 15, 13, 11, 9, 7, 5, 3, 1,
  125567. 0, 2, 4, 6, 8, 10, 12, 14,
  125568. 16,
  125569. };
  125570. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125571. _vq_quantthresh__16c2_s_p9_1,
  125572. _vq_quantmap__16c2_s_p9_1,
  125573. 17,
  125574. 17
  125575. };
  125576. static static_codebook _16c2_s_p9_1 = {
  125577. 2, 289,
  125578. _vq_lengthlist__16c2_s_p9_1,
  125579. 1, -518488064, 1622704128, 5, 0,
  125580. _vq_quantlist__16c2_s_p9_1,
  125581. NULL,
  125582. &_vq_auxt__16c2_s_p9_1,
  125583. NULL,
  125584. 0
  125585. };
  125586. static long _vq_quantlist__16c2_s_p9_2[] = {
  125587. 13,
  125588. 12,
  125589. 14,
  125590. 11,
  125591. 15,
  125592. 10,
  125593. 16,
  125594. 9,
  125595. 17,
  125596. 8,
  125597. 18,
  125598. 7,
  125599. 19,
  125600. 6,
  125601. 20,
  125602. 5,
  125603. 21,
  125604. 4,
  125605. 22,
  125606. 3,
  125607. 23,
  125608. 2,
  125609. 24,
  125610. 1,
  125611. 25,
  125612. 0,
  125613. 26,
  125614. };
  125615. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125616. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125617. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125618. };
  125619. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125620. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125621. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125622. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125623. 11.5, 12.5,
  125624. };
  125625. static long _vq_quantmap__16c2_s_p9_2[] = {
  125626. 25, 23, 21, 19, 17, 15, 13, 11,
  125627. 9, 7, 5, 3, 1, 0, 2, 4,
  125628. 6, 8, 10, 12, 14, 16, 18, 20,
  125629. 22, 24, 26,
  125630. };
  125631. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125632. _vq_quantthresh__16c2_s_p9_2,
  125633. _vq_quantmap__16c2_s_p9_2,
  125634. 27,
  125635. 27
  125636. };
  125637. static static_codebook _16c2_s_p9_2 = {
  125638. 1, 27,
  125639. _vq_lengthlist__16c2_s_p9_2,
  125640. 1, -528875520, 1611661312, 5, 0,
  125641. _vq_quantlist__16c2_s_p9_2,
  125642. NULL,
  125643. &_vq_auxt__16c2_s_p9_2,
  125644. NULL,
  125645. 0
  125646. };
  125647. static long _huff_lengthlist__16c2_s_short[] = {
  125648. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125649. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125650. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125651. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125652. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125653. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125654. 15,12,14,14,
  125655. };
  125656. static static_codebook _huff_book__16c2_s_short = {
  125657. 2, 100,
  125658. _huff_lengthlist__16c2_s_short,
  125659. 0, 0, 0, 0, 0,
  125660. NULL,
  125661. NULL,
  125662. NULL,
  125663. NULL,
  125664. 0
  125665. };
  125666. static long _vq_quantlist__8c0_s_p1_0[] = {
  125667. 1,
  125668. 0,
  125669. 2,
  125670. };
  125671. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125672. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125673. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125677. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125678. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125682. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125683. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125718. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  125723. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  125728. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125764. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125769. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125774. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0,
  126083. };
  126084. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126085. -0.5, 0.5,
  126086. };
  126087. static long _vq_quantmap__8c0_s_p1_0[] = {
  126088. 1, 0, 2,
  126089. };
  126090. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126091. _vq_quantthresh__8c0_s_p1_0,
  126092. _vq_quantmap__8c0_s_p1_0,
  126093. 3,
  126094. 3
  126095. };
  126096. static static_codebook _8c0_s_p1_0 = {
  126097. 8, 6561,
  126098. _vq_lengthlist__8c0_s_p1_0,
  126099. 1, -535822336, 1611661312, 2, 0,
  126100. _vq_quantlist__8c0_s_p1_0,
  126101. NULL,
  126102. &_vq_auxt__8c0_s_p1_0,
  126103. NULL,
  126104. 0
  126105. };
  126106. static long _vq_quantlist__8c0_s_p2_0[] = {
  126107. 2,
  126108. 1,
  126109. 3,
  126110. 0,
  126111. 4,
  126112. };
  126113. static long _vq_lengthlist__8c0_s_p2_0[] = {
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0,
  126154. };
  126155. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126156. -1.5, -0.5, 0.5, 1.5,
  126157. };
  126158. static long _vq_quantmap__8c0_s_p2_0[] = {
  126159. 3, 1, 0, 2, 4,
  126160. };
  126161. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126162. _vq_quantthresh__8c0_s_p2_0,
  126163. _vq_quantmap__8c0_s_p2_0,
  126164. 5,
  126165. 5
  126166. };
  126167. static static_codebook _8c0_s_p2_0 = {
  126168. 4, 625,
  126169. _vq_lengthlist__8c0_s_p2_0,
  126170. 1, -533725184, 1611661312, 3, 0,
  126171. _vq_quantlist__8c0_s_p2_0,
  126172. NULL,
  126173. &_vq_auxt__8c0_s_p2_0,
  126174. NULL,
  126175. 0
  126176. };
  126177. static long _vq_quantlist__8c0_s_p3_0[] = {
  126178. 2,
  126179. 1,
  126180. 3,
  126181. 0,
  126182. 4,
  126183. };
  126184. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126185. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126224. 0,
  126225. };
  126226. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126227. -1.5, -0.5, 0.5, 1.5,
  126228. };
  126229. static long _vq_quantmap__8c0_s_p3_0[] = {
  126230. 3, 1, 0, 2, 4,
  126231. };
  126232. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126233. _vq_quantthresh__8c0_s_p3_0,
  126234. _vq_quantmap__8c0_s_p3_0,
  126235. 5,
  126236. 5
  126237. };
  126238. static static_codebook _8c0_s_p3_0 = {
  126239. 4, 625,
  126240. _vq_lengthlist__8c0_s_p3_0,
  126241. 1, -533725184, 1611661312, 3, 0,
  126242. _vq_quantlist__8c0_s_p3_0,
  126243. NULL,
  126244. &_vq_auxt__8c0_s_p3_0,
  126245. NULL,
  126246. 0
  126247. };
  126248. static long _vq_quantlist__8c0_s_p4_0[] = {
  126249. 4,
  126250. 3,
  126251. 5,
  126252. 2,
  126253. 6,
  126254. 1,
  126255. 7,
  126256. 0,
  126257. 8,
  126258. };
  126259. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126260. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126261. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126262. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126263. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126264. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126265. 0,
  126266. };
  126267. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126268. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126269. };
  126270. static long _vq_quantmap__8c0_s_p4_0[] = {
  126271. 7, 5, 3, 1, 0, 2, 4, 6,
  126272. 8,
  126273. };
  126274. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126275. _vq_quantthresh__8c0_s_p4_0,
  126276. _vq_quantmap__8c0_s_p4_0,
  126277. 9,
  126278. 9
  126279. };
  126280. static static_codebook _8c0_s_p4_0 = {
  126281. 2, 81,
  126282. _vq_lengthlist__8c0_s_p4_0,
  126283. 1, -531628032, 1611661312, 4, 0,
  126284. _vq_quantlist__8c0_s_p4_0,
  126285. NULL,
  126286. &_vq_auxt__8c0_s_p4_0,
  126287. NULL,
  126288. 0
  126289. };
  126290. static long _vq_quantlist__8c0_s_p5_0[] = {
  126291. 4,
  126292. 3,
  126293. 5,
  126294. 2,
  126295. 6,
  126296. 1,
  126297. 7,
  126298. 0,
  126299. 8,
  126300. };
  126301. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126302. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126303. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126304. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126305. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126306. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126307. 10,
  126308. };
  126309. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126310. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126311. };
  126312. static long _vq_quantmap__8c0_s_p5_0[] = {
  126313. 7, 5, 3, 1, 0, 2, 4, 6,
  126314. 8,
  126315. };
  126316. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126317. _vq_quantthresh__8c0_s_p5_0,
  126318. _vq_quantmap__8c0_s_p5_0,
  126319. 9,
  126320. 9
  126321. };
  126322. static static_codebook _8c0_s_p5_0 = {
  126323. 2, 81,
  126324. _vq_lengthlist__8c0_s_p5_0,
  126325. 1, -531628032, 1611661312, 4, 0,
  126326. _vq_quantlist__8c0_s_p5_0,
  126327. NULL,
  126328. &_vq_auxt__8c0_s_p5_0,
  126329. NULL,
  126330. 0
  126331. };
  126332. static long _vq_quantlist__8c0_s_p6_0[] = {
  126333. 8,
  126334. 7,
  126335. 9,
  126336. 6,
  126337. 10,
  126338. 5,
  126339. 11,
  126340. 4,
  126341. 12,
  126342. 3,
  126343. 13,
  126344. 2,
  126345. 14,
  126346. 1,
  126347. 15,
  126348. 0,
  126349. 16,
  126350. };
  126351. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126352. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126353. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126354. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126355. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126356. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126357. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126358. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126359. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126360. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126361. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126362. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126363. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126364. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126365. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126366. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126367. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126368. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126369. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126370. 14,
  126371. };
  126372. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126373. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126374. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126375. };
  126376. static long _vq_quantmap__8c0_s_p6_0[] = {
  126377. 15, 13, 11, 9, 7, 5, 3, 1,
  126378. 0, 2, 4, 6, 8, 10, 12, 14,
  126379. 16,
  126380. };
  126381. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126382. _vq_quantthresh__8c0_s_p6_0,
  126383. _vq_quantmap__8c0_s_p6_0,
  126384. 17,
  126385. 17
  126386. };
  126387. static static_codebook _8c0_s_p6_0 = {
  126388. 2, 289,
  126389. _vq_lengthlist__8c0_s_p6_0,
  126390. 1, -529530880, 1611661312, 5, 0,
  126391. _vq_quantlist__8c0_s_p6_0,
  126392. NULL,
  126393. &_vq_auxt__8c0_s_p6_0,
  126394. NULL,
  126395. 0
  126396. };
  126397. static long _vq_quantlist__8c0_s_p7_0[] = {
  126398. 1,
  126399. 0,
  126400. 2,
  126401. };
  126402. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126403. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126404. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126405. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126406. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126407. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126408. 10,
  126409. };
  126410. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126411. -5.5, 5.5,
  126412. };
  126413. static long _vq_quantmap__8c0_s_p7_0[] = {
  126414. 1, 0, 2,
  126415. };
  126416. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126417. _vq_quantthresh__8c0_s_p7_0,
  126418. _vq_quantmap__8c0_s_p7_0,
  126419. 3,
  126420. 3
  126421. };
  126422. static static_codebook _8c0_s_p7_0 = {
  126423. 4, 81,
  126424. _vq_lengthlist__8c0_s_p7_0,
  126425. 1, -529137664, 1618345984, 2, 0,
  126426. _vq_quantlist__8c0_s_p7_0,
  126427. NULL,
  126428. &_vq_auxt__8c0_s_p7_0,
  126429. NULL,
  126430. 0
  126431. };
  126432. static long _vq_quantlist__8c0_s_p7_1[] = {
  126433. 5,
  126434. 4,
  126435. 6,
  126436. 3,
  126437. 7,
  126438. 2,
  126439. 8,
  126440. 1,
  126441. 9,
  126442. 0,
  126443. 10,
  126444. };
  126445. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126446. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126447. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126448. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126449. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126450. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126451. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126452. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126453. 10,10,10, 9, 9, 9,10,10,10,
  126454. };
  126455. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126456. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126457. 3.5, 4.5,
  126458. };
  126459. static long _vq_quantmap__8c0_s_p7_1[] = {
  126460. 9, 7, 5, 3, 1, 0, 2, 4,
  126461. 6, 8, 10,
  126462. };
  126463. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126464. _vq_quantthresh__8c0_s_p7_1,
  126465. _vq_quantmap__8c0_s_p7_1,
  126466. 11,
  126467. 11
  126468. };
  126469. static static_codebook _8c0_s_p7_1 = {
  126470. 2, 121,
  126471. _vq_lengthlist__8c0_s_p7_1,
  126472. 1, -531365888, 1611661312, 4, 0,
  126473. _vq_quantlist__8c0_s_p7_1,
  126474. NULL,
  126475. &_vq_auxt__8c0_s_p7_1,
  126476. NULL,
  126477. 0
  126478. };
  126479. static long _vq_quantlist__8c0_s_p8_0[] = {
  126480. 6,
  126481. 5,
  126482. 7,
  126483. 4,
  126484. 8,
  126485. 3,
  126486. 9,
  126487. 2,
  126488. 10,
  126489. 1,
  126490. 11,
  126491. 0,
  126492. 12,
  126493. };
  126494. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126495. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126496. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126497. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126498. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126499. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126500. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126501. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126502. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126503. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126504. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126505. 0, 0,13,13,11,13,13,11,12,
  126506. };
  126507. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126508. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126509. 12.5, 17.5, 22.5, 27.5,
  126510. };
  126511. static long _vq_quantmap__8c0_s_p8_0[] = {
  126512. 11, 9, 7, 5, 3, 1, 0, 2,
  126513. 4, 6, 8, 10, 12,
  126514. };
  126515. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126516. _vq_quantthresh__8c0_s_p8_0,
  126517. _vq_quantmap__8c0_s_p8_0,
  126518. 13,
  126519. 13
  126520. };
  126521. static static_codebook _8c0_s_p8_0 = {
  126522. 2, 169,
  126523. _vq_lengthlist__8c0_s_p8_0,
  126524. 1, -526516224, 1616117760, 4, 0,
  126525. _vq_quantlist__8c0_s_p8_0,
  126526. NULL,
  126527. &_vq_auxt__8c0_s_p8_0,
  126528. NULL,
  126529. 0
  126530. };
  126531. static long _vq_quantlist__8c0_s_p8_1[] = {
  126532. 2,
  126533. 1,
  126534. 3,
  126535. 0,
  126536. 4,
  126537. };
  126538. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126539. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126540. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126541. };
  126542. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126543. -1.5, -0.5, 0.5, 1.5,
  126544. };
  126545. static long _vq_quantmap__8c0_s_p8_1[] = {
  126546. 3, 1, 0, 2, 4,
  126547. };
  126548. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126549. _vq_quantthresh__8c0_s_p8_1,
  126550. _vq_quantmap__8c0_s_p8_1,
  126551. 5,
  126552. 5
  126553. };
  126554. static static_codebook _8c0_s_p8_1 = {
  126555. 2, 25,
  126556. _vq_lengthlist__8c0_s_p8_1,
  126557. 1, -533725184, 1611661312, 3, 0,
  126558. _vq_quantlist__8c0_s_p8_1,
  126559. NULL,
  126560. &_vq_auxt__8c0_s_p8_1,
  126561. NULL,
  126562. 0
  126563. };
  126564. static long _vq_quantlist__8c0_s_p9_0[] = {
  126565. 1,
  126566. 0,
  126567. 2,
  126568. };
  126569. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126570. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126571. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126572. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126573. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126574. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126575. 7,
  126576. };
  126577. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126578. -157.5, 157.5,
  126579. };
  126580. static long _vq_quantmap__8c0_s_p9_0[] = {
  126581. 1, 0, 2,
  126582. };
  126583. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126584. _vq_quantthresh__8c0_s_p9_0,
  126585. _vq_quantmap__8c0_s_p9_0,
  126586. 3,
  126587. 3
  126588. };
  126589. static static_codebook _8c0_s_p9_0 = {
  126590. 4, 81,
  126591. _vq_lengthlist__8c0_s_p9_0,
  126592. 1, -518803456, 1628680192, 2, 0,
  126593. _vq_quantlist__8c0_s_p9_0,
  126594. NULL,
  126595. &_vq_auxt__8c0_s_p9_0,
  126596. NULL,
  126597. 0
  126598. };
  126599. static long _vq_quantlist__8c0_s_p9_1[] = {
  126600. 7,
  126601. 6,
  126602. 8,
  126603. 5,
  126604. 9,
  126605. 4,
  126606. 10,
  126607. 3,
  126608. 11,
  126609. 2,
  126610. 12,
  126611. 1,
  126612. 13,
  126613. 0,
  126614. 14,
  126615. };
  126616. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126617. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126618. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126619. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126620. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126621. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126622. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126623. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126624. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126625. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126626. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126627. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126628. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126629. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126630. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126631. 11,
  126632. };
  126633. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126634. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126635. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126636. };
  126637. static long _vq_quantmap__8c0_s_p9_1[] = {
  126638. 13, 11, 9, 7, 5, 3, 1, 0,
  126639. 2, 4, 6, 8, 10, 12, 14,
  126640. };
  126641. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126642. _vq_quantthresh__8c0_s_p9_1,
  126643. _vq_quantmap__8c0_s_p9_1,
  126644. 15,
  126645. 15
  126646. };
  126647. static static_codebook _8c0_s_p9_1 = {
  126648. 2, 225,
  126649. _vq_lengthlist__8c0_s_p9_1,
  126650. 1, -520986624, 1620377600, 4, 0,
  126651. _vq_quantlist__8c0_s_p9_1,
  126652. NULL,
  126653. &_vq_auxt__8c0_s_p9_1,
  126654. NULL,
  126655. 0
  126656. };
  126657. static long _vq_quantlist__8c0_s_p9_2[] = {
  126658. 10,
  126659. 9,
  126660. 11,
  126661. 8,
  126662. 12,
  126663. 7,
  126664. 13,
  126665. 6,
  126666. 14,
  126667. 5,
  126668. 15,
  126669. 4,
  126670. 16,
  126671. 3,
  126672. 17,
  126673. 2,
  126674. 18,
  126675. 1,
  126676. 19,
  126677. 0,
  126678. 20,
  126679. };
  126680. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126681. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126682. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126683. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126684. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126685. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126686. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126687. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126688. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126689. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126690. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126691. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126692. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126693. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126694. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126695. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126696. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126697. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126698. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126699. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126700. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126701. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126702. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126703. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126704. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126705. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126706. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126707. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126708. 10,11, 9,11,10, 9,10, 9,10,
  126709. };
  126710. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126711. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126712. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126713. 6.5, 7.5, 8.5, 9.5,
  126714. };
  126715. static long _vq_quantmap__8c0_s_p9_2[] = {
  126716. 19, 17, 15, 13, 11, 9, 7, 5,
  126717. 3, 1, 0, 2, 4, 6, 8, 10,
  126718. 12, 14, 16, 18, 20,
  126719. };
  126720. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126721. _vq_quantthresh__8c0_s_p9_2,
  126722. _vq_quantmap__8c0_s_p9_2,
  126723. 21,
  126724. 21
  126725. };
  126726. static static_codebook _8c0_s_p9_2 = {
  126727. 2, 441,
  126728. _vq_lengthlist__8c0_s_p9_2,
  126729. 1, -529268736, 1611661312, 5, 0,
  126730. _vq_quantlist__8c0_s_p9_2,
  126731. NULL,
  126732. &_vq_auxt__8c0_s_p9_2,
  126733. NULL,
  126734. 0
  126735. };
  126736. static long _huff_lengthlist__8c0_s_single[] = {
  126737. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126738. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126739. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126740. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126741. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126742. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126743. 17,16,17,17,
  126744. };
  126745. static static_codebook _huff_book__8c0_s_single = {
  126746. 2, 100,
  126747. _huff_lengthlist__8c0_s_single,
  126748. 0, 0, 0, 0, 0,
  126749. NULL,
  126750. NULL,
  126751. NULL,
  126752. NULL,
  126753. 0
  126754. };
  126755. static long _vq_quantlist__8c1_s_p1_0[] = {
  126756. 1,
  126757. 0,
  126758. 2,
  126759. };
  126760. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126761. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126762. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126766. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126767. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126771. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126772. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126807. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126812. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126817. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126853. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126857. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126858. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126862. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126863. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0,
  127172. };
  127173. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127174. -0.5, 0.5,
  127175. };
  127176. static long _vq_quantmap__8c1_s_p1_0[] = {
  127177. 1, 0, 2,
  127178. };
  127179. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127180. _vq_quantthresh__8c1_s_p1_0,
  127181. _vq_quantmap__8c1_s_p1_0,
  127182. 3,
  127183. 3
  127184. };
  127185. static static_codebook _8c1_s_p1_0 = {
  127186. 8, 6561,
  127187. _vq_lengthlist__8c1_s_p1_0,
  127188. 1, -535822336, 1611661312, 2, 0,
  127189. _vq_quantlist__8c1_s_p1_0,
  127190. NULL,
  127191. &_vq_auxt__8c1_s_p1_0,
  127192. NULL,
  127193. 0
  127194. };
  127195. static long _vq_quantlist__8c1_s_p2_0[] = {
  127196. 2,
  127197. 1,
  127198. 3,
  127199. 0,
  127200. 4,
  127201. };
  127202. static long _vq_lengthlist__8c1_s_p2_0[] = {
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127242. 0,
  127243. };
  127244. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127245. -1.5, -0.5, 0.5, 1.5,
  127246. };
  127247. static long _vq_quantmap__8c1_s_p2_0[] = {
  127248. 3, 1, 0, 2, 4,
  127249. };
  127250. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127251. _vq_quantthresh__8c1_s_p2_0,
  127252. _vq_quantmap__8c1_s_p2_0,
  127253. 5,
  127254. 5
  127255. };
  127256. static static_codebook _8c1_s_p2_0 = {
  127257. 4, 625,
  127258. _vq_lengthlist__8c1_s_p2_0,
  127259. 1, -533725184, 1611661312, 3, 0,
  127260. _vq_quantlist__8c1_s_p2_0,
  127261. NULL,
  127262. &_vq_auxt__8c1_s_p2_0,
  127263. NULL,
  127264. 0
  127265. };
  127266. static long _vq_quantlist__8c1_s_p3_0[] = {
  127267. 2,
  127268. 1,
  127269. 3,
  127270. 0,
  127271. 4,
  127272. };
  127273. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127274. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127277. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127280. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127313. 0,
  127314. };
  127315. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127316. -1.5, -0.5, 0.5, 1.5,
  127317. };
  127318. static long _vq_quantmap__8c1_s_p3_0[] = {
  127319. 3, 1, 0, 2, 4,
  127320. };
  127321. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127322. _vq_quantthresh__8c1_s_p3_0,
  127323. _vq_quantmap__8c1_s_p3_0,
  127324. 5,
  127325. 5
  127326. };
  127327. static static_codebook _8c1_s_p3_0 = {
  127328. 4, 625,
  127329. _vq_lengthlist__8c1_s_p3_0,
  127330. 1, -533725184, 1611661312, 3, 0,
  127331. _vq_quantlist__8c1_s_p3_0,
  127332. NULL,
  127333. &_vq_auxt__8c1_s_p3_0,
  127334. NULL,
  127335. 0
  127336. };
  127337. static long _vq_quantlist__8c1_s_p4_0[] = {
  127338. 4,
  127339. 3,
  127340. 5,
  127341. 2,
  127342. 6,
  127343. 1,
  127344. 7,
  127345. 0,
  127346. 8,
  127347. };
  127348. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127349. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127350. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127351. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127352. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127353. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127354. 0,
  127355. };
  127356. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127357. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127358. };
  127359. static long _vq_quantmap__8c1_s_p4_0[] = {
  127360. 7, 5, 3, 1, 0, 2, 4, 6,
  127361. 8,
  127362. };
  127363. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127364. _vq_quantthresh__8c1_s_p4_0,
  127365. _vq_quantmap__8c1_s_p4_0,
  127366. 9,
  127367. 9
  127368. };
  127369. static static_codebook _8c1_s_p4_0 = {
  127370. 2, 81,
  127371. _vq_lengthlist__8c1_s_p4_0,
  127372. 1, -531628032, 1611661312, 4, 0,
  127373. _vq_quantlist__8c1_s_p4_0,
  127374. NULL,
  127375. &_vq_auxt__8c1_s_p4_0,
  127376. NULL,
  127377. 0
  127378. };
  127379. static long _vq_quantlist__8c1_s_p5_0[] = {
  127380. 4,
  127381. 3,
  127382. 5,
  127383. 2,
  127384. 6,
  127385. 1,
  127386. 7,
  127387. 0,
  127388. 8,
  127389. };
  127390. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127391. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127392. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127393. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127394. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127395. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127396. 10,
  127397. };
  127398. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127399. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127400. };
  127401. static long _vq_quantmap__8c1_s_p5_0[] = {
  127402. 7, 5, 3, 1, 0, 2, 4, 6,
  127403. 8,
  127404. };
  127405. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127406. _vq_quantthresh__8c1_s_p5_0,
  127407. _vq_quantmap__8c1_s_p5_0,
  127408. 9,
  127409. 9
  127410. };
  127411. static static_codebook _8c1_s_p5_0 = {
  127412. 2, 81,
  127413. _vq_lengthlist__8c1_s_p5_0,
  127414. 1, -531628032, 1611661312, 4, 0,
  127415. _vq_quantlist__8c1_s_p5_0,
  127416. NULL,
  127417. &_vq_auxt__8c1_s_p5_0,
  127418. NULL,
  127419. 0
  127420. };
  127421. static long _vq_quantlist__8c1_s_p6_0[] = {
  127422. 8,
  127423. 7,
  127424. 9,
  127425. 6,
  127426. 10,
  127427. 5,
  127428. 11,
  127429. 4,
  127430. 12,
  127431. 3,
  127432. 13,
  127433. 2,
  127434. 14,
  127435. 1,
  127436. 15,
  127437. 0,
  127438. 16,
  127439. };
  127440. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127441. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127442. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127443. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127444. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127445. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127446. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127447. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127448. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127449. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127450. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127451. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127452. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127453. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127454. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127455. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127456. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127457. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127458. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127459. 14,
  127460. };
  127461. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127462. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127463. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127464. };
  127465. static long _vq_quantmap__8c1_s_p6_0[] = {
  127466. 15, 13, 11, 9, 7, 5, 3, 1,
  127467. 0, 2, 4, 6, 8, 10, 12, 14,
  127468. 16,
  127469. };
  127470. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127471. _vq_quantthresh__8c1_s_p6_0,
  127472. _vq_quantmap__8c1_s_p6_0,
  127473. 17,
  127474. 17
  127475. };
  127476. static static_codebook _8c1_s_p6_0 = {
  127477. 2, 289,
  127478. _vq_lengthlist__8c1_s_p6_0,
  127479. 1, -529530880, 1611661312, 5, 0,
  127480. _vq_quantlist__8c1_s_p6_0,
  127481. NULL,
  127482. &_vq_auxt__8c1_s_p6_0,
  127483. NULL,
  127484. 0
  127485. };
  127486. static long _vq_quantlist__8c1_s_p7_0[] = {
  127487. 1,
  127488. 0,
  127489. 2,
  127490. };
  127491. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127492. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127493. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127494. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127495. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127496. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127497. 9,
  127498. };
  127499. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127500. -5.5, 5.5,
  127501. };
  127502. static long _vq_quantmap__8c1_s_p7_0[] = {
  127503. 1, 0, 2,
  127504. };
  127505. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127506. _vq_quantthresh__8c1_s_p7_0,
  127507. _vq_quantmap__8c1_s_p7_0,
  127508. 3,
  127509. 3
  127510. };
  127511. static static_codebook _8c1_s_p7_0 = {
  127512. 4, 81,
  127513. _vq_lengthlist__8c1_s_p7_0,
  127514. 1, -529137664, 1618345984, 2, 0,
  127515. _vq_quantlist__8c1_s_p7_0,
  127516. NULL,
  127517. &_vq_auxt__8c1_s_p7_0,
  127518. NULL,
  127519. 0
  127520. };
  127521. static long _vq_quantlist__8c1_s_p7_1[] = {
  127522. 5,
  127523. 4,
  127524. 6,
  127525. 3,
  127526. 7,
  127527. 2,
  127528. 8,
  127529. 1,
  127530. 9,
  127531. 0,
  127532. 10,
  127533. };
  127534. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127535. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127536. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127537. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127538. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127539. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127540. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127541. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127542. 10,10,10, 8, 8, 8, 8, 8, 8,
  127543. };
  127544. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127545. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127546. 3.5, 4.5,
  127547. };
  127548. static long _vq_quantmap__8c1_s_p7_1[] = {
  127549. 9, 7, 5, 3, 1, 0, 2, 4,
  127550. 6, 8, 10,
  127551. };
  127552. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127553. _vq_quantthresh__8c1_s_p7_1,
  127554. _vq_quantmap__8c1_s_p7_1,
  127555. 11,
  127556. 11
  127557. };
  127558. static static_codebook _8c1_s_p7_1 = {
  127559. 2, 121,
  127560. _vq_lengthlist__8c1_s_p7_1,
  127561. 1, -531365888, 1611661312, 4, 0,
  127562. _vq_quantlist__8c1_s_p7_1,
  127563. NULL,
  127564. &_vq_auxt__8c1_s_p7_1,
  127565. NULL,
  127566. 0
  127567. };
  127568. static long _vq_quantlist__8c1_s_p8_0[] = {
  127569. 6,
  127570. 5,
  127571. 7,
  127572. 4,
  127573. 8,
  127574. 3,
  127575. 9,
  127576. 2,
  127577. 10,
  127578. 1,
  127579. 11,
  127580. 0,
  127581. 12,
  127582. };
  127583. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127584. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127585. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127586. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127587. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127588. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127589. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127590. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127591. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127592. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127593. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127594. 0,12,12,11,10,12,11,13,12,
  127595. };
  127596. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127597. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127598. 12.5, 17.5, 22.5, 27.5,
  127599. };
  127600. static long _vq_quantmap__8c1_s_p8_0[] = {
  127601. 11, 9, 7, 5, 3, 1, 0, 2,
  127602. 4, 6, 8, 10, 12,
  127603. };
  127604. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127605. _vq_quantthresh__8c1_s_p8_0,
  127606. _vq_quantmap__8c1_s_p8_0,
  127607. 13,
  127608. 13
  127609. };
  127610. static static_codebook _8c1_s_p8_0 = {
  127611. 2, 169,
  127612. _vq_lengthlist__8c1_s_p8_0,
  127613. 1, -526516224, 1616117760, 4, 0,
  127614. _vq_quantlist__8c1_s_p8_0,
  127615. NULL,
  127616. &_vq_auxt__8c1_s_p8_0,
  127617. NULL,
  127618. 0
  127619. };
  127620. static long _vq_quantlist__8c1_s_p8_1[] = {
  127621. 2,
  127622. 1,
  127623. 3,
  127624. 0,
  127625. 4,
  127626. };
  127627. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127628. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127629. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127630. };
  127631. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127632. -1.5, -0.5, 0.5, 1.5,
  127633. };
  127634. static long _vq_quantmap__8c1_s_p8_1[] = {
  127635. 3, 1, 0, 2, 4,
  127636. };
  127637. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127638. _vq_quantthresh__8c1_s_p8_1,
  127639. _vq_quantmap__8c1_s_p8_1,
  127640. 5,
  127641. 5
  127642. };
  127643. static static_codebook _8c1_s_p8_1 = {
  127644. 2, 25,
  127645. _vq_lengthlist__8c1_s_p8_1,
  127646. 1, -533725184, 1611661312, 3, 0,
  127647. _vq_quantlist__8c1_s_p8_1,
  127648. NULL,
  127649. &_vq_auxt__8c1_s_p8_1,
  127650. NULL,
  127651. 0
  127652. };
  127653. static long _vq_quantlist__8c1_s_p9_0[] = {
  127654. 6,
  127655. 5,
  127656. 7,
  127657. 4,
  127658. 8,
  127659. 3,
  127660. 9,
  127661. 2,
  127662. 10,
  127663. 1,
  127664. 11,
  127665. 0,
  127666. 12,
  127667. };
  127668. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127669. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127670. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127671. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127672. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127673. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127674. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127675. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127676. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127677. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127678. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127679. 10,10,10,10,10, 9, 9, 9, 9,
  127680. };
  127681. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127682. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127683. 787.5, 1102.5, 1417.5, 1732.5,
  127684. };
  127685. static long _vq_quantmap__8c1_s_p9_0[] = {
  127686. 11, 9, 7, 5, 3, 1, 0, 2,
  127687. 4, 6, 8, 10, 12,
  127688. };
  127689. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127690. _vq_quantthresh__8c1_s_p9_0,
  127691. _vq_quantmap__8c1_s_p9_0,
  127692. 13,
  127693. 13
  127694. };
  127695. static static_codebook _8c1_s_p9_0 = {
  127696. 2, 169,
  127697. _vq_lengthlist__8c1_s_p9_0,
  127698. 1, -513964032, 1628680192, 4, 0,
  127699. _vq_quantlist__8c1_s_p9_0,
  127700. NULL,
  127701. &_vq_auxt__8c1_s_p9_0,
  127702. NULL,
  127703. 0
  127704. };
  127705. static long _vq_quantlist__8c1_s_p9_1[] = {
  127706. 7,
  127707. 6,
  127708. 8,
  127709. 5,
  127710. 9,
  127711. 4,
  127712. 10,
  127713. 3,
  127714. 11,
  127715. 2,
  127716. 12,
  127717. 1,
  127718. 13,
  127719. 0,
  127720. 14,
  127721. };
  127722. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127723. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127724. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127725. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127726. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127727. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127728. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127729. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127730. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127731. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127732. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127733. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127734. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127735. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127736. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127737. 15,
  127738. };
  127739. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127740. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127741. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127742. };
  127743. static long _vq_quantmap__8c1_s_p9_1[] = {
  127744. 13, 11, 9, 7, 5, 3, 1, 0,
  127745. 2, 4, 6, 8, 10, 12, 14,
  127746. };
  127747. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127748. _vq_quantthresh__8c1_s_p9_1,
  127749. _vq_quantmap__8c1_s_p9_1,
  127750. 15,
  127751. 15
  127752. };
  127753. static static_codebook _8c1_s_p9_1 = {
  127754. 2, 225,
  127755. _vq_lengthlist__8c1_s_p9_1,
  127756. 1, -520986624, 1620377600, 4, 0,
  127757. _vq_quantlist__8c1_s_p9_1,
  127758. NULL,
  127759. &_vq_auxt__8c1_s_p9_1,
  127760. NULL,
  127761. 0
  127762. };
  127763. static long _vq_quantlist__8c1_s_p9_2[] = {
  127764. 10,
  127765. 9,
  127766. 11,
  127767. 8,
  127768. 12,
  127769. 7,
  127770. 13,
  127771. 6,
  127772. 14,
  127773. 5,
  127774. 15,
  127775. 4,
  127776. 16,
  127777. 3,
  127778. 17,
  127779. 2,
  127780. 18,
  127781. 1,
  127782. 19,
  127783. 0,
  127784. 20,
  127785. };
  127786. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127787. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127788. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127789. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127790. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127791. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127792. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127793. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127794. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127795. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127796. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127797. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127798. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127799. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127800. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127801. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127802. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127803. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127804. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127805. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127806. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127807. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127808. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127809. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127810. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127811. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127812. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127813. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127814. 10,10,10,10,10,10,10,10,10,
  127815. };
  127816. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127817. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127818. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127819. 6.5, 7.5, 8.5, 9.5,
  127820. };
  127821. static long _vq_quantmap__8c1_s_p9_2[] = {
  127822. 19, 17, 15, 13, 11, 9, 7, 5,
  127823. 3, 1, 0, 2, 4, 6, 8, 10,
  127824. 12, 14, 16, 18, 20,
  127825. };
  127826. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127827. _vq_quantthresh__8c1_s_p9_2,
  127828. _vq_quantmap__8c1_s_p9_2,
  127829. 21,
  127830. 21
  127831. };
  127832. static static_codebook _8c1_s_p9_2 = {
  127833. 2, 441,
  127834. _vq_lengthlist__8c1_s_p9_2,
  127835. 1, -529268736, 1611661312, 5, 0,
  127836. _vq_quantlist__8c1_s_p9_2,
  127837. NULL,
  127838. &_vq_auxt__8c1_s_p9_2,
  127839. NULL,
  127840. 0
  127841. };
  127842. static long _huff_lengthlist__8c1_s_single[] = {
  127843. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127844. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127845. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127846. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127847. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127848. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127849. 9, 7, 7, 8,
  127850. };
  127851. static static_codebook _huff_book__8c1_s_single = {
  127852. 2, 100,
  127853. _huff_lengthlist__8c1_s_single,
  127854. 0, 0, 0, 0, 0,
  127855. NULL,
  127856. NULL,
  127857. NULL,
  127858. NULL,
  127859. 0
  127860. };
  127861. static long _huff_lengthlist__44c2_s_long[] = {
  127862. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127863. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127864. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127865. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127866. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127867. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127868. 10, 8, 8, 9,
  127869. };
  127870. static static_codebook _huff_book__44c2_s_long = {
  127871. 2, 100,
  127872. _huff_lengthlist__44c2_s_long,
  127873. 0, 0, 0, 0, 0,
  127874. NULL,
  127875. NULL,
  127876. NULL,
  127877. NULL,
  127878. 0
  127879. };
  127880. static long _vq_quantlist__44c2_s_p1_0[] = {
  127881. 1,
  127882. 0,
  127883. 2,
  127884. };
  127885. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127886. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127887. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127891. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127892. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127896. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127897. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127932. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127937. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127942. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127978. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127982. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127983. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  127984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127987. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127988. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128296. 0,
  128297. };
  128298. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128299. -0.5, 0.5,
  128300. };
  128301. static long _vq_quantmap__44c2_s_p1_0[] = {
  128302. 1, 0, 2,
  128303. };
  128304. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128305. _vq_quantthresh__44c2_s_p1_0,
  128306. _vq_quantmap__44c2_s_p1_0,
  128307. 3,
  128308. 3
  128309. };
  128310. static static_codebook _44c2_s_p1_0 = {
  128311. 8, 6561,
  128312. _vq_lengthlist__44c2_s_p1_0,
  128313. 1, -535822336, 1611661312, 2, 0,
  128314. _vq_quantlist__44c2_s_p1_0,
  128315. NULL,
  128316. &_vq_auxt__44c2_s_p1_0,
  128317. NULL,
  128318. 0
  128319. };
  128320. static long _vq_quantlist__44c2_s_p2_0[] = {
  128321. 2,
  128322. 1,
  128323. 3,
  128324. 0,
  128325. 4,
  128326. };
  128327. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128328. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128329. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128330. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128331. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128332. 0, 0, 9, 9, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128338. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128339. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128340. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128345. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128346. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128347. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  128348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128353. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128354. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128355. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128367. 0,
  128368. };
  128369. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128370. -1.5, -0.5, 0.5, 1.5,
  128371. };
  128372. static long _vq_quantmap__44c2_s_p2_0[] = {
  128373. 3, 1, 0, 2, 4,
  128374. };
  128375. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128376. _vq_quantthresh__44c2_s_p2_0,
  128377. _vq_quantmap__44c2_s_p2_0,
  128378. 5,
  128379. 5
  128380. };
  128381. static static_codebook _44c2_s_p2_0 = {
  128382. 4, 625,
  128383. _vq_lengthlist__44c2_s_p2_0,
  128384. 1, -533725184, 1611661312, 3, 0,
  128385. _vq_quantlist__44c2_s_p2_0,
  128386. NULL,
  128387. &_vq_auxt__44c2_s_p2_0,
  128388. NULL,
  128389. 0
  128390. };
  128391. static long _vq_quantlist__44c2_s_p3_0[] = {
  128392. 2,
  128393. 1,
  128394. 3,
  128395. 0,
  128396. 4,
  128397. };
  128398. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128399. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128402. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128405. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128438. 0,
  128439. };
  128440. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128441. -1.5, -0.5, 0.5, 1.5,
  128442. };
  128443. static long _vq_quantmap__44c2_s_p3_0[] = {
  128444. 3, 1, 0, 2, 4,
  128445. };
  128446. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128447. _vq_quantthresh__44c2_s_p3_0,
  128448. _vq_quantmap__44c2_s_p3_0,
  128449. 5,
  128450. 5
  128451. };
  128452. static static_codebook _44c2_s_p3_0 = {
  128453. 4, 625,
  128454. _vq_lengthlist__44c2_s_p3_0,
  128455. 1, -533725184, 1611661312, 3, 0,
  128456. _vq_quantlist__44c2_s_p3_0,
  128457. NULL,
  128458. &_vq_auxt__44c2_s_p3_0,
  128459. NULL,
  128460. 0
  128461. };
  128462. static long _vq_quantlist__44c2_s_p4_0[] = {
  128463. 4,
  128464. 3,
  128465. 5,
  128466. 2,
  128467. 6,
  128468. 1,
  128469. 7,
  128470. 0,
  128471. 8,
  128472. };
  128473. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128474. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128475. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128476. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128477. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128478. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128479. 0,
  128480. };
  128481. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128482. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128483. };
  128484. static long _vq_quantmap__44c2_s_p4_0[] = {
  128485. 7, 5, 3, 1, 0, 2, 4, 6,
  128486. 8,
  128487. };
  128488. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128489. _vq_quantthresh__44c2_s_p4_0,
  128490. _vq_quantmap__44c2_s_p4_0,
  128491. 9,
  128492. 9
  128493. };
  128494. static static_codebook _44c2_s_p4_0 = {
  128495. 2, 81,
  128496. _vq_lengthlist__44c2_s_p4_0,
  128497. 1, -531628032, 1611661312, 4, 0,
  128498. _vq_quantlist__44c2_s_p4_0,
  128499. NULL,
  128500. &_vq_auxt__44c2_s_p4_0,
  128501. NULL,
  128502. 0
  128503. };
  128504. static long _vq_quantlist__44c2_s_p5_0[] = {
  128505. 4,
  128506. 3,
  128507. 5,
  128508. 2,
  128509. 6,
  128510. 1,
  128511. 7,
  128512. 0,
  128513. 8,
  128514. };
  128515. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128516. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128517. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128518. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128519. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128520. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128521. 11,
  128522. };
  128523. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128524. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128525. };
  128526. static long _vq_quantmap__44c2_s_p5_0[] = {
  128527. 7, 5, 3, 1, 0, 2, 4, 6,
  128528. 8,
  128529. };
  128530. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128531. _vq_quantthresh__44c2_s_p5_0,
  128532. _vq_quantmap__44c2_s_p5_0,
  128533. 9,
  128534. 9
  128535. };
  128536. static static_codebook _44c2_s_p5_0 = {
  128537. 2, 81,
  128538. _vq_lengthlist__44c2_s_p5_0,
  128539. 1, -531628032, 1611661312, 4, 0,
  128540. _vq_quantlist__44c2_s_p5_0,
  128541. NULL,
  128542. &_vq_auxt__44c2_s_p5_0,
  128543. NULL,
  128544. 0
  128545. };
  128546. static long _vq_quantlist__44c2_s_p6_0[] = {
  128547. 8,
  128548. 7,
  128549. 9,
  128550. 6,
  128551. 10,
  128552. 5,
  128553. 11,
  128554. 4,
  128555. 12,
  128556. 3,
  128557. 13,
  128558. 2,
  128559. 14,
  128560. 1,
  128561. 15,
  128562. 0,
  128563. 16,
  128564. };
  128565. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128566. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128567. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128568. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128569. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128570. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128571. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128572. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128573. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128574. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128575. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128576. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128577. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128578. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128579. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128580. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128581. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128582. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128583. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128584. 14,
  128585. };
  128586. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128587. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128588. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128589. };
  128590. static long _vq_quantmap__44c2_s_p6_0[] = {
  128591. 15, 13, 11, 9, 7, 5, 3, 1,
  128592. 0, 2, 4, 6, 8, 10, 12, 14,
  128593. 16,
  128594. };
  128595. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128596. _vq_quantthresh__44c2_s_p6_0,
  128597. _vq_quantmap__44c2_s_p6_0,
  128598. 17,
  128599. 17
  128600. };
  128601. static static_codebook _44c2_s_p6_0 = {
  128602. 2, 289,
  128603. _vq_lengthlist__44c2_s_p6_0,
  128604. 1, -529530880, 1611661312, 5, 0,
  128605. _vq_quantlist__44c2_s_p6_0,
  128606. NULL,
  128607. &_vq_auxt__44c2_s_p6_0,
  128608. NULL,
  128609. 0
  128610. };
  128611. static long _vq_quantlist__44c2_s_p7_0[] = {
  128612. 1,
  128613. 0,
  128614. 2,
  128615. };
  128616. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128617. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128618. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128619. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128620. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128621. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128622. 11,
  128623. };
  128624. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128625. -5.5, 5.5,
  128626. };
  128627. static long _vq_quantmap__44c2_s_p7_0[] = {
  128628. 1, 0, 2,
  128629. };
  128630. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128631. _vq_quantthresh__44c2_s_p7_0,
  128632. _vq_quantmap__44c2_s_p7_0,
  128633. 3,
  128634. 3
  128635. };
  128636. static static_codebook _44c2_s_p7_0 = {
  128637. 4, 81,
  128638. _vq_lengthlist__44c2_s_p7_0,
  128639. 1, -529137664, 1618345984, 2, 0,
  128640. _vq_quantlist__44c2_s_p7_0,
  128641. NULL,
  128642. &_vq_auxt__44c2_s_p7_0,
  128643. NULL,
  128644. 0
  128645. };
  128646. static long _vq_quantlist__44c2_s_p7_1[] = {
  128647. 5,
  128648. 4,
  128649. 6,
  128650. 3,
  128651. 7,
  128652. 2,
  128653. 8,
  128654. 1,
  128655. 9,
  128656. 0,
  128657. 10,
  128658. };
  128659. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128660. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128661. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128662. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128663. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128664. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128665. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128666. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128667. 10,10,10, 8, 8, 8, 8, 8, 8,
  128668. };
  128669. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128670. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128671. 3.5, 4.5,
  128672. };
  128673. static long _vq_quantmap__44c2_s_p7_1[] = {
  128674. 9, 7, 5, 3, 1, 0, 2, 4,
  128675. 6, 8, 10,
  128676. };
  128677. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128678. _vq_quantthresh__44c2_s_p7_1,
  128679. _vq_quantmap__44c2_s_p7_1,
  128680. 11,
  128681. 11
  128682. };
  128683. static static_codebook _44c2_s_p7_1 = {
  128684. 2, 121,
  128685. _vq_lengthlist__44c2_s_p7_1,
  128686. 1, -531365888, 1611661312, 4, 0,
  128687. _vq_quantlist__44c2_s_p7_1,
  128688. NULL,
  128689. &_vq_auxt__44c2_s_p7_1,
  128690. NULL,
  128691. 0
  128692. };
  128693. static long _vq_quantlist__44c2_s_p8_0[] = {
  128694. 6,
  128695. 5,
  128696. 7,
  128697. 4,
  128698. 8,
  128699. 3,
  128700. 9,
  128701. 2,
  128702. 10,
  128703. 1,
  128704. 11,
  128705. 0,
  128706. 12,
  128707. };
  128708. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128709. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128710. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128711. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128712. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128713. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128714. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128715. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128716. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128717. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128718. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128719. 0,12,12,12,12,13,12,14,14,
  128720. };
  128721. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128722. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128723. 12.5, 17.5, 22.5, 27.5,
  128724. };
  128725. static long _vq_quantmap__44c2_s_p8_0[] = {
  128726. 11, 9, 7, 5, 3, 1, 0, 2,
  128727. 4, 6, 8, 10, 12,
  128728. };
  128729. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128730. _vq_quantthresh__44c2_s_p8_0,
  128731. _vq_quantmap__44c2_s_p8_0,
  128732. 13,
  128733. 13
  128734. };
  128735. static static_codebook _44c2_s_p8_0 = {
  128736. 2, 169,
  128737. _vq_lengthlist__44c2_s_p8_0,
  128738. 1, -526516224, 1616117760, 4, 0,
  128739. _vq_quantlist__44c2_s_p8_0,
  128740. NULL,
  128741. &_vq_auxt__44c2_s_p8_0,
  128742. NULL,
  128743. 0
  128744. };
  128745. static long _vq_quantlist__44c2_s_p8_1[] = {
  128746. 2,
  128747. 1,
  128748. 3,
  128749. 0,
  128750. 4,
  128751. };
  128752. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128753. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128754. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128755. };
  128756. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128757. -1.5, -0.5, 0.5, 1.5,
  128758. };
  128759. static long _vq_quantmap__44c2_s_p8_1[] = {
  128760. 3, 1, 0, 2, 4,
  128761. };
  128762. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128763. _vq_quantthresh__44c2_s_p8_1,
  128764. _vq_quantmap__44c2_s_p8_1,
  128765. 5,
  128766. 5
  128767. };
  128768. static static_codebook _44c2_s_p8_1 = {
  128769. 2, 25,
  128770. _vq_lengthlist__44c2_s_p8_1,
  128771. 1, -533725184, 1611661312, 3, 0,
  128772. _vq_quantlist__44c2_s_p8_1,
  128773. NULL,
  128774. &_vq_auxt__44c2_s_p8_1,
  128775. NULL,
  128776. 0
  128777. };
  128778. static long _vq_quantlist__44c2_s_p9_0[] = {
  128779. 6,
  128780. 5,
  128781. 7,
  128782. 4,
  128783. 8,
  128784. 3,
  128785. 9,
  128786. 2,
  128787. 10,
  128788. 1,
  128789. 11,
  128790. 0,
  128791. 12,
  128792. };
  128793. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128794. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128795. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128796. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128797. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128798. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128799. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128800. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128801. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128802. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128803. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128804. 11,11,11,11,11,11,11,11,11,
  128805. };
  128806. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128807. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128808. 552.5, 773.5, 994.5, 1215.5,
  128809. };
  128810. static long _vq_quantmap__44c2_s_p9_0[] = {
  128811. 11, 9, 7, 5, 3, 1, 0, 2,
  128812. 4, 6, 8, 10, 12,
  128813. };
  128814. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128815. _vq_quantthresh__44c2_s_p9_0,
  128816. _vq_quantmap__44c2_s_p9_0,
  128817. 13,
  128818. 13
  128819. };
  128820. static static_codebook _44c2_s_p9_0 = {
  128821. 2, 169,
  128822. _vq_lengthlist__44c2_s_p9_0,
  128823. 1, -514541568, 1627103232, 4, 0,
  128824. _vq_quantlist__44c2_s_p9_0,
  128825. NULL,
  128826. &_vq_auxt__44c2_s_p9_0,
  128827. NULL,
  128828. 0
  128829. };
  128830. static long _vq_quantlist__44c2_s_p9_1[] = {
  128831. 6,
  128832. 5,
  128833. 7,
  128834. 4,
  128835. 8,
  128836. 3,
  128837. 9,
  128838. 2,
  128839. 10,
  128840. 1,
  128841. 11,
  128842. 0,
  128843. 12,
  128844. };
  128845. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128846. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128847. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128848. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128849. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128850. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128851. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128852. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128853. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128854. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128855. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128856. 17,13,12,12,10,13,11,14,14,
  128857. };
  128858. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128859. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128860. 42.5, 59.5, 76.5, 93.5,
  128861. };
  128862. static long _vq_quantmap__44c2_s_p9_1[] = {
  128863. 11, 9, 7, 5, 3, 1, 0, 2,
  128864. 4, 6, 8, 10, 12,
  128865. };
  128866. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128867. _vq_quantthresh__44c2_s_p9_1,
  128868. _vq_quantmap__44c2_s_p9_1,
  128869. 13,
  128870. 13
  128871. };
  128872. static static_codebook _44c2_s_p9_1 = {
  128873. 2, 169,
  128874. _vq_lengthlist__44c2_s_p9_1,
  128875. 1, -522616832, 1620115456, 4, 0,
  128876. _vq_quantlist__44c2_s_p9_1,
  128877. NULL,
  128878. &_vq_auxt__44c2_s_p9_1,
  128879. NULL,
  128880. 0
  128881. };
  128882. static long _vq_quantlist__44c2_s_p9_2[] = {
  128883. 8,
  128884. 7,
  128885. 9,
  128886. 6,
  128887. 10,
  128888. 5,
  128889. 11,
  128890. 4,
  128891. 12,
  128892. 3,
  128893. 13,
  128894. 2,
  128895. 14,
  128896. 1,
  128897. 15,
  128898. 0,
  128899. 16,
  128900. };
  128901. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128902. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128903. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128904. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128905. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128906. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128907. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128908. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128909. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128910. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128911. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128912. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128913. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128914. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128915. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128916. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128917. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128918. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128919. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128920. 10,
  128921. };
  128922. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128923. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128924. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128925. };
  128926. static long _vq_quantmap__44c2_s_p9_2[] = {
  128927. 15, 13, 11, 9, 7, 5, 3, 1,
  128928. 0, 2, 4, 6, 8, 10, 12, 14,
  128929. 16,
  128930. };
  128931. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128932. _vq_quantthresh__44c2_s_p9_2,
  128933. _vq_quantmap__44c2_s_p9_2,
  128934. 17,
  128935. 17
  128936. };
  128937. static static_codebook _44c2_s_p9_2 = {
  128938. 2, 289,
  128939. _vq_lengthlist__44c2_s_p9_2,
  128940. 1, -529530880, 1611661312, 5, 0,
  128941. _vq_quantlist__44c2_s_p9_2,
  128942. NULL,
  128943. &_vq_auxt__44c2_s_p9_2,
  128944. NULL,
  128945. 0
  128946. };
  128947. static long _huff_lengthlist__44c2_s_short[] = {
  128948. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128949. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128950. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128951. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128952. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128953. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128954. 6, 8, 9,12,
  128955. };
  128956. static static_codebook _huff_book__44c2_s_short = {
  128957. 2, 100,
  128958. _huff_lengthlist__44c2_s_short,
  128959. 0, 0, 0, 0, 0,
  128960. NULL,
  128961. NULL,
  128962. NULL,
  128963. NULL,
  128964. 0
  128965. };
  128966. static long _huff_lengthlist__44c3_s_long[] = {
  128967. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128968. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128969. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128970. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128971. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128972. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128973. 9, 8, 8, 8,
  128974. };
  128975. static static_codebook _huff_book__44c3_s_long = {
  128976. 2, 100,
  128977. _huff_lengthlist__44c3_s_long,
  128978. 0, 0, 0, 0, 0,
  128979. NULL,
  128980. NULL,
  128981. NULL,
  128982. NULL,
  128983. 0
  128984. };
  128985. static long _vq_quantlist__44c3_s_p1_0[] = {
  128986. 1,
  128987. 0,
  128988. 2,
  128989. };
  128990. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128991. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128992. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128996. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128997. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129001. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129002. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129037. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129042. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129047. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129083. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129087. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129088. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129092. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129093. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  129094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129401. 0,
  129402. };
  129403. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129404. -0.5, 0.5,
  129405. };
  129406. static long _vq_quantmap__44c3_s_p1_0[] = {
  129407. 1, 0, 2,
  129408. };
  129409. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129410. _vq_quantthresh__44c3_s_p1_0,
  129411. _vq_quantmap__44c3_s_p1_0,
  129412. 3,
  129413. 3
  129414. };
  129415. static static_codebook _44c3_s_p1_0 = {
  129416. 8, 6561,
  129417. _vq_lengthlist__44c3_s_p1_0,
  129418. 1, -535822336, 1611661312, 2, 0,
  129419. _vq_quantlist__44c3_s_p1_0,
  129420. NULL,
  129421. &_vq_auxt__44c3_s_p1_0,
  129422. NULL,
  129423. 0
  129424. };
  129425. static long _vq_quantlist__44c3_s_p2_0[] = {
  129426. 2,
  129427. 1,
  129428. 3,
  129429. 0,
  129430. 4,
  129431. };
  129432. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129433. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129434. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129435. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129436. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129437. 0, 0,10,10, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129443. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129444. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129445. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129450. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129451. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129452. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129458. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129459. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129460. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129472. 0,
  129473. };
  129474. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129475. -1.5, -0.5, 0.5, 1.5,
  129476. };
  129477. static long _vq_quantmap__44c3_s_p2_0[] = {
  129478. 3, 1, 0, 2, 4,
  129479. };
  129480. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129481. _vq_quantthresh__44c3_s_p2_0,
  129482. _vq_quantmap__44c3_s_p2_0,
  129483. 5,
  129484. 5
  129485. };
  129486. static static_codebook _44c3_s_p2_0 = {
  129487. 4, 625,
  129488. _vq_lengthlist__44c3_s_p2_0,
  129489. 1, -533725184, 1611661312, 3, 0,
  129490. _vq_quantlist__44c3_s_p2_0,
  129491. NULL,
  129492. &_vq_auxt__44c3_s_p2_0,
  129493. NULL,
  129494. 0
  129495. };
  129496. static long _vq_quantlist__44c3_s_p3_0[] = {
  129497. 2,
  129498. 1,
  129499. 3,
  129500. 0,
  129501. 4,
  129502. };
  129503. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129504. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129507. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129510. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129543. 0,
  129544. };
  129545. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129546. -1.5, -0.5, 0.5, 1.5,
  129547. };
  129548. static long _vq_quantmap__44c3_s_p3_0[] = {
  129549. 3, 1, 0, 2, 4,
  129550. };
  129551. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129552. _vq_quantthresh__44c3_s_p3_0,
  129553. _vq_quantmap__44c3_s_p3_0,
  129554. 5,
  129555. 5
  129556. };
  129557. static static_codebook _44c3_s_p3_0 = {
  129558. 4, 625,
  129559. _vq_lengthlist__44c3_s_p3_0,
  129560. 1, -533725184, 1611661312, 3, 0,
  129561. _vq_quantlist__44c3_s_p3_0,
  129562. NULL,
  129563. &_vq_auxt__44c3_s_p3_0,
  129564. NULL,
  129565. 0
  129566. };
  129567. static long _vq_quantlist__44c3_s_p4_0[] = {
  129568. 4,
  129569. 3,
  129570. 5,
  129571. 2,
  129572. 6,
  129573. 1,
  129574. 7,
  129575. 0,
  129576. 8,
  129577. };
  129578. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129579. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129580. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129581. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129582. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129583. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129584. 0,
  129585. };
  129586. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129587. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129588. };
  129589. static long _vq_quantmap__44c3_s_p4_0[] = {
  129590. 7, 5, 3, 1, 0, 2, 4, 6,
  129591. 8,
  129592. };
  129593. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129594. _vq_quantthresh__44c3_s_p4_0,
  129595. _vq_quantmap__44c3_s_p4_0,
  129596. 9,
  129597. 9
  129598. };
  129599. static static_codebook _44c3_s_p4_0 = {
  129600. 2, 81,
  129601. _vq_lengthlist__44c3_s_p4_0,
  129602. 1, -531628032, 1611661312, 4, 0,
  129603. _vq_quantlist__44c3_s_p4_0,
  129604. NULL,
  129605. &_vq_auxt__44c3_s_p4_0,
  129606. NULL,
  129607. 0
  129608. };
  129609. static long _vq_quantlist__44c3_s_p5_0[] = {
  129610. 4,
  129611. 3,
  129612. 5,
  129613. 2,
  129614. 6,
  129615. 1,
  129616. 7,
  129617. 0,
  129618. 8,
  129619. };
  129620. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129621. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129622. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129623. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129624. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129625. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129626. 11,
  129627. };
  129628. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129629. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129630. };
  129631. static long _vq_quantmap__44c3_s_p5_0[] = {
  129632. 7, 5, 3, 1, 0, 2, 4, 6,
  129633. 8,
  129634. };
  129635. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129636. _vq_quantthresh__44c3_s_p5_0,
  129637. _vq_quantmap__44c3_s_p5_0,
  129638. 9,
  129639. 9
  129640. };
  129641. static static_codebook _44c3_s_p5_0 = {
  129642. 2, 81,
  129643. _vq_lengthlist__44c3_s_p5_0,
  129644. 1, -531628032, 1611661312, 4, 0,
  129645. _vq_quantlist__44c3_s_p5_0,
  129646. NULL,
  129647. &_vq_auxt__44c3_s_p5_0,
  129648. NULL,
  129649. 0
  129650. };
  129651. static long _vq_quantlist__44c3_s_p6_0[] = {
  129652. 8,
  129653. 7,
  129654. 9,
  129655. 6,
  129656. 10,
  129657. 5,
  129658. 11,
  129659. 4,
  129660. 12,
  129661. 3,
  129662. 13,
  129663. 2,
  129664. 14,
  129665. 1,
  129666. 15,
  129667. 0,
  129668. 16,
  129669. };
  129670. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129671. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129672. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129673. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129674. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129675. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129676. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129677. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129678. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129679. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129680. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129681. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129682. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129683. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129684. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129685. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129686. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129687. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129688. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129689. 13,
  129690. };
  129691. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129692. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129693. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129694. };
  129695. static long _vq_quantmap__44c3_s_p6_0[] = {
  129696. 15, 13, 11, 9, 7, 5, 3, 1,
  129697. 0, 2, 4, 6, 8, 10, 12, 14,
  129698. 16,
  129699. };
  129700. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129701. _vq_quantthresh__44c3_s_p6_0,
  129702. _vq_quantmap__44c3_s_p6_0,
  129703. 17,
  129704. 17
  129705. };
  129706. static static_codebook _44c3_s_p6_0 = {
  129707. 2, 289,
  129708. _vq_lengthlist__44c3_s_p6_0,
  129709. 1, -529530880, 1611661312, 5, 0,
  129710. _vq_quantlist__44c3_s_p6_0,
  129711. NULL,
  129712. &_vq_auxt__44c3_s_p6_0,
  129713. NULL,
  129714. 0
  129715. };
  129716. static long _vq_quantlist__44c3_s_p7_0[] = {
  129717. 1,
  129718. 0,
  129719. 2,
  129720. };
  129721. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129722. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129723. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129724. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129725. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129726. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129727. 10,
  129728. };
  129729. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129730. -5.5, 5.5,
  129731. };
  129732. static long _vq_quantmap__44c3_s_p7_0[] = {
  129733. 1, 0, 2,
  129734. };
  129735. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129736. _vq_quantthresh__44c3_s_p7_0,
  129737. _vq_quantmap__44c3_s_p7_0,
  129738. 3,
  129739. 3
  129740. };
  129741. static static_codebook _44c3_s_p7_0 = {
  129742. 4, 81,
  129743. _vq_lengthlist__44c3_s_p7_0,
  129744. 1, -529137664, 1618345984, 2, 0,
  129745. _vq_quantlist__44c3_s_p7_0,
  129746. NULL,
  129747. &_vq_auxt__44c3_s_p7_0,
  129748. NULL,
  129749. 0
  129750. };
  129751. static long _vq_quantlist__44c3_s_p7_1[] = {
  129752. 5,
  129753. 4,
  129754. 6,
  129755. 3,
  129756. 7,
  129757. 2,
  129758. 8,
  129759. 1,
  129760. 9,
  129761. 0,
  129762. 10,
  129763. };
  129764. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129765. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129766. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129767. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129768. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129769. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129770. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129771. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129772. 10,10,10, 8, 8, 8, 8, 8, 8,
  129773. };
  129774. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129775. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129776. 3.5, 4.5,
  129777. };
  129778. static long _vq_quantmap__44c3_s_p7_1[] = {
  129779. 9, 7, 5, 3, 1, 0, 2, 4,
  129780. 6, 8, 10,
  129781. };
  129782. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129783. _vq_quantthresh__44c3_s_p7_1,
  129784. _vq_quantmap__44c3_s_p7_1,
  129785. 11,
  129786. 11
  129787. };
  129788. static static_codebook _44c3_s_p7_1 = {
  129789. 2, 121,
  129790. _vq_lengthlist__44c3_s_p7_1,
  129791. 1, -531365888, 1611661312, 4, 0,
  129792. _vq_quantlist__44c3_s_p7_1,
  129793. NULL,
  129794. &_vq_auxt__44c3_s_p7_1,
  129795. NULL,
  129796. 0
  129797. };
  129798. static long _vq_quantlist__44c3_s_p8_0[] = {
  129799. 6,
  129800. 5,
  129801. 7,
  129802. 4,
  129803. 8,
  129804. 3,
  129805. 9,
  129806. 2,
  129807. 10,
  129808. 1,
  129809. 11,
  129810. 0,
  129811. 12,
  129812. };
  129813. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129814. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129815. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129816. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129817. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129818. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129819. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129820. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129821. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129822. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129823. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129824. 0,13,13,12,12,13,12,14,13,
  129825. };
  129826. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129827. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129828. 12.5, 17.5, 22.5, 27.5,
  129829. };
  129830. static long _vq_quantmap__44c3_s_p8_0[] = {
  129831. 11, 9, 7, 5, 3, 1, 0, 2,
  129832. 4, 6, 8, 10, 12,
  129833. };
  129834. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129835. _vq_quantthresh__44c3_s_p8_0,
  129836. _vq_quantmap__44c3_s_p8_0,
  129837. 13,
  129838. 13
  129839. };
  129840. static static_codebook _44c3_s_p8_0 = {
  129841. 2, 169,
  129842. _vq_lengthlist__44c3_s_p8_0,
  129843. 1, -526516224, 1616117760, 4, 0,
  129844. _vq_quantlist__44c3_s_p8_0,
  129845. NULL,
  129846. &_vq_auxt__44c3_s_p8_0,
  129847. NULL,
  129848. 0
  129849. };
  129850. static long _vq_quantlist__44c3_s_p8_1[] = {
  129851. 2,
  129852. 1,
  129853. 3,
  129854. 0,
  129855. 4,
  129856. };
  129857. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129858. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129859. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129860. };
  129861. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129862. -1.5, -0.5, 0.5, 1.5,
  129863. };
  129864. static long _vq_quantmap__44c3_s_p8_1[] = {
  129865. 3, 1, 0, 2, 4,
  129866. };
  129867. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129868. _vq_quantthresh__44c3_s_p8_1,
  129869. _vq_quantmap__44c3_s_p8_1,
  129870. 5,
  129871. 5
  129872. };
  129873. static static_codebook _44c3_s_p8_1 = {
  129874. 2, 25,
  129875. _vq_lengthlist__44c3_s_p8_1,
  129876. 1, -533725184, 1611661312, 3, 0,
  129877. _vq_quantlist__44c3_s_p8_1,
  129878. NULL,
  129879. &_vq_auxt__44c3_s_p8_1,
  129880. NULL,
  129881. 0
  129882. };
  129883. static long _vq_quantlist__44c3_s_p9_0[] = {
  129884. 6,
  129885. 5,
  129886. 7,
  129887. 4,
  129888. 8,
  129889. 3,
  129890. 9,
  129891. 2,
  129892. 10,
  129893. 1,
  129894. 11,
  129895. 0,
  129896. 12,
  129897. };
  129898. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129899. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129900. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129901. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129902. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129903. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129904. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129905. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129906. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129907. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129908. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129909. 11,11,11,11,11,11,11,11,11,
  129910. };
  129911. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129912. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129913. 637.5, 892.5, 1147.5, 1402.5,
  129914. };
  129915. static long _vq_quantmap__44c3_s_p9_0[] = {
  129916. 11, 9, 7, 5, 3, 1, 0, 2,
  129917. 4, 6, 8, 10, 12,
  129918. };
  129919. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129920. _vq_quantthresh__44c3_s_p9_0,
  129921. _vq_quantmap__44c3_s_p9_0,
  129922. 13,
  129923. 13
  129924. };
  129925. static static_codebook _44c3_s_p9_0 = {
  129926. 2, 169,
  129927. _vq_lengthlist__44c3_s_p9_0,
  129928. 1, -514332672, 1627381760, 4, 0,
  129929. _vq_quantlist__44c3_s_p9_0,
  129930. NULL,
  129931. &_vq_auxt__44c3_s_p9_0,
  129932. NULL,
  129933. 0
  129934. };
  129935. static long _vq_quantlist__44c3_s_p9_1[] = {
  129936. 7,
  129937. 6,
  129938. 8,
  129939. 5,
  129940. 9,
  129941. 4,
  129942. 10,
  129943. 3,
  129944. 11,
  129945. 2,
  129946. 12,
  129947. 1,
  129948. 13,
  129949. 0,
  129950. 14,
  129951. };
  129952. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129953. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129954. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129955. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129956. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129957. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129958. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129959. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129960. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129961. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129962. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129963. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129964. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129965. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129966. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129967. 15,
  129968. };
  129969. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129970. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129971. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129972. };
  129973. static long _vq_quantmap__44c3_s_p9_1[] = {
  129974. 13, 11, 9, 7, 5, 3, 1, 0,
  129975. 2, 4, 6, 8, 10, 12, 14,
  129976. };
  129977. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129978. _vq_quantthresh__44c3_s_p9_1,
  129979. _vq_quantmap__44c3_s_p9_1,
  129980. 15,
  129981. 15
  129982. };
  129983. static static_codebook _44c3_s_p9_1 = {
  129984. 2, 225,
  129985. _vq_lengthlist__44c3_s_p9_1,
  129986. 1, -522338304, 1620115456, 4, 0,
  129987. _vq_quantlist__44c3_s_p9_1,
  129988. NULL,
  129989. &_vq_auxt__44c3_s_p9_1,
  129990. NULL,
  129991. 0
  129992. };
  129993. static long _vq_quantlist__44c3_s_p9_2[] = {
  129994. 8,
  129995. 7,
  129996. 9,
  129997. 6,
  129998. 10,
  129999. 5,
  130000. 11,
  130001. 4,
  130002. 12,
  130003. 3,
  130004. 13,
  130005. 2,
  130006. 14,
  130007. 1,
  130008. 15,
  130009. 0,
  130010. 16,
  130011. };
  130012. static long _vq_lengthlist__44c3_s_p9_2[] = {
  130013. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  130014. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  130015. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  130016. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130017. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  130018. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  130019. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  130020. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  130021. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  130022. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  130023. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  130024. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  130025. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  130026. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  130027. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  130028. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  130029. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  130030. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  130031. 10,
  130032. };
  130033. static float _vq_quantthresh__44c3_s_p9_2[] = {
  130034. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130035. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130036. };
  130037. static long _vq_quantmap__44c3_s_p9_2[] = {
  130038. 15, 13, 11, 9, 7, 5, 3, 1,
  130039. 0, 2, 4, 6, 8, 10, 12, 14,
  130040. 16,
  130041. };
  130042. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  130043. _vq_quantthresh__44c3_s_p9_2,
  130044. _vq_quantmap__44c3_s_p9_2,
  130045. 17,
  130046. 17
  130047. };
  130048. static static_codebook _44c3_s_p9_2 = {
  130049. 2, 289,
  130050. _vq_lengthlist__44c3_s_p9_2,
  130051. 1, -529530880, 1611661312, 5, 0,
  130052. _vq_quantlist__44c3_s_p9_2,
  130053. NULL,
  130054. &_vq_auxt__44c3_s_p9_2,
  130055. NULL,
  130056. 0
  130057. };
  130058. static long _huff_lengthlist__44c3_s_short[] = {
  130059. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130060. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130061. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130062. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130063. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130064. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130065. 6, 8, 9,11,
  130066. };
  130067. static static_codebook _huff_book__44c3_s_short = {
  130068. 2, 100,
  130069. _huff_lengthlist__44c3_s_short,
  130070. 0, 0, 0, 0, 0,
  130071. NULL,
  130072. NULL,
  130073. NULL,
  130074. NULL,
  130075. 0
  130076. };
  130077. static long _huff_lengthlist__44c4_s_long[] = {
  130078. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130079. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130080. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130081. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130082. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130083. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130084. 9, 8, 7, 7,
  130085. };
  130086. static static_codebook _huff_book__44c4_s_long = {
  130087. 2, 100,
  130088. _huff_lengthlist__44c4_s_long,
  130089. 0, 0, 0, 0, 0,
  130090. NULL,
  130091. NULL,
  130092. NULL,
  130093. NULL,
  130094. 0
  130095. };
  130096. static long _vq_quantlist__44c4_s_p1_0[] = {
  130097. 1,
  130098. 0,
  130099. 2,
  130100. };
  130101. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130102. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130103. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130107. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130108. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130112. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130113. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130148. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130153. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  130158. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130194. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130198. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130199. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  130200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130203. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130204. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130512. 0,
  130513. };
  130514. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130515. -0.5, 0.5,
  130516. };
  130517. static long _vq_quantmap__44c4_s_p1_0[] = {
  130518. 1, 0, 2,
  130519. };
  130520. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130521. _vq_quantthresh__44c4_s_p1_0,
  130522. _vq_quantmap__44c4_s_p1_0,
  130523. 3,
  130524. 3
  130525. };
  130526. static static_codebook _44c4_s_p1_0 = {
  130527. 8, 6561,
  130528. _vq_lengthlist__44c4_s_p1_0,
  130529. 1, -535822336, 1611661312, 2, 0,
  130530. _vq_quantlist__44c4_s_p1_0,
  130531. NULL,
  130532. &_vq_auxt__44c4_s_p1_0,
  130533. NULL,
  130534. 0
  130535. };
  130536. static long _vq_quantlist__44c4_s_p2_0[] = {
  130537. 2,
  130538. 1,
  130539. 3,
  130540. 0,
  130541. 4,
  130542. };
  130543. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130544. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130545. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130546. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130547. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130548. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130554. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130555. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130556. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130561. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130562. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130563. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130569. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130570. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130571. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130583. 0,
  130584. };
  130585. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130586. -1.5, -0.5, 0.5, 1.5,
  130587. };
  130588. static long _vq_quantmap__44c4_s_p2_0[] = {
  130589. 3, 1, 0, 2, 4,
  130590. };
  130591. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130592. _vq_quantthresh__44c4_s_p2_0,
  130593. _vq_quantmap__44c4_s_p2_0,
  130594. 5,
  130595. 5
  130596. };
  130597. static static_codebook _44c4_s_p2_0 = {
  130598. 4, 625,
  130599. _vq_lengthlist__44c4_s_p2_0,
  130600. 1, -533725184, 1611661312, 3, 0,
  130601. _vq_quantlist__44c4_s_p2_0,
  130602. NULL,
  130603. &_vq_auxt__44c4_s_p2_0,
  130604. NULL,
  130605. 0
  130606. };
  130607. static long _vq_quantlist__44c4_s_p3_0[] = {
  130608. 2,
  130609. 1,
  130610. 3,
  130611. 0,
  130612. 4,
  130613. };
  130614. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130615. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130618. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130621. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130654. 0,
  130655. };
  130656. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130657. -1.5, -0.5, 0.5, 1.5,
  130658. };
  130659. static long _vq_quantmap__44c4_s_p3_0[] = {
  130660. 3, 1, 0, 2, 4,
  130661. };
  130662. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130663. _vq_quantthresh__44c4_s_p3_0,
  130664. _vq_quantmap__44c4_s_p3_0,
  130665. 5,
  130666. 5
  130667. };
  130668. static static_codebook _44c4_s_p3_0 = {
  130669. 4, 625,
  130670. _vq_lengthlist__44c4_s_p3_0,
  130671. 1, -533725184, 1611661312, 3, 0,
  130672. _vq_quantlist__44c4_s_p3_0,
  130673. NULL,
  130674. &_vq_auxt__44c4_s_p3_0,
  130675. NULL,
  130676. 0
  130677. };
  130678. static long _vq_quantlist__44c4_s_p4_0[] = {
  130679. 4,
  130680. 3,
  130681. 5,
  130682. 2,
  130683. 6,
  130684. 1,
  130685. 7,
  130686. 0,
  130687. 8,
  130688. };
  130689. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130690. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130691. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130692. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130693. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130694. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130695. 0,
  130696. };
  130697. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130698. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130699. };
  130700. static long _vq_quantmap__44c4_s_p4_0[] = {
  130701. 7, 5, 3, 1, 0, 2, 4, 6,
  130702. 8,
  130703. };
  130704. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130705. _vq_quantthresh__44c4_s_p4_0,
  130706. _vq_quantmap__44c4_s_p4_0,
  130707. 9,
  130708. 9
  130709. };
  130710. static static_codebook _44c4_s_p4_0 = {
  130711. 2, 81,
  130712. _vq_lengthlist__44c4_s_p4_0,
  130713. 1, -531628032, 1611661312, 4, 0,
  130714. _vq_quantlist__44c4_s_p4_0,
  130715. NULL,
  130716. &_vq_auxt__44c4_s_p4_0,
  130717. NULL,
  130718. 0
  130719. };
  130720. static long _vq_quantlist__44c4_s_p5_0[] = {
  130721. 4,
  130722. 3,
  130723. 5,
  130724. 2,
  130725. 6,
  130726. 1,
  130727. 7,
  130728. 0,
  130729. 8,
  130730. };
  130731. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130732. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130733. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130734. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130735. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130736. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130737. 10,
  130738. };
  130739. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130740. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130741. };
  130742. static long _vq_quantmap__44c4_s_p5_0[] = {
  130743. 7, 5, 3, 1, 0, 2, 4, 6,
  130744. 8,
  130745. };
  130746. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130747. _vq_quantthresh__44c4_s_p5_0,
  130748. _vq_quantmap__44c4_s_p5_0,
  130749. 9,
  130750. 9
  130751. };
  130752. static static_codebook _44c4_s_p5_0 = {
  130753. 2, 81,
  130754. _vq_lengthlist__44c4_s_p5_0,
  130755. 1, -531628032, 1611661312, 4, 0,
  130756. _vq_quantlist__44c4_s_p5_0,
  130757. NULL,
  130758. &_vq_auxt__44c4_s_p5_0,
  130759. NULL,
  130760. 0
  130761. };
  130762. static long _vq_quantlist__44c4_s_p6_0[] = {
  130763. 8,
  130764. 7,
  130765. 9,
  130766. 6,
  130767. 10,
  130768. 5,
  130769. 11,
  130770. 4,
  130771. 12,
  130772. 3,
  130773. 13,
  130774. 2,
  130775. 14,
  130776. 1,
  130777. 15,
  130778. 0,
  130779. 16,
  130780. };
  130781. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130782. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130783. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130784. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130785. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130786. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130787. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130788. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130789. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130790. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130791. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130792. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130793. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130794. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130795. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130796. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130797. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130798. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130799. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130800. 13,
  130801. };
  130802. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130803. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130804. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130805. };
  130806. static long _vq_quantmap__44c4_s_p6_0[] = {
  130807. 15, 13, 11, 9, 7, 5, 3, 1,
  130808. 0, 2, 4, 6, 8, 10, 12, 14,
  130809. 16,
  130810. };
  130811. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130812. _vq_quantthresh__44c4_s_p6_0,
  130813. _vq_quantmap__44c4_s_p6_0,
  130814. 17,
  130815. 17
  130816. };
  130817. static static_codebook _44c4_s_p6_0 = {
  130818. 2, 289,
  130819. _vq_lengthlist__44c4_s_p6_0,
  130820. 1, -529530880, 1611661312, 5, 0,
  130821. _vq_quantlist__44c4_s_p6_0,
  130822. NULL,
  130823. &_vq_auxt__44c4_s_p6_0,
  130824. NULL,
  130825. 0
  130826. };
  130827. static long _vq_quantlist__44c4_s_p7_0[] = {
  130828. 1,
  130829. 0,
  130830. 2,
  130831. };
  130832. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130833. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130834. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130835. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130836. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130837. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130838. 10,
  130839. };
  130840. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130841. -5.5, 5.5,
  130842. };
  130843. static long _vq_quantmap__44c4_s_p7_0[] = {
  130844. 1, 0, 2,
  130845. };
  130846. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130847. _vq_quantthresh__44c4_s_p7_0,
  130848. _vq_quantmap__44c4_s_p7_0,
  130849. 3,
  130850. 3
  130851. };
  130852. static static_codebook _44c4_s_p7_0 = {
  130853. 4, 81,
  130854. _vq_lengthlist__44c4_s_p7_0,
  130855. 1, -529137664, 1618345984, 2, 0,
  130856. _vq_quantlist__44c4_s_p7_0,
  130857. NULL,
  130858. &_vq_auxt__44c4_s_p7_0,
  130859. NULL,
  130860. 0
  130861. };
  130862. static long _vq_quantlist__44c4_s_p7_1[] = {
  130863. 5,
  130864. 4,
  130865. 6,
  130866. 3,
  130867. 7,
  130868. 2,
  130869. 8,
  130870. 1,
  130871. 9,
  130872. 0,
  130873. 10,
  130874. };
  130875. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130876. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130877. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130878. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130879. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130880. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130881. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130882. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130883. 10,10,10, 8, 8, 8, 8, 9, 9,
  130884. };
  130885. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130886. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130887. 3.5, 4.5,
  130888. };
  130889. static long _vq_quantmap__44c4_s_p7_1[] = {
  130890. 9, 7, 5, 3, 1, 0, 2, 4,
  130891. 6, 8, 10,
  130892. };
  130893. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130894. _vq_quantthresh__44c4_s_p7_1,
  130895. _vq_quantmap__44c4_s_p7_1,
  130896. 11,
  130897. 11
  130898. };
  130899. static static_codebook _44c4_s_p7_1 = {
  130900. 2, 121,
  130901. _vq_lengthlist__44c4_s_p7_1,
  130902. 1, -531365888, 1611661312, 4, 0,
  130903. _vq_quantlist__44c4_s_p7_1,
  130904. NULL,
  130905. &_vq_auxt__44c4_s_p7_1,
  130906. NULL,
  130907. 0
  130908. };
  130909. static long _vq_quantlist__44c4_s_p8_0[] = {
  130910. 6,
  130911. 5,
  130912. 7,
  130913. 4,
  130914. 8,
  130915. 3,
  130916. 9,
  130917. 2,
  130918. 10,
  130919. 1,
  130920. 11,
  130921. 0,
  130922. 12,
  130923. };
  130924. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130925. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130926. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130927. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130928. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130929. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130930. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130931. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130932. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130933. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130934. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130935. 0,13,12,12,12,12,12,13,13,
  130936. };
  130937. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130938. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130939. 12.5, 17.5, 22.5, 27.5,
  130940. };
  130941. static long _vq_quantmap__44c4_s_p8_0[] = {
  130942. 11, 9, 7, 5, 3, 1, 0, 2,
  130943. 4, 6, 8, 10, 12,
  130944. };
  130945. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130946. _vq_quantthresh__44c4_s_p8_0,
  130947. _vq_quantmap__44c4_s_p8_0,
  130948. 13,
  130949. 13
  130950. };
  130951. static static_codebook _44c4_s_p8_0 = {
  130952. 2, 169,
  130953. _vq_lengthlist__44c4_s_p8_0,
  130954. 1, -526516224, 1616117760, 4, 0,
  130955. _vq_quantlist__44c4_s_p8_0,
  130956. NULL,
  130957. &_vq_auxt__44c4_s_p8_0,
  130958. NULL,
  130959. 0
  130960. };
  130961. static long _vq_quantlist__44c4_s_p8_1[] = {
  130962. 2,
  130963. 1,
  130964. 3,
  130965. 0,
  130966. 4,
  130967. };
  130968. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130969. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130970. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130971. };
  130972. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130973. -1.5, -0.5, 0.5, 1.5,
  130974. };
  130975. static long _vq_quantmap__44c4_s_p8_1[] = {
  130976. 3, 1, 0, 2, 4,
  130977. };
  130978. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130979. _vq_quantthresh__44c4_s_p8_1,
  130980. _vq_quantmap__44c4_s_p8_1,
  130981. 5,
  130982. 5
  130983. };
  130984. static static_codebook _44c4_s_p8_1 = {
  130985. 2, 25,
  130986. _vq_lengthlist__44c4_s_p8_1,
  130987. 1, -533725184, 1611661312, 3, 0,
  130988. _vq_quantlist__44c4_s_p8_1,
  130989. NULL,
  130990. &_vq_auxt__44c4_s_p8_1,
  130991. NULL,
  130992. 0
  130993. };
  130994. static long _vq_quantlist__44c4_s_p9_0[] = {
  130995. 6,
  130996. 5,
  130997. 7,
  130998. 4,
  130999. 8,
  131000. 3,
  131001. 9,
  131002. 2,
  131003. 10,
  131004. 1,
  131005. 11,
  131006. 0,
  131007. 12,
  131008. };
  131009. static long _vq_lengthlist__44c4_s_p9_0[] = {
  131010. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  131011. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  131012. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131013. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131014. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131015. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131016. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131017. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131018. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131019. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131020. 12,12,12,12,12,12,12,12,12,
  131021. };
  131022. static float _vq_quantthresh__44c4_s_p9_0[] = {
  131023. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  131024. 787.5, 1102.5, 1417.5, 1732.5,
  131025. };
  131026. static long _vq_quantmap__44c4_s_p9_0[] = {
  131027. 11, 9, 7, 5, 3, 1, 0, 2,
  131028. 4, 6, 8, 10, 12,
  131029. };
  131030. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  131031. _vq_quantthresh__44c4_s_p9_0,
  131032. _vq_quantmap__44c4_s_p9_0,
  131033. 13,
  131034. 13
  131035. };
  131036. static static_codebook _44c4_s_p9_0 = {
  131037. 2, 169,
  131038. _vq_lengthlist__44c4_s_p9_0,
  131039. 1, -513964032, 1628680192, 4, 0,
  131040. _vq_quantlist__44c4_s_p9_0,
  131041. NULL,
  131042. &_vq_auxt__44c4_s_p9_0,
  131043. NULL,
  131044. 0
  131045. };
  131046. static long _vq_quantlist__44c4_s_p9_1[] = {
  131047. 7,
  131048. 6,
  131049. 8,
  131050. 5,
  131051. 9,
  131052. 4,
  131053. 10,
  131054. 3,
  131055. 11,
  131056. 2,
  131057. 12,
  131058. 1,
  131059. 13,
  131060. 0,
  131061. 14,
  131062. };
  131063. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131064. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131065. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131066. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131067. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131068. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131069. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131070. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131071. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131072. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131073. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131074. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131075. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131076. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131077. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131078. 15,
  131079. };
  131080. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131081. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131082. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131083. };
  131084. static long _vq_quantmap__44c4_s_p9_1[] = {
  131085. 13, 11, 9, 7, 5, 3, 1, 0,
  131086. 2, 4, 6, 8, 10, 12, 14,
  131087. };
  131088. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131089. _vq_quantthresh__44c4_s_p9_1,
  131090. _vq_quantmap__44c4_s_p9_1,
  131091. 15,
  131092. 15
  131093. };
  131094. static static_codebook _44c4_s_p9_1 = {
  131095. 2, 225,
  131096. _vq_lengthlist__44c4_s_p9_1,
  131097. 1, -520986624, 1620377600, 4, 0,
  131098. _vq_quantlist__44c4_s_p9_1,
  131099. NULL,
  131100. &_vq_auxt__44c4_s_p9_1,
  131101. NULL,
  131102. 0
  131103. };
  131104. static long _vq_quantlist__44c4_s_p9_2[] = {
  131105. 10,
  131106. 9,
  131107. 11,
  131108. 8,
  131109. 12,
  131110. 7,
  131111. 13,
  131112. 6,
  131113. 14,
  131114. 5,
  131115. 15,
  131116. 4,
  131117. 16,
  131118. 3,
  131119. 17,
  131120. 2,
  131121. 18,
  131122. 1,
  131123. 19,
  131124. 0,
  131125. 20,
  131126. };
  131127. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131128. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131129. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131130. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131131. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131132. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131133. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131134. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131135. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131136. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131137. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131138. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131139. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131140. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131141. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131142. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131143. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131144. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131145. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131146. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131147. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131148. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131149. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131150. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131151. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131152. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131153. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131154. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131155. 10,10,10,10,10,10,10,10,10,
  131156. };
  131157. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131158. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131159. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131160. 6.5, 7.5, 8.5, 9.5,
  131161. };
  131162. static long _vq_quantmap__44c4_s_p9_2[] = {
  131163. 19, 17, 15, 13, 11, 9, 7, 5,
  131164. 3, 1, 0, 2, 4, 6, 8, 10,
  131165. 12, 14, 16, 18, 20,
  131166. };
  131167. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131168. _vq_quantthresh__44c4_s_p9_2,
  131169. _vq_quantmap__44c4_s_p9_2,
  131170. 21,
  131171. 21
  131172. };
  131173. static static_codebook _44c4_s_p9_2 = {
  131174. 2, 441,
  131175. _vq_lengthlist__44c4_s_p9_2,
  131176. 1, -529268736, 1611661312, 5, 0,
  131177. _vq_quantlist__44c4_s_p9_2,
  131178. NULL,
  131179. &_vq_auxt__44c4_s_p9_2,
  131180. NULL,
  131181. 0
  131182. };
  131183. static long _huff_lengthlist__44c4_s_short[] = {
  131184. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131185. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131186. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131187. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131188. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131189. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131190. 7, 9,12,17,
  131191. };
  131192. static static_codebook _huff_book__44c4_s_short = {
  131193. 2, 100,
  131194. _huff_lengthlist__44c4_s_short,
  131195. 0, 0, 0, 0, 0,
  131196. NULL,
  131197. NULL,
  131198. NULL,
  131199. NULL,
  131200. 0
  131201. };
  131202. static long _huff_lengthlist__44c5_s_long[] = {
  131203. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131204. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131205. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131206. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131207. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131208. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131209. 9, 8, 7, 7,
  131210. };
  131211. static static_codebook _huff_book__44c5_s_long = {
  131212. 2, 100,
  131213. _huff_lengthlist__44c5_s_long,
  131214. 0, 0, 0, 0, 0,
  131215. NULL,
  131216. NULL,
  131217. NULL,
  131218. NULL,
  131219. 0
  131220. };
  131221. static long _vq_quantlist__44c5_s_p1_0[] = {
  131222. 1,
  131223. 0,
  131224. 2,
  131225. };
  131226. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131227. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131228. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131232. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131233. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131237. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131238. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131273. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131278. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131283. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131319. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131323. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131324. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131328. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131329. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131637. 0,
  131638. };
  131639. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131640. -0.5, 0.5,
  131641. };
  131642. static long _vq_quantmap__44c5_s_p1_0[] = {
  131643. 1, 0, 2,
  131644. };
  131645. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131646. _vq_quantthresh__44c5_s_p1_0,
  131647. _vq_quantmap__44c5_s_p1_0,
  131648. 3,
  131649. 3
  131650. };
  131651. static static_codebook _44c5_s_p1_0 = {
  131652. 8, 6561,
  131653. _vq_lengthlist__44c5_s_p1_0,
  131654. 1, -535822336, 1611661312, 2, 0,
  131655. _vq_quantlist__44c5_s_p1_0,
  131656. NULL,
  131657. &_vq_auxt__44c5_s_p1_0,
  131658. NULL,
  131659. 0
  131660. };
  131661. static long _vq_quantlist__44c5_s_p2_0[] = {
  131662. 2,
  131663. 1,
  131664. 3,
  131665. 0,
  131666. 4,
  131667. };
  131668. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131669. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131670. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131671. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131672. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131673. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131679. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131680. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131681. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131686. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131687. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131688. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131694. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131695. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131696. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131708. 0,
  131709. };
  131710. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131711. -1.5, -0.5, 0.5, 1.5,
  131712. };
  131713. static long _vq_quantmap__44c5_s_p2_0[] = {
  131714. 3, 1, 0, 2, 4,
  131715. };
  131716. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131717. _vq_quantthresh__44c5_s_p2_0,
  131718. _vq_quantmap__44c5_s_p2_0,
  131719. 5,
  131720. 5
  131721. };
  131722. static static_codebook _44c5_s_p2_0 = {
  131723. 4, 625,
  131724. _vq_lengthlist__44c5_s_p2_0,
  131725. 1, -533725184, 1611661312, 3, 0,
  131726. _vq_quantlist__44c5_s_p2_0,
  131727. NULL,
  131728. &_vq_auxt__44c5_s_p2_0,
  131729. NULL,
  131730. 0
  131731. };
  131732. static long _vq_quantlist__44c5_s_p3_0[] = {
  131733. 2,
  131734. 1,
  131735. 3,
  131736. 0,
  131737. 4,
  131738. };
  131739. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131740. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131743. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131746. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131779. 0,
  131780. };
  131781. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131782. -1.5, -0.5, 0.5, 1.5,
  131783. };
  131784. static long _vq_quantmap__44c5_s_p3_0[] = {
  131785. 3, 1, 0, 2, 4,
  131786. };
  131787. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131788. _vq_quantthresh__44c5_s_p3_0,
  131789. _vq_quantmap__44c5_s_p3_0,
  131790. 5,
  131791. 5
  131792. };
  131793. static static_codebook _44c5_s_p3_0 = {
  131794. 4, 625,
  131795. _vq_lengthlist__44c5_s_p3_0,
  131796. 1, -533725184, 1611661312, 3, 0,
  131797. _vq_quantlist__44c5_s_p3_0,
  131798. NULL,
  131799. &_vq_auxt__44c5_s_p3_0,
  131800. NULL,
  131801. 0
  131802. };
  131803. static long _vq_quantlist__44c5_s_p4_0[] = {
  131804. 4,
  131805. 3,
  131806. 5,
  131807. 2,
  131808. 6,
  131809. 1,
  131810. 7,
  131811. 0,
  131812. 8,
  131813. };
  131814. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131815. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131816. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131817. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131818. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131819. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131820. 0,
  131821. };
  131822. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131823. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131824. };
  131825. static long _vq_quantmap__44c5_s_p4_0[] = {
  131826. 7, 5, 3, 1, 0, 2, 4, 6,
  131827. 8,
  131828. };
  131829. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131830. _vq_quantthresh__44c5_s_p4_0,
  131831. _vq_quantmap__44c5_s_p4_0,
  131832. 9,
  131833. 9
  131834. };
  131835. static static_codebook _44c5_s_p4_0 = {
  131836. 2, 81,
  131837. _vq_lengthlist__44c5_s_p4_0,
  131838. 1, -531628032, 1611661312, 4, 0,
  131839. _vq_quantlist__44c5_s_p4_0,
  131840. NULL,
  131841. &_vq_auxt__44c5_s_p4_0,
  131842. NULL,
  131843. 0
  131844. };
  131845. static long _vq_quantlist__44c5_s_p5_0[] = {
  131846. 4,
  131847. 3,
  131848. 5,
  131849. 2,
  131850. 6,
  131851. 1,
  131852. 7,
  131853. 0,
  131854. 8,
  131855. };
  131856. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131857. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131858. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131859. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131860. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131861. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131862. 10,
  131863. };
  131864. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131865. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131866. };
  131867. static long _vq_quantmap__44c5_s_p5_0[] = {
  131868. 7, 5, 3, 1, 0, 2, 4, 6,
  131869. 8,
  131870. };
  131871. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131872. _vq_quantthresh__44c5_s_p5_0,
  131873. _vq_quantmap__44c5_s_p5_0,
  131874. 9,
  131875. 9
  131876. };
  131877. static static_codebook _44c5_s_p5_0 = {
  131878. 2, 81,
  131879. _vq_lengthlist__44c5_s_p5_0,
  131880. 1, -531628032, 1611661312, 4, 0,
  131881. _vq_quantlist__44c5_s_p5_0,
  131882. NULL,
  131883. &_vq_auxt__44c5_s_p5_0,
  131884. NULL,
  131885. 0
  131886. };
  131887. static long _vq_quantlist__44c5_s_p6_0[] = {
  131888. 8,
  131889. 7,
  131890. 9,
  131891. 6,
  131892. 10,
  131893. 5,
  131894. 11,
  131895. 4,
  131896. 12,
  131897. 3,
  131898. 13,
  131899. 2,
  131900. 14,
  131901. 1,
  131902. 15,
  131903. 0,
  131904. 16,
  131905. };
  131906. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131907. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131908. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131909. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131910. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131911. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131912. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131913. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131914. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131915. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131916. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131917. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131918. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131919. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131920. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131921. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131922. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131923. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131924. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131925. 13,
  131926. };
  131927. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131928. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131929. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131930. };
  131931. static long _vq_quantmap__44c5_s_p6_0[] = {
  131932. 15, 13, 11, 9, 7, 5, 3, 1,
  131933. 0, 2, 4, 6, 8, 10, 12, 14,
  131934. 16,
  131935. };
  131936. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131937. _vq_quantthresh__44c5_s_p6_0,
  131938. _vq_quantmap__44c5_s_p6_0,
  131939. 17,
  131940. 17
  131941. };
  131942. static static_codebook _44c5_s_p6_0 = {
  131943. 2, 289,
  131944. _vq_lengthlist__44c5_s_p6_0,
  131945. 1, -529530880, 1611661312, 5, 0,
  131946. _vq_quantlist__44c5_s_p6_0,
  131947. NULL,
  131948. &_vq_auxt__44c5_s_p6_0,
  131949. NULL,
  131950. 0
  131951. };
  131952. static long _vq_quantlist__44c5_s_p7_0[] = {
  131953. 1,
  131954. 0,
  131955. 2,
  131956. };
  131957. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131958. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131959. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131960. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131961. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131962. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131963. 10,
  131964. };
  131965. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131966. -5.5, 5.5,
  131967. };
  131968. static long _vq_quantmap__44c5_s_p7_0[] = {
  131969. 1, 0, 2,
  131970. };
  131971. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131972. _vq_quantthresh__44c5_s_p7_0,
  131973. _vq_quantmap__44c5_s_p7_0,
  131974. 3,
  131975. 3
  131976. };
  131977. static static_codebook _44c5_s_p7_0 = {
  131978. 4, 81,
  131979. _vq_lengthlist__44c5_s_p7_0,
  131980. 1, -529137664, 1618345984, 2, 0,
  131981. _vq_quantlist__44c5_s_p7_0,
  131982. NULL,
  131983. &_vq_auxt__44c5_s_p7_0,
  131984. NULL,
  131985. 0
  131986. };
  131987. static long _vq_quantlist__44c5_s_p7_1[] = {
  131988. 5,
  131989. 4,
  131990. 6,
  131991. 3,
  131992. 7,
  131993. 2,
  131994. 8,
  131995. 1,
  131996. 9,
  131997. 0,
  131998. 10,
  131999. };
  132000. static long _vq_lengthlist__44c5_s_p7_1[] = {
  132001. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  132002. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132003. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132004. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132005. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132006. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  132007. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132008. 10,10,10, 8, 8, 8, 8, 8, 8,
  132009. };
  132010. static float _vq_quantthresh__44c5_s_p7_1[] = {
  132011. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132012. 3.5, 4.5,
  132013. };
  132014. static long _vq_quantmap__44c5_s_p7_1[] = {
  132015. 9, 7, 5, 3, 1, 0, 2, 4,
  132016. 6, 8, 10,
  132017. };
  132018. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  132019. _vq_quantthresh__44c5_s_p7_1,
  132020. _vq_quantmap__44c5_s_p7_1,
  132021. 11,
  132022. 11
  132023. };
  132024. static static_codebook _44c5_s_p7_1 = {
  132025. 2, 121,
  132026. _vq_lengthlist__44c5_s_p7_1,
  132027. 1, -531365888, 1611661312, 4, 0,
  132028. _vq_quantlist__44c5_s_p7_1,
  132029. NULL,
  132030. &_vq_auxt__44c5_s_p7_1,
  132031. NULL,
  132032. 0
  132033. };
  132034. static long _vq_quantlist__44c5_s_p8_0[] = {
  132035. 6,
  132036. 5,
  132037. 7,
  132038. 4,
  132039. 8,
  132040. 3,
  132041. 9,
  132042. 2,
  132043. 10,
  132044. 1,
  132045. 11,
  132046. 0,
  132047. 12,
  132048. };
  132049. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132050. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132051. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132052. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132053. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132054. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132055. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132056. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132057. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132058. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132059. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132060. 0,12,12,12,12,12,12,13,13,
  132061. };
  132062. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132063. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132064. 12.5, 17.5, 22.5, 27.5,
  132065. };
  132066. static long _vq_quantmap__44c5_s_p8_0[] = {
  132067. 11, 9, 7, 5, 3, 1, 0, 2,
  132068. 4, 6, 8, 10, 12,
  132069. };
  132070. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132071. _vq_quantthresh__44c5_s_p8_0,
  132072. _vq_quantmap__44c5_s_p8_0,
  132073. 13,
  132074. 13
  132075. };
  132076. static static_codebook _44c5_s_p8_0 = {
  132077. 2, 169,
  132078. _vq_lengthlist__44c5_s_p8_0,
  132079. 1, -526516224, 1616117760, 4, 0,
  132080. _vq_quantlist__44c5_s_p8_0,
  132081. NULL,
  132082. &_vq_auxt__44c5_s_p8_0,
  132083. NULL,
  132084. 0
  132085. };
  132086. static long _vq_quantlist__44c5_s_p8_1[] = {
  132087. 2,
  132088. 1,
  132089. 3,
  132090. 0,
  132091. 4,
  132092. };
  132093. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132094. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132095. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132096. };
  132097. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132098. -1.5, -0.5, 0.5, 1.5,
  132099. };
  132100. static long _vq_quantmap__44c5_s_p8_1[] = {
  132101. 3, 1, 0, 2, 4,
  132102. };
  132103. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132104. _vq_quantthresh__44c5_s_p8_1,
  132105. _vq_quantmap__44c5_s_p8_1,
  132106. 5,
  132107. 5
  132108. };
  132109. static static_codebook _44c5_s_p8_1 = {
  132110. 2, 25,
  132111. _vq_lengthlist__44c5_s_p8_1,
  132112. 1, -533725184, 1611661312, 3, 0,
  132113. _vq_quantlist__44c5_s_p8_1,
  132114. NULL,
  132115. &_vq_auxt__44c5_s_p8_1,
  132116. NULL,
  132117. 0
  132118. };
  132119. static long _vq_quantlist__44c5_s_p9_0[] = {
  132120. 7,
  132121. 6,
  132122. 8,
  132123. 5,
  132124. 9,
  132125. 4,
  132126. 10,
  132127. 3,
  132128. 11,
  132129. 2,
  132130. 12,
  132131. 1,
  132132. 13,
  132133. 0,
  132134. 14,
  132135. };
  132136. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132137. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132138. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132139. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132140. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132141. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132142. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132143. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132144. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132145. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132146. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132147. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132148. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132149. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132150. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132151. 12,
  132152. };
  132153. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132154. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132155. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132156. };
  132157. static long _vq_quantmap__44c5_s_p9_0[] = {
  132158. 13, 11, 9, 7, 5, 3, 1, 0,
  132159. 2, 4, 6, 8, 10, 12, 14,
  132160. };
  132161. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132162. _vq_quantthresh__44c5_s_p9_0,
  132163. _vq_quantmap__44c5_s_p9_0,
  132164. 15,
  132165. 15
  132166. };
  132167. static static_codebook _44c5_s_p9_0 = {
  132168. 2, 225,
  132169. _vq_lengthlist__44c5_s_p9_0,
  132170. 1, -512522752, 1628852224, 4, 0,
  132171. _vq_quantlist__44c5_s_p9_0,
  132172. NULL,
  132173. &_vq_auxt__44c5_s_p9_0,
  132174. NULL,
  132175. 0
  132176. };
  132177. static long _vq_quantlist__44c5_s_p9_1[] = {
  132178. 8,
  132179. 7,
  132180. 9,
  132181. 6,
  132182. 10,
  132183. 5,
  132184. 11,
  132185. 4,
  132186. 12,
  132187. 3,
  132188. 13,
  132189. 2,
  132190. 14,
  132191. 1,
  132192. 15,
  132193. 0,
  132194. 16,
  132195. };
  132196. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132197. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132198. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132199. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132200. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132201. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132202. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132203. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132204. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132205. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132206. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132207. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132208. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132209. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132210. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132211. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132212. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132213. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132214. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132215. 15,
  132216. };
  132217. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132218. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132219. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132220. };
  132221. static long _vq_quantmap__44c5_s_p9_1[] = {
  132222. 15, 13, 11, 9, 7, 5, 3, 1,
  132223. 0, 2, 4, 6, 8, 10, 12, 14,
  132224. 16,
  132225. };
  132226. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132227. _vq_quantthresh__44c5_s_p9_1,
  132228. _vq_quantmap__44c5_s_p9_1,
  132229. 17,
  132230. 17
  132231. };
  132232. static static_codebook _44c5_s_p9_1 = {
  132233. 2, 289,
  132234. _vq_lengthlist__44c5_s_p9_1,
  132235. 1, -520814592, 1620377600, 5, 0,
  132236. _vq_quantlist__44c5_s_p9_1,
  132237. NULL,
  132238. &_vq_auxt__44c5_s_p9_1,
  132239. NULL,
  132240. 0
  132241. };
  132242. static long _vq_quantlist__44c5_s_p9_2[] = {
  132243. 10,
  132244. 9,
  132245. 11,
  132246. 8,
  132247. 12,
  132248. 7,
  132249. 13,
  132250. 6,
  132251. 14,
  132252. 5,
  132253. 15,
  132254. 4,
  132255. 16,
  132256. 3,
  132257. 17,
  132258. 2,
  132259. 18,
  132260. 1,
  132261. 19,
  132262. 0,
  132263. 20,
  132264. };
  132265. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132266. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132267. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132268. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132269. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132270. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132271. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132272. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132273. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132274. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132275. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132276. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132277. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132278. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132279. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132280. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132281. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132282. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132283. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132284. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132285. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132286. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132287. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132288. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132289. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132290. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132291. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132292. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132293. 10,10,10,10,10,10,10,10,10,
  132294. };
  132295. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132296. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132297. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132298. 6.5, 7.5, 8.5, 9.5,
  132299. };
  132300. static long _vq_quantmap__44c5_s_p9_2[] = {
  132301. 19, 17, 15, 13, 11, 9, 7, 5,
  132302. 3, 1, 0, 2, 4, 6, 8, 10,
  132303. 12, 14, 16, 18, 20,
  132304. };
  132305. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132306. _vq_quantthresh__44c5_s_p9_2,
  132307. _vq_quantmap__44c5_s_p9_2,
  132308. 21,
  132309. 21
  132310. };
  132311. static static_codebook _44c5_s_p9_2 = {
  132312. 2, 441,
  132313. _vq_lengthlist__44c5_s_p9_2,
  132314. 1, -529268736, 1611661312, 5, 0,
  132315. _vq_quantlist__44c5_s_p9_2,
  132316. NULL,
  132317. &_vq_auxt__44c5_s_p9_2,
  132318. NULL,
  132319. 0
  132320. };
  132321. static long _huff_lengthlist__44c5_s_short[] = {
  132322. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132323. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132324. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132325. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132326. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132327. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132328. 6, 8,11,16,
  132329. };
  132330. static static_codebook _huff_book__44c5_s_short = {
  132331. 2, 100,
  132332. _huff_lengthlist__44c5_s_short,
  132333. 0, 0, 0, 0, 0,
  132334. NULL,
  132335. NULL,
  132336. NULL,
  132337. NULL,
  132338. 0
  132339. };
  132340. static long _huff_lengthlist__44c6_s_long[] = {
  132341. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132342. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132343. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132344. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132345. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132346. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132347. 11,10,10,12,
  132348. };
  132349. static static_codebook _huff_book__44c6_s_long = {
  132350. 2, 100,
  132351. _huff_lengthlist__44c6_s_long,
  132352. 0, 0, 0, 0, 0,
  132353. NULL,
  132354. NULL,
  132355. NULL,
  132356. NULL,
  132357. 0
  132358. };
  132359. static long _vq_quantlist__44c6_s_p1_0[] = {
  132360. 1,
  132361. 0,
  132362. 2,
  132363. };
  132364. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132365. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132366. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132367. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132368. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132369. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132370. 8,
  132371. };
  132372. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132373. -0.5, 0.5,
  132374. };
  132375. static long _vq_quantmap__44c6_s_p1_0[] = {
  132376. 1, 0, 2,
  132377. };
  132378. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132379. _vq_quantthresh__44c6_s_p1_0,
  132380. _vq_quantmap__44c6_s_p1_0,
  132381. 3,
  132382. 3
  132383. };
  132384. static static_codebook _44c6_s_p1_0 = {
  132385. 4, 81,
  132386. _vq_lengthlist__44c6_s_p1_0,
  132387. 1, -535822336, 1611661312, 2, 0,
  132388. _vq_quantlist__44c6_s_p1_0,
  132389. NULL,
  132390. &_vq_auxt__44c6_s_p1_0,
  132391. NULL,
  132392. 0
  132393. };
  132394. static long _vq_quantlist__44c6_s_p2_0[] = {
  132395. 2,
  132396. 1,
  132397. 3,
  132398. 0,
  132399. 4,
  132400. };
  132401. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132402. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132403. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132404. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132405. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132406. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132407. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132408. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132409. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132411. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132412. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132413. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132414. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132415. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132416. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132417. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132419. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132420. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132421. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132422. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132423. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132424. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132425. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132427. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132428. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132429. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132430. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132431. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132432. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132433. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132438. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132439. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132440. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132441. 13,
  132442. };
  132443. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132444. -1.5, -0.5, 0.5, 1.5,
  132445. };
  132446. static long _vq_quantmap__44c6_s_p2_0[] = {
  132447. 3, 1, 0, 2, 4,
  132448. };
  132449. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132450. _vq_quantthresh__44c6_s_p2_0,
  132451. _vq_quantmap__44c6_s_p2_0,
  132452. 5,
  132453. 5
  132454. };
  132455. static static_codebook _44c6_s_p2_0 = {
  132456. 4, 625,
  132457. _vq_lengthlist__44c6_s_p2_0,
  132458. 1, -533725184, 1611661312, 3, 0,
  132459. _vq_quantlist__44c6_s_p2_0,
  132460. NULL,
  132461. &_vq_auxt__44c6_s_p2_0,
  132462. NULL,
  132463. 0
  132464. };
  132465. static long _vq_quantlist__44c6_s_p3_0[] = {
  132466. 4,
  132467. 3,
  132468. 5,
  132469. 2,
  132470. 6,
  132471. 1,
  132472. 7,
  132473. 0,
  132474. 8,
  132475. };
  132476. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132477. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132478. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132479. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132480. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132482. 0,
  132483. };
  132484. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132485. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132486. };
  132487. static long _vq_quantmap__44c6_s_p3_0[] = {
  132488. 7, 5, 3, 1, 0, 2, 4, 6,
  132489. 8,
  132490. };
  132491. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132492. _vq_quantthresh__44c6_s_p3_0,
  132493. _vq_quantmap__44c6_s_p3_0,
  132494. 9,
  132495. 9
  132496. };
  132497. static static_codebook _44c6_s_p3_0 = {
  132498. 2, 81,
  132499. _vq_lengthlist__44c6_s_p3_0,
  132500. 1, -531628032, 1611661312, 4, 0,
  132501. _vq_quantlist__44c6_s_p3_0,
  132502. NULL,
  132503. &_vq_auxt__44c6_s_p3_0,
  132504. NULL,
  132505. 0
  132506. };
  132507. static long _vq_quantlist__44c6_s_p4_0[] = {
  132508. 8,
  132509. 7,
  132510. 9,
  132511. 6,
  132512. 10,
  132513. 5,
  132514. 11,
  132515. 4,
  132516. 12,
  132517. 3,
  132518. 13,
  132519. 2,
  132520. 14,
  132521. 1,
  132522. 15,
  132523. 0,
  132524. 16,
  132525. };
  132526. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132527. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132528. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132529. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132530. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132531. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132532. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132533. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132534. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132535. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132536. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132545. 0,
  132546. };
  132547. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132548. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132549. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132550. };
  132551. static long _vq_quantmap__44c6_s_p4_0[] = {
  132552. 15, 13, 11, 9, 7, 5, 3, 1,
  132553. 0, 2, 4, 6, 8, 10, 12, 14,
  132554. 16,
  132555. };
  132556. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132557. _vq_quantthresh__44c6_s_p4_0,
  132558. _vq_quantmap__44c6_s_p4_0,
  132559. 17,
  132560. 17
  132561. };
  132562. static static_codebook _44c6_s_p4_0 = {
  132563. 2, 289,
  132564. _vq_lengthlist__44c6_s_p4_0,
  132565. 1, -529530880, 1611661312, 5, 0,
  132566. _vq_quantlist__44c6_s_p4_0,
  132567. NULL,
  132568. &_vq_auxt__44c6_s_p4_0,
  132569. NULL,
  132570. 0
  132571. };
  132572. static long _vq_quantlist__44c6_s_p5_0[] = {
  132573. 1,
  132574. 0,
  132575. 2,
  132576. };
  132577. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132578. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132579. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132580. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132581. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132582. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132583. 12,
  132584. };
  132585. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132586. -5.5, 5.5,
  132587. };
  132588. static long _vq_quantmap__44c6_s_p5_0[] = {
  132589. 1, 0, 2,
  132590. };
  132591. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132592. _vq_quantthresh__44c6_s_p5_0,
  132593. _vq_quantmap__44c6_s_p5_0,
  132594. 3,
  132595. 3
  132596. };
  132597. static static_codebook _44c6_s_p5_0 = {
  132598. 4, 81,
  132599. _vq_lengthlist__44c6_s_p5_0,
  132600. 1, -529137664, 1618345984, 2, 0,
  132601. _vq_quantlist__44c6_s_p5_0,
  132602. NULL,
  132603. &_vq_auxt__44c6_s_p5_0,
  132604. NULL,
  132605. 0
  132606. };
  132607. static long _vq_quantlist__44c6_s_p5_1[] = {
  132608. 5,
  132609. 4,
  132610. 6,
  132611. 3,
  132612. 7,
  132613. 2,
  132614. 8,
  132615. 1,
  132616. 9,
  132617. 0,
  132618. 10,
  132619. };
  132620. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132621. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132622. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132623. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132624. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132625. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132626. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132627. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132628. 11,10,10, 7, 7, 8, 8, 8, 8,
  132629. };
  132630. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132631. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132632. 3.5, 4.5,
  132633. };
  132634. static long _vq_quantmap__44c6_s_p5_1[] = {
  132635. 9, 7, 5, 3, 1, 0, 2, 4,
  132636. 6, 8, 10,
  132637. };
  132638. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132639. _vq_quantthresh__44c6_s_p5_1,
  132640. _vq_quantmap__44c6_s_p5_1,
  132641. 11,
  132642. 11
  132643. };
  132644. static static_codebook _44c6_s_p5_1 = {
  132645. 2, 121,
  132646. _vq_lengthlist__44c6_s_p5_1,
  132647. 1, -531365888, 1611661312, 4, 0,
  132648. _vq_quantlist__44c6_s_p5_1,
  132649. NULL,
  132650. &_vq_auxt__44c6_s_p5_1,
  132651. NULL,
  132652. 0
  132653. };
  132654. static long _vq_quantlist__44c6_s_p6_0[] = {
  132655. 6,
  132656. 5,
  132657. 7,
  132658. 4,
  132659. 8,
  132660. 3,
  132661. 9,
  132662. 2,
  132663. 10,
  132664. 1,
  132665. 11,
  132666. 0,
  132667. 12,
  132668. };
  132669. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132670. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132671. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132672. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132673. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132674. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132675. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132680. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132681. };
  132682. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132683. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132684. 12.5, 17.5, 22.5, 27.5,
  132685. };
  132686. static long _vq_quantmap__44c6_s_p6_0[] = {
  132687. 11, 9, 7, 5, 3, 1, 0, 2,
  132688. 4, 6, 8, 10, 12,
  132689. };
  132690. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132691. _vq_quantthresh__44c6_s_p6_0,
  132692. _vq_quantmap__44c6_s_p6_0,
  132693. 13,
  132694. 13
  132695. };
  132696. static static_codebook _44c6_s_p6_0 = {
  132697. 2, 169,
  132698. _vq_lengthlist__44c6_s_p6_0,
  132699. 1, -526516224, 1616117760, 4, 0,
  132700. _vq_quantlist__44c6_s_p6_0,
  132701. NULL,
  132702. &_vq_auxt__44c6_s_p6_0,
  132703. NULL,
  132704. 0
  132705. };
  132706. static long _vq_quantlist__44c6_s_p6_1[] = {
  132707. 2,
  132708. 1,
  132709. 3,
  132710. 0,
  132711. 4,
  132712. };
  132713. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132714. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132715. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132716. };
  132717. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132718. -1.5, -0.5, 0.5, 1.5,
  132719. };
  132720. static long _vq_quantmap__44c6_s_p6_1[] = {
  132721. 3, 1, 0, 2, 4,
  132722. };
  132723. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132724. _vq_quantthresh__44c6_s_p6_1,
  132725. _vq_quantmap__44c6_s_p6_1,
  132726. 5,
  132727. 5
  132728. };
  132729. static static_codebook _44c6_s_p6_1 = {
  132730. 2, 25,
  132731. _vq_lengthlist__44c6_s_p6_1,
  132732. 1, -533725184, 1611661312, 3, 0,
  132733. _vq_quantlist__44c6_s_p6_1,
  132734. NULL,
  132735. &_vq_auxt__44c6_s_p6_1,
  132736. NULL,
  132737. 0
  132738. };
  132739. static long _vq_quantlist__44c6_s_p7_0[] = {
  132740. 6,
  132741. 5,
  132742. 7,
  132743. 4,
  132744. 8,
  132745. 3,
  132746. 9,
  132747. 2,
  132748. 10,
  132749. 1,
  132750. 11,
  132751. 0,
  132752. 12,
  132753. };
  132754. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132755. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132756. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132757. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132758. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132759. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132760. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132761. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132762. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132763. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132764. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132765. 20,13,13,13,13,13,13,14,14,
  132766. };
  132767. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132768. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132769. 27.5, 38.5, 49.5, 60.5,
  132770. };
  132771. static long _vq_quantmap__44c6_s_p7_0[] = {
  132772. 11, 9, 7, 5, 3, 1, 0, 2,
  132773. 4, 6, 8, 10, 12,
  132774. };
  132775. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132776. _vq_quantthresh__44c6_s_p7_0,
  132777. _vq_quantmap__44c6_s_p7_0,
  132778. 13,
  132779. 13
  132780. };
  132781. static static_codebook _44c6_s_p7_0 = {
  132782. 2, 169,
  132783. _vq_lengthlist__44c6_s_p7_0,
  132784. 1, -523206656, 1618345984, 4, 0,
  132785. _vq_quantlist__44c6_s_p7_0,
  132786. NULL,
  132787. &_vq_auxt__44c6_s_p7_0,
  132788. NULL,
  132789. 0
  132790. };
  132791. static long _vq_quantlist__44c6_s_p7_1[] = {
  132792. 5,
  132793. 4,
  132794. 6,
  132795. 3,
  132796. 7,
  132797. 2,
  132798. 8,
  132799. 1,
  132800. 9,
  132801. 0,
  132802. 10,
  132803. };
  132804. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132805. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132806. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132807. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132808. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132809. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132810. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132811. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132812. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132813. };
  132814. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132815. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132816. 3.5, 4.5,
  132817. };
  132818. static long _vq_quantmap__44c6_s_p7_1[] = {
  132819. 9, 7, 5, 3, 1, 0, 2, 4,
  132820. 6, 8, 10,
  132821. };
  132822. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132823. _vq_quantthresh__44c6_s_p7_1,
  132824. _vq_quantmap__44c6_s_p7_1,
  132825. 11,
  132826. 11
  132827. };
  132828. static static_codebook _44c6_s_p7_1 = {
  132829. 2, 121,
  132830. _vq_lengthlist__44c6_s_p7_1,
  132831. 1, -531365888, 1611661312, 4, 0,
  132832. _vq_quantlist__44c6_s_p7_1,
  132833. NULL,
  132834. &_vq_auxt__44c6_s_p7_1,
  132835. NULL,
  132836. 0
  132837. };
  132838. static long _vq_quantlist__44c6_s_p8_0[] = {
  132839. 7,
  132840. 6,
  132841. 8,
  132842. 5,
  132843. 9,
  132844. 4,
  132845. 10,
  132846. 3,
  132847. 11,
  132848. 2,
  132849. 12,
  132850. 1,
  132851. 13,
  132852. 0,
  132853. 14,
  132854. };
  132855. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132856. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132857. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132858. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132859. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132860. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132861. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132862. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132863. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132864. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132865. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132866. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132867. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132868. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132869. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132870. 14,
  132871. };
  132872. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132873. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132874. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132875. };
  132876. static long _vq_quantmap__44c6_s_p8_0[] = {
  132877. 13, 11, 9, 7, 5, 3, 1, 0,
  132878. 2, 4, 6, 8, 10, 12, 14,
  132879. };
  132880. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132881. _vq_quantthresh__44c6_s_p8_0,
  132882. _vq_quantmap__44c6_s_p8_0,
  132883. 15,
  132884. 15
  132885. };
  132886. static static_codebook _44c6_s_p8_0 = {
  132887. 2, 225,
  132888. _vq_lengthlist__44c6_s_p8_0,
  132889. 1, -520986624, 1620377600, 4, 0,
  132890. _vq_quantlist__44c6_s_p8_0,
  132891. NULL,
  132892. &_vq_auxt__44c6_s_p8_0,
  132893. NULL,
  132894. 0
  132895. };
  132896. static long _vq_quantlist__44c6_s_p8_1[] = {
  132897. 10,
  132898. 9,
  132899. 11,
  132900. 8,
  132901. 12,
  132902. 7,
  132903. 13,
  132904. 6,
  132905. 14,
  132906. 5,
  132907. 15,
  132908. 4,
  132909. 16,
  132910. 3,
  132911. 17,
  132912. 2,
  132913. 18,
  132914. 1,
  132915. 19,
  132916. 0,
  132917. 20,
  132918. };
  132919. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132920. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132921. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132922. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132923. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132924. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132925. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132926. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132927. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132928. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132929. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132930. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132931. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132932. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132933. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132934. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132935. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132936. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132937. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132938. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132939. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132940. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132941. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132942. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132943. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132944. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132945. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132946. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132947. 10,10,10,10,10,10,10,10,10,
  132948. };
  132949. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132950. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132951. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132952. 6.5, 7.5, 8.5, 9.5,
  132953. };
  132954. static long _vq_quantmap__44c6_s_p8_1[] = {
  132955. 19, 17, 15, 13, 11, 9, 7, 5,
  132956. 3, 1, 0, 2, 4, 6, 8, 10,
  132957. 12, 14, 16, 18, 20,
  132958. };
  132959. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132960. _vq_quantthresh__44c6_s_p8_1,
  132961. _vq_quantmap__44c6_s_p8_1,
  132962. 21,
  132963. 21
  132964. };
  132965. static static_codebook _44c6_s_p8_1 = {
  132966. 2, 441,
  132967. _vq_lengthlist__44c6_s_p8_1,
  132968. 1, -529268736, 1611661312, 5, 0,
  132969. _vq_quantlist__44c6_s_p8_1,
  132970. NULL,
  132971. &_vq_auxt__44c6_s_p8_1,
  132972. NULL,
  132973. 0
  132974. };
  132975. static long _vq_quantlist__44c6_s_p9_0[] = {
  132976. 6,
  132977. 5,
  132978. 7,
  132979. 4,
  132980. 8,
  132981. 3,
  132982. 9,
  132983. 2,
  132984. 10,
  132985. 1,
  132986. 11,
  132987. 0,
  132988. 12,
  132989. };
  132990. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132991. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132992. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132993. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132994. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132995. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132996. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132997. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132998. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132999. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133000. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133001. 10,10,10,10,10,10,10,10,10,
  133002. };
  133003. static float _vq_quantthresh__44c6_s_p9_0[] = {
  133004. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133005. 1592.5, 2229.5, 2866.5, 3503.5,
  133006. };
  133007. static long _vq_quantmap__44c6_s_p9_0[] = {
  133008. 11, 9, 7, 5, 3, 1, 0, 2,
  133009. 4, 6, 8, 10, 12,
  133010. };
  133011. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  133012. _vq_quantthresh__44c6_s_p9_0,
  133013. _vq_quantmap__44c6_s_p9_0,
  133014. 13,
  133015. 13
  133016. };
  133017. static static_codebook _44c6_s_p9_0 = {
  133018. 2, 169,
  133019. _vq_lengthlist__44c6_s_p9_0,
  133020. 1, -511845376, 1630791680, 4, 0,
  133021. _vq_quantlist__44c6_s_p9_0,
  133022. NULL,
  133023. &_vq_auxt__44c6_s_p9_0,
  133024. NULL,
  133025. 0
  133026. };
  133027. static long _vq_quantlist__44c6_s_p9_1[] = {
  133028. 6,
  133029. 5,
  133030. 7,
  133031. 4,
  133032. 8,
  133033. 3,
  133034. 9,
  133035. 2,
  133036. 10,
  133037. 1,
  133038. 11,
  133039. 0,
  133040. 12,
  133041. };
  133042. static long _vq_lengthlist__44c6_s_p9_1[] = {
  133043. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133044. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  133045. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133046. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133047. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133048. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133049. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133050. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133051. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133052. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133053. 15,12,10,11,11,13,11,12,13,
  133054. };
  133055. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133056. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133057. 122.5, 171.5, 220.5, 269.5,
  133058. };
  133059. static long _vq_quantmap__44c6_s_p9_1[] = {
  133060. 11, 9, 7, 5, 3, 1, 0, 2,
  133061. 4, 6, 8, 10, 12,
  133062. };
  133063. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133064. _vq_quantthresh__44c6_s_p9_1,
  133065. _vq_quantmap__44c6_s_p9_1,
  133066. 13,
  133067. 13
  133068. };
  133069. static static_codebook _44c6_s_p9_1 = {
  133070. 2, 169,
  133071. _vq_lengthlist__44c6_s_p9_1,
  133072. 1, -518889472, 1622704128, 4, 0,
  133073. _vq_quantlist__44c6_s_p9_1,
  133074. NULL,
  133075. &_vq_auxt__44c6_s_p9_1,
  133076. NULL,
  133077. 0
  133078. };
  133079. static long _vq_quantlist__44c6_s_p9_2[] = {
  133080. 24,
  133081. 23,
  133082. 25,
  133083. 22,
  133084. 26,
  133085. 21,
  133086. 27,
  133087. 20,
  133088. 28,
  133089. 19,
  133090. 29,
  133091. 18,
  133092. 30,
  133093. 17,
  133094. 31,
  133095. 16,
  133096. 32,
  133097. 15,
  133098. 33,
  133099. 14,
  133100. 34,
  133101. 13,
  133102. 35,
  133103. 12,
  133104. 36,
  133105. 11,
  133106. 37,
  133107. 10,
  133108. 38,
  133109. 9,
  133110. 39,
  133111. 8,
  133112. 40,
  133113. 7,
  133114. 41,
  133115. 6,
  133116. 42,
  133117. 5,
  133118. 43,
  133119. 4,
  133120. 44,
  133121. 3,
  133122. 45,
  133123. 2,
  133124. 46,
  133125. 1,
  133126. 47,
  133127. 0,
  133128. 48,
  133129. };
  133130. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133131. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133132. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133133. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133134. 7,
  133135. };
  133136. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133137. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133138. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133139. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133140. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133141. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133142. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133143. };
  133144. static long _vq_quantmap__44c6_s_p9_2[] = {
  133145. 47, 45, 43, 41, 39, 37, 35, 33,
  133146. 31, 29, 27, 25, 23, 21, 19, 17,
  133147. 15, 13, 11, 9, 7, 5, 3, 1,
  133148. 0, 2, 4, 6, 8, 10, 12, 14,
  133149. 16, 18, 20, 22, 24, 26, 28, 30,
  133150. 32, 34, 36, 38, 40, 42, 44, 46,
  133151. 48,
  133152. };
  133153. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133154. _vq_quantthresh__44c6_s_p9_2,
  133155. _vq_quantmap__44c6_s_p9_2,
  133156. 49,
  133157. 49
  133158. };
  133159. static static_codebook _44c6_s_p9_2 = {
  133160. 1, 49,
  133161. _vq_lengthlist__44c6_s_p9_2,
  133162. 1, -526909440, 1611661312, 6, 0,
  133163. _vq_quantlist__44c6_s_p9_2,
  133164. NULL,
  133165. &_vq_auxt__44c6_s_p9_2,
  133166. NULL,
  133167. 0
  133168. };
  133169. static long _huff_lengthlist__44c6_s_short[] = {
  133170. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133171. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133172. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133173. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133174. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133175. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133176. 9,10,17,18,
  133177. };
  133178. static static_codebook _huff_book__44c6_s_short = {
  133179. 2, 100,
  133180. _huff_lengthlist__44c6_s_short,
  133181. 0, 0, 0, 0, 0,
  133182. NULL,
  133183. NULL,
  133184. NULL,
  133185. NULL,
  133186. 0
  133187. };
  133188. static long _huff_lengthlist__44c7_s_long[] = {
  133189. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133190. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133191. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133192. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133193. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133194. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133195. 11,10,10,12,
  133196. };
  133197. static static_codebook _huff_book__44c7_s_long = {
  133198. 2, 100,
  133199. _huff_lengthlist__44c7_s_long,
  133200. 0, 0, 0, 0, 0,
  133201. NULL,
  133202. NULL,
  133203. NULL,
  133204. NULL,
  133205. 0
  133206. };
  133207. static long _vq_quantlist__44c7_s_p1_0[] = {
  133208. 1,
  133209. 0,
  133210. 2,
  133211. };
  133212. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133213. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133214. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133215. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133216. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133217. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133218. 8,
  133219. };
  133220. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133221. -0.5, 0.5,
  133222. };
  133223. static long _vq_quantmap__44c7_s_p1_0[] = {
  133224. 1, 0, 2,
  133225. };
  133226. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133227. _vq_quantthresh__44c7_s_p1_0,
  133228. _vq_quantmap__44c7_s_p1_0,
  133229. 3,
  133230. 3
  133231. };
  133232. static static_codebook _44c7_s_p1_0 = {
  133233. 4, 81,
  133234. _vq_lengthlist__44c7_s_p1_0,
  133235. 1, -535822336, 1611661312, 2, 0,
  133236. _vq_quantlist__44c7_s_p1_0,
  133237. NULL,
  133238. &_vq_auxt__44c7_s_p1_0,
  133239. NULL,
  133240. 0
  133241. };
  133242. static long _vq_quantlist__44c7_s_p2_0[] = {
  133243. 2,
  133244. 1,
  133245. 3,
  133246. 0,
  133247. 4,
  133248. };
  133249. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133250. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133251. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133252. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133253. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133254. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133255. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133256. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133257. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133259. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133260. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133261. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133262. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133263. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133264. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133265. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133267. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133268. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133269. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133270. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133271. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133272. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133273. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133275. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133276. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133277. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133278. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133279. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133280. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133281. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133286. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133287. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133288. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133289. 13,
  133290. };
  133291. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133292. -1.5, -0.5, 0.5, 1.5,
  133293. };
  133294. static long _vq_quantmap__44c7_s_p2_0[] = {
  133295. 3, 1, 0, 2, 4,
  133296. };
  133297. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133298. _vq_quantthresh__44c7_s_p2_0,
  133299. _vq_quantmap__44c7_s_p2_0,
  133300. 5,
  133301. 5
  133302. };
  133303. static static_codebook _44c7_s_p2_0 = {
  133304. 4, 625,
  133305. _vq_lengthlist__44c7_s_p2_0,
  133306. 1, -533725184, 1611661312, 3, 0,
  133307. _vq_quantlist__44c7_s_p2_0,
  133308. NULL,
  133309. &_vq_auxt__44c7_s_p2_0,
  133310. NULL,
  133311. 0
  133312. };
  133313. static long _vq_quantlist__44c7_s_p3_0[] = {
  133314. 4,
  133315. 3,
  133316. 5,
  133317. 2,
  133318. 6,
  133319. 1,
  133320. 7,
  133321. 0,
  133322. 8,
  133323. };
  133324. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133325. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133326. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133327. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133328. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133330. 0,
  133331. };
  133332. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133333. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133334. };
  133335. static long _vq_quantmap__44c7_s_p3_0[] = {
  133336. 7, 5, 3, 1, 0, 2, 4, 6,
  133337. 8,
  133338. };
  133339. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133340. _vq_quantthresh__44c7_s_p3_0,
  133341. _vq_quantmap__44c7_s_p3_0,
  133342. 9,
  133343. 9
  133344. };
  133345. static static_codebook _44c7_s_p3_0 = {
  133346. 2, 81,
  133347. _vq_lengthlist__44c7_s_p3_0,
  133348. 1, -531628032, 1611661312, 4, 0,
  133349. _vq_quantlist__44c7_s_p3_0,
  133350. NULL,
  133351. &_vq_auxt__44c7_s_p3_0,
  133352. NULL,
  133353. 0
  133354. };
  133355. static long _vq_quantlist__44c7_s_p4_0[] = {
  133356. 8,
  133357. 7,
  133358. 9,
  133359. 6,
  133360. 10,
  133361. 5,
  133362. 11,
  133363. 4,
  133364. 12,
  133365. 3,
  133366. 13,
  133367. 2,
  133368. 14,
  133369. 1,
  133370. 15,
  133371. 0,
  133372. 16,
  133373. };
  133374. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133375. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133376. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133377. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133378. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133379. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133380. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133381. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133382. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133383. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133384. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133393. 0,
  133394. };
  133395. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133396. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133397. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133398. };
  133399. static long _vq_quantmap__44c7_s_p4_0[] = {
  133400. 15, 13, 11, 9, 7, 5, 3, 1,
  133401. 0, 2, 4, 6, 8, 10, 12, 14,
  133402. 16,
  133403. };
  133404. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133405. _vq_quantthresh__44c7_s_p4_0,
  133406. _vq_quantmap__44c7_s_p4_0,
  133407. 17,
  133408. 17
  133409. };
  133410. static static_codebook _44c7_s_p4_0 = {
  133411. 2, 289,
  133412. _vq_lengthlist__44c7_s_p4_0,
  133413. 1, -529530880, 1611661312, 5, 0,
  133414. _vq_quantlist__44c7_s_p4_0,
  133415. NULL,
  133416. &_vq_auxt__44c7_s_p4_0,
  133417. NULL,
  133418. 0
  133419. };
  133420. static long _vq_quantlist__44c7_s_p5_0[] = {
  133421. 1,
  133422. 0,
  133423. 2,
  133424. };
  133425. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133426. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133427. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133428. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133429. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133430. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133431. 12,
  133432. };
  133433. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133434. -5.5, 5.5,
  133435. };
  133436. static long _vq_quantmap__44c7_s_p5_0[] = {
  133437. 1, 0, 2,
  133438. };
  133439. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133440. _vq_quantthresh__44c7_s_p5_0,
  133441. _vq_quantmap__44c7_s_p5_0,
  133442. 3,
  133443. 3
  133444. };
  133445. static static_codebook _44c7_s_p5_0 = {
  133446. 4, 81,
  133447. _vq_lengthlist__44c7_s_p5_0,
  133448. 1, -529137664, 1618345984, 2, 0,
  133449. _vq_quantlist__44c7_s_p5_0,
  133450. NULL,
  133451. &_vq_auxt__44c7_s_p5_0,
  133452. NULL,
  133453. 0
  133454. };
  133455. static long _vq_quantlist__44c7_s_p5_1[] = {
  133456. 5,
  133457. 4,
  133458. 6,
  133459. 3,
  133460. 7,
  133461. 2,
  133462. 8,
  133463. 1,
  133464. 9,
  133465. 0,
  133466. 10,
  133467. };
  133468. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133469. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133470. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133471. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133472. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133473. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133474. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133475. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133476. 11,11,11, 7, 7, 8, 8, 8, 8,
  133477. };
  133478. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133479. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133480. 3.5, 4.5,
  133481. };
  133482. static long _vq_quantmap__44c7_s_p5_1[] = {
  133483. 9, 7, 5, 3, 1, 0, 2, 4,
  133484. 6, 8, 10,
  133485. };
  133486. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133487. _vq_quantthresh__44c7_s_p5_1,
  133488. _vq_quantmap__44c7_s_p5_1,
  133489. 11,
  133490. 11
  133491. };
  133492. static static_codebook _44c7_s_p5_1 = {
  133493. 2, 121,
  133494. _vq_lengthlist__44c7_s_p5_1,
  133495. 1, -531365888, 1611661312, 4, 0,
  133496. _vq_quantlist__44c7_s_p5_1,
  133497. NULL,
  133498. &_vq_auxt__44c7_s_p5_1,
  133499. NULL,
  133500. 0
  133501. };
  133502. static long _vq_quantlist__44c7_s_p6_0[] = {
  133503. 6,
  133504. 5,
  133505. 7,
  133506. 4,
  133507. 8,
  133508. 3,
  133509. 9,
  133510. 2,
  133511. 10,
  133512. 1,
  133513. 11,
  133514. 0,
  133515. 12,
  133516. };
  133517. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133518. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133519. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133520. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133521. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133522. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133523. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133528. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133529. };
  133530. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133531. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133532. 12.5, 17.5, 22.5, 27.5,
  133533. };
  133534. static long _vq_quantmap__44c7_s_p6_0[] = {
  133535. 11, 9, 7, 5, 3, 1, 0, 2,
  133536. 4, 6, 8, 10, 12,
  133537. };
  133538. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133539. _vq_quantthresh__44c7_s_p6_0,
  133540. _vq_quantmap__44c7_s_p6_0,
  133541. 13,
  133542. 13
  133543. };
  133544. static static_codebook _44c7_s_p6_0 = {
  133545. 2, 169,
  133546. _vq_lengthlist__44c7_s_p6_0,
  133547. 1, -526516224, 1616117760, 4, 0,
  133548. _vq_quantlist__44c7_s_p6_0,
  133549. NULL,
  133550. &_vq_auxt__44c7_s_p6_0,
  133551. NULL,
  133552. 0
  133553. };
  133554. static long _vq_quantlist__44c7_s_p6_1[] = {
  133555. 2,
  133556. 1,
  133557. 3,
  133558. 0,
  133559. 4,
  133560. };
  133561. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133562. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133563. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133564. };
  133565. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133566. -1.5, -0.5, 0.5, 1.5,
  133567. };
  133568. static long _vq_quantmap__44c7_s_p6_1[] = {
  133569. 3, 1, 0, 2, 4,
  133570. };
  133571. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133572. _vq_quantthresh__44c7_s_p6_1,
  133573. _vq_quantmap__44c7_s_p6_1,
  133574. 5,
  133575. 5
  133576. };
  133577. static static_codebook _44c7_s_p6_1 = {
  133578. 2, 25,
  133579. _vq_lengthlist__44c7_s_p6_1,
  133580. 1, -533725184, 1611661312, 3, 0,
  133581. _vq_quantlist__44c7_s_p6_1,
  133582. NULL,
  133583. &_vq_auxt__44c7_s_p6_1,
  133584. NULL,
  133585. 0
  133586. };
  133587. static long _vq_quantlist__44c7_s_p7_0[] = {
  133588. 6,
  133589. 5,
  133590. 7,
  133591. 4,
  133592. 8,
  133593. 3,
  133594. 9,
  133595. 2,
  133596. 10,
  133597. 1,
  133598. 11,
  133599. 0,
  133600. 12,
  133601. };
  133602. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133603. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133604. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133605. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133606. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133607. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133608. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133609. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133610. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133611. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133612. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133613. 19,13,13,13,13,14,14,15,15,
  133614. };
  133615. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133616. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133617. 27.5, 38.5, 49.5, 60.5,
  133618. };
  133619. static long _vq_quantmap__44c7_s_p7_0[] = {
  133620. 11, 9, 7, 5, 3, 1, 0, 2,
  133621. 4, 6, 8, 10, 12,
  133622. };
  133623. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133624. _vq_quantthresh__44c7_s_p7_0,
  133625. _vq_quantmap__44c7_s_p7_0,
  133626. 13,
  133627. 13
  133628. };
  133629. static static_codebook _44c7_s_p7_0 = {
  133630. 2, 169,
  133631. _vq_lengthlist__44c7_s_p7_0,
  133632. 1, -523206656, 1618345984, 4, 0,
  133633. _vq_quantlist__44c7_s_p7_0,
  133634. NULL,
  133635. &_vq_auxt__44c7_s_p7_0,
  133636. NULL,
  133637. 0
  133638. };
  133639. static long _vq_quantlist__44c7_s_p7_1[] = {
  133640. 5,
  133641. 4,
  133642. 6,
  133643. 3,
  133644. 7,
  133645. 2,
  133646. 8,
  133647. 1,
  133648. 9,
  133649. 0,
  133650. 10,
  133651. };
  133652. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133653. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133654. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133655. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133656. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133657. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133658. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133659. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133660. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133661. };
  133662. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133663. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133664. 3.5, 4.5,
  133665. };
  133666. static long _vq_quantmap__44c7_s_p7_1[] = {
  133667. 9, 7, 5, 3, 1, 0, 2, 4,
  133668. 6, 8, 10,
  133669. };
  133670. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133671. _vq_quantthresh__44c7_s_p7_1,
  133672. _vq_quantmap__44c7_s_p7_1,
  133673. 11,
  133674. 11
  133675. };
  133676. static static_codebook _44c7_s_p7_1 = {
  133677. 2, 121,
  133678. _vq_lengthlist__44c7_s_p7_1,
  133679. 1, -531365888, 1611661312, 4, 0,
  133680. _vq_quantlist__44c7_s_p7_1,
  133681. NULL,
  133682. &_vq_auxt__44c7_s_p7_1,
  133683. NULL,
  133684. 0
  133685. };
  133686. static long _vq_quantlist__44c7_s_p8_0[] = {
  133687. 7,
  133688. 6,
  133689. 8,
  133690. 5,
  133691. 9,
  133692. 4,
  133693. 10,
  133694. 3,
  133695. 11,
  133696. 2,
  133697. 12,
  133698. 1,
  133699. 13,
  133700. 0,
  133701. 14,
  133702. };
  133703. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133704. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133705. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133706. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133707. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133708. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133709. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133710. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133711. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133712. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133713. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133714. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133715. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133716. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133717. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133718. 14,
  133719. };
  133720. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133721. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133722. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133723. };
  133724. static long _vq_quantmap__44c7_s_p8_0[] = {
  133725. 13, 11, 9, 7, 5, 3, 1, 0,
  133726. 2, 4, 6, 8, 10, 12, 14,
  133727. };
  133728. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133729. _vq_quantthresh__44c7_s_p8_0,
  133730. _vq_quantmap__44c7_s_p8_0,
  133731. 15,
  133732. 15
  133733. };
  133734. static static_codebook _44c7_s_p8_0 = {
  133735. 2, 225,
  133736. _vq_lengthlist__44c7_s_p8_0,
  133737. 1, -520986624, 1620377600, 4, 0,
  133738. _vq_quantlist__44c7_s_p8_0,
  133739. NULL,
  133740. &_vq_auxt__44c7_s_p8_0,
  133741. NULL,
  133742. 0
  133743. };
  133744. static long _vq_quantlist__44c7_s_p8_1[] = {
  133745. 10,
  133746. 9,
  133747. 11,
  133748. 8,
  133749. 12,
  133750. 7,
  133751. 13,
  133752. 6,
  133753. 14,
  133754. 5,
  133755. 15,
  133756. 4,
  133757. 16,
  133758. 3,
  133759. 17,
  133760. 2,
  133761. 18,
  133762. 1,
  133763. 19,
  133764. 0,
  133765. 20,
  133766. };
  133767. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133768. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133769. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133770. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133771. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133772. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133773. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133774. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133775. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133776. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133777. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133778. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133779. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133780. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133781. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133782. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133783. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133784. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133785. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133786. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133787. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133788. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133789. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133790. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133791. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133792. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133793. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133794. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133795. 10,10,10,10,10,10,10,10,10,
  133796. };
  133797. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133798. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133799. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133800. 6.5, 7.5, 8.5, 9.5,
  133801. };
  133802. static long _vq_quantmap__44c7_s_p8_1[] = {
  133803. 19, 17, 15, 13, 11, 9, 7, 5,
  133804. 3, 1, 0, 2, 4, 6, 8, 10,
  133805. 12, 14, 16, 18, 20,
  133806. };
  133807. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133808. _vq_quantthresh__44c7_s_p8_1,
  133809. _vq_quantmap__44c7_s_p8_1,
  133810. 21,
  133811. 21
  133812. };
  133813. static static_codebook _44c7_s_p8_1 = {
  133814. 2, 441,
  133815. _vq_lengthlist__44c7_s_p8_1,
  133816. 1, -529268736, 1611661312, 5, 0,
  133817. _vq_quantlist__44c7_s_p8_1,
  133818. NULL,
  133819. &_vq_auxt__44c7_s_p8_1,
  133820. NULL,
  133821. 0
  133822. };
  133823. static long _vq_quantlist__44c7_s_p9_0[] = {
  133824. 6,
  133825. 5,
  133826. 7,
  133827. 4,
  133828. 8,
  133829. 3,
  133830. 9,
  133831. 2,
  133832. 10,
  133833. 1,
  133834. 11,
  133835. 0,
  133836. 12,
  133837. };
  133838. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133839. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133840. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133841. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133842. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133844. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133845. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133847. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133849. 11,11,11,11,11,11,11,11,11,
  133850. };
  133851. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133852. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133853. 1592.5, 2229.5, 2866.5, 3503.5,
  133854. };
  133855. static long _vq_quantmap__44c7_s_p9_0[] = {
  133856. 11, 9, 7, 5, 3, 1, 0, 2,
  133857. 4, 6, 8, 10, 12,
  133858. };
  133859. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133860. _vq_quantthresh__44c7_s_p9_0,
  133861. _vq_quantmap__44c7_s_p9_0,
  133862. 13,
  133863. 13
  133864. };
  133865. static static_codebook _44c7_s_p9_0 = {
  133866. 2, 169,
  133867. _vq_lengthlist__44c7_s_p9_0,
  133868. 1, -511845376, 1630791680, 4, 0,
  133869. _vq_quantlist__44c7_s_p9_0,
  133870. NULL,
  133871. &_vq_auxt__44c7_s_p9_0,
  133872. NULL,
  133873. 0
  133874. };
  133875. static long _vq_quantlist__44c7_s_p9_1[] = {
  133876. 6,
  133877. 5,
  133878. 7,
  133879. 4,
  133880. 8,
  133881. 3,
  133882. 9,
  133883. 2,
  133884. 10,
  133885. 1,
  133886. 11,
  133887. 0,
  133888. 12,
  133889. };
  133890. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133891. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133892. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133893. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133894. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133895. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133896. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133897. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133898. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133899. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133900. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133901. 15,11,11,10,10,12,12,12,12,
  133902. };
  133903. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133904. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133905. 122.5, 171.5, 220.5, 269.5,
  133906. };
  133907. static long _vq_quantmap__44c7_s_p9_1[] = {
  133908. 11, 9, 7, 5, 3, 1, 0, 2,
  133909. 4, 6, 8, 10, 12,
  133910. };
  133911. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133912. _vq_quantthresh__44c7_s_p9_1,
  133913. _vq_quantmap__44c7_s_p9_1,
  133914. 13,
  133915. 13
  133916. };
  133917. static static_codebook _44c7_s_p9_1 = {
  133918. 2, 169,
  133919. _vq_lengthlist__44c7_s_p9_1,
  133920. 1, -518889472, 1622704128, 4, 0,
  133921. _vq_quantlist__44c7_s_p9_1,
  133922. NULL,
  133923. &_vq_auxt__44c7_s_p9_1,
  133924. NULL,
  133925. 0
  133926. };
  133927. static long _vq_quantlist__44c7_s_p9_2[] = {
  133928. 24,
  133929. 23,
  133930. 25,
  133931. 22,
  133932. 26,
  133933. 21,
  133934. 27,
  133935. 20,
  133936. 28,
  133937. 19,
  133938. 29,
  133939. 18,
  133940. 30,
  133941. 17,
  133942. 31,
  133943. 16,
  133944. 32,
  133945. 15,
  133946. 33,
  133947. 14,
  133948. 34,
  133949. 13,
  133950. 35,
  133951. 12,
  133952. 36,
  133953. 11,
  133954. 37,
  133955. 10,
  133956. 38,
  133957. 9,
  133958. 39,
  133959. 8,
  133960. 40,
  133961. 7,
  133962. 41,
  133963. 6,
  133964. 42,
  133965. 5,
  133966. 43,
  133967. 4,
  133968. 44,
  133969. 3,
  133970. 45,
  133971. 2,
  133972. 46,
  133973. 1,
  133974. 47,
  133975. 0,
  133976. 48,
  133977. };
  133978. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133979. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133980. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133981. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133982. 7,
  133983. };
  133984. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133985. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133986. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133987. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133988. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133989. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133990. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133991. };
  133992. static long _vq_quantmap__44c7_s_p9_2[] = {
  133993. 47, 45, 43, 41, 39, 37, 35, 33,
  133994. 31, 29, 27, 25, 23, 21, 19, 17,
  133995. 15, 13, 11, 9, 7, 5, 3, 1,
  133996. 0, 2, 4, 6, 8, 10, 12, 14,
  133997. 16, 18, 20, 22, 24, 26, 28, 30,
  133998. 32, 34, 36, 38, 40, 42, 44, 46,
  133999. 48,
  134000. };
  134001. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  134002. _vq_quantthresh__44c7_s_p9_2,
  134003. _vq_quantmap__44c7_s_p9_2,
  134004. 49,
  134005. 49
  134006. };
  134007. static static_codebook _44c7_s_p9_2 = {
  134008. 1, 49,
  134009. _vq_lengthlist__44c7_s_p9_2,
  134010. 1, -526909440, 1611661312, 6, 0,
  134011. _vq_quantlist__44c7_s_p9_2,
  134012. NULL,
  134013. &_vq_auxt__44c7_s_p9_2,
  134014. NULL,
  134015. 0
  134016. };
  134017. static long _huff_lengthlist__44c7_s_short[] = {
  134018. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  134019. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  134020. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  134021. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  134022. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  134023. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  134024. 10, 9,11,14,
  134025. };
  134026. static static_codebook _huff_book__44c7_s_short = {
  134027. 2, 100,
  134028. _huff_lengthlist__44c7_s_short,
  134029. 0, 0, 0, 0, 0,
  134030. NULL,
  134031. NULL,
  134032. NULL,
  134033. NULL,
  134034. 0
  134035. };
  134036. static long _huff_lengthlist__44c8_s_long[] = {
  134037. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  134038. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  134039. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  134040. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  134041. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  134042. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  134043. 11, 9, 9,10,
  134044. };
  134045. static static_codebook _huff_book__44c8_s_long = {
  134046. 2, 100,
  134047. _huff_lengthlist__44c8_s_long,
  134048. 0, 0, 0, 0, 0,
  134049. NULL,
  134050. NULL,
  134051. NULL,
  134052. NULL,
  134053. 0
  134054. };
  134055. static long _vq_quantlist__44c8_s_p1_0[] = {
  134056. 1,
  134057. 0,
  134058. 2,
  134059. };
  134060. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134061. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134062. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134063. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134064. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134065. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134066. 8,
  134067. };
  134068. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134069. -0.5, 0.5,
  134070. };
  134071. static long _vq_quantmap__44c8_s_p1_0[] = {
  134072. 1, 0, 2,
  134073. };
  134074. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134075. _vq_quantthresh__44c8_s_p1_0,
  134076. _vq_quantmap__44c8_s_p1_0,
  134077. 3,
  134078. 3
  134079. };
  134080. static static_codebook _44c8_s_p1_0 = {
  134081. 4, 81,
  134082. _vq_lengthlist__44c8_s_p1_0,
  134083. 1, -535822336, 1611661312, 2, 0,
  134084. _vq_quantlist__44c8_s_p1_0,
  134085. NULL,
  134086. &_vq_auxt__44c8_s_p1_0,
  134087. NULL,
  134088. 0
  134089. };
  134090. static long _vq_quantlist__44c8_s_p2_0[] = {
  134091. 2,
  134092. 1,
  134093. 3,
  134094. 0,
  134095. 4,
  134096. };
  134097. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134098. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134099. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134100. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134101. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134102. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134103. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134104. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134105. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134107. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134108. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134109. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134110. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134111. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134112. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134113. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134115. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134116. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134117. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134118. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134119. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134120. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134121. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134123. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134124. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134125. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134126. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134127. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134128. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134129. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134134. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134135. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134136. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134137. 13,
  134138. };
  134139. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134140. -1.5, -0.5, 0.5, 1.5,
  134141. };
  134142. static long _vq_quantmap__44c8_s_p2_0[] = {
  134143. 3, 1, 0, 2, 4,
  134144. };
  134145. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134146. _vq_quantthresh__44c8_s_p2_0,
  134147. _vq_quantmap__44c8_s_p2_0,
  134148. 5,
  134149. 5
  134150. };
  134151. static static_codebook _44c8_s_p2_0 = {
  134152. 4, 625,
  134153. _vq_lengthlist__44c8_s_p2_0,
  134154. 1, -533725184, 1611661312, 3, 0,
  134155. _vq_quantlist__44c8_s_p2_0,
  134156. NULL,
  134157. &_vq_auxt__44c8_s_p2_0,
  134158. NULL,
  134159. 0
  134160. };
  134161. static long _vq_quantlist__44c8_s_p3_0[] = {
  134162. 4,
  134163. 3,
  134164. 5,
  134165. 2,
  134166. 6,
  134167. 1,
  134168. 7,
  134169. 0,
  134170. 8,
  134171. };
  134172. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134173. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134174. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134175. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134176. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134178. 0,
  134179. };
  134180. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134181. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134182. };
  134183. static long _vq_quantmap__44c8_s_p3_0[] = {
  134184. 7, 5, 3, 1, 0, 2, 4, 6,
  134185. 8,
  134186. };
  134187. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134188. _vq_quantthresh__44c8_s_p3_0,
  134189. _vq_quantmap__44c8_s_p3_0,
  134190. 9,
  134191. 9
  134192. };
  134193. static static_codebook _44c8_s_p3_0 = {
  134194. 2, 81,
  134195. _vq_lengthlist__44c8_s_p3_0,
  134196. 1, -531628032, 1611661312, 4, 0,
  134197. _vq_quantlist__44c8_s_p3_0,
  134198. NULL,
  134199. &_vq_auxt__44c8_s_p3_0,
  134200. NULL,
  134201. 0
  134202. };
  134203. static long _vq_quantlist__44c8_s_p4_0[] = {
  134204. 8,
  134205. 7,
  134206. 9,
  134207. 6,
  134208. 10,
  134209. 5,
  134210. 11,
  134211. 4,
  134212. 12,
  134213. 3,
  134214. 13,
  134215. 2,
  134216. 14,
  134217. 1,
  134218. 15,
  134219. 0,
  134220. 16,
  134221. };
  134222. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134223. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134224. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134225. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134226. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134227. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134228. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134229. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134230. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134231. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134232. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134241. 0,
  134242. };
  134243. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134244. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134245. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134246. };
  134247. static long _vq_quantmap__44c8_s_p4_0[] = {
  134248. 15, 13, 11, 9, 7, 5, 3, 1,
  134249. 0, 2, 4, 6, 8, 10, 12, 14,
  134250. 16,
  134251. };
  134252. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134253. _vq_quantthresh__44c8_s_p4_0,
  134254. _vq_quantmap__44c8_s_p4_0,
  134255. 17,
  134256. 17
  134257. };
  134258. static static_codebook _44c8_s_p4_0 = {
  134259. 2, 289,
  134260. _vq_lengthlist__44c8_s_p4_0,
  134261. 1, -529530880, 1611661312, 5, 0,
  134262. _vq_quantlist__44c8_s_p4_0,
  134263. NULL,
  134264. &_vq_auxt__44c8_s_p4_0,
  134265. NULL,
  134266. 0
  134267. };
  134268. static long _vq_quantlist__44c8_s_p5_0[] = {
  134269. 1,
  134270. 0,
  134271. 2,
  134272. };
  134273. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134274. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134275. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134276. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134277. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134278. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134279. 12,
  134280. };
  134281. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134282. -5.5, 5.5,
  134283. };
  134284. static long _vq_quantmap__44c8_s_p5_0[] = {
  134285. 1, 0, 2,
  134286. };
  134287. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134288. _vq_quantthresh__44c8_s_p5_0,
  134289. _vq_quantmap__44c8_s_p5_0,
  134290. 3,
  134291. 3
  134292. };
  134293. static static_codebook _44c8_s_p5_0 = {
  134294. 4, 81,
  134295. _vq_lengthlist__44c8_s_p5_0,
  134296. 1, -529137664, 1618345984, 2, 0,
  134297. _vq_quantlist__44c8_s_p5_0,
  134298. NULL,
  134299. &_vq_auxt__44c8_s_p5_0,
  134300. NULL,
  134301. 0
  134302. };
  134303. static long _vq_quantlist__44c8_s_p5_1[] = {
  134304. 5,
  134305. 4,
  134306. 6,
  134307. 3,
  134308. 7,
  134309. 2,
  134310. 8,
  134311. 1,
  134312. 9,
  134313. 0,
  134314. 10,
  134315. };
  134316. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134317. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134318. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134319. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134320. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134321. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134322. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134323. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134324. 11,11,11, 7, 7, 7, 7, 8, 8,
  134325. };
  134326. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134327. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134328. 3.5, 4.5,
  134329. };
  134330. static long _vq_quantmap__44c8_s_p5_1[] = {
  134331. 9, 7, 5, 3, 1, 0, 2, 4,
  134332. 6, 8, 10,
  134333. };
  134334. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134335. _vq_quantthresh__44c8_s_p5_1,
  134336. _vq_quantmap__44c8_s_p5_1,
  134337. 11,
  134338. 11
  134339. };
  134340. static static_codebook _44c8_s_p5_1 = {
  134341. 2, 121,
  134342. _vq_lengthlist__44c8_s_p5_1,
  134343. 1, -531365888, 1611661312, 4, 0,
  134344. _vq_quantlist__44c8_s_p5_1,
  134345. NULL,
  134346. &_vq_auxt__44c8_s_p5_1,
  134347. NULL,
  134348. 0
  134349. };
  134350. static long _vq_quantlist__44c8_s_p6_0[] = {
  134351. 6,
  134352. 5,
  134353. 7,
  134354. 4,
  134355. 8,
  134356. 3,
  134357. 9,
  134358. 2,
  134359. 10,
  134360. 1,
  134361. 11,
  134362. 0,
  134363. 12,
  134364. };
  134365. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134366. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134367. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134368. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134369. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134370. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134371. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134376. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134377. };
  134378. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134379. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134380. 12.5, 17.5, 22.5, 27.5,
  134381. };
  134382. static long _vq_quantmap__44c8_s_p6_0[] = {
  134383. 11, 9, 7, 5, 3, 1, 0, 2,
  134384. 4, 6, 8, 10, 12,
  134385. };
  134386. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134387. _vq_quantthresh__44c8_s_p6_0,
  134388. _vq_quantmap__44c8_s_p6_0,
  134389. 13,
  134390. 13
  134391. };
  134392. static static_codebook _44c8_s_p6_0 = {
  134393. 2, 169,
  134394. _vq_lengthlist__44c8_s_p6_0,
  134395. 1, -526516224, 1616117760, 4, 0,
  134396. _vq_quantlist__44c8_s_p6_0,
  134397. NULL,
  134398. &_vq_auxt__44c8_s_p6_0,
  134399. NULL,
  134400. 0
  134401. };
  134402. static long _vq_quantlist__44c8_s_p6_1[] = {
  134403. 2,
  134404. 1,
  134405. 3,
  134406. 0,
  134407. 4,
  134408. };
  134409. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134410. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134411. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134412. };
  134413. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134414. -1.5, -0.5, 0.5, 1.5,
  134415. };
  134416. static long _vq_quantmap__44c8_s_p6_1[] = {
  134417. 3, 1, 0, 2, 4,
  134418. };
  134419. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134420. _vq_quantthresh__44c8_s_p6_1,
  134421. _vq_quantmap__44c8_s_p6_1,
  134422. 5,
  134423. 5
  134424. };
  134425. static static_codebook _44c8_s_p6_1 = {
  134426. 2, 25,
  134427. _vq_lengthlist__44c8_s_p6_1,
  134428. 1, -533725184, 1611661312, 3, 0,
  134429. _vq_quantlist__44c8_s_p6_1,
  134430. NULL,
  134431. &_vq_auxt__44c8_s_p6_1,
  134432. NULL,
  134433. 0
  134434. };
  134435. static long _vq_quantlist__44c8_s_p7_0[] = {
  134436. 6,
  134437. 5,
  134438. 7,
  134439. 4,
  134440. 8,
  134441. 3,
  134442. 9,
  134443. 2,
  134444. 10,
  134445. 1,
  134446. 11,
  134447. 0,
  134448. 12,
  134449. };
  134450. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134451. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134452. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134453. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134454. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134455. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134456. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134457. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134458. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134459. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134460. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134461. 20,13,13,13,13,14,13,15,15,
  134462. };
  134463. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134464. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134465. 27.5, 38.5, 49.5, 60.5,
  134466. };
  134467. static long _vq_quantmap__44c8_s_p7_0[] = {
  134468. 11, 9, 7, 5, 3, 1, 0, 2,
  134469. 4, 6, 8, 10, 12,
  134470. };
  134471. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134472. _vq_quantthresh__44c8_s_p7_0,
  134473. _vq_quantmap__44c8_s_p7_0,
  134474. 13,
  134475. 13
  134476. };
  134477. static static_codebook _44c8_s_p7_0 = {
  134478. 2, 169,
  134479. _vq_lengthlist__44c8_s_p7_0,
  134480. 1, -523206656, 1618345984, 4, 0,
  134481. _vq_quantlist__44c8_s_p7_0,
  134482. NULL,
  134483. &_vq_auxt__44c8_s_p7_0,
  134484. NULL,
  134485. 0
  134486. };
  134487. static long _vq_quantlist__44c8_s_p7_1[] = {
  134488. 5,
  134489. 4,
  134490. 6,
  134491. 3,
  134492. 7,
  134493. 2,
  134494. 8,
  134495. 1,
  134496. 9,
  134497. 0,
  134498. 10,
  134499. };
  134500. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134501. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134502. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134503. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134504. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134505. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134506. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134507. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134508. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134509. };
  134510. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134511. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134512. 3.5, 4.5,
  134513. };
  134514. static long _vq_quantmap__44c8_s_p7_1[] = {
  134515. 9, 7, 5, 3, 1, 0, 2, 4,
  134516. 6, 8, 10,
  134517. };
  134518. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134519. _vq_quantthresh__44c8_s_p7_1,
  134520. _vq_quantmap__44c8_s_p7_1,
  134521. 11,
  134522. 11
  134523. };
  134524. static static_codebook _44c8_s_p7_1 = {
  134525. 2, 121,
  134526. _vq_lengthlist__44c8_s_p7_1,
  134527. 1, -531365888, 1611661312, 4, 0,
  134528. _vq_quantlist__44c8_s_p7_1,
  134529. NULL,
  134530. &_vq_auxt__44c8_s_p7_1,
  134531. NULL,
  134532. 0
  134533. };
  134534. static long _vq_quantlist__44c8_s_p8_0[] = {
  134535. 7,
  134536. 6,
  134537. 8,
  134538. 5,
  134539. 9,
  134540. 4,
  134541. 10,
  134542. 3,
  134543. 11,
  134544. 2,
  134545. 12,
  134546. 1,
  134547. 13,
  134548. 0,
  134549. 14,
  134550. };
  134551. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134552. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134553. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134554. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134555. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134556. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134557. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134558. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134559. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134560. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134561. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134562. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134563. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134564. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134565. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134566. 15,
  134567. };
  134568. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134569. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134570. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134571. };
  134572. static long _vq_quantmap__44c8_s_p8_0[] = {
  134573. 13, 11, 9, 7, 5, 3, 1, 0,
  134574. 2, 4, 6, 8, 10, 12, 14,
  134575. };
  134576. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134577. _vq_quantthresh__44c8_s_p8_0,
  134578. _vq_quantmap__44c8_s_p8_0,
  134579. 15,
  134580. 15
  134581. };
  134582. static static_codebook _44c8_s_p8_0 = {
  134583. 2, 225,
  134584. _vq_lengthlist__44c8_s_p8_0,
  134585. 1, -520986624, 1620377600, 4, 0,
  134586. _vq_quantlist__44c8_s_p8_0,
  134587. NULL,
  134588. &_vq_auxt__44c8_s_p8_0,
  134589. NULL,
  134590. 0
  134591. };
  134592. static long _vq_quantlist__44c8_s_p8_1[] = {
  134593. 10,
  134594. 9,
  134595. 11,
  134596. 8,
  134597. 12,
  134598. 7,
  134599. 13,
  134600. 6,
  134601. 14,
  134602. 5,
  134603. 15,
  134604. 4,
  134605. 16,
  134606. 3,
  134607. 17,
  134608. 2,
  134609. 18,
  134610. 1,
  134611. 19,
  134612. 0,
  134613. 20,
  134614. };
  134615. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134616. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134617. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134618. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134619. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134620. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134621. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134622. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134623. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134624. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134625. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134626. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134627. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134628. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134629. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134630. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134631. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134632. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134633. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134634. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134635. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134636. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134637. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134638. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134639. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134640. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134641. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134642. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134643. 10, 9, 9,10,10, 9,10, 9, 9,
  134644. };
  134645. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134646. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134647. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134648. 6.5, 7.5, 8.5, 9.5,
  134649. };
  134650. static long _vq_quantmap__44c8_s_p8_1[] = {
  134651. 19, 17, 15, 13, 11, 9, 7, 5,
  134652. 3, 1, 0, 2, 4, 6, 8, 10,
  134653. 12, 14, 16, 18, 20,
  134654. };
  134655. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134656. _vq_quantthresh__44c8_s_p8_1,
  134657. _vq_quantmap__44c8_s_p8_1,
  134658. 21,
  134659. 21
  134660. };
  134661. static static_codebook _44c8_s_p8_1 = {
  134662. 2, 441,
  134663. _vq_lengthlist__44c8_s_p8_1,
  134664. 1, -529268736, 1611661312, 5, 0,
  134665. _vq_quantlist__44c8_s_p8_1,
  134666. NULL,
  134667. &_vq_auxt__44c8_s_p8_1,
  134668. NULL,
  134669. 0
  134670. };
  134671. static long _vq_quantlist__44c8_s_p9_0[] = {
  134672. 8,
  134673. 7,
  134674. 9,
  134675. 6,
  134676. 10,
  134677. 5,
  134678. 11,
  134679. 4,
  134680. 12,
  134681. 3,
  134682. 13,
  134683. 2,
  134684. 14,
  134685. 1,
  134686. 15,
  134687. 0,
  134688. 16,
  134689. };
  134690. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134691. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134692. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134693. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134694. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134695. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134696. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134697. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134698. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134699. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134700. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134701. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134702. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134703. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134704. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134705. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134706. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134707. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134708. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134709. 10,
  134710. };
  134711. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134712. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134713. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134714. };
  134715. static long _vq_quantmap__44c8_s_p9_0[] = {
  134716. 15, 13, 11, 9, 7, 5, 3, 1,
  134717. 0, 2, 4, 6, 8, 10, 12, 14,
  134718. 16,
  134719. };
  134720. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134721. _vq_quantthresh__44c8_s_p9_0,
  134722. _vq_quantmap__44c8_s_p9_0,
  134723. 17,
  134724. 17
  134725. };
  134726. static static_codebook _44c8_s_p9_0 = {
  134727. 2, 289,
  134728. _vq_lengthlist__44c8_s_p9_0,
  134729. 1, -509798400, 1631393792, 5, 0,
  134730. _vq_quantlist__44c8_s_p9_0,
  134731. NULL,
  134732. &_vq_auxt__44c8_s_p9_0,
  134733. NULL,
  134734. 0
  134735. };
  134736. static long _vq_quantlist__44c8_s_p9_1[] = {
  134737. 9,
  134738. 8,
  134739. 10,
  134740. 7,
  134741. 11,
  134742. 6,
  134743. 12,
  134744. 5,
  134745. 13,
  134746. 4,
  134747. 14,
  134748. 3,
  134749. 15,
  134750. 2,
  134751. 16,
  134752. 1,
  134753. 17,
  134754. 0,
  134755. 18,
  134756. };
  134757. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134758. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134759. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134760. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134761. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134762. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134763. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134764. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134765. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134766. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134767. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134768. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134769. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134770. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134771. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134772. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134773. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134774. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134775. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134776. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134777. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134778. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134779. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134780. 14,13,13,14,14,15,14,15,14,
  134781. };
  134782. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134783. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134784. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134785. 367.5, 416.5,
  134786. };
  134787. static long _vq_quantmap__44c8_s_p9_1[] = {
  134788. 17, 15, 13, 11, 9, 7, 5, 3,
  134789. 1, 0, 2, 4, 6, 8, 10, 12,
  134790. 14, 16, 18,
  134791. };
  134792. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134793. _vq_quantthresh__44c8_s_p9_1,
  134794. _vq_quantmap__44c8_s_p9_1,
  134795. 19,
  134796. 19
  134797. };
  134798. static static_codebook _44c8_s_p9_1 = {
  134799. 2, 361,
  134800. _vq_lengthlist__44c8_s_p9_1,
  134801. 1, -518287360, 1622704128, 5, 0,
  134802. _vq_quantlist__44c8_s_p9_1,
  134803. NULL,
  134804. &_vq_auxt__44c8_s_p9_1,
  134805. NULL,
  134806. 0
  134807. };
  134808. static long _vq_quantlist__44c8_s_p9_2[] = {
  134809. 24,
  134810. 23,
  134811. 25,
  134812. 22,
  134813. 26,
  134814. 21,
  134815. 27,
  134816. 20,
  134817. 28,
  134818. 19,
  134819. 29,
  134820. 18,
  134821. 30,
  134822. 17,
  134823. 31,
  134824. 16,
  134825. 32,
  134826. 15,
  134827. 33,
  134828. 14,
  134829. 34,
  134830. 13,
  134831. 35,
  134832. 12,
  134833. 36,
  134834. 11,
  134835. 37,
  134836. 10,
  134837. 38,
  134838. 9,
  134839. 39,
  134840. 8,
  134841. 40,
  134842. 7,
  134843. 41,
  134844. 6,
  134845. 42,
  134846. 5,
  134847. 43,
  134848. 4,
  134849. 44,
  134850. 3,
  134851. 45,
  134852. 2,
  134853. 46,
  134854. 1,
  134855. 47,
  134856. 0,
  134857. 48,
  134858. };
  134859. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134860. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134861. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134862. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134863. 7,
  134864. };
  134865. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134866. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134867. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134868. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134869. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134870. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134871. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134872. };
  134873. static long _vq_quantmap__44c8_s_p9_2[] = {
  134874. 47, 45, 43, 41, 39, 37, 35, 33,
  134875. 31, 29, 27, 25, 23, 21, 19, 17,
  134876. 15, 13, 11, 9, 7, 5, 3, 1,
  134877. 0, 2, 4, 6, 8, 10, 12, 14,
  134878. 16, 18, 20, 22, 24, 26, 28, 30,
  134879. 32, 34, 36, 38, 40, 42, 44, 46,
  134880. 48,
  134881. };
  134882. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134883. _vq_quantthresh__44c8_s_p9_2,
  134884. _vq_quantmap__44c8_s_p9_2,
  134885. 49,
  134886. 49
  134887. };
  134888. static static_codebook _44c8_s_p9_2 = {
  134889. 1, 49,
  134890. _vq_lengthlist__44c8_s_p9_2,
  134891. 1, -526909440, 1611661312, 6, 0,
  134892. _vq_quantlist__44c8_s_p9_2,
  134893. NULL,
  134894. &_vq_auxt__44c8_s_p9_2,
  134895. NULL,
  134896. 0
  134897. };
  134898. static long _huff_lengthlist__44c8_s_short[] = {
  134899. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134900. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134901. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134902. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134903. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134904. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134905. 10, 9,11,14,
  134906. };
  134907. static static_codebook _huff_book__44c8_s_short = {
  134908. 2, 100,
  134909. _huff_lengthlist__44c8_s_short,
  134910. 0, 0, 0, 0, 0,
  134911. NULL,
  134912. NULL,
  134913. NULL,
  134914. NULL,
  134915. 0
  134916. };
  134917. static long _huff_lengthlist__44c9_s_long[] = {
  134918. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134919. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134920. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134921. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134922. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134923. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134924. 10, 9, 8, 9,
  134925. };
  134926. static static_codebook _huff_book__44c9_s_long = {
  134927. 2, 100,
  134928. _huff_lengthlist__44c9_s_long,
  134929. 0, 0, 0, 0, 0,
  134930. NULL,
  134931. NULL,
  134932. NULL,
  134933. NULL,
  134934. 0
  134935. };
  134936. static long _vq_quantlist__44c9_s_p1_0[] = {
  134937. 1,
  134938. 0,
  134939. 2,
  134940. };
  134941. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134942. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134943. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134944. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134945. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134946. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134947. 7,
  134948. };
  134949. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134950. -0.5, 0.5,
  134951. };
  134952. static long _vq_quantmap__44c9_s_p1_0[] = {
  134953. 1, 0, 2,
  134954. };
  134955. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134956. _vq_quantthresh__44c9_s_p1_0,
  134957. _vq_quantmap__44c9_s_p1_0,
  134958. 3,
  134959. 3
  134960. };
  134961. static static_codebook _44c9_s_p1_0 = {
  134962. 4, 81,
  134963. _vq_lengthlist__44c9_s_p1_0,
  134964. 1, -535822336, 1611661312, 2, 0,
  134965. _vq_quantlist__44c9_s_p1_0,
  134966. NULL,
  134967. &_vq_auxt__44c9_s_p1_0,
  134968. NULL,
  134969. 0
  134970. };
  134971. static long _vq_quantlist__44c9_s_p2_0[] = {
  134972. 2,
  134973. 1,
  134974. 3,
  134975. 0,
  134976. 4,
  134977. };
  134978. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134979. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134980. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134981. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134982. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134983. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134984. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134985. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134986. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134988. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134989. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134990. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134991. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134992. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134993. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134994. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134996. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134997. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134998. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134999. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  135000. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  135001. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  135002. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135004. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  135005. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  135006. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  135007. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  135008. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  135009. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  135010. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  135015. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  135016. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  135017. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  135018. 12,
  135019. };
  135020. static float _vq_quantthresh__44c9_s_p2_0[] = {
  135021. -1.5, -0.5, 0.5, 1.5,
  135022. };
  135023. static long _vq_quantmap__44c9_s_p2_0[] = {
  135024. 3, 1, 0, 2, 4,
  135025. };
  135026. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  135027. _vq_quantthresh__44c9_s_p2_0,
  135028. _vq_quantmap__44c9_s_p2_0,
  135029. 5,
  135030. 5
  135031. };
  135032. static static_codebook _44c9_s_p2_0 = {
  135033. 4, 625,
  135034. _vq_lengthlist__44c9_s_p2_0,
  135035. 1, -533725184, 1611661312, 3, 0,
  135036. _vq_quantlist__44c9_s_p2_0,
  135037. NULL,
  135038. &_vq_auxt__44c9_s_p2_0,
  135039. NULL,
  135040. 0
  135041. };
  135042. static long _vq_quantlist__44c9_s_p3_0[] = {
  135043. 4,
  135044. 3,
  135045. 5,
  135046. 2,
  135047. 6,
  135048. 1,
  135049. 7,
  135050. 0,
  135051. 8,
  135052. };
  135053. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135054. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135055. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135056. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135057. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135059. 0,
  135060. };
  135061. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135062. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135063. };
  135064. static long _vq_quantmap__44c9_s_p3_0[] = {
  135065. 7, 5, 3, 1, 0, 2, 4, 6,
  135066. 8,
  135067. };
  135068. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135069. _vq_quantthresh__44c9_s_p3_0,
  135070. _vq_quantmap__44c9_s_p3_0,
  135071. 9,
  135072. 9
  135073. };
  135074. static static_codebook _44c9_s_p3_0 = {
  135075. 2, 81,
  135076. _vq_lengthlist__44c9_s_p3_0,
  135077. 1, -531628032, 1611661312, 4, 0,
  135078. _vq_quantlist__44c9_s_p3_0,
  135079. NULL,
  135080. &_vq_auxt__44c9_s_p3_0,
  135081. NULL,
  135082. 0
  135083. };
  135084. static long _vq_quantlist__44c9_s_p4_0[] = {
  135085. 8,
  135086. 7,
  135087. 9,
  135088. 6,
  135089. 10,
  135090. 5,
  135091. 11,
  135092. 4,
  135093. 12,
  135094. 3,
  135095. 13,
  135096. 2,
  135097. 14,
  135098. 1,
  135099. 15,
  135100. 0,
  135101. 16,
  135102. };
  135103. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135104. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135105. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135106. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135107. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135108. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135109. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135110. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135111. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135112. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135113. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135122. 0,
  135123. };
  135124. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135125. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135126. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135127. };
  135128. static long _vq_quantmap__44c9_s_p4_0[] = {
  135129. 15, 13, 11, 9, 7, 5, 3, 1,
  135130. 0, 2, 4, 6, 8, 10, 12, 14,
  135131. 16,
  135132. };
  135133. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135134. _vq_quantthresh__44c9_s_p4_0,
  135135. _vq_quantmap__44c9_s_p4_0,
  135136. 17,
  135137. 17
  135138. };
  135139. static static_codebook _44c9_s_p4_0 = {
  135140. 2, 289,
  135141. _vq_lengthlist__44c9_s_p4_0,
  135142. 1, -529530880, 1611661312, 5, 0,
  135143. _vq_quantlist__44c9_s_p4_0,
  135144. NULL,
  135145. &_vq_auxt__44c9_s_p4_0,
  135146. NULL,
  135147. 0
  135148. };
  135149. static long _vq_quantlist__44c9_s_p5_0[] = {
  135150. 1,
  135151. 0,
  135152. 2,
  135153. };
  135154. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135155. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135156. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135157. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135158. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135159. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135160. 12,
  135161. };
  135162. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135163. -5.5, 5.5,
  135164. };
  135165. static long _vq_quantmap__44c9_s_p5_0[] = {
  135166. 1, 0, 2,
  135167. };
  135168. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135169. _vq_quantthresh__44c9_s_p5_0,
  135170. _vq_quantmap__44c9_s_p5_0,
  135171. 3,
  135172. 3
  135173. };
  135174. static static_codebook _44c9_s_p5_0 = {
  135175. 4, 81,
  135176. _vq_lengthlist__44c9_s_p5_0,
  135177. 1, -529137664, 1618345984, 2, 0,
  135178. _vq_quantlist__44c9_s_p5_0,
  135179. NULL,
  135180. &_vq_auxt__44c9_s_p5_0,
  135181. NULL,
  135182. 0
  135183. };
  135184. static long _vq_quantlist__44c9_s_p5_1[] = {
  135185. 5,
  135186. 4,
  135187. 6,
  135188. 3,
  135189. 7,
  135190. 2,
  135191. 8,
  135192. 1,
  135193. 9,
  135194. 0,
  135195. 10,
  135196. };
  135197. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135198. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135199. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135200. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135201. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135202. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135203. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135204. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135205. 11,11,11, 7, 7, 7, 7, 7, 7,
  135206. };
  135207. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135208. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135209. 3.5, 4.5,
  135210. };
  135211. static long _vq_quantmap__44c9_s_p5_1[] = {
  135212. 9, 7, 5, 3, 1, 0, 2, 4,
  135213. 6, 8, 10,
  135214. };
  135215. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135216. _vq_quantthresh__44c9_s_p5_1,
  135217. _vq_quantmap__44c9_s_p5_1,
  135218. 11,
  135219. 11
  135220. };
  135221. static static_codebook _44c9_s_p5_1 = {
  135222. 2, 121,
  135223. _vq_lengthlist__44c9_s_p5_1,
  135224. 1, -531365888, 1611661312, 4, 0,
  135225. _vq_quantlist__44c9_s_p5_1,
  135226. NULL,
  135227. &_vq_auxt__44c9_s_p5_1,
  135228. NULL,
  135229. 0
  135230. };
  135231. static long _vq_quantlist__44c9_s_p6_0[] = {
  135232. 6,
  135233. 5,
  135234. 7,
  135235. 4,
  135236. 8,
  135237. 3,
  135238. 9,
  135239. 2,
  135240. 10,
  135241. 1,
  135242. 11,
  135243. 0,
  135244. 12,
  135245. };
  135246. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135247. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135248. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135249. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135250. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135251. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135252. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135257. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135258. };
  135259. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135260. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135261. 12.5, 17.5, 22.5, 27.5,
  135262. };
  135263. static long _vq_quantmap__44c9_s_p6_0[] = {
  135264. 11, 9, 7, 5, 3, 1, 0, 2,
  135265. 4, 6, 8, 10, 12,
  135266. };
  135267. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135268. _vq_quantthresh__44c9_s_p6_0,
  135269. _vq_quantmap__44c9_s_p6_0,
  135270. 13,
  135271. 13
  135272. };
  135273. static static_codebook _44c9_s_p6_0 = {
  135274. 2, 169,
  135275. _vq_lengthlist__44c9_s_p6_0,
  135276. 1, -526516224, 1616117760, 4, 0,
  135277. _vq_quantlist__44c9_s_p6_0,
  135278. NULL,
  135279. &_vq_auxt__44c9_s_p6_0,
  135280. NULL,
  135281. 0
  135282. };
  135283. static long _vq_quantlist__44c9_s_p6_1[] = {
  135284. 2,
  135285. 1,
  135286. 3,
  135287. 0,
  135288. 4,
  135289. };
  135290. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135291. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135292. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135293. };
  135294. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135295. -1.5, -0.5, 0.5, 1.5,
  135296. };
  135297. static long _vq_quantmap__44c9_s_p6_1[] = {
  135298. 3, 1, 0, 2, 4,
  135299. };
  135300. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135301. _vq_quantthresh__44c9_s_p6_1,
  135302. _vq_quantmap__44c9_s_p6_1,
  135303. 5,
  135304. 5
  135305. };
  135306. static static_codebook _44c9_s_p6_1 = {
  135307. 2, 25,
  135308. _vq_lengthlist__44c9_s_p6_1,
  135309. 1, -533725184, 1611661312, 3, 0,
  135310. _vq_quantlist__44c9_s_p6_1,
  135311. NULL,
  135312. &_vq_auxt__44c9_s_p6_1,
  135313. NULL,
  135314. 0
  135315. };
  135316. static long _vq_quantlist__44c9_s_p7_0[] = {
  135317. 6,
  135318. 5,
  135319. 7,
  135320. 4,
  135321. 8,
  135322. 3,
  135323. 9,
  135324. 2,
  135325. 10,
  135326. 1,
  135327. 11,
  135328. 0,
  135329. 12,
  135330. };
  135331. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135332. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135333. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135334. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135335. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135336. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135337. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135338. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135339. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135340. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135341. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135342. 19,12,12,12,12,13,13,14,14,
  135343. };
  135344. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135345. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135346. 27.5, 38.5, 49.5, 60.5,
  135347. };
  135348. static long _vq_quantmap__44c9_s_p7_0[] = {
  135349. 11, 9, 7, 5, 3, 1, 0, 2,
  135350. 4, 6, 8, 10, 12,
  135351. };
  135352. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135353. _vq_quantthresh__44c9_s_p7_0,
  135354. _vq_quantmap__44c9_s_p7_0,
  135355. 13,
  135356. 13
  135357. };
  135358. static static_codebook _44c9_s_p7_0 = {
  135359. 2, 169,
  135360. _vq_lengthlist__44c9_s_p7_0,
  135361. 1, -523206656, 1618345984, 4, 0,
  135362. _vq_quantlist__44c9_s_p7_0,
  135363. NULL,
  135364. &_vq_auxt__44c9_s_p7_0,
  135365. NULL,
  135366. 0
  135367. };
  135368. static long _vq_quantlist__44c9_s_p7_1[] = {
  135369. 5,
  135370. 4,
  135371. 6,
  135372. 3,
  135373. 7,
  135374. 2,
  135375. 8,
  135376. 1,
  135377. 9,
  135378. 0,
  135379. 10,
  135380. };
  135381. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135382. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135383. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135384. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135385. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135386. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135387. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135388. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135389. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135390. };
  135391. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135392. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135393. 3.5, 4.5,
  135394. };
  135395. static long _vq_quantmap__44c9_s_p7_1[] = {
  135396. 9, 7, 5, 3, 1, 0, 2, 4,
  135397. 6, 8, 10,
  135398. };
  135399. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135400. _vq_quantthresh__44c9_s_p7_1,
  135401. _vq_quantmap__44c9_s_p7_1,
  135402. 11,
  135403. 11
  135404. };
  135405. static static_codebook _44c9_s_p7_1 = {
  135406. 2, 121,
  135407. _vq_lengthlist__44c9_s_p7_1,
  135408. 1, -531365888, 1611661312, 4, 0,
  135409. _vq_quantlist__44c9_s_p7_1,
  135410. NULL,
  135411. &_vq_auxt__44c9_s_p7_1,
  135412. NULL,
  135413. 0
  135414. };
  135415. static long _vq_quantlist__44c9_s_p8_0[] = {
  135416. 7,
  135417. 6,
  135418. 8,
  135419. 5,
  135420. 9,
  135421. 4,
  135422. 10,
  135423. 3,
  135424. 11,
  135425. 2,
  135426. 12,
  135427. 1,
  135428. 13,
  135429. 0,
  135430. 14,
  135431. };
  135432. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135433. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135434. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135435. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135436. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135437. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135438. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135439. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135440. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135441. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135442. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135443. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135444. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135445. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135446. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135447. 14,
  135448. };
  135449. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135450. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135451. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135452. };
  135453. static long _vq_quantmap__44c9_s_p8_0[] = {
  135454. 13, 11, 9, 7, 5, 3, 1, 0,
  135455. 2, 4, 6, 8, 10, 12, 14,
  135456. };
  135457. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135458. _vq_quantthresh__44c9_s_p8_0,
  135459. _vq_quantmap__44c9_s_p8_0,
  135460. 15,
  135461. 15
  135462. };
  135463. static static_codebook _44c9_s_p8_0 = {
  135464. 2, 225,
  135465. _vq_lengthlist__44c9_s_p8_0,
  135466. 1, -520986624, 1620377600, 4, 0,
  135467. _vq_quantlist__44c9_s_p8_0,
  135468. NULL,
  135469. &_vq_auxt__44c9_s_p8_0,
  135470. NULL,
  135471. 0
  135472. };
  135473. static long _vq_quantlist__44c9_s_p8_1[] = {
  135474. 10,
  135475. 9,
  135476. 11,
  135477. 8,
  135478. 12,
  135479. 7,
  135480. 13,
  135481. 6,
  135482. 14,
  135483. 5,
  135484. 15,
  135485. 4,
  135486. 16,
  135487. 3,
  135488. 17,
  135489. 2,
  135490. 18,
  135491. 1,
  135492. 19,
  135493. 0,
  135494. 20,
  135495. };
  135496. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135497. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135498. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135499. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135500. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135501. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135502. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135503. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135504. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135505. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135506. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135507. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135508. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135509. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135510. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135511. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135512. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135513. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135514. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135515. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135516. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135517. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135518. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135519. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135520. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135521. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135522. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135523. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135524. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135525. };
  135526. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135527. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135528. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135529. 6.5, 7.5, 8.5, 9.5,
  135530. };
  135531. static long _vq_quantmap__44c9_s_p8_1[] = {
  135532. 19, 17, 15, 13, 11, 9, 7, 5,
  135533. 3, 1, 0, 2, 4, 6, 8, 10,
  135534. 12, 14, 16, 18, 20,
  135535. };
  135536. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135537. _vq_quantthresh__44c9_s_p8_1,
  135538. _vq_quantmap__44c9_s_p8_1,
  135539. 21,
  135540. 21
  135541. };
  135542. static static_codebook _44c9_s_p8_1 = {
  135543. 2, 441,
  135544. _vq_lengthlist__44c9_s_p8_1,
  135545. 1, -529268736, 1611661312, 5, 0,
  135546. _vq_quantlist__44c9_s_p8_1,
  135547. NULL,
  135548. &_vq_auxt__44c9_s_p8_1,
  135549. NULL,
  135550. 0
  135551. };
  135552. static long _vq_quantlist__44c9_s_p9_0[] = {
  135553. 9,
  135554. 8,
  135555. 10,
  135556. 7,
  135557. 11,
  135558. 6,
  135559. 12,
  135560. 5,
  135561. 13,
  135562. 4,
  135563. 14,
  135564. 3,
  135565. 15,
  135566. 2,
  135567. 16,
  135568. 1,
  135569. 17,
  135570. 0,
  135571. 18,
  135572. };
  135573. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135574. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135575. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135576. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135577. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135578. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135579. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135580. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135581. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135582. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135583. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135584. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135585. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135586. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135587. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135588. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135589. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135590. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135591. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135592. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135593. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135594. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135595. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135596. 11,11,11,11,11,11,11,11,11,
  135597. };
  135598. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135599. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135600. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135601. 6982.5, 7913.5,
  135602. };
  135603. static long _vq_quantmap__44c9_s_p9_0[] = {
  135604. 17, 15, 13, 11, 9, 7, 5, 3,
  135605. 1, 0, 2, 4, 6, 8, 10, 12,
  135606. 14, 16, 18,
  135607. };
  135608. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135609. _vq_quantthresh__44c9_s_p9_0,
  135610. _vq_quantmap__44c9_s_p9_0,
  135611. 19,
  135612. 19
  135613. };
  135614. static static_codebook _44c9_s_p9_0 = {
  135615. 2, 361,
  135616. _vq_lengthlist__44c9_s_p9_0,
  135617. 1, -508535424, 1631393792, 5, 0,
  135618. _vq_quantlist__44c9_s_p9_0,
  135619. NULL,
  135620. &_vq_auxt__44c9_s_p9_0,
  135621. NULL,
  135622. 0
  135623. };
  135624. static long _vq_quantlist__44c9_s_p9_1[] = {
  135625. 9,
  135626. 8,
  135627. 10,
  135628. 7,
  135629. 11,
  135630. 6,
  135631. 12,
  135632. 5,
  135633. 13,
  135634. 4,
  135635. 14,
  135636. 3,
  135637. 15,
  135638. 2,
  135639. 16,
  135640. 1,
  135641. 17,
  135642. 0,
  135643. 18,
  135644. };
  135645. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135646. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135647. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135648. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135649. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135650. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135651. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135652. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135653. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135654. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135655. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135656. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135657. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135658. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135659. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135660. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135661. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135662. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135663. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135664. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135665. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135666. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135667. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135668. 13,13,13,14,13,14,15,15,15,
  135669. };
  135670. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135671. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135672. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135673. 367.5, 416.5,
  135674. };
  135675. static long _vq_quantmap__44c9_s_p9_1[] = {
  135676. 17, 15, 13, 11, 9, 7, 5, 3,
  135677. 1, 0, 2, 4, 6, 8, 10, 12,
  135678. 14, 16, 18,
  135679. };
  135680. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135681. _vq_quantthresh__44c9_s_p9_1,
  135682. _vq_quantmap__44c9_s_p9_1,
  135683. 19,
  135684. 19
  135685. };
  135686. static static_codebook _44c9_s_p9_1 = {
  135687. 2, 361,
  135688. _vq_lengthlist__44c9_s_p9_1,
  135689. 1, -518287360, 1622704128, 5, 0,
  135690. _vq_quantlist__44c9_s_p9_1,
  135691. NULL,
  135692. &_vq_auxt__44c9_s_p9_1,
  135693. NULL,
  135694. 0
  135695. };
  135696. static long _vq_quantlist__44c9_s_p9_2[] = {
  135697. 24,
  135698. 23,
  135699. 25,
  135700. 22,
  135701. 26,
  135702. 21,
  135703. 27,
  135704. 20,
  135705. 28,
  135706. 19,
  135707. 29,
  135708. 18,
  135709. 30,
  135710. 17,
  135711. 31,
  135712. 16,
  135713. 32,
  135714. 15,
  135715. 33,
  135716. 14,
  135717. 34,
  135718. 13,
  135719. 35,
  135720. 12,
  135721. 36,
  135722. 11,
  135723. 37,
  135724. 10,
  135725. 38,
  135726. 9,
  135727. 39,
  135728. 8,
  135729. 40,
  135730. 7,
  135731. 41,
  135732. 6,
  135733. 42,
  135734. 5,
  135735. 43,
  135736. 4,
  135737. 44,
  135738. 3,
  135739. 45,
  135740. 2,
  135741. 46,
  135742. 1,
  135743. 47,
  135744. 0,
  135745. 48,
  135746. };
  135747. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135748. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135749. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135750. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135751. 7,
  135752. };
  135753. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135754. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135755. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135756. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135757. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135758. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135759. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135760. };
  135761. static long _vq_quantmap__44c9_s_p9_2[] = {
  135762. 47, 45, 43, 41, 39, 37, 35, 33,
  135763. 31, 29, 27, 25, 23, 21, 19, 17,
  135764. 15, 13, 11, 9, 7, 5, 3, 1,
  135765. 0, 2, 4, 6, 8, 10, 12, 14,
  135766. 16, 18, 20, 22, 24, 26, 28, 30,
  135767. 32, 34, 36, 38, 40, 42, 44, 46,
  135768. 48,
  135769. };
  135770. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135771. _vq_quantthresh__44c9_s_p9_2,
  135772. _vq_quantmap__44c9_s_p9_2,
  135773. 49,
  135774. 49
  135775. };
  135776. static static_codebook _44c9_s_p9_2 = {
  135777. 1, 49,
  135778. _vq_lengthlist__44c9_s_p9_2,
  135779. 1, -526909440, 1611661312, 6, 0,
  135780. _vq_quantlist__44c9_s_p9_2,
  135781. NULL,
  135782. &_vq_auxt__44c9_s_p9_2,
  135783. NULL,
  135784. 0
  135785. };
  135786. static long _huff_lengthlist__44c9_s_short[] = {
  135787. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135788. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135789. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135790. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135791. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135792. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135793. 9, 8,10,13,
  135794. };
  135795. static static_codebook _huff_book__44c9_s_short = {
  135796. 2, 100,
  135797. _huff_lengthlist__44c9_s_short,
  135798. 0, 0, 0, 0, 0,
  135799. NULL,
  135800. NULL,
  135801. NULL,
  135802. NULL,
  135803. 0
  135804. };
  135805. static long _huff_lengthlist__44c0_s_long[] = {
  135806. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135807. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135808. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135809. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135810. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135811. 12,
  135812. };
  135813. static static_codebook _huff_book__44c0_s_long = {
  135814. 2, 81,
  135815. _huff_lengthlist__44c0_s_long,
  135816. 0, 0, 0, 0, 0,
  135817. NULL,
  135818. NULL,
  135819. NULL,
  135820. NULL,
  135821. 0
  135822. };
  135823. static long _vq_quantlist__44c0_s_p1_0[] = {
  135824. 1,
  135825. 0,
  135826. 2,
  135827. };
  135828. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135829. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135830. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135834. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135835. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135839. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135840. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135875. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135880. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135885. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135921. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135926. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135930. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135931. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136239. 0,
  136240. };
  136241. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136242. -0.5, 0.5,
  136243. };
  136244. static long _vq_quantmap__44c0_s_p1_0[] = {
  136245. 1, 0, 2,
  136246. };
  136247. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136248. _vq_quantthresh__44c0_s_p1_0,
  136249. _vq_quantmap__44c0_s_p1_0,
  136250. 3,
  136251. 3
  136252. };
  136253. static static_codebook _44c0_s_p1_0 = {
  136254. 8, 6561,
  136255. _vq_lengthlist__44c0_s_p1_0,
  136256. 1, -535822336, 1611661312, 2, 0,
  136257. _vq_quantlist__44c0_s_p1_0,
  136258. NULL,
  136259. &_vq_auxt__44c0_s_p1_0,
  136260. NULL,
  136261. 0
  136262. };
  136263. static long _vq_quantlist__44c0_s_p2_0[] = {
  136264. 2,
  136265. 1,
  136266. 3,
  136267. 0,
  136268. 4,
  136269. };
  136270. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136271. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136277. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136310. 0,
  136311. };
  136312. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136313. -1.5, -0.5, 0.5, 1.5,
  136314. };
  136315. static long _vq_quantmap__44c0_s_p2_0[] = {
  136316. 3, 1, 0, 2, 4,
  136317. };
  136318. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136319. _vq_quantthresh__44c0_s_p2_0,
  136320. _vq_quantmap__44c0_s_p2_0,
  136321. 5,
  136322. 5
  136323. };
  136324. static static_codebook _44c0_s_p2_0 = {
  136325. 4, 625,
  136326. _vq_lengthlist__44c0_s_p2_0,
  136327. 1, -533725184, 1611661312, 3, 0,
  136328. _vq_quantlist__44c0_s_p2_0,
  136329. NULL,
  136330. &_vq_auxt__44c0_s_p2_0,
  136331. NULL,
  136332. 0
  136333. };
  136334. static long _vq_quantlist__44c0_s_p3_0[] = {
  136335. 4,
  136336. 3,
  136337. 5,
  136338. 2,
  136339. 6,
  136340. 1,
  136341. 7,
  136342. 0,
  136343. 8,
  136344. };
  136345. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136346. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136347. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136348. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136349. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136350. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136351. 0,
  136352. };
  136353. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136354. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136355. };
  136356. static long _vq_quantmap__44c0_s_p3_0[] = {
  136357. 7, 5, 3, 1, 0, 2, 4, 6,
  136358. 8,
  136359. };
  136360. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136361. _vq_quantthresh__44c0_s_p3_0,
  136362. _vq_quantmap__44c0_s_p3_0,
  136363. 9,
  136364. 9
  136365. };
  136366. static static_codebook _44c0_s_p3_0 = {
  136367. 2, 81,
  136368. _vq_lengthlist__44c0_s_p3_0,
  136369. 1, -531628032, 1611661312, 4, 0,
  136370. _vq_quantlist__44c0_s_p3_0,
  136371. NULL,
  136372. &_vq_auxt__44c0_s_p3_0,
  136373. NULL,
  136374. 0
  136375. };
  136376. static long _vq_quantlist__44c0_s_p4_0[] = {
  136377. 4,
  136378. 3,
  136379. 5,
  136380. 2,
  136381. 6,
  136382. 1,
  136383. 7,
  136384. 0,
  136385. 8,
  136386. };
  136387. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136388. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136389. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136390. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136391. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136392. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136393. 10,
  136394. };
  136395. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136396. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136397. };
  136398. static long _vq_quantmap__44c0_s_p4_0[] = {
  136399. 7, 5, 3, 1, 0, 2, 4, 6,
  136400. 8,
  136401. };
  136402. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136403. _vq_quantthresh__44c0_s_p4_0,
  136404. _vq_quantmap__44c0_s_p4_0,
  136405. 9,
  136406. 9
  136407. };
  136408. static static_codebook _44c0_s_p4_0 = {
  136409. 2, 81,
  136410. _vq_lengthlist__44c0_s_p4_0,
  136411. 1, -531628032, 1611661312, 4, 0,
  136412. _vq_quantlist__44c0_s_p4_0,
  136413. NULL,
  136414. &_vq_auxt__44c0_s_p4_0,
  136415. NULL,
  136416. 0
  136417. };
  136418. static long _vq_quantlist__44c0_s_p5_0[] = {
  136419. 8,
  136420. 7,
  136421. 9,
  136422. 6,
  136423. 10,
  136424. 5,
  136425. 11,
  136426. 4,
  136427. 12,
  136428. 3,
  136429. 13,
  136430. 2,
  136431. 14,
  136432. 1,
  136433. 15,
  136434. 0,
  136435. 16,
  136436. };
  136437. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136438. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136439. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136440. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136441. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136442. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136443. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136444. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136445. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136446. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136447. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136448. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136449. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136450. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136451. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136452. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136453. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136454. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136455. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136456. 14,
  136457. };
  136458. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136459. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136460. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136461. };
  136462. static long _vq_quantmap__44c0_s_p5_0[] = {
  136463. 15, 13, 11, 9, 7, 5, 3, 1,
  136464. 0, 2, 4, 6, 8, 10, 12, 14,
  136465. 16,
  136466. };
  136467. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136468. _vq_quantthresh__44c0_s_p5_0,
  136469. _vq_quantmap__44c0_s_p5_0,
  136470. 17,
  136471. 17
  136472. };
  136473. static static_codebook _44c0_s_p5_0 = {
  136474. 2, 289,
  136475. _vq_lengthlist__44c0_s_p5_0,
  136476. 1, -529530880, 1611661312, 5, 0,
  136477. _vq_quantlist__44c0_s_p5_0,
  136478. NULL,
  136479. &_vq_auxt__44c0_s_p5_0,
  136480. NULL,
  136481. 0
  136482. };
  136483. static long _vq_quantlist__44c0_s_p6_0[] = {
  136484. 1,
  136485. 0,
  136486. 2,
  136487. };
  136488. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136489. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136490. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136491. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136492. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136493. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136494. 10,
  136495. };
  136496. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136497. -5.5, 5.5,
  136498. };
  136499. static long _vq_quantmap__44c0_s_p6_0[] = {
  136500. 1, 0, 2,
  136501. };
  136502. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136503. _vq_quantthresh__44c0_s_p6_0,
  136504. _vq_quantmap__44c0_s_p6_0,
  136505. 3,
  136506. 3
  136507. };
  136508. static static_codebook _44c0_s_p6_0 = {
  136509. 4, 81,
  136510. _vq_lengthlist__44c0_s_p6_0,
  136511. 1, -529137664, 1618345984, 2, 0,
  136512. _vq_quantlist__44c0_s_p6_0,
  136513. NULL,
  136514. &_vq_auxt__44c0_s_p6_0,
  136515. NULL,
  136516. 0
  136517. };
  136518. static long _vq_quantlist__44c0_s_p6_1[] = {
  136519. 5,
  136520. 4,
  136521. 6,
  136522. 3,
  136523. 7,
  136524. 2,
  136525. 8,
  136526. 1,
  136527. 9,
  136528. 0,
  136529. 10,
  136530. };
  136531. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136532. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136533. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136534. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136535. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136536. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136537. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136538. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136539. 10,10,10, 8, 8, 8, 8, 8, 8,
  136540. };
  136541. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136542. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136543. 3.5, 4.5,
  136544. };
  136545. static long _vq_quantmap__44c0_s_p6_1[] = {
  136546. 9, 7, 5, 3, 1, 0, 2, 4,
  136547. 6, 8, 10,
  136548. };
  136549. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136550. _vq_quantthresh__44c0_s_p6_1,
  136551. _vq_quantmap__44c0_s_p6_1,
  136552. 11,
  136553. 11
  136554. };
  136555. static static_codebook _44c0_s_p6_1 = {
  136556. 2, 121,
  136557. _vq_lengthlist__44c0_s_p6_1,
  136558. 1, -531365888, 1611661312, 4, 0,
  136559. _vq_quantlist__44c0_s_p6_1,
  136560. NULL,
  136561. &_vq_auxt__44c0_s_p6_1,
  136562. NULL,
  136563. 0
  136564. };
  136565. static long _vq_quantlist__44c0_s_p7_0[] = {
  136566. 6,
  136567. 5,
  136568. 7,
  136569. 4,
  136570. 8,
  136571. 3,
  136572. 9,
  136573. 2,
  136574. 10,
  136575. 1,
  136576. 11,
  136577. 0,
  136578. 12,
  136579. };
  136580. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136581. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136582. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136583. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136584. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136585. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136586. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136587. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136588. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136589. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136590. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136591. 0,12,12,11,11,12,12,13,13,
  136592. };
  136593. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136594. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136595. 12.5, 17.5, 22.5, 27.5,
  136596. };
  136597. static long _vq_quantmap__44c0_s_p7_0[] = {
  136598. 11, 9, 7, 5, 3, 1, 0, 2,
  136599. 4, 6, 8, 10, 12,
  136600. };
  136601. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136602. _vq_quantthresh__44c0_s_p7_0,
  136603. _vq_quantmap__44c0_s_p7_0,
  136604. 13,
  136605. 13
  136606. };
  136607. static static_codebook _44c0_s_p7_0 = {
  136608. 2, 169,
  136609. _vq_lengthlist__44c0_s_p7_0,
  136610. 1, -526516224, 1616117760, 4, 0,
  136611. _vq_quantlist__44c0_s_p7_0,
  136612. NULL,
  136613. &_vq_auxt__44c0_s_p7_0,
  136614. NULL,
  136615. 0
  136616. };
  136617. static long _vq_quantlist__44c0_s_p7_1[] = {
  136618. 2,
  136619. 1,
  136620. 3,
  136621. 0,
  136622. 4,
  136623. };
  136624. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136625. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136626. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136627. };
  136628. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136629. -1.5, -0.5, 0.5, 1.5,
  136630. };
  136631. static long _vq_quantmap__44c0_s_p7_1[] = {
  136632. 3, 1, 0, 2, 4,
  136633. };
  136634. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136635. _vq_quantthresh__44c0_s_p7_1,
  136636. _vq_quantmap__44c0_s_p7_1,
  136637. 5,
  136638. 5
  136639. };
  136640. static static_codebook _44c0_s_p7_1 = {
  136641. 2, 25,
  136642. _vq_lengthlist__44c0_s_p7_1,
  136643. 1, -533725184, 1611661312, 3, 0,
  136644. _vq_quantlist__44c0_s_p7_1,
  136645. NULL,
  136646. &_vq_auxt__44c0_s_p7_1,
  136647. NULL,
  136648. 0
  136649. };
  136650. static long _vq_quantlist__44c0_s_p8_0[] = {
  136651. 2,
  136652. 1,
  136653. 3,
  136654. 0,
  136655. 4,
  136656. };
  136657. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136658. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136659. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136660. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136661. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136662. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136663. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136664. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136665. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136666. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136667. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136668. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136669. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136670. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136671. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136672. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136673. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136674. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136675. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136676. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136677. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136678. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136679. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136680. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136681. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136682. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136683. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136684. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136685. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136686. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136687. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136688. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136689. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136690. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136691. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136692. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136693. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136694. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136695. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136696. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136697. 11,
  136698. };
  136699. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136700. -331.5, -110.5, 110.5, 331.5,
  136701. };
  136702. static long _vq_quantmap__44c0_s_p8_0[] = {
  136703. 3, 1, 0, 2, 4,
  136704. };
  136705. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136706. _vq_quantthresh__44c0_s_p8_0,
  136707. _vq_quantmap__44c0_s_p8_0,
  136708. 5,
  136709. 5
  136710. };
  136711. static static_codebook _44c0_s_p8_0 = {
  136712. 4, 625,
  136713. _vq_lengthlist__44c0_s_p8_0,
  136714. 1, -518283264, 1627103232, 3, 0,
  136715. _vq_quantlist__44c0_s_p8_0,
  136716. NULL,
  136717. &_vq_auxt__44c0_s_p8_0,
  136718. NULL,
  136719. 0
  136720. };
  136721. static long _vq_quantlist__44c0_s_p8_1[] = {
  136722. 6,
  136723. 5,
  136724. 7,
  136725. 4,
  136726. 8,
  136727. 3,
  136728. 9,
  136729. 2,
  136730. 10,
  136731. 1,
  136732. 11,
  136733. 0,
  136734. 12,
  136735. };
  136736. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136737. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136738. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136739. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136740. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136741. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136742. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136743. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136744. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136745. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136746. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136747. 16,13,13,12,12,14,14,15,13,
  136748. };
  136749. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136750. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136751. 42.5, 59.5, 76.5, 93.5,
  136752. };
  136753. static long _vq_quantmap__44c0_s_p8_1[] = {
  136754. 11, 9, 7, 5, 3, 1, 0, 2,
  136755. 4, 6, 8, 10, 12,
  136756. };
  136757. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136758. _vq_quantthresh__44c0_s_p8_1,
  136759. _vq_quantmap__44c0_s_p8_1,
  136760. 13,
  136761. 13
  136762. };
  136763. static static_codebook _44c0_s_p8_1 = {
  136764. 2, 169,
  136765. _vq_lengthlist__44c0_s_p8_1,
  136766. 1, -522616832, 1620115456, 4, 0,
  136767. _vq_quantlist__44c0_s_p8_1,
  136768. NULL,
  136769. &_vq_auxt__44c0_s_p8_1,
  136770. NULL,
  136771. 0
  136772. };
  136773. static long _vq_quantlist__44c0_s_p8_2[] = {
  136774. 8,
  136775. 7,
  136776. 9,
  136777. 6,
  136778. 10,
  136779. 5,
  136780. 11,
  136781. 4,
  136782. 12,
  136783. 3,
  136784. 13,
  136785. 2,
  136786. 14,
  136787. 1,
  136788. 15,
  136789. 0,
  136790. 16,
  136791. };
  136792. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136793. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136794. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136795. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136796. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136797. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136798. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136799. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136800. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136801. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136802. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136803. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136804. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136805. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136806. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136807. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136808. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136809. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136810. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136811. 10,
  136812. };
  136813. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136814. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136815. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136816. };
  136817. static long _vq_quantmap__44c0_s_p8_2[] = {
  136818. 15, 13, 11, 9, 7, 5, 3, 1,
  136819. 0, 2, 4, 6, 8, 10, 12, 14,
  136820. 16,
  136821. };
  136822. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136823. _vq_quantthresh__44c0_s_p8_2,
  136824. _vq_quantmap__44c0_s_p8_2,
  136825. 17,
  136826. 17
  136827. };
  136828. static static_codebook _44c0_s_p8_2 = {
  136829. 2, 289,
  136830. _vq_lengthlist__44c0_s_p8_2,
  136831. 1, -529530880, 1611661312, 5, 0,
  136832. _vq_quantlist__44c0_s_p8_2,
  136833. NULL,
  136834. &_vq_auxt__44c0_s_p8_2,
  136835. NULL,
  136836. 0
  136837. };
  136838. static long _huff_lengthlist__44c0_s_short[] = {
  136839. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136840. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136841. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136842. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136843. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136844. 12,
  136845. };
  136846. static static_codebook _huff_book__44c0_s_short = {
  136847. 2, 81,
  136848. _huff_lengthlist__44c0_s_short,
  136849. 0, 0, 0, 0, 0,
  136850. NULL,
  136851. NULL,
  136852. NULL,
  136853. NULL,
  136854. 0
  136855. };
  136856. static long _huff_lengthlist__44c0_sm_long[] = {
  136857. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136858. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136859. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136860. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136861. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136862. 13,
  136863. };
  136864. static static_codebook _huff_book__44c0_sm_long = {
  136865. 2, 81,
  136866. _huff_lengthlist__44c0_sm_long,
  136867. 0, 0, 0, 0, 0,
  136868. NULL,
  136869. NULL,
  136870. NULL,
  136871. NULL,
  136872. 0
  136873. };
  136874. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136875. 1,
  136876. 0,
  136877. 2,
  136878. };
  136879. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136880. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136881. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136885. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136886. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136890. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136891. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136926. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136931. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136936. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136972. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136977. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136981. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136982. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137290. 0,
  137291. };
  137292. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137293. -0.5, 0.5,
  137294. };
  137295. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137296. 1, 0, 2,
  137297. };
  137298. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137299. _vq_quantthresh__44c0_sm_p1_0,
  137300. _vq_quantmap__44c0_sm_p1_0,
  137301. 3,
  137302. 3
  137303. };
  137304. static static_codebook _44c0_sm_p1_0 = {
  137305. 8, 6561,
  137306. _vq_lengthlist__44c0_sm_p1_0,
  137307. 1, -535822336, 1611661312, 2, 0,
  137308. _vq_quantlist__44c0_sm_p1_0,
  137309. NULL,
  137310. &_vq_auxt__44c0_sm_p1_0,
  137311. NULL,
  137312. 0
  137313. };
  137314. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137315. 2,
  137316. 1,
  137317. 3,
  137318. 0,
  137319. 4,
  137320. };
  137321. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137322. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137325. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137328. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137361. 0,
  137362. };
  137363. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137364. -1.5, -0.5, 0.5, 1.5,
  137365. };
  137366. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137367. 3, 1, 0, 2, 4,
  137368. };
  137369. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137370. _vq_quantthresh__44c0_sm_p2_0,
  137371. _vq_quantmap__44c0_sm_p2_0,
  137372. 5,
  137373. 5
  137374. };
  137375. static static_codebook _44c0_sm_p2_0 = {
  137376. 4, 625,
  137377. _vq_lengthlist__44c0_sm_p2_0,
  137378. 1, -533725184, 1611661312, 3, 0,
  137379. _vq_quantlist__44c0_sm_p2_0,
  137380. NULL,
  137381. &_vq_auxt__44c0_sm_p2_0,
  137382. NULL,
  137383. 0
  137384. };
  137385. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137386. 4,
  137387. 3,
  137388. 5,
  137389. 2,
  137390. 6,
  137391. 1,
  137392. 7,
  137393. 0,
  137394. 8,
  137395. };
  137396. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137397. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137398. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137399. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137400. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137401. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137402. 0,
  137403. };
  137404. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137405. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137406. };
  137407. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137408. 7, 5, 3, 1, 0, 2, 4, 6,
  137409. 8,
  137410. };
  137411. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137412. _vq_quantthresh__44c0_sm_p3_0,
  137413. _vq_quantmap__44c0_sm_p3_0,
  137414. 9,
  137415. 9
  137416. };
  137417. static static_codebook _44c0_sm_p3_0 = {
  137418. 2, 81,
  137419. _vq_lengthlist__44c0_sm_p3_0,
  137420. 1, -531628032, 1611661312, 4, 0,
  137421. _vq_quantlist__44c0_sm_p3_0,
  137422. NULL,
  137423. &_vq_auxt__44c0_sm_p3_0,
  137424. NULL,
  137425. 0
  137426. };
  137427. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137428. 4,
  137429. 3,
  137430. 5,
  137431. 2,
  137432. 6,
  137433. 1,
  137434. 7,
  137435. 0,
  137436. 8,
  137437. };
  137438. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137439. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137440. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137441. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137442. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137443. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137444. 11,
  137445. };
  137446. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137447. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137448. };
  137449. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137450. 7, 5, 3, 1, 0, 2, 4, 6,
  137451. 8,
  137452. };
  137453. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137454. _vq_quantthresh__44c0_sm_p4_0,
  137455. _vq_quantmap__44c0_sm_p4_0,
  137456. 9,
  137457. 9
  137458. };
  137459. static static_codebook _44c0_sm_p4_0 = {
  137460. 2, 81,
  137461. _vq_lengthlist__44c0_sm_p4_0,
  137462. 1, -531628032, 1611661312, 4, 0,
  137463. _vq_quantlist__44c0_sm_p4_0,
  137464. NULL,
  137465. &_vq_auxt__44c0_sm_p4_0,
  137466. NULL,
  137467. 0
  137468. };
  137469. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137470. 8,
  137471. 7,
  137472. 9,
  137473. 6,
  137474. 10,
  137475. 5,
  137476. 11,
  137477. 4,
  137478. 12,
  137479. 3,
  137480. 13,
  137481. 2,
  137482. 14,
  137483. 1,
  137484. 15,
  137485. 0,
  137486. 16,
  137487. };
  137488. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137489. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137490. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137491. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137492. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137493. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137494. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137495. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137496. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137497. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137498. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137499. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137500. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137501. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137502. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137503. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137504. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137505. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137506. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137507. 14,
  137508. };
  137509. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137510. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137511. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137512. };
  137513. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137514. 15, 13, 11, 9, 7, 5, 3, 1,
  137515. 0, 2, 4, 6, 8, 10, 12, 14,
  137516. 16,
  137517. };
  137518. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137519. _vq_quantthresh__44c0_sm_p5_0,
  137520. _vq_quantmap__44c0_sm_p5_0,
  137521. 17,
  137522. 17
  137523. };
  137524. static static_codebook _44c0_sm_p5_0 = {
  137525. 2, 289,
  137526. _vq_lengthlist__44c0_sm_p5_0,
  137527. 1, -529530880, 1611661312, 5, 0,
  137528. _vq_quantlist__44c0_sm_p5_0,
  137529. NULL,
  137530. &_vq_auxt__44c0_sm_p5_0,
  137531. NULL,
  137532. 0
  137533. };
  137534. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137535. 1,
  137536. 0,
  137537. 2,
  137538. };
  137539. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137540. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137541. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137542. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137543. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137544. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137545. 11,
  137546. };
  137547. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137548. -5.5, 5.5,
  137549. };
  137550. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137551. 1, 0, 2,
  137552. };
  137553. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137554. _vq_quantthresh__44c0_sm_p6_0,
  137555. _vq_quantmap__44c0_sm_p6_0,
  137556. 3,
  137557. 3
  137558. };
  137559. static static_codebook _44c0_sm_p6_0 = {
  137560. 4, 81,
  137561. _vq_lengthlist__44c0_sm_p6_0,
  137562. 1, -529137664, 1618345984, 2, 0,
  137563. _vq_quantlist__44c0_sm_p6_0,
  137564. NULL,
  137565. &_vq_auxt__44c0_sm_p6_0,
  137566. NULL,
  137567. 0
  137568. };
  137569. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137570. 5,
  137571. 4,
  137572. 6,
  137573. 3,
  137574. 7,
  137575. 2,
  137576. 8,
  137577. 1,
  137578. 9,
  137579. 0,
  137580. 10,
  137581. };
  137582. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137583. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137584. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137585. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137586. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137587. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137588. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137589. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137590. 10,10,10, 8, 8, 8, 8, 8, 8,
  137591. };
  137592. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137593. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137594. 3.5, 4.5,
  137595. };
  137596. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137597. 9, 7, 5, 3, 1, 0, 2, 4,
  137598. 6, 8, 10,
  137599. };
  137600. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137601. _vq_quantthresh__44c0_sm_p6_1,
  137602. _vq_quantmap__44c0_sm_p6_1,
  137603. 11,
  137604. 11
  137605. };
  137606. static static_codebook _44c0_sm_p6_1 = {
  137607. 2, 121,
  137608. _vq_lengthlist__44c0_sm_p6_1,
  137609. 1, -531365888, 1611661312, 4, 0,
  137610. _vq_quantlist__44c0_sm_p6_1,
  137611. NULL,
  137612. &_vq_auxt__44c0_sm_p6_1,
  137613. NULL,
  137614. 0
  137615. };
  137616. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137617. 6,
  137618. 5,
  137619. 7,
  137620. 4,
  137621. 8,
  137622. 3,
  137623. 9,
  137624. 2,
  137625. 10,
  137626. 1,
  137627. 11,
  137628. 0,
  137629. 12,
  137630. };
  137631. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137632. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137633. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137634. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137635. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137636. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137637. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137638. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137639. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137640. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137641. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137642. 0,12,12,11,11,13,12,14,14,
  137643. };
  137644. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137645. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137646. 12.5, 17.5, 22.5, 27.5,
  137647. };
  137648. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137649. 11, 9, 7, 5, 3, 1, 0, 2,
  137650. 4, 6, 8, 10, 12,
  137651. };
  137652. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137653. _vq_quantthresh__44c0_sm_p7_0,
  137654. _vq_quantmap__44c0_sm_p7_0,
  137655. 13,
  137656. 13
  137657. };
  137658. static static_codebook _44c0_sm_p7_0 = {
  137659. 2, 169,
  137660. _vq_lengthlist__44c0_sm_p7_0,
  137661. 1, -526516224, 1616117760, 4, 0,
  137662. _vq_quantlist__44c0_sm_p7_0,
  137663. NULL,
  137664. &_vq_auxt__44c0_sm_p7_0,
  137665. NULL,
  137666. 0
  137667. };
  137668. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137669. 2,
  137670. 1,
  137671. 3,
  137672. 0,
  137673. 4,
  137674. };
  137675. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137676. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137677. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137678. };
  137679. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137680. -1.5, -0.5, 0.5, 1.5,
  137681. };
  137682. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137683. 3, 1, 0, 2, 4,
  137684. };
  137685. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137686. _vq_quantthresh__44c0_sm_p7_1,
  137687. _vq_quantmap__44c0_sm_p7_1,
  137688. 5,
  137689. 5
  137690. };
  137691. static static_codebook _44c0_sm_p7_1 = {
  137692. 2, 25,
  137693. _vq_lengthlist__44c0_sm_p7_1,
  137694. 1, -533725184, 1611661312, 3, 0,
  137695. _vq_quantlist__44c0_sm_p7_1,
  137696. NULL,
  137697. &_vq_auxt__44c0_sm_p7_1,
  137698. NULL,
  137699. 0
  137700. };
  137701. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137702. 4,
  137703. 3,
  137704. 5,
  137705. 2,
  137706. 6,
  137707. 1,
  137708. 7,
  137709. 0,
  137710. 8,
  137711. };
  137712. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137713. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137714. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137715. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137716. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137717. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137718. 12,
  137719. };
  137720. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137721. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137722. };
  137723. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137724. 7, 5, 3, 1, 0, 2, 4, 6,
  137725. 8,
  137726. };
  137727. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137728. _vq_quantthresh__44c0_sm_p8_0,
  137729. _vq_quantmap__44c0_sm_p8_0,
  137730. 9,
  137731. 9
  137732. };
  137733. static static_codebook _44c0_sm_p8_0 = {
  137734. 2, 81,
  137735. _vq_lengthlist__44c0_sm_p8_0,
  137736. 1, -516186112, 1627103232, 4, 0,
  137737. _vq_quantlist__44c0_sm_p8_0,
  137738. NULL,
  137739. &_vq_auxt__44c0_sm_p8_0,
  137740. NULL,
  137741. 0
  137742. };
  137743. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137744. 6,
  137745. 5,
  137746. 7,
  137747. 4,
  137748. 8,
  137749. 3,
  137750. 9,
  137751. 2,
  137752. 10,
  137753. 1,
  137754. 11,
  137755. 0,
  137756. 12,
  137757. };
  137758. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137759. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137760. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137761. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137762. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137763. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137764. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137765. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137766. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137767. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137768. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137769. 20,13,13,12,12,16,13,15,13,
  137770. };
  137771. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137772. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137773. 42.5, 59.5, 76.5, 93.5,
  137774. };
  137775. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137776. 11, 9, 7, 5, 3, 1, 0, 2,
  137777. 4, 6, 8, 10, 12,
  137778. };
  137779. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137780. _vq_quantthresh__44c0_sm_p8_1,
  137781. _vq_quantmap__44c0_sm_p8_1,
  137782. 13,
  137783. 13
  137784. };
  137785. static static_codebook _44c0_sm_p8_1 = {
  137786. 2, 169,
  137787. _vq_lengthlist__44c0_sm_p8_1,
  137788. 1, -522616832, 1620115456, 4, 0,
  137789. _vq_quantlist__44c0_sm_p8_1,
  137790. NULL,
  137791. &_vq_auxt__44c0_sm_p8_1,
  137792. NULL,
  137793. 0
  137794. };
  137795. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137796. 8,
  137797. 7,
  137798. 9,
  137799. 6,
  137800. 10,
  137801. 5,
  137802. 11,
  137803. 4,
  137804. 12,
  137805. 3,
  137806. 13,
  137807. 2,
  137808. 14,
  137809. 1,
  137810. 15,
  137811. 0,
  137812. 16,
  137813. };
  137814. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137815. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137816. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137817. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137818. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137819. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137820. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137821. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137822. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137823. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137824. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137825. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137826. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137827. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137828. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137829. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137830. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137831. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137832. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137833. 9,
  137834. };
  137835. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137836. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137837. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137838. };
  137839. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137840. 15, 13, 11, 9, 7, 5, 3, 1,
  137841. 0, 2, 4, 6, 8, 10, 12, 14,
  137842. 16,
  137843. };
  137844. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137845. _vq_quantthresh__44c0_sm_p8_2,
  137846. _vq_quantmap__44c0_sm_p8_2,
  137847. 17,
  137848. 17
  137849. };
  137850. static static_codebook _44c0_sm_p8_2 = {
  137851. 2, 289,
  137852. _vq_lengthlist__44c0_sm_p8_2,
  137853. 1, -529530880, 1611661312, 5, 0,
  137854. _vq_quantlist__44c0_sm_p8_2,
  137855. NULL,
  137856. &_vq_auxt__44c0_sm_p8_2,
  137857. NULL,
  137858. 0
  137859. };
  137860. static long _huff_lengthlist__44c0_sm_short[] = {
  137861. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137862. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137863. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137864. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137865. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137866. 12,
  137867. };
  137868. static static_codebook _huff_book__44c0_sm_short = {
  137869. 2, 81,
  137870. _huff_lengthlist__44c0_sm_short,
  137871. 0, 0, 0, 0, 0,
  137872. NULL,
  137873. NULL,
  137874. NULL,
  137875. NULL,
  137876. 0
  137877. };
  137878. static long _huff_lengthlist__44c1_s_long[] = {
  137879. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137880. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137881. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137882. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137883. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137884. 11,
  137885. };
  137886. static static_codebook _huff_book__44c1_s_long = {
  137887. 2, 81,
  137888. _huff_lengthlist__44c1_s_long,
  137889. 0, 0, 0, 0, 0,
  137890. NULL,
  137891. NULL,
  137892. NULL,
  137893. NULL,
  137894. 0
  137895. };
  137896. static long _vq_quantlist__44c1_s_p1_0[] = {
  137897. 1,
  137898. 0,
  137899. 2,
  137900. };
  137901. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137902. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137903. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137907. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137908. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137912. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137913. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  137948. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137953. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  137954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  137958. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137994. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137998. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137999. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  138000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138003. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138004. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138312. 0,
  138313. };
  138314. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138315. -0.5, 0.5,
  138316. };
  138317. static long _vq_quantmap__44c1_s_p1_0[] = {
  138318. 1, 0, 2,
  138319. };
  138320. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138321. _vq_quantthresh__44c1_s_p1_0,
  138322. _vq_quantmap__44c1_s_p1_0,
  138323. 3,
  138324. 3
  138325. };
  138326. static static_codebook _44c1_s_p1_0 = {
  138327. 8, 6561,
  138328. _vq_lengthlist__44c1_s_p1_0,
  138329. 1, -535822336, 1611661312, 2, 0,
  138330. _vq_quantlist__44c1_s_p1_0,
  138331. NULL,
  138332. &_vq_auxt__44c1_s_p1_0,
  138333. NULL,
  138334. 0
  138335. };
  138336. static long _vq_quantlist__44c1_s_p2_0[] = {
  138337. 2,
  138338. 1,
  138339. 3,
  138340. 0,
  138341. 4,
  138342. };
  138343. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138344. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138347. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138350. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138383. 0,
  138384. };
  138385. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138386. -1.5, -0.5, 0.5, 1.5,
  138387. };
  138388. static long _vq_quantmap__44c1_s_p2_0[] = {
  138389. 3, 1, 0, 2, 4,
  138390. };
  138391. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138392. _vq_quantthresh__44c1_s_p2_0,
  138393. _vq_quantmap__44c1_s_p2_0,
  138394. 5,
  138395. 5
  138396. };
  138397. static static_codebook _44c1_s_p2_0 = {
  138398. 4, 625,
  138399. _vq_lengthlist__44c1_s_p2_0,
  138400. 1, -533725184, 1611661312, 3, 0,
  138401. _vq_quantlist__44c1_s_p2_0,
  138402. NULL,
  138403. &_vq_auxt__44c1_s_p2_0,
  138404. NULL,
  138405. 0
  138406. };
  138407. static long _vq_quantlist__44c1_s_p3_0[] = {
  138408. 4,
  138409. 3,
  138410. 5,
  138411. 2,
  138412. 6,
  138413. 1,
  138414. 7,
  138415. 0,
  138416. 8,
  138417. };
  138418. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138419. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138420. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138421. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138422. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138423. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138424. 0,
  138425. };
  138426. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138427. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138428. };
  138429. static long _vq_quantmap__44c1_s_p3_0[] = {
  138430. 7, 5, 3, 1, 0, 2, 4, 6,
  138431. 8,
  138432. };
  138433. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138434. _vq_quantthresh__44c1_s_p3_0,
  138435. _vq_quantmap__44c1_s_p3_0,
  138436. 9,
  138437. 9
  138438. };
  138439. static static_codebook _44c1_s_p3_0 = {
  138440. 2, 81,
  138441. _vq_lengthlist__44c1_s_p3_0,
  138442. 1, -531628032, 1611661312, 4, 0,
  138443. _vq_quantlist__44c1_s_p3_0,
  138444. NULL,
  138445. &_vq_auxt__44c1_s_p3_0,
  138446. NULL,
  138447. 0
  138448. };
  138449. static long _vq_quantlist__44c1_s_p4_0[] = {
  138450. 4,
  138451. 3,
  138452. 5,
  138453. 2,
  138454. 6,
  138455. 1,
  138456. 7,
  138457. 0,
  138458. 8,
  138459. };
  138460. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138461. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138462. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138463. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138464. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138465. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138466. 11,
  138467. };
  138468. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138469. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138470. };
  138471. static long _vq_quantmap__44c1_s_p4_0[] = {
  138472. 7, 5, 3, 1, 0, 2, 4, 6,
  138473. 8,
  138474. };
  138475. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138476. _vq_quantthresh__44c1_s_p4_0,
  138477. _vq_quantmap__44c1_s_p4_0,
  138478. 9,
  138479. 9
  138480. };
  138481. static static_codebook _44c1_s_p4_0 = {
  138482. 2, 81,
  138483. _vq_lengthlist__44c1_s_p4_0,
  138484. 1, -531628032, 1611661312, 4, 0,
  138485. _vq_quantlist__44c1_s_p4_0,
  138486. NULL,
  138487. &_vq_auxt__44c1_s_p4_0,
  138488. NULL,
  138489. 0
  138490. };
  138491. static long _vq_quantlist__44c1_s_p5_0[] = {
  138492. 8,
  138493. 7,
  138494. 9,
  138495. 6,
  138496. 10,
  138497. 5,
  138498. 11,
  138499. 4,
  138500. 12,
  138501. 3,
  138502. 13,
  138503. 2,
  138504. 14,
  138505. 1,
  138506. 15,
  138507. 0,
  138508. 16,
  138509. };
  138510. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138511. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138512. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138513. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138514. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138515. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138516. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138517. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138518. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138519. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138520. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138521. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138522. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138523. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138524. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138525. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138526. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138527. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138528. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138529. 14,
  138530. };
  138531. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138532. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138533. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138534. };
  138535. static long _vq_quantmap__44c1_s_p5_0[] = {
  138536. 15, 13, 11, 9, 7, 5, 3, 1,
  138537. 0, 2, 4, 6, 8, 10, 12, 14,
  138538. 16,
  138539. };
  138540. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138541. _vq_quantthresh__44c1_s_p5_0,
  138542. _vq_quantmap__44c1_s_p5_0,
  138543. 17,
  138544. 17
  138545. };
  138546. static static_codebook _44c1_s_p5_0 = {
  138547. 2, 289,
  138548. _vq_lengthlist__44c1_s_p5_0,
  138549. 1, -529530880, 1611661312, 5, 0,
  138550. _vq_quantlist__44c1_s_p5_0,
  138551. NULL,
  138552. &_vq_auxt__44c1_s_p5_0,
  138553. NULL,
  138554. 0
  138555. };
  138556. static long _vq_quantlist__44c1_s_p6_0[] = {
  138557. 1,
  138558. 0,
  138559. 2,
  138560. };
  138561. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138562. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138563. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138564. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138565. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138566. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138567. 11,
  138568. };
  138569. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138570. -5.5, 5.5,
  138571. };
  138572. static long _vq_quantmap__44c1_s_p6_0[] = {
  138573. 1, 0, 2,
  138574. };
  138575. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138576. _vq_quantthresh__44c1_s_p6_0,
  138577. _vq_quantmap__44c1_s_p6_0,
  138578. 3,
  138579. 3
  138580. };
  138581. static static_codebook _44c1_s_p6_0 = {
  138582. 4, 81,
  138583. _vq_lengthlist__44c1_s_p6_0,
  138584. 1, -529137664, 1618345984, 2, 0,
  138585. _vq_quantlist__44c1_s_p6_0,
  138586. NULL,
  138587. &_vq_auxt__44c1_s_p6_0,
  138588. NULL,
  138589. 0
  138590. };
  138591. static long _vq_quantlist__44c1_s_p6_1[] = {
  138592. 5,
  138593. 4,
  138594. 6,
  138595. 3,
  138596. 7,
  138597. 2,
  138598. 8,
  138599. 1,
  138600. 9,
  138601. 0,
  138602. 10,
  138603. };
  138604. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138605. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138606. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138607. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138608. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138609. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138610. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138611. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138612. 10,10,10, 8, 8, 8, 8, 8, 8,
  138613. };
  138614. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138615. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138616. 3.5, 4.5,
  138617. };
  138618. static long _vq_quantmap__44c1_s_p6_1[] = {
  138619. 9, 7, 5, 3, 1, 0, 2, 4,
  138620. 6, 8, 10,
  138621. };
  138622. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138623. _vq_quantthresh__44c1_s_p6_1,
  138624. _vq_quantmap__44c1_s_p6_1,
  138625. 11,
  138626. 11
  138627. };
  138628. static static_codebook _44c1_s_p6_1 = {
  138629. 2, 121,
  138630. _vq_lengthlist__44c1_s_p6_1,
  138631. 1, -531365888, 1611661312, 4, 0,
  138632. _vq_quantlist__44c1_s_p6_1,
  138633. NULL,
  138634. &_vq_auxt__44c1_s_p6_1,
  138635. NULL,
  138636. 0
  138637. };
  138638. static long _vq_quantlist__44c1_s_p7_0[] = {
  138639. 6,
  138640. 5,
  138641. 7,
  138642. 4,
  138643. 8,
  138644. 3,
  138645. 9,
  138646. 2,
  138647. 10,
  138648. 1,
  138649. 11,
  138650. 0,
  138651. 12,
  138652. };
  138653. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138654. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138655. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138656. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138657. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138658. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138659. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138660. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138661. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138662. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138663. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138664. 0,12,11,11,11,13,10,14,13,
  138665. };
  138666. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138667. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138668. 12.5, 17.5, 22.5, 27.5,
  138669. };
  138670. static long _vq_quantmap__44c1_s_p7_0[] = {
  138671. 11, 9, 7, 5, 3, 1, 0, 2,
  138672. 4, 6, 8, 10, 12,
  138673. };
  138674. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138675. _vq_quantthresh__44c1_s_p7_0,
  138676. _vq_quantmap__44c1_s_p7_0,
  138677. 13,
  138678. 13
  138679. };
  138680. static static_codebook _44c1_s_p7_0 = {
  138681. 2, 169,
  138682. _vq_lengthlist__44c1_s_p7_0,
  138683. 1, -526516224, 1616117760, 4, 0,
  138684. _vq_quantlist__44c1_s_p7_0,
  138685. NULL,
  138686. &_vq_auxt__44c1_s_p7_0,
  138687. NULL,
  138688. 0
  138689. };
  138690. static long _vq_quantlist__44c1_s_p7_1[] = {
  138691. 2,
  138692. 1,
  138693. 3,
  138694. 0,
  138695. 4,
  138696. };
  138697. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138698. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138699. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138700. };
  138701. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138702. -1.5, -0.5, 0.5, 1.5,
  138703. };
  138704. static long _vq_quantmap__44c1_s_p7_1[] = {
  138705. 3, 1, 0, 2, 4,
  138706. };
  138707. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138708. _vq_quantthresh__44c1_s_p7_1,
  138709. _vq_quantmap__44c1_s_p7_1,
  138710. 5,
  138711. 5
  138712. };
  138713. static static_codebook _44c1_s_p7_1 = {
  138714. 2, 25,
  138715. _vq_lengthlist__44c1_s_p7_1,
  138716. 1, -533725184, 1611661312, 3, 0,
  138717. _vq_quantlist__44c1_s_p7_1,
  138718. NULL,
  138719. &_vq_auxt__44c1_s_p7_1,
  138720. NULL,
  138721. 0
  138722. };
  138723. static long _vq_quantlist__44c1_s_p8_0[] = {
  138724. 6,
  138725. 5,
  138726. 7,
  138727. 4,
  138728. 8,
  138729. 3,
  138730. 9,
  138731. 2,
  138732. 10,
  138733. 1,
  138734. 11,
  138735. 0,
  138736. 12,
  138737. };
  138738. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138739. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138740. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138741. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138742. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138743. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138744. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138745. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138746. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138747. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138748. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138749. 10,10,10,10,10,10,10,10,10,
  138750. };
  138751. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138752. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138753. 552.5, 773.5, 994.5, 1215.5,
  138754. };
  138755. static long _vq_quantmap__44c1_s_p8_0[] = {
  138756. 11, 9, 7, 5, 3, 1, 0, 2,
  138757. 4, 6, 8, 10, 12,
  138758. };
  138759. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138760. _vq_quantthresh__44c1_s_p8_0,
  138761. _vq_quantmap__44c1_s_p8_0,
  138762. 13,
  138763. 13
  138764. };
  138765. static static_codebook _44c1_s_p8_0 = {
  138766. 2, 169,
  138767. _vq_lengthlist__44c1_s_p8_0,
  138768. 1, -514541568, 1627103232, 4, 0,
  138769. _vq_quantlist__44c1_s_p8_0,
  138770. NULL,
  138771. &_vq_auxt__44c1_s_p8_0,
  138772. NULL,
  138773. 0
  138774. };
  138775. static long _vq_quantlist__44c1_s_p8_1[] = {
  138776. 6,
  138777. 5,
  138778. 7,
  138779. 4,
  138780. 8,
  138781. 3,
  138782. 9,
  138783. 2,
  138784. 10,
  138785. 1,
  138786. 11,
  138787. 0,
  138788. 12,
  138789. };
  138790. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138791. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138792. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138793. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138794. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138795. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138796. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138797. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138798. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138799. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138800. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138801. 16,13,12,12,11,14,12,15,13,
  138802. };
  138803. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138804. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138805. 42.5, 59.5, 76.5, 93.5,
  138806. };
  138807. static long _vq_quantmap__44c1_s_p8_1[] = {
  138808. 11, 9, 7, 5, 3, 1, 0, 2,
  138809. 4, 6, 8, 10, 12,
  138810. };
  138811. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138812. _vq_quantthresh__44c1_s_p8_1,
  138813. _vq_quantmap__44c1_s_p8_1,
  138814. 13,
  138815. 13
  138816. };
  138817. static static_codebook _44c1_s_p8_1 = {
  138818. 2, 169,
  138819. _vq_lengthlist__44c1_s_p8_1,
  138820. 1, -522616832, 1620115456, 4, 0,
  138821. _vq_quantlist__44c1_s_p8_1,
  138822. NULL,
  138823. &_vq_auxt__44c1_s_p8_1,
  138824. NULL,
  138825. 0
  138826. };
  138827. static long _vq_quantlist__44c1_s_p8_2[] = {
  138828. 8,
  138829. 7,
  138830. 9,
  138831. 6,
  138832. 10,
  138833. 5,
  138834. 11,
  138835. 4,
  138836. 12,
  138837. 3,
  138838. 13,
  138839. 2,
  138840. 14,
  138841. 1,
  138842. 15,
  138843. 0,
  138844. 16,
  138845. };
  138846. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138847. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138848. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138849. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138850. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138851. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138852. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138853. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138854. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138855. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138856. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138857. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138858. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138859. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138860. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138861. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138862. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138863. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138864. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138865. 9,
  138866. };
  138867. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138868. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138869. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138870. };
  138871. static long _vq_quantmap__44c1_s_p8_2[] = {
  138872. 15, 13, 11, 9, 7, 5, 3, 1,
  138873. 0, 2, 4, 6, 8, 10, 12, 14,
  138874. 16,
  138875. };
  138876. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138877. _vq_quantthresh__44c1_s_p8_2,
  138878. _vq_quantmap__44c1_s_p8_2,
  138879. 17,
  138880. 17
  138881. };
  138882. static static_codebook _44c1_s_p8_2 = {
  138883. 2, 289,
  138884. _vq_lengthlist__44c1_s_p8_2,
  138885. 1, -529530880, 1611661312, 5, 0,
  138886. _vq_quantlist__44c1_s_p8_2,
  138887. NULL,
  138888. &_vq_auxt__44c1_s_p8_2,
  138889. NULL,
  138890. 0
  138891. };
  138892. static long _huff_lengthlist__44c1_s_short[] = {
  138893. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138894. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138895. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138896. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138897. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138898. 11,
  138899. };
  138900. static static_codebook _huff_book__44c1_s_short = {
  138901. 2, 81,
  138902. _huff_lengthlist__44c1_s_short,
  138903. 0, 0, 0, 0, 0,
  138904. NULL,
  138905. NULL,
  138906. NULL,
  138907. NULL,
  138908. 0
  138909. };
  138910. static long _huff_lengthlist__44c1_sm_long[] = {
  138911. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138912. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138913. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138914. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138915. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138916. 11,
  138917. };
  138918. static static_codebook _huff_book__44c1_sm_long = {
  138919. 2, 81,
  138920. _huff_lengthlist__44c1_sm_long,
  138921. 0, 0, 0, 0, 0,
  138922. NULL,
  138923. NULL,
  138924. NULL,
  138925. NULL,
  138926. 0
  138927. };
  138928. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138929. 1,
  138930. 0,
  138931. 2,
  138932. };
  138933. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138934. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138935. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138939. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138940. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138944. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138945. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  138980. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138985. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  138990. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139026. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139030. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139031. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  139032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139035. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139036. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  139037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139344. 0,
  139345. };
  139346. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139347. -0.5, 0.5,
  139348. };
  139349. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139350. 1, 0, 2,
  139351. };
  139352. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139353. _vq_quantthresh__44c1_sm_p1_0,
  139354. _vq_quantmap__44c1_sm_p1_0,
  139355. 3,
  139356. 3
  139357. };
  139358. static static_codebook _44c1_sm_p1_0 = {
  139359. 8, 6561,
  139360. _vq_lengthlist__44c1_sm_p1_0,
  139361. 1, -535822336, 1611661312, 2, 0,
  139362. _vq_quantlist__44c1_sm_p1_0,
  139363. NULL,
  139364. &_vq_auxt__44c1_sm_p1_0,
  139365. NULL,
  139366. 0
  139367. };
  139368. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139369. 2,
  139370. 1,
  139371. 3,
  139372. 0,
  139373. 4,
  139374. };
  139375. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139376. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139379. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139382. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139415. 0,
  139416. };
  139417. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139418. -1.5, -0.5, 0.5, 1.5,
  139419. };
  139420. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139421. 3, 1, 0, 2, 4,
  139422. };
  139423. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139424. _vq_quantthresh__44c1_sm_p2_0,
  139425. _vq_quantmap__44c1_sm_p2_0,
  139426. 5,
  139427. 5
  139428. };
  139429. static static_codebook _44c1_sm_p2_0 = {
  139430. 4, 625,
  139431. _vq_lengthlist__44c1_sm_p2_0,
  139432. 1, -533725184, 1611661312, 3, 0,
  139433. _vq_quantlist__44c1_sm_p2_0,
  139434. NULL,
  139435. &_vq_auxt__44c1_sm_p2_0,
  139436. NULL,
  139437. 0
  139438. };
  139439. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139440. 4,
  139441. 3,
  139442. 5,
  139443. 2,
  139444. 6,
  139445. 1,
  139446. 7,
  139447. 0,
  139448. 8,
  139449. };
  139450. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139451. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139452. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139453. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139454. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139455. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139456. 0,
  139457. };
  139458. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139459. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139460. };
  139461. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139462. 7, 5, 3, 1, 0, 2, 4, 6,
  139463. 8,
  139464. };
  139465. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139466. _vq_quantthresh__44c1_sm_p3_0,
  139467. _vq_quantmap__44c1_sm_p3_0,
  139468. 9,
  139469. 9
  139470. };
  139471. static static_codebook _44c1_sm_p3_0 = {
  139472. 2, 81,
  139473. _vq_lengthlist__44c1_sm_p3_0,
  139474. 1, -531628032, 1611661312, 4, 0,
  139475. _vq_quantlist__44c1_sm_p3_0,
  139476. NULL,
  139477. &_vq_auxt__44c1_sm_p3_0,
  139478. NULL,
  139479. 0
  139480. };
  139481. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139482. 4,
  139483. 3,
  139484. 5,
  139485. 2,
  139486. 6,
  139487. 1,
  139488. 7,
  139489. 0,
  139490. 8,
  139491. };
  139492. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139493. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139494. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139495. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139496. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139497. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139498. 11,
  139499. };
  139500. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139501. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139502. };
  139503. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139504. 7, 5, 3, 1, 0, 2, 4, 6,
  139505. 8,
  139506. };
  139507. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139508. _vq_quantthresh__44c1_sm_p4_0,
  139509. _vq_quantmap__44c1_sm_p4_0,
  139510. 9,
  139511. 9
  139512. };
  139513. static static_codebook _44c1_sm_p4_0 = {
  139514. 2, 81,
  139515. _vq_lengthlist__44c1_sm_p4_0,
  139516. 1, -531628032, 1611661312, 4, 0,
  139517. _vq_quantlist__44c1_sm_p4_0,
  139518. NULL,
  139519. &_vq_auxt__44c1_sm_p4_0,
  139520. NULL,
  139521. 0
  139522. };
  139523. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139524. 8,
  139525. 7,
  139526. 9,
  139527. 6,
  139528. 10,
  139529. 5,
  139530. 11,
  139531. 4,
  139532. 12,
  139533. 3,
  139534. 13,
  139535. 2,
  139536. 14,
  139537. 1,
  139538. 15,
  139539. 0,
  139540. 16,
  139541. };
  139542. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139543. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139544. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139545. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139546. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139547. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139548. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139549. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139550. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139551. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139552. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139553. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139554. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139555. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139556. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139557. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139558. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139559. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139560. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139561. 14,
  139562. };
  139563. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139564. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139565. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139566. };
  139567. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139568. 15, 13, 11, 9, 7, 5, 3, 1,
  139569. 0, 2, 4, 6, 8, 10, 12, 14,
  139570. 16,
  139571. };
  139572. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139573. _vq_quantthresh__44c1_sm_p5_0,
  139574. _vq_quantmap__44c1_sm_p5_0,
  139575. 17,
  139576. 17
  139577. };
  139578. static static_codebook _44c1_sm_p5_0 = {
  139579. 2, 289,
  139580. _vq_lengthlist__44c1_sm_p5_0,
  139581. 1, -529530880, 1611661312, 5, 0,
  139582. _vq_quantlist__44c1_sm_p5_0,
  139583. NULL,
  139584. &_vq_auxt__44c1_sm_p5_0,
  139585. NULL,
  139586. 0
  139587. };
  139588. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139589. 1,
  139590. 0,
  139591. 2,
  139592. };
  139593. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139594. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139595. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139596. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139597. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139598. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139599. 11,
  139600. };
  139601. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139602. -5.5, 5.5,
  139603. };
  139604. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139605. 1, 0, 2,
  139606. };
  139607. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139608. _vq_quantthresh__44c1_sm_p6_0,
  139609. _vq_quantmap__44c1_sm_p6_0,
  139610. 3,
  139611. 3
  139612. };
  139613. static static_codebook _44c1_sm_p6_0 = {
  139614. 4, 81,
  139615. _vq_lengthlist__44c1_sm_p6_0,
  139616. 1, -529137664, 1618345984, 2, 0,
  139617. _vq_quantlist__44c1_sm_p6_0,
  139618. NULL,
  139619. &_vq_auxt__44c1_sm_p6_0,
  139620. NULL,
  139621. 0
  139622. };
  139623. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139624. 5,
  139625. 4,
  139626. 6,
  139627. 3,
  139628. 7,
  139629. 2,
  139630. 8,
  139631. 1,
  139632. 9,
  139633. 0,
  139634. 10,
  139635. };
  139636. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139637. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139638. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139639. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139640. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139641. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139642. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139643. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139644. 10,10,10, 8, 8, 8, 8, 8, 8,
  139645. };
  139646. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139647. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139648. 3.5, 4.5,
  139649. };
  139650. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139651. 9, 7, 5, 3, 1, 0, 2, 4,
  139652. 6, 8, 10,
  139653. };
  139654. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139655. _vq_quantthresh__44c1_sm_p6_1,
  139656. _vq_quantmap__44c1_sm_p6_1,
  139657. 11,
  139658. 11
  139659. };
  139660. static static_codebook _44c1_sm_p6_1 = {
  139661. 2, 121,
  139662. _vq_lengthlist__44c1_sm_p6_1,
  139663. 1, -531365888, 1611661312, 4, 0,
  139664. _vq_quantlist__44c1_sm_p6_1,
  139665. NULL,
  139666. &_vq_auxt__44c1_sm_p6_1,
  139667. NULL,
  139668. 0
  139669. };
  139670. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139671. 6,
  139672. 5,
  139673. 7,
  139674. 4,
  139675. 8,
  139676. 3,
  139677. 9,
  139678. 2,
  139679. 10,
  139680. 1,
  139681. 11,
  139682. 0,
  139683. 12,
  139684. };
  139685. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139686. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139687. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139688. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139689. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139690. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139691. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139692. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139693. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139694. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139695. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139696. 0,12,12,11,11,13,12,14,13,
  139697. };
  139698. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139699. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139700. 12.5, 17.5, 22.5, 27.5,
  139701. };
  139702. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139703. 11, 9, 7, 5, 3, 1, 0, 2,
  139704. 4, 6, 8, 10, 12,
  139705. };
  139706. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139707. _vq_quantthresh__44c1_sm_p7_0,
  139708. _vq_quantmap__44c1_sm_p7_0,
  139709. 13,
  139710. 13
  139711. };
  139712. static static_codebook _44c1_sm_p7_0 = {
  139713. 2, 169,
  139714. _vq_lengthlist__44c1_sm_p7_0,
  139715. 1, -526516224, 1616117760, 4, 0,
  139716. _vq_quantlist__44c1_sm_p7_0,
  139717. NULL,
  139718. &_vq_auxt__44c1_sm_p7_0,
  139719. NULL,
  139720. 0
  139721. };
  139722. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139723. 2,
  139724. 1,
  139725. 3,
  139726. 0,
  139727. 4,
  139728. };
  139729. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139730. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139731. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139732. };
  139733. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139734. -1.5, -0.5, 0.5, 1.5,
  139735. };
  139736. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139737. 3, 1, 0, 2, 4,
  139738. };
  139739. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139740. _vq_quantthresh__44c1_sm_p7_1,
  139741. _vq_quantmap__44c1_sm_p7_1,
  139742. 5,
  139743. 5
  139744. };
  139745. static static_codebook _44c1_sm_p7_1 = {
  139746. 2, 25,
  139747. _vq_lengthlist__44c1_sm_p7_1,
  139748. 1, -533725184, 1611661312, 3, 0,
  139749. _vq_quantlist__44c1_sm_p7_1,
  139750. NULL,
  139751. &_vq_auxt__44c1_sm_p7_1,
  139752. NULL,
  139753. 0
  139754. };
  139755. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139756. 6,
  139757. 5,
  139758. 7,
  139759. 4,
  139760. 8,
  139761. 3,
  139762. 9,
  139763. 2,
  139764. 10,
  139765. 1,
  139766. 11,
  139767. 0,
  139768. 12,
  139769. };
  139770. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139771. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139772. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139773. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139774. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139775. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139776. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139777. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139778. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139779. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139780. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139781. 13,13,13,13,13,13,13,13,13,
  139782. };
  139783. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139784. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139785. 552.5, 773.5, 994.5, 1215.5,
  139786. };
  139787. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139788. 11, 9, 7, 5, 3, 1, 0, 2,
  139789. 4, 6, 8, 10, 12,
  139790. };
  139791. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139792. _vq_quantthresh__44c1_sm_p8_0,
  139793. _vq_quantmap__44c1_sm_p8_0,
  139794. 13,
  139795. 13
  139796. };
  139797. static static_codebook _44c1_sm_p8_0 = {
  139798. 2, 169,
  139799. _vq_lengthlist__44c1_sm_p8_0,
  139800. 1, -514541568, 1627103232, 4, 0,
  139801. _vq_quantlist__44c1_sm_p8_0,
  139802. NULL,
  139803. &_vq_auxt__44c1_sm_p8_0,
  139804. NULL,
  139805. 0
  139806. };
  139807. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139808. 6,
  139809. 5,
  139810. 7,
  139811. 4,
  139812. 8,
  139813. 3,
  139814. 9,
  139815. 2,
  139816. 10,
  139817. 1,
  139818. 11,
  139819. 0,
  139820. 12,
  139821. };
  139822. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139823. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139824. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139825. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139826. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139827. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139828. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139829. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139830. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139831. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139832. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139833. 20,13,12,12,12,14,12,14,13,
  139834. };
  139835. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139836. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139837. 42.5, 59.5, 76.5, 93.5,
  139838. };
  139839. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139840. 11, 9, 7, 5, 3, 1, 0, 2,
  139841. 4, 6, 8, 10, 12,
  139842. };
  139843. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139844. _vq_quantthresh__44c1_sm_p8_1,
  139845. _vq_quantmap__44c1_sm_p8_1,
  139846. 13,
  139847. 13
  139848. };
  139849. static static_codebook _44c1_sm_p8_1 = {
  139850. 2, 169,
  139851. _vq_lengthlist__44c1_sm_p8_1,
  139852. 1, -522616832, 1620115456, 4, 0,
  139853. _vq_quantlist__44c1_sm_p8_1,
  139854. NULL,
  139855. &_vq_auxt__44c1_sm_p8_1,
  139856. NULL,
  139857. 0
  139858. };
  139859. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139860. 8,
  139861. 7,
  139862. 9,
  139863. 6,
  139864. 10,
  139865. 5,
  139866. 11,
  139867. 4,
  139868. 12,
  139869. 3,
  139870. 13,
  139871. 2,
  139872. 14,
  139873. 1,
  139874. 15,
  139875. 0,
  139876. 16,
  139877. };
  139878. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139879. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139880. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139881. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139882. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139883. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139884. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139885. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139886. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139887. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139888. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139889. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139890. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139891. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139892. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139893. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139894. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139895. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139896. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139897. 9,
  139898. };
  139899. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139900. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139901. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139902. };
  139903. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139904. 15, 13, 11, 9, 7, 5, 3, 1,
  139905. 0, 2, 4, 6, 8, 10, 12, 14,
  139906. 16,
  139907. };
  139908. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139909. _vq_quantthresh__44c1_sm_p8_2,
  139910. _vq_quantmap__44c1_sm_p8_2,
  139911. 17,
  139912. 17
  139913. };
  139914. static static_codebook _44c1_sm_p8_2 = {
  139915. 2, 289,
  139916. _vq_lengthlist__44c1_sm_p8_2,
  139917. 1, -529530880, 1611661312, 5, 0,
  139918. _vq_quantlist__44c1_sm_p8_2,
  139919. NULL,
  139920. &_vq_auxt__44c1_sm_p8_2,
  139921. NULL,
  139922. 0
  139923. };
  139924. static long _huff_lengthlist__44c1_sm_short[] = {
  139925. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139926. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139927. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139928. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139929. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139930. 11,
  139931. };
  139932. static static_codebook _huff_book__44c1_sm_short = {
  139933. 2, 81,
  139934. _huff_lengthlist__44c1_sm_short,
  139935. 0, 0, 0, 0, 0,
  139936. NULL,
  139937. NULL,
  139938. NULL,
  139939. NULL,
  139940. 0
  139941. };
  139942. static long _huff_lengthlist__44cn1_s_long[] = {
  139943. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139944. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139945. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139946. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139947. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139948. 20,
  139949. };
  139950. static static_codebook _huff_book__44cn1_s_long = {
  139951. 2, 81,
  139952. _huff_lengthlist__44cn1_s_long,
  139953. 0, 0, 0, 0, 0,
  139954. NULL,
  139955. NULL,
  139956. NULL,
  139957. NULL,
  139958. 0
  139959. };
  139960. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139961. 1,
  139962. 0,
  139963. 2,
  139964. };
  139965. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139966. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139967. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139971. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139972. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139976. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139977. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140012. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  140013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  140017. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  140022. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  140023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140058. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140062. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140063. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  140064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140067. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140068. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  140069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140376. 0,
  140377. };
  140378. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140379. -0.5, 0.5,
  140380. };
  140381. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140382. 1, 0, 2,
  140383. };
  140384. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140385. _vq_quantthresh__44cn1_s_p1_0,
  140386. _vq_quantmap__44cn1_s_p1_0,
  140387. 3,
  140388. 3
  140389. };
  140390. static static_codebook _44cn1_s_p1_0 = {
  140391. 8, 6561,
  140392. _vq_lengthlist__44cn1_s_p1_0,
  140393. 1, -535822336, 1611661312, 2, 0,
  140394. _vq_quantlist__44cn1_s_p1_0,
  140395. NULL,
  140396. &_vq_auxt__44cn1_s_p1_0,
  140397. NULL,
  140398. 0
  140399. };
  140400. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140401. 2,
  140402. 1,
  140403. 3,
  140404. 0,
  140405. 4,
  140406. };
  140407. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140408. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140411. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140414. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140447. 0,
  140448. };
  140449. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140450. -1.5, -0.5, 0.5, 1.5,
  140451. };
  140452. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140453. 3, 1, 0, 2, 4,
  140454. };
  140455. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140456. _vq_quantthresh__44cn1_s_p2_0,
  140457. _vq_quantmap__44cn1_s_p2_0,
  140458. 5,
  140459. 5
  140460. };
  140461. static static_codebook _44cn1_s_p2_0 = {
  140462. 4, 625,
  140463. _vq_lengthlist__44cn1_s_p2_0,
  140464. 1, -533725184, 1611661312, 3, 0,
  140465. _vq_quantlist__44cn1_s_p2_0,
  140466. NULL,
  140467. &_vq_auxt__44cn1_s_p2_0,
  140468. NULL,
  140469. 0
  140470. };
  140471. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140472. 4,
  140473. 3,
  140474. 5,
  140475. 2,
  140476. 6,
  140477. 1,
  140478. 7,
  140479. 0,
  140480. 8,
  140481. };
  140482. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140483. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140484. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140485. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140486. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140487. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140488. 0,
  140489. };
  140490. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140491. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140492. };
  140493. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140494. 7, 5, 3, 1, 0, 2, 4, 6,
  140495. 8,
  140496. };
  140497. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140498. _vq_quantthresh__44cn1_s_p3_0,
  140499. _vq_quantmap__44cn1_s_p3_0,
  140500. 9,
  140501. 9
  140502. };
  140503. static static_codebook _44cn1_s_p3_0 = {
  140504. 2, 81,
  140505. _vq_lengthlist__44cn1_s_p3_0,
  140506. 1, -531628032, 1611661312, 4, 0,
  140507. _vq_quantlist__44cn1_s_p3_0,
  140508. NULL,
  140509. &_vq_auxt__44cn1_s_p3_0,
  140510. NULL,
  140511. 0
  140512. };
  140513. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140514. 4,
  140515. 3,
  140516. 5,
  140517. 2,
  140518. 6,
  140519. 1,
  140520. 7,
  140521. 0,
  140522. 8,
  140523. };
  140524. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140525. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140526. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140527. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140528. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140529. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140530. 11,
  140531. };
  140532. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140533. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140534. };
  140535. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140536. 7, 5, 3, 1, 0, 2, 4, 6,
  140537. 8,
  140538. };
  140539. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140540. _vq_quantthresh__44cn1_s_p4_0,
  140541. _vq_quantmap__44cn1_s_p4_0,
  140542. 9,
  140543. 9
  140544. };
  140545. static static_codebook _44cn1_s_p4_0 = {
  140546. 2, 81,
  140547. _vq_lengthlist__44cn1_s_p4_0,
  140548. 1, -531628032, 1611661312, 4, 0,
  140549. _vq_quantlist__44cn1_s_p4_0,
  140550. NULL,
  140551. &_vq_auxt__44cn1_s_p4_0,
  140552. NULL,
  140553. 0
  140554. };
  140555. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140556. 8,
  140557. 7,
  140558. 9,
  140559. 6,
  140560. 10,
  140561. 5,
  140562. 11,
  140563. 4,
  140564. 12,
  140565. 3,
  140566. 13,
  140567. 2,
  140568. 14,
  140569. 1,
  140570. 15,
  140571. 0,
  140572. 16,
  140573. };
  140574. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140575. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140576. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140577. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140578. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140579. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140580. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140581. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140582. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140583. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140584. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140585. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140586. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140587. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140588. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140589. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140590. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140591. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140592. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140593. 14,
  140594. };
  140595. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140596. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140597. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140598. };
  140599. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140600. 15, 13, 11, 9, 7, 5, 3, 1,
  140601. 0, 2, 4, 6, 8, 10, 12, 14,
  140602. 16,
  140603. };
  140604. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140605. _vq_quantthresh__44cn1_s_p5_0,
  140606. _vq_quantmap__44cn1_s_p5_0,
  140607. 17,
  140608. 17
  140609. };
  140610. static static_codebook _44cn1_s_p5_0 = {
  140611. 2, 289,
  140612. _vq_lengthlist__44cn1_s_p5_0,
  140613. 1, -529530880, 1611661312, 5, 0,
  140614. _vq_quantlist__44cn1_s_p5_0,
  140615. NULL,
  140616. &_vq_auxt__44cn1_s_p5_0,
  140617. NULL,
  140618. 0
  140619. };
  140620. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140621. 1,
  140622. 0,
  140623. 2,
  140624. };
  140625. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140626. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140627. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140628. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140629. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140630. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140631. 10,
  140632. };
  140633. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140634. -5.5, 5.5,
  140635. };
  140636. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140637. 1, 0, 2,
  140638. };
  140639. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140640. _vq_quantthresh__44cn1_s_p6_0,
  140641. _vq_quantmap__44cn1_s_p6_0,
  140642. 3,
  140643. 3
  140644. };
  140645. static static_codebook _44cn1_s_p6_0 = {
  140646. 4, 81,
  140647. _vq_lengthlist__44cn1_s_p6_0,
  140648. 1, -529137664, 1618345984, 2, 0,
  140649. _vq_quantlist__44cn1_s_p6_0,
  140650. NULL,
  140651. &_vq_auxt__44cn1_s_p6_0,
  140652. NULL,
  140653. 0
  140654. };
  140655. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140656. 5,
  140657. 4,
  140658. 6,
  140659. 3,
  140660. 7,
  140661. 2,
  140662. 8,
  140663. 1,
  140664. 9,
  140665. 0,
  140666. 10,
  140667. };
  140668. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140669. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140670. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140671. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140672. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140673. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140674. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140675. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140676. 10,10,10, 9, 9, 9, 9, 9, 9,
  140677. };
  140678. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140679. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140680. 3.5, 4.5,
  140681. };
  140682. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140683. 9, 7, 5, 3, 1, 0, 2, 4,
  140684. 6, 8, 10,
  140685. };
  140686. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140687. _vq_quantthresh__44cn1_s_p6_1,
  140688. _vq_quantmap__44cn1_s_p6_1,
  140689. 11,
  140690. 11
  140691. };
  140692. static static_codebook _44cn1_s_p6_1 = {
  140693. 2, 121,
  140694. _vq_lengthlist__44cn1_s_p6_1,
  140695. 1, -531365888, 1611661312, 4, 0,
  140696. _vq_quantlist__44cn1_s_p6_1,
  140697. NULL,
  140698. &_vq_auxt__44cn1_s_p6_1,
  140699. NULL,
  140700. 0
  140701. };
  140702. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140703. 6,
  140704. 5,
  140705. 7,
  140706. 4,
  140707. 8,
  140708. 3,
  140709. 9,
  140710. 2,
  140711. 10,
  140712. 1,
  140713. 11,
  140714. 0,
  140715. 12,
  140716. };
  140717. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140718. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140719. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140720. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140721. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140722. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140723. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140724. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140725. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140726. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140727. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140728. 0,13,13,12,12,13,13,13,14,
  140729. };
  140730. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140731. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140732. 12.5, 17.5, 22.5, 27.5,
  140733. };
  140734. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140735. 11, 9, 7, 5, 3, 1, 0, 2,
  140736. 4, 6, 8, 10, 12,
  140737. };
  140738. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140739. _vq_quantthresh__44cn1_s_p7_0,
  140740. _vq_quantmap__44cn1_s_p7_0,
  140741. 13,
  140742. 13
  140743. };
  140744. static static_codebook _44cn1_s_p7_0 = {
  140745. 2, 169,
  140746. _vq_lengthlist__44cn1_s_p7_0,
  140747. 1, -526516224, 1616117760, 4, 0,
  140748. _vq_quantlist__44cn1_s_p7_0,
  140749. NULL,
  140750. &_vq_auxt__44cn1_s_p7_0,
  140751. NULL,
  140752. 0
  140753. };
  140754. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140755. 2,
  140756. 1,
  140757. 3,
  140758. 0,
  140759. 4,
  140760. };
  140761. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140762. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140763. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140764. };
  140765. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140766. -1.5, -0.5, 0.5, 1.5,
  140767. };
  140768. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140769. 3, 1, 0, 2, 4,
  140770. };
  140771. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140772. _vq_quantthresh__44cn1_s_p7_1,
  140773. _vq_quantmap__44cn1_s_p7_1,
  140774. 5,
  140775. 5
  140776. };
  140777. static static_codebook _44cn1_s_p7_1 = {
  140778. 2, 25,
  140779. _vq_lengthlist__44cn1_s_p7_1,
  140780. 1, -533725184, 1611661312, 3, 0,
  140781. _vq_quantlist__44cn1_s_p7_1,
  140782. NULL,
  140783. &_vq_auxt__44cn1_s_p7_1,
  140784. NULL,
  140785. 0
  140786. };
  140787. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140788. 2,
  140789. 1,
  140790. 3,
  140791. 0,
  140792. 4,
  140793. };
  140794. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140795. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140796. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140797. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140798. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140799. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140800. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140801. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140802. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140803. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140804. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140805. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140806. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140807. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140808. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140809. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140810. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140811. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140812. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140813. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140814. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140815. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140816. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140817. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140818. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140819. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140820. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140821. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140822. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140823. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140824. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140825. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140826. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140827. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140828. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140829. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140830. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140831. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140832. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140833. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140834. 12,
  140835. };
  140836. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140837. -331.5, -110.5, 110.5, 331.5,
  140838. };
  140839. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140840. 3, 1, 0, 2, 4,
  140841. };
  140842. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140843. _vq_quantthresh__44cn1_s_p8_0,
  140844. _vq_quantmap__44cn1_s_p8_0,
  140845. 5,
  140846. 5
  140847. };
  140848. static static_codebook _44cn1_s_p8_0 = {
  140849. 4, 625,
  140850. _vq_lengthlist__44cn1_s_p8_0,
  140851. 1, -518283264, 1627103232, 3, 0,
  140852. _vq_quantlist__44cn1_s_p8_0,
  140853. NULL,
  140854. &_vq_auxt__44cn1_s_p8_0,
  140855. NULL,
  140856. 0
  140857. };
  140858. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140859. 6,
  140860. 5,
  140861. 7,
  140862. 4,
  140863. 8,
  140864. 3,
  140865. 9,
  140866. 2,
  140867. 10,
  140868. 1,
  140869. 11,
  140870. 0,
  140871. 12,
  140872. };
  140873. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140874. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140875. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140876. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140877. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140878. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140879. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140880. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140881. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140882. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140883. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140884. 15,12,12,11,11,14,12,13,14,
  140885. };
  140886. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140887. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140888. 42.5, 59.5, 76.5, 93.5,
  140889. };
  140890. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140891. 11, 9, 7, 5, 3, 1, 0, 2,
  140892. 4, 6, 8, 10, 12,
  140893. };
  140894. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140895. _vq_quantthresh__44cn1_s_p8_1,
  140896. _vq_quantmap__44cn1_s_p8_1,
  140897. 13,
  140898. 13
  140899. };
  140900. static static_codebook _44cn1_s_p8_1 = {
  140901. 2, 169,
  140902. _vq_lengthlist__44cn1_s_p8_1,
  140903. 1, -522616832, 1620115456, 4, 0,
  140904. _vq_quantlist__44cn1_s_p8_1,
  140905. NULL,
  140906. &_vq_auxt__44cn1_s_p8_1,
  140907. NULL,
  140908. 0
  140909. };
  140910. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140911. 8,
  140912. 7,
  140913. 9,
  140914. 6,
  140915. 10,
  140916. 5,
  140917. 11,
  140918. 4,
  140919. 12,
  140920. 3,
  140921. 13,
  140922. 2,
  140923. 14,
  140924. 1,
  140925. 15,
  140926. 0,
  140927. 16,
  140928. };
  140929. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140930. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140931. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140932. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140933. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140934. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140935. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140936. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140937. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140938. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140939. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140940. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140941. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140942. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140943. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140944. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140945. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140946. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140947. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140948. 9,
  140949. };
  140950. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140951. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140952. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140953. };
  140954. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140955. 15, 13, 11, 9, 7, 5, 3, 1,
  140956. 0, 2, 4, 6, 8, 10, 12, 14,
  140957. 16,
  140958. };
  140959. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140960. _vq_quantthresh__44cn1_s_p8_2,
  140961. _vq_quantmap__44cn1_s_p8_2,
  140962. 17,
  140963. 17
  140964. };
  140965. static static_codebook _44cn1_s_p8_2 = {
  140966. 2, 289,
  140967. _vq_lengthlist__44cn1_s_p8_2,
  140968. 1, -529530880, 1611661312, 5, 0,
  140969. _vq_quantlist__44cn1_s_p8_2,
  140970. NULL,
  140971. &_vq_auxt__44cn1_s_p8_2,
  140972. NULL,
  140973. 0
  140974. };
  140975. static long _huff_lengthlist__44cn1_s_short[] = {
  140976. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140977. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140978. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140979. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140980. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140981. 10,
  140982. };
  140983. static static_codebook _huff_book__44cn1_s_short = {
  140984. 2, 81,
  140985. _huff_lengthlist__44cn1_s_short,
  140986. 0, 0, 0, 0, 0,
  140987. NULL,
  140988. NULL,
  140989. NULL,
  140990. NULL,
  140991. 0
  140992. };
  140993. static long _huff_lengthlist__44cn1_sm_long[] = {
  140994. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140995. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140996. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140997. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140998. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140999. 17,
  141000. };
  141001. static static_codebook _huff_book__44cn1_sm_long = {
  141002. 2, 81,
  141003. _huff_lengthlist__44cn1_sm_long,
  141004. 0, 0, 0, 0, 0,
  141005. NULL,
  141006. NULL,
  141007. NULL,
  141008. NULL,
  141009. 0
  141010. };
  141011. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  141012. 1,
  141013. 0,
  141014. 2,
  141015. };
  141016. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  141017. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  141018. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141022. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  141023. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141027. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  141028. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  141063. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  141068. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  141073. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  141074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141109. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141113. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141114. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  141115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141118. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141119. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141427. 0,
  141428. };
  141429. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141430. -0.5, 0.5,
  141431. };
  141432. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141433. 1, 0, 2,
  141434. };
  141435. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141436. _vq_quantthresh__44cn1_sm_p1_0,
  141437. _vq_quantmap__44cn1_sm_p1_0,
  141438. 3,
  141439. 3
  141440. };
  141441. static static_codebook _44cn1_sm_p1_0 = {
  141442. 8, 6561,
  141443. _vq_lengthlist__44cn1_sm_p1_0,
  141444. 1, -535822336, 1611661312, 2, 0,
  141445. _vq_quantlist__44cn1_sm_p1_0,
  141446. NULL,
  141447. &_vq_auxt__44cn1_sm_p1_0,
  141448. NULL,
  141449. 0
  141450. };
  141451. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141452. 2,
  141453. 1,
  141454. 3,
  141455. 0,
  141456. 4,
  141457. };
  141458. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141459. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141462. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141465. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141498. 0,
  141499. };
  141500. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141501. -1.5, -0.5, 0.5, 1.5,
  141502. };
  141503. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141504. 3, 1, 0, 2, 4,
  141505. };
  141506. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141507. _vq_quantthresh__44cn1_sm_p2_0,
  141508. _vq_quantmap__44cn1_sm_p2_0,
  141509. 5,
  141510. 5
  141511. };
  141512. static static_codebook _44cn1_sm_p2_0 = {
  141513. 4, 625,
  141514. _vq_lengthlist__44cn1_sm_p2_0,
  141515. 1, -533725184, 1611661312, 3, 0,
  141516. _vq_quantlist__44cn1_sm_p2_0,
  141517. NULL,
  141518. &_vq_auxt__44cn1_sm_p2_0,
  141519. NULL,
  141520. 0
  141521. };
  141522. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141523. 4,
  141524. 3,
  141525. 5,
  141526. 2,
  141527. 6,
  141528. 1,
  141529. 7,
  141530. 0,
  141531. 8,
  141532. };
  141533. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141534. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141535. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141536. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141537. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141538. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141539. 0,
  141540. };
  141541. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141542. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141543. };
  141544. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141545. 7, 5, 3, 1, 0, 2, 4, 6,
  141546. 8,
  141547. };
  141548. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141549. _vq_quantthresh__44cn1_sm_p3_0,
  141550. _vq_quantmap__44cn1_sm_p3_0,
  141551. 9,
  141552. 9
  141553. };
  141554. static static_codebook _44cn1_sm_p3_0 = {
  141555. 2, 81,
  141556. _vq_lengthlist__44cn1_sm_p3_0,
  141557. 1, -531628032, 1611661312, 4, 0,
  141558. _vq_quantlist__44cn1_sm_p3_0,
  141559. NULL,
  141560. &_vq_auxt__44cn1_sm_p3_0,
  141561. NULL,
  141562. 0
  141563. };
  141564. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141565. 4,
  141566. 3,
  141567. 5,
  141568. 2,
  141569. 6,
  141570. 1,
  141571. 7,
  141572. 0,
  141573. 8,
  141574. };
  141575. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141576. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141577. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141578. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141579. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141580. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141581. 11,
  141582. };
  141583. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141584. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141585. };
  141586. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141587. 7, 5, 3, 1, 0, 2, 4, 6,
  141588. 8,
  141589. };
  141590. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141591. _vq_quantthresh__44cn1_sm_p4_0,
  141592. _vq_quantmap__44cn1_sm_p4_0,
  141593. 9,
  141594. 9
  141595. };
  141596. static static_codebook _44cn1_sm_p4_0 = {
  141597. 2, 81,
  141598. _vq_lengthlist__44cn1_sm_p4_0,
  141599. 1, -531628032, 1611661312, 4, 0,
  141600. _vq_quantlist__44cn1_sm_p4_0,
  141601. NULL,
  141602. &_vq_auxt__44cn1_sm_p4_0,
  141603. NULL,
  141604. 0
  141605. };
  141606. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141607. 8,
  141608. 7,
  141609. 9,
  141610. 6,
  141611. 10,
  141612. 5,
  141613. 11,
  141614. 4,
  141615. 12,
  141616. 3,
  141617. 13,
  141618. 2,
  141619. 14,
  141620. 1,
  141621. 15,
  141622. 0,
  141623. 16,
  141624. };
  141625. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141626. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141627. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141628. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141629. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141630. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141631. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141632. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141633. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141634. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141635. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141636. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141637. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141638. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141639. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141640. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141641. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141642. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141643. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141644. 14,
  141645. };
  141646. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141647. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141648. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141649. };
  141650. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141651. 15, 13, 11, 9, 7, 5, 3, 1,
  141652. 0, 2, 4, 6, 8, 10, 12, 14,
  141653. 16,
  141654. };
  141655. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141656. _vq_quantthresh__44cn1_sm_p5_0,
  141657. _vq_quantmap__44cn1_sm_p5_0,
  141658. 17,
  141659. 17
  141660. };
  141661. static static_codebook _44cn1_sm_p5_0 = {
  141662. 2, 289,
  141663. _vq_lengthlist__44cn1_sm_p5_0,
  141664. 1, -529530880, 1611661312, 5, 0,
  141665. _vq_quantlist__44cn1_sm_p5_0,
  141666. NULL,
  141667. &_vq_auxt__44cn1_sm_p5_0,
  141668. NULL,
  141669. 0
  141670. };
  141671. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141672. 1,
  141673. 0,
  141674. 2,
  141675. };
  141676. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141677. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141678. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141679. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141680. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141681. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141682. 10,
  141683. };
  141684. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141685. -5.5, 5.5,
  141686. };
  141687. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141688. 1, 0, 2,
  141689. };
  141690. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141691. _vq_quantthresh__44cn1_sm_p6_0,
  141692. _vq_quantmap__44cn1_sm_p6_0,
  141693. 3,
  141694. 3
  141695. };
  141696. static static_codebook _44cn1_sm_p6_0 = {
  141697. 4, 81,
  141698. _vq_lengthlist__44cn1_sm_p6_0,
  141699. 1, -529137664, 1618345984, 2, 0,
  141700. _vq_quantlist__44cn1_sm_p6_0,
  141701. NULL,
  141702. &_vq_auxt__44cn1_sm_p6_0,
  141703. NULL,
  141704. 0
  141705. };
  141706. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141707. 5,
  141708. 4,
  141709. 6,
  141710. 3,
  141711. 7,
  141712. 2,
  141713. 8,
  141714. 1,
  141715. 9,
  141716. 0,
  141717. 10,
  141718. };
  141719. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141720. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141721. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141722. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141723. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141724. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141725. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141726. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141727. 10,10,10, 8, 9, 8, 8, 9, 8,
  141728. };
  141729. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141730. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141731. 3.5, 4.5,
  141732. };
  141733. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141734. 9, 7, 5, 3, 1, 0, 2, 4,
  141735. 6, 8, 10,
  141736. };
  141737. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141738. _vq_quantthresh__44cn1_sm_p6_1,
  141739. _vq_quantmap__44cn1_sm_p6_1,
  141740. 11,
  141741. 11
  141742. };
  141743. static static_codebook _44cn1_sm_p6_1 = {
  141744. 2, 121,
  141745. _vq_lengthlist__44cn1_sm_p6_1,
  141746. 1, -531365888, 1611661312, 4, 0,
  141747. _vq_quantlist__44cn1_sm_p6_1,
  141748. NULL,
  141749. &_vq_auxt__44cn1_sm_p6_1,
  141750. NULL,
  141751. 0
  141752. };
  141753. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141754. 6,
  141755. 5,
  141756. 7,
  141757. 4,
  141758. 8,
  141759. 3,
  141760. 9,
  141761. 2,
  141762. 10,
  141763. 1,
  141764. 11,
  141765. 0,
  141766. 12,
  141767. };
  141768. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141769. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141770. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141771. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141772. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141773. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141774. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141775. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141776. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141777. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141778. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141779. 0,13,12,12,12,13,13,13,14,
  141780. };
  141781. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141782. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141783. 12.5, 17.5, 22.5, 27.5,
  141784. };
  141785. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141786. 11, 9, 7, 5, 3, 1, 0, 2,
  141787. 4, 6, 8, 10, 12,
  141788. };
  141789. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141790. _vq_quantthresh__44cn1_sm_p7_0,
  141791. _vq_quantmap__44cn1_sm_p7_0,
  141792. 13,
  141793. 13
  141794. };
  141795. static static_codebook _44cn1_sm_p7_0 = {
  141796. 2, 169,
  141797. _vq_lengthlist__44cn1_sm_p7_0,
  141798. 1, -526516224, 1616117760, 4, 0,
  141799. _vq_quantlist__44cn1_sm_p7_0,
  141800. NULL,
  141801. &_vq_auxt__44cn1_sm_p7_0,
  141802. NULL,
  141803. 0
  141804. };
  141805. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141806. 2,
  141807. 1,
  141808. 3,
  141809. 0,
  141810. 4,
  141811. };
  141812. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141813. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141814. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141815. };
  141816. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141817. -1.5, -0.5, 0.5, 1.5,
  141818. };
  141819. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141820. 3, 1, 0, 2, 4,
  141821. };
  141822. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141823. _vq_quantthresh__44cn1_sm_p7_1,
  141824. _vq_quantmap__44cn1_sm_p7_1,
  141825. 5,
  141826. 5
  141827. };
  141828. static static_codebook _44cn1_sm_p7_1 = {
  141829. 2, 25,
  141830. _vq_lengthlist__44cn1_sm_p7_1,
  141831. 1, -533725184, 1611661312, 3, 0,
  141832. _vq_quantlist__44cn1_sm_p7_1,
  141833. NULL,
  141834. &_vq_auxt__44cn1_sm_p7_1,
  141835. NULL,
  141836. 0
  141837. };
  141838. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141839. 4,
  141840. 3,
  141841. 5,
  141842. 2,
  141843. 6,
  141844. 1,
  141845. 7,
  141846. 0,
  141847. 8,
  141848. };
  141849. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141850. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141851. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141852. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141853. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141854. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141855. 14,
  141856. };
  141857. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141858. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141859. };
  141860. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141861. 7, 5, 3, 1, 0, 2, 4, 6,
  141862. 8,
  141863. };
  141864. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141865. _vq_quantthresh__44cn1_sm_p8_0,
  141866. _vq_quantmap__44cn1_sm_p8_0,
  141867. 9,
  141868. 9
  141869. };
  141870. static static_codebook _44cn1_sm_p8_0 = {
  141871. 2, 81,
  141872. _vq_lengthlist__44cn1_sm_p8_0,
  141873. 1, -516186112, 1627103232, 4, 0,
  141874. _vq_quantlist__44cn1_sm_p8_0,
  141875. NULL,
  141876. &_vq_auxt__44cn1_sm_p8_0,
  141877. NULL,
  141878. 0
  141879. };
  141880. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141881. 6,
  141882. 5,
  141883. 7,
  141884. 4,
  141885. 8,
  141886. 3,
  141887. 9,
  141888. 2,
  141889. 10,
  141890. 1,
  141891. 11,
  141892. 0,
  141893. 12,
  141894. };
  141895. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141896. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141897. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141898. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141899. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141900. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141901. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141902. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141903. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141904. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141905. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141906. 17,12,12,11,10,13,11,13,13,
  141907. };
  141908. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141909. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141910. 42.5, 59.5, 76.5, 93.5,
  141911. };
  141912. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141913. 11, 9, 7, 5, 3, 1, 0, 2,
  141914. 4, 6, 8, 10, 12,
  141915. };
  141916. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141917. _vq_quantthresh__44cn1_sm_p8_1,
  141918. _vq_quantmap__44cn1_sm_p8_1,
  141919. 13,
  141920. 13
  141921. };
  141922. static static_codebook _44cn1_sm_p8_1 = {
  141923. 2, 169,
  141924. _vq_lengthlist__44cn1_sm_p8_1,
  141925. 1, -522616832, 1620115456, 4, 0,
  141926. _vq_quantlist__44cn1_sm_p8_1,
  141927. NULL,
  141928. &_vq_auxt__44cn1_sm_p8_1,
  141929. NULL,
  141930. 0
  141931. };
  141932. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141933. 8,
  141934. 7,
  141935. 9,
  141936. 6,
  141937. 10,
  141938. 5,
  141939. 11,
  141940. 4,
  141941. 12,
  141942. 3,
  141943. 13,
  141944. 2,
  141945. 14,
  141946. 1,
  141947. 15,
  141948. 0,
  141949. 16,
  141950. };
  141951. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141952. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141953. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141954. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141955. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141956. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141957. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141958. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141959. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141960. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141961. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141962. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141963. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141964. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141965. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141966. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141967. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141968. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141969. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141970. 9,
  141971. };
  141972. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141973. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141974. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141975. };
  141976. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141977. 15, 13, 11, 9, 7, 5, 3, 1,
  141978. 0, 2, 4, 6, 8, 10, 12, 14,
  141979. 16,
  141980. };
  141981. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141982. _vq_quantthresh__44cn1_sm_p8_2,
  141983. _vq_quantmap__44cn1_sm_p8_2,
  141984. 17,
  141985. 17
  141986. };
  141987. static static_codebook _44cn1_sm_p8_2 = {
  141988. 2, 289,
  141989. _vq_lengthlist__44cn1_sm_p8_2,
  141990. 1, -529530880, 1611661312, 5, 0,
  141991. _vq_quantlist__44cn1_sm_p8_2,
  141992. NULL,
  141993. &_vq_auxt__44cn1_sm_p8_2,
  141994. NULL,
  141995. 0
  141996. };
  141997. static long _huff_lengthlist__44cn1_sm_short[] = {
  141998. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141999. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  142000. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  142001. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  142002. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  142003. 9,
  142004. };
  142005. static static_codebook _huff_book__44cn1_sm_short = {
  142006. 2, 81,
  142007. _huff_lengthlist__44cn1_sm_short,
  142008. 0, 0, 0, 0, 0,
  142009. NULL,
  142010. NULL,
  142011. NULL,
  142012. NULL,
  142013. 0
  142014. };
  142015. /*** End of inlined file: res_books_stereo.h ***/
  142016. /***** residue backends *********************************************/
  142017. static vorbis_info_residue0 _residue_44_low={
  142018. 0,-1, -1, 9,-1,
  142019. /* 0 1 2 3 4 5 6 7 */
  142020. {0},
  142021. {-1},
  142022. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142023. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  142024. };
  142025. static vorbis_info_residue0 _residue_44_mid={
  142026. 0,-1, -1, 10,-1,
  142027. /* 0 1 2 3 4 5 6 7 8 */
  142028. {0},
  142029. {-1},
  142030. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142031. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  142032. };
  142033. static vorbis_info_residue0 _residue_44_high={
  142034. 0,-1, -1, 10,-1,
  142035. /* 0 1 2 3 4 5 6 7 8 */
  142036. {0},
  142037. {-1},
  142038. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  142039. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  142040. };
  142041. static static_bookblock _resbook_44s_n1={
  142042. {
  142043. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  142044. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  142045. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142046. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142047. }
  142048. };
  142049. static static_bookblock _resbook_44sm_n1={
  142050. {
  142051. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142052. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142053. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142054. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142055. }
  142056. };
  142057. static static_bookblock _resbook_44s_0={
  142058. {
  142059. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142060. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142061. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142062. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142063. }
  142064. };
  142065. static static_bookblock _resbook_44sm_0={
  142066. {
  142067. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142068. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142069. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142070. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142071. }
  142072. };
  142073. static static_bookblock _resbook_44s_1={
  142074. {
  142075. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142076. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142077. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142078. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142079. }
  142080. };
  142081. static static_bookblock _resbook_44sm_1={
  142082. {
  142083. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142084. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142085. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142086. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142087. }
  142088. };
  142089. static static_bookblock _resbook_44s_2={
  142090. {
  142091. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142092. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142093. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142094. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142095. }
  142096. };
  142097. static static_bookblock _resbook_44s_3={
  142098. {
  142099. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142100. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142101. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142102. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142103. }
  142104. };
  142105. static static_bookblock _resbook_44s_4={
  142106. {
  142107. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142108. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142109. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142110. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142111. }
  142112. };
  142113. static static_bookblock _resbook_44s_5={
  142114. {
  142115. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142116. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142117. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142118. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142119. }
  142120. };
  142121. static static_bookblock _resbook_44s_6={
  142122. {
  142123. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142124. {0,0,&_44c6_s_p4_0},
  142125. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142126. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142127. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142128. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142129. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142130. }
  142131. };
  142132. static static_bookblock _resbook_44s_7={
  142133. {
  142134. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142135. {0,0,&_44c7_s_p4_0},
  142136. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142137. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142138. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142139. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142140. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142141. }
  142142. };
  142143. static static_bookblock _resbook_44s_8={
  142144. {
  142145. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142146. {0,0,&_44c8_s_p4_0},
  142147. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142148. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142149. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142150. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142151. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142152. }
  142153. };
  142154. static static_bookblock _resbook_44s_9={
  142155. {
  142156. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142157. {0,0,&_44c9_s_p4_0},
  142158. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142159. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142160. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142161. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142162. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142163. }
  142164. };
  142165. static vorbis_residue_template _res_44s_n1[]={
  142166. {2,0, &_residue_44_low,
  142167. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142168. &_resbook_44s_n1,&_resbook_44sm_n1},
  142169. {2,0, &_residue_44_low,
  142170. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142171. &_resbook_44s_n1,&_resbook_44sm_n1}
  142172. };
  142173. static vorbis_residue_template _res_44s_0[]={
  142174. {2,0, &_residue_44_low,
  142175. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142176. &_resbook_44s_0,&_resbook_44sm_0},
  142177. {2,0, &_residue_44_low,
  142178. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142179. &_resbook_44s_0,&_resbook_44sm_0}
  142180. };
  142181. static vorbis_residue_template _res_44s_1[]={
  142182. {2,0, &_residue_44_low,
  142183. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142184. &_resbook_44s_1,&_resbook_44sm_1},
  142185. {2,0, &_residue_44_low,
  142186. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142187. &_resbook_44s_1,&_resbook_44sm_1}
  142188. };
  142189. static vorbis_residue_template _res_44s_2[]={
  142190. {2,0, &_residue_44_mid,
  142191. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142192. &_resbook_44s_2,&_resbook_44s_2},
  142193. {2,0, &_residue_44_mid,
  142194. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142195. &_resbook_44s_2,&_resbook_44s_2}
  142196. };
  142197. static vorbis_residue_template _res_44s_3[]={
  142198. {2,0, &_residue_44_mid,
  142199. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142200. &_resbook_44s_3,&_resbook_44s_3},
  142201. {2,0, &_residue_44_mid,
  142202. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142203. &_resbook_44s_3,&_resbook_44s_3}
  142204. };
  142205. static vorbis_residue_template _res_44s_4[]={
  142206. {2,0, &_residue_44_mid,
  142207. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142208. &_resbook_44s_4,&_resbook_44s_4},
  142209. {2,0, &_residue_44_mid,
  142210. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142211. &_resbook_44s_4,&_resbook_44s_4}
  142212. };
  142213. static vorbis_residue_template _res_44s_5[]={
  142214. {2,0, &_residue_44_mid,
  142215. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142216. &_resbook_44s_5,&_resbook_44s_5},
  142217. {2,0, &_residue_44_mid,
  142218. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142219. &_resbook_44s_5,&_resbook_44s_5}
  142220. };
  142221. static vorbis_residue_template _res_44s_6[]={
  142222. {2,0, &_residue_44_high,
  142223. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142224. &_resbook_44s_6,&_resbook_44s_6},
  142225. {2,0, &_residue_44_high,
  142226. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142227. &_resbook_44s_6,&_resbook_44s_6}
  142228. };
  142229. static vorbis_residue_template _res_44s_7[]={
  142230. {2,0, &_residue_44_high,
  142231. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142232. &_resbook_44s_7,&_resbook_44s_7},
  142233. {2,0, &_residue_44_high,
  142234. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142235. &_resbook_44s_7,&_resbook_44s_7}
  142236. };
  142237. static vorbis_residue_template _res_44s_8[]={
  142238. {2,0, &_residue_44_high,
  142239. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142240. &_resbook_44s_8,&_resbook_44s_8},
  142241. {2,0, &_residue_44_high,
  142242. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142243. &_resbook_44s_8,&_resbook_44s_8}
  142244. };
  142245. static vorbis_residue_template _res_44s_9[]={
  142246. {2,0, &_residue_44_high,
  142247. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142248. &_resbook_44s_9,&_resbook_44s_9},
  142249. {2,0, &_residue_44_high,
  142250. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142251. &_resbook_44s_9,&_resbook_44s_9}
  142252. };
  142253. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142254. { _map_nominal, _res_44s_n1 }, /* -1 */
  142255. { _map_nominal, _res_44s_0 }, /* 0 */
  142256. { _map_nominal, _res_44s_1 }, /* 1 */
  142257. { _map_nominal, _res_44s_2 }, /* 2 */
  142258. { _map_nominal, _res_44s_3 }, /* 3 */
  142259. { _map_nominal, _res_44s_4 }, /* 4 */
  142260. { _map_nominal, _res_44s_5 }, /* 5 */
  142261. { _map_nominal, _res_44s_6 }, /* 6 */
  142262. { _map_nominal, _res_44s_7 }, /* 7 */
  142263. { _map_nominal, _res_44s_8 }, /* 8 */
  142264. { _map_nominal, _res_44s_9 }, /* 9 */
  142265. };
  142266. /*** End of inlined file: residue_44.h ***/
  142267. /*** Start of inlined file: psych_44.h ***/
  142268. /* preecho trigger settings *****************************************/
  142269. static vorbis_info_psy_global _psy_global_44[5]={
  142270. {8, /* lines per eighth octave */
  142271. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142272. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142273. -6.f,
  142274. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142275. },
  142276. {8, /* lines per eighth octave */
  142277. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142278. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142279. -6.f,
  142280. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142281. },
  142282. {8, /* lines per eighth octave */
  142283. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142284. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142285. -6.f,
  142286. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142287. },
  142288. {8, /* lines per eighth octave */
  142289. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142290. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142291. -6.f,
  142292. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142293. },
  142294. {8, /* lines per eighth octave */
  142295. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142296. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142297. -6.f,
  142298. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142299. },
  142300. };
  142301. /* noise compander lookups * low, mid, high quality ****************/
  142302. static compandblock _psy_compand_44[6]={
  142303. /* sub-mode Z short */
  142304. {{
  142305. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142306. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142307. 16,17,18,19,20,21,22, 23, /* 23dB */
  142308. 24,25,26,27,28,29,30, 31, /* 31dB */
  142309. 32,33,34,35,36,37,38, 39, /* 39dB */
  142310. }},
  142311. /* mode_Z nominal short */
  142312. {{
  142313. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142314. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142315. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142316. 15,16,17,17,17,18,18, 19, /* 31dB */
  142317. 19,19,20,21,22,23,24, 25, /* 39dB */
  142318. }},
  142319. /* mode A short */
  142320. {{
  142321. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142322. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142323. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142324. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142325. 11,12,13,14,15,16,17, 18, /* 39dB */
  142326. }},
  142327. /* sub-mode Z long */
  142328. {{
  142329. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142330. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142331. 16,17,18,19,20,21,22, 23, /* 23dB */
  142332. 24,25,26,27,28,29,30, 31, /* 31dB */
  142333. 32,33,34,35,36,37,38, 39, /* 39dB */
  142334. }},
  142335. /* mode_Z nominal long */
  142336. {{
  142337. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142338. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142339. 13,14,14,14,15,15,15, 15, /* 23dB */
  142340. 16,16,17,17,17,18,18, 19, /* 31dB */
  142341. 19,19,20,21,22,23,24, 25, /* 39dB */
  142342. }},
  142343. /* mode A long */
  142344. {{
  142345. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142346. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142347. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142348. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142349. 11,12,13,14,15,16,17, 18, /* 39dB */
  142350. }}
  142351. };
  142352. /* tonal masking curve level adjustments *************************/
  142353. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142354. /* 63 125 250 500 1 2 4 8 16 */
  142355. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142356. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142357. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142358. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142359. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142360. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142361. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142362. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142363. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142364. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142365. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142366. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142367. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142368. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142369. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142370. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142371. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142372. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142373. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142374. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142375. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142376. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142377. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142378. };
  142379. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142380. /* 63 125 250 500 1 2 4 8 16 */
  142381. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142382. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142383. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142384. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142385. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142386. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142387. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142388. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142389. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142390. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142391. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142392. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142393. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142394. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142395. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142396. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142397. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142398. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142399. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142400. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142401. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142402. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142403. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142404. };
  142405. /* noise bias (transition block) */
  142406. static noise3 _psy_noisebias_trans[12]={
  142407. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142408. /* -1 */
  142409. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142410. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142411. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142412. /* 0
  142413. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142414. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142415. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142416. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142417. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142418. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142419. /* 1
  142420. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142421. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142422. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142423. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142424. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142425. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142426. /* 2
  142427. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142428. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142429. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142430. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142431. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142432. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142433. /* 3
  142434. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142435. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142436. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142437. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142438. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142439. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142440. /* 4
  142441. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142442. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142443. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142444. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142445. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142446. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142447. /* 5
  142448. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142449. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142450. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142451. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142452. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142453. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142454. /* 6
  142455. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142456. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142457. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142458. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142459. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142460. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142461. /* 7
  142462. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142463. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142464. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142465. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142466. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142467. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142468. /* 8
  142469. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142470. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142471. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142472. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142473. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142474. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142475. /* 9
  142476. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142477. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142478. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142479. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142480. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142481. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142482. /* 10 */
  142483. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142484. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142485. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142486. };
  142487. /* noise bias (long block) */
  142488. static noise3 _psy_noisebias_long[12]={
  142489. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142490. /* -1 */
  142491. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142492. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142493. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142494. /* 0 */
  142495. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142496. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142497. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142498. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142499. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142500. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142501. /* 1 */
  142502. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142503. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142504. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142505. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142506. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142507. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142508. /* 2 */
  142509. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142510. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142511. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142512. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142513. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142514. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142515. /* 3 */
  142516. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142517. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142518. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142519. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142520. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142521. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142522. /* 4 */
  142523. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142524. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142525. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142526. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142527. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142528. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142529. /* 5 */
  142530. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142531. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142532. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142533. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142534. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142535. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142536. /* 6 */
  142537. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142538. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142539. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142540. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142541. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142542. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142543. /* 7 */
  142544. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142545. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142546. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142547. /* 8 */
  142548. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142549. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142550. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142551. /* 9 */
  142552. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142553. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142554. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142555. /* 10 */
  142556. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142557. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142558. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142559. };
  142560. /* noise bias (impulse block) */
  142561. static noise3 _psy_noisebias_impulse[12]={
  142562. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142563. /* -1 */
  142564. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142565. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142566. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142567. /* 0 */
  142568. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142569. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142570. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142571. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142572. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142573. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142574. /* 1 */
  142575. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142576. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142577. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142578. /* 2 */
  142579. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142580. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142581. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142582. /* 3 */
  142583. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142584. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142585. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142586. /* 4 */
  142587. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142588. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142589. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142590. /* 5 */
  142591. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142592. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142593. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142594. /* 6
  142595. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142596. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142597. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142598. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142599. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142600. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142601. /* 7 */
  142602. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142603. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142604. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142605. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142606. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142607. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142608. /* 8 */
  142609. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142610. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142611. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142612. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142613. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142614. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142615. /* 9 */
  142616. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142617. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142618. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142619. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142620. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142621. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142622. /* 10 */
  142623. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142624. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142625. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142626. };
  142627. /* noise bias (padding block) */
  142628. static noise3 _psy_noisebias_padding[12]={
  142629. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142630. /* -1 */
  142631. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142632. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142633. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142634. /* 0 */
  142635. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142636. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142637. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142638. /* 1 */
  142639. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142640. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142641. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142642. /* 2 */
  142643. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142644. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142645. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142646. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142647. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142648. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142649. /* 3 */
  142650. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142651. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142652. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142653. /* 4 */
  142654. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142655. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142656. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142657. /* 5 */
  142658. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142659. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142660. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142661. /* 6 */
  142662. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142663. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142664. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142665. /* 7 */
  142666. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142667. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142668. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142669. /* 8 */
  142670. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142671. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142672. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142673. /* 9 */
  142674. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142675. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142676. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142677. /* 10 */
  142678. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142679. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142680. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142681. };
  142682. static noiseguard _psy_noiseguards_44[4]={
  142683. {3,3,15},
  142684. {3,3,15},
  142685. {10,10,100},
  142686. {10,10,100},
  142687. };
  142688. static int _psy_tone_suppress[12]={
  142689. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142690. };
  142691. static int _psy_tone_0dB[12]={
  142692. 90,90,95,95,95,95,105,105,105,105,105,105,
  142693. };
  142694. static int _psy_noise_suppress[12]={
  142695. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142696. };
  142697. static vorbis_info_psy _psy_info_template={
  142698. /* blockflag */
  142699. -1,
  142700. /* ath_adjatt, ath_maxatt */
  142701. -140.,-140.,
  142702. /* tonemask att boost/decay,suppr,curves */
  142703. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142704. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142705. 1, -0.f, .5f, .5f, 0,0,0,
  142706. /* noiseoffset*3, noisecompand, max_curve_dB */
  142707. {{-1},{-1},{-1}},{-1},105.f,
  142708. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142709. 0,0,-1,-1,0.,
  142710. };
  142711. /* ath ****************/
  142712. static int _psy_ath_floater[12]={
  142713. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142714. };
  142715. static int _psy_ath_abs[12]={
  142716. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142717. };
  142718. /* stereo setup. These don't map directly to quality level, there's
  142719. an additional indirection as several of the below may be used in a
  142720. single bitmanaged stream
  142721. ****************/
  142722. /* various stereo possibilities */
  142723. /* stereo mode by base quality level */
  142724. static adj_stereo _psy_stereo_modes_44[12]={
  142725. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142726. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142727. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142728. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142729. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142730. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142731. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142732. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142733. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142734. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142735. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142736. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142737. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142738. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142739. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142740. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142741. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142742. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142743. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142744. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142745. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142746. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142747. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142748. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142749. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142750. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142751. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142752. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142753. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142754. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142755. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142756. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142757. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142758. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142759. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142760. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142761. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142762. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142763. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142764. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142765. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142766. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142767. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142768. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142769. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142770. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142771. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142772. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142773. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142774. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142775. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142776. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142777. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142778. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142779. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142780. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142781. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142782. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142783. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142784. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142785. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142786. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142787. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142788. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142789. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142790. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142791. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142792. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142793. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142794. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142795. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142796. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142797. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142798. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142799. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142800. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142801. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142802. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142803. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142804. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142805. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142806. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142807. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142808. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142809. };
  142810. /* tone master attenuation by base quality mode and bitrate tweak */
  142811. static att3 _psy_tone_masteratt_44[12]={
  142812. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142813. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142814. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142815. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142816. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142817. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142818. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142819. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142820. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142821. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142822. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142823. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142824. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142825. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142826. };
  142827. /* lowpass by mode **************/
  142828. static double _psy_lowpass_44[12]={
  142829. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142830. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142831. };
  142832. /* noise normalization **********/
  142833. static int _noise_start_short_44[11]={
  142834. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142835. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142836. };
  142837. static int _noise_start_long_44[11]={
  142838. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142839. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142840. };
  142841. static int _noise_part_short_44[11]={
  142842. 8,8,8,8,8,8,8,8,8,8,8
  142843. };
  142844. static int _noise_part_long_44[11]={
  142845. 32,32,32,32,32,32,32,32,32,32,32
  142846. };
  142847. static double _noise_thresh_44[11]={
  142848. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142849. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142850. };
  142851. static double _noise_thresh_5only[2]={
  142852. .5,.5,
  142853. };
  142854. /*** End of inlined file: psych_44.h ***/
  142855. static double rate_mapping_44_stereo[12]={
  142856. 22500.,32000.,40000.,48000.,56000.,64000.,
  142857. 80000.,96000.,112000.,128000.,160000.,250001.
  142858. };
  142859. static double quality_mapping_44[12]={
  142860. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142861. };
  142862. static int blocksize_short_44[11]={
  142863. 512,256,256,256,256,256,256,256,256,256,256
  142864. };
  142865. static int blocksize_long_44[11]={
  142866. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142867. };
  142868. static double _psy_compand_short_mapping[12]={
  142869. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142870. };
  142871. static double _psy_compand_long_mapping[12]={
  142872. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142873. };
  142874. static double _global_mapping_44[12]={
  142875. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142876. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142877. };
  142878. static int _floor_short_mapping_44[11]={
  142879. 1,0,0,2,2,4,5,5,5,5,5
  142880. };
  142881. static int _floor_long_mapping_44[11]={
  142882. 8,7,7,7,7,7,7,7,7,7,7
  142883. };
  142884. ve_setup_data_template ve_setup_44_stereo={
  142885. 11,
  142886. rate_mapping_44_stereo,
  142887. quality_mapping_44,
  142888. 2,
  142889. 40000,
  142890. 50000,
  142891. blocksize_short_44,
  142892. blocksize_long_44,
  142893. _psy_tone_masteratt_44,
  142894. _psy_tone_0dB,
  142895. _psy_tone_suppress,
  142896. _vp_tonemask_adj_otherblock,
  142897. _vp_tonemask_adj_longblock,
  142898. _vp_tonemask_adj_otherblock,
  142899. _psy_noiseguards_44,
  142900. _psy_noisebias_impulse,
  142901. _psy_noisebias_padding,
  142902. _psy_noisebias_trans,
  142903. _psy_noisebias_long,
  142904. _psy_noise_suppress,
  142905. _psy_compand_44,
  142906. _psy_compand_short_mapping,
  142907. _psy_compand_long_mapping,
  142908. {_noise_start_short_44,_noise_start_long_44},
  142909. {_noise_part_short_44,_noise_part_long_44},
  142910. _noise_thresh_44,
  142911. _psy_ath_floater,
  142912. _psy_ath_abs,
  142913. _psy_lowpass_44,
  142914. _psy_global_44,
  142915. _global_mapping_44,
  142916. _psy_stereo_modes_44,
  142917. _floor_books,
  142918. _floor,
  142919. _floor_short_mapping_44,
  142920. _floor_long_mapping_44,
  142921. _mapres_template_44_stereo
  142922. };
  142923. /*** End of inlined file: setup_44.h ***/
  142924. /*** Start of inlined file: setup_44u.h ***/
  142925. /*** Start of inlined file: residue_44u.h ***/
  142926. /*** Start of inlined file: res_books_uncoupled.h ***/
  142927. static long _vq_quantlist__16u0__p1_0[] = {
  142928. 1,
  142929. 0,
  142930. 2,
  142931. };
  142932. static long _vq_lengthlist__16u0__p1_0[] = {
  142933. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142934. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142935. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142936. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142937. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142938. 12,
  142939. };
  142940. static float _vq_quantthresh__16u0__p1_0[] = {
  142941. -0.5, 0.5,
  142942. };
  142943. static long _vq_quantmap__16u0__p1_0[] = {
  142944. 1, 0, 2,
  142945. };
  142946. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142947. _vq_quantthresh__16u0__p1_0,
  142948. _vq_quantmap__16u0__p1_0,
  142949. 3,
  142950. 3
  142951. };
  142952. static static_codebook _16u0__p1_0 = {
  142953. 4, 81,
  142954. _vq_lengthlist__16u0__p1_0,
  142955. 1, -535822336, 1611661312, 2, 0,
  142956. _vq_quantlist__16u0__p1_0,
  142957. NULL,
  142958. &_vq_auxt__16u0__p1_0,
  142959. NULL,
  142960. 0
  142961. };
  142962. static long _vq_quantlist__16u0__p2_0[] = {
  142963. 1,
  142964. 0,
  142965. 2,
  142966. };
  142967. static long _vq_lengthlist__16u0__p2_0[] = {
  142968. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142969. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142970. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142971. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142972. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142973. 8,
  142974. };
  142975. static float _vq_quantthresh__16u0__p2_0[] = {
  142976. -0.5, 0.5,
  142977. };
  142978. static long _vq_quantmap__16u0__p2_0[] = {
  142979. 1, 0, 2,
  142980. };
  142981. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142982. _vq_quantthresh__16u0__p2_0,
  142983. _vq_quantmap__16u0__p2_0,
  142984. 3,
  142985. 3
  142986. };
  142987. static static_codebook _16u0__p2_0 = {
  142988. 4, 81,
  142989. _vq_lengthlist__16u0__p2_0,
  142990. 1, -535822336, 1611661312, 2, 0,
  142991. _vq_quantlist__16u0__p2_0,
  142992. NULL,
  142993. &_vq_auxt__16u0__p2_0,
  142994. NULL,
  142995. 0
  142996. };
  142997. static long _vq_quantlist__16u0__p3_0[] = {
  142998. 2,
  142999. 1,
  143000. 3,
  143001. 0,
  143002. 4,
  143003. };
  143004. static long _vq_lengthlist__16u0__p3_0[] = {
  143005. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  143006. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  143007. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  143008. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  143009. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  143010. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  143011. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  143012. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  143013. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  143014. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  143015. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  143016. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  143017. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  143018. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  143019. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  143020. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  143021. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  143022. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  143023. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  143024. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  143025. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  143026. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  143027. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  143028. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  143029. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  143030. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  143031. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  143032. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  143033. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  143034. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  143035. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  143036. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  143037. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  143038. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  143039. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  143040. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  143041. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  143042. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  143043. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  143044. 18,
  143045. };
  143046. static float _vq_quantthresh__16u0__p3_0[] = {
  143047. -1.5, -0.5, 0.5, 1.5,
  143048. };
  143049. static long _vq_quantmap__16u0__p3_0[] = {
  143050. 3, 1, 0, 2, 4,
  143051. };
  143052. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143053. _vq_quantthresh__16u0__p3_0,
  143054. _vq_quantmap__16u0__p3_0,
  143055. 5,
  143056. 5
  143057. };
  143058. static static_codebook _16u0__p3_0 = {
  143059. 4, 625,
  143060. _vq_lengthlist__16u0__p3_0,
  143061. 1, -533725184, 1611661312, 3, 0,
  143062. _vq_quantlist__16u0__p3_0,
  143063. NULL,
  143064. &_vq_auxt__16u0__p3_0,
  143065. NULL,
  143066. 0
  143067. };
  143068. static long _vq_quantlist__16u0__p4_0[] = {
  143069. 2,
  143070. 1,
  143071. 3,
  143072. 0,
  143073. 4,
  143074. };
  143075. static long _vq_lengthlist__16u0__p4_0[] = {
  143076. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143077. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143078. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143079. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143080. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143081. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143082. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143083. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143084. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143085. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143086. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143087. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143088. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143089. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143090. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143091. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143092. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143093. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143094. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143095. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143096. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143097. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143098. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143099. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143100. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143101. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143102. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143103. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143104. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143105. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143106. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143107. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143108. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143109. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143110. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143111. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143112. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143113. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143114. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143115. 11,
  143116. };
  143117. static float _vq_quantthresh__16u0__p4_0[] = {
  143118. -1.5, -0.5, 0.5, 1.5,
  143119. };
  143120. static long _vq_quantmap__16u0__p4_0[] = {
  143121. 3, 1, 0, 2, 4,
  143122. };
  143123. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143124. _vq_quantthresh__16u0__p4_0,
  143125. _vq_quantmap__16u0__p4_0,
  143126. 5,
  143127. 5
  143128. };
  143129. static static_codebook _16u0__p4_0 = {
  143130. 4, 625,
  143131. _vq_lengthlist__16u0__p4_0,
  143132. 1, -533725184, 1611661312, 3, 0,
  143133. _vq_quantlist__16u0__p4_0,
  143134. NULL,
  143135. &_vq_auxt__16u0__p4_0,
  143136. NULL,
  143137. 0
  143138. };
  143139. static long _vq_quantlist__16u0__p5_0[] = {
  143140. 4,
  143141. 3,
  143142. 5,
  143143. 2,
  143144. 6,
  143145. 1,
  143146. 7,
  143147. 0,
  143148. 8,
  143149. };
  143150. static long _vq_lengthlist__16u0__p5_0[] = {
  143151. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143152. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143153. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143154. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143155. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143156. 12,
  143157. };
  143158. static float _vq_quantthresh__16u0__p5_0[] = {
  143159. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143160. };
  143161. static long _vq_quantmap__16u0__p5_0[] = {
  143162. 7, 5, 3, 1, 0, 2, 4, 6,
  143163. 8,
  143164. };
  143165. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143166. _vq_quantthresh__16u0__p5_0,
  143167. _vq_quantmap__16u0__p5_0,
  143168. 9,
  143169. 9
  143170. };
  143171. static static_codebook _16u0__p5_0 = {
  143172. 2, 81,
  143173. _vq_lengthlist__16u0__p5_0,
  143174. 1, -531628032, 1611661312, 4, 0,
  143175. _vq_quantlist__16u0__p5_0,
  143176. NULL,
  143177. &_vq_auxt__16u0__p5_0,
  143178. NULL,
  143179. 0
  143180. };
  143181. static long _vq_quantlist__16u0__p6_0[] = {
  143182. 6,
  143183. 5,
  143184. 7,
  143185. 4,
  143186. 8,
  143187. 3,
  143188. 9,
  143189. 2,
  143190. 10,
  143191. 1,
  143192. 11,
  143193. 0,
  143194. 12,
  143195. };
  143196. static long _vq_lengthlist__16u0__p6_0[] = {
  143197. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143198. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143199. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143200. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143201. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143202. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143203. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143204. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143205. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143206. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143207. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143208. };
  143209. static float _vq_quantthresh__16u0__p6_0[] = {
  143210. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143211. 12.5, 17.5, 22.5, 27.5,
  143212. };
  143213. static long _vq_quantmap__16u0__p6_0[] = {
  143214. 11, 9, 7, 5, 3, 1, 0, 2,
  143215. 4, 6, 8, 10, 12,
  143216. };
  143217. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143218. _vq_quantthresh__16u0__p6_0,
  143219. _vq_quantmap__16u0__p6_0,
  143220. 13,
  143221. 13
  143222. };
  143223. static static_codebook _16u0__p6_0 = {
  143224. 2, 169,
  143225. _vq_lengthlist__16u0__p6_0,
  143226. 1, -526516224, 1616117760, 4, 0,
  143227. _vq_quantlist__16u0__p6_0,
  143228. NULL,
  143229. &_vq_auxt__16u0__p6_0,
  143230. NULL,
  143231. 0
  143232. };
  143233. static long _vq_quantlist__16u0__p6_1[] = {
  143234. 2,
  143235. 1,
  143236. 3,
  143237. 0,
  143238. 4,
  143239. };
  143240. static long _vq_lengthlist__16u0__p6_1[] = {
  143241. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143242. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143243. };
  143244. static float _vq_quantthresh__16u0__p6_1[] = {
  143245. -1.5, -0.5, 0.5, 1.5,
  143246. };
  143247. static long _vq_quantmap__16u0__p6_1[] = {
  143248. 3, 1, 0, 2, 4,
  143249. };
  143250. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143251. _vq_quantthresh__16u0__p6_1,
  143252. _vq_quantmap__16u0__p6_1,
  143253. 5,
  143254. 5
  143255. };
  143256. static static_codebook _16u0__p6_1 = {
  143257. 2, 25,
  143258. _vq_lengthlist__16u0__p6_1,
  143259. 1, -533725184, 1611661312, 3, 0,
  143260. _vq_quantlist__16u0__p6_1,
  143261. NULL,
  143262. &_vq_auxt__16u0__p6_1,
  143263. NULL,
  143264. 0
  143265. };
  143266. static long _vq_quantlist__16u0__p7_0[] = {
  143267. 1,
  143268. 0,
  143269. 2,
  143270. };
  143271. static long _vq_lengthlist__16u0__p7_0[] = {
  143272. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143273. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143274. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143275. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143276. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143277. 7,
  143278. };
  143279. static float _vq_quantthresh__16u0__p7_0[] = {
  143280. -157.5, 157.5,
  143281. };
  143282. static long _vq_quantmap__16u0__p7_0[] = {
  143283. 1, 0, 2,
  143284. };
  143285. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143286. _vq_quantthresh__16u0__p7_0,
  143287. _vq_quantmap__16u0__p7_0,
  143288. 3,
  143289. 3
  143290. };
  143291. static static_codebook _16u0__p7_0 = {
  143292. 4, 81,
  143293. _vq_lengthlist__16u0__p7_0,
  143294. 1, -518803456, 1628680192, 2, 0,
  143295. _vq_quantlist__16u0__p7_0,
  143296. NULL,
  143297. &_vq_auxt__16u0__p7_0,
  143298. NULL,
  143299. 0
  143300. };
  143301. static long _vq_quantlist__16u0__p7_1[] = {
  143302. 7,
  143303. 6,
  143304. 8,
  143305. 5,
  143306. 9,
  143307. 4,
  143308. 10,
  143309. 3,
  143310. 11,
  143311. 2,
  143312. 12,
  143313. 1,
  143314. 13,
  143315. 0,
  143316. 14,
  143317. };
  143318. static long _vq_lengthlist__16u0__p7_1[] = {
  143319. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143320. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143321. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143322. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143323. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143324. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143325. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143326. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143327. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143328. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143329. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143330. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143331. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143332. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143333. 10,
  143334. };
  143335. static float _vq_quantthresh__16u0__p7_1[] = {
  143336. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143337. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143338. };
  143339. static long _vq_quantmap__16u0__p7_1[] = {
  143340. 13, 11, 9, 7, 5, 3, 1, 0,
  143341. 2, 4, 6, 8, 10, 12, 14,
  143342. };
  143343. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143344. _vq_quantthresh__16u0__p7_1,
  143345. _vq_quantmap__16u0__p7_1,
  143346. 15,
  143347. 15
  143348. };
  143349. static static_codebook _16u0__p7_1 = {
  143350. 2, 225,
  143351. _vq_lengthlist__16u0__p7_1,
  143352. 1, -520986624, 1620377600, 4, 0,
  143353. _vq_quantlist__16u0__p7_1,
  143354. NULL,
  143355. &_vq_auxt__16u0__p7_1,
  143356. NULL,
  143357. 0
  143358. };
  143359. static long _vq_quantlist__16u0__p7_2[] = {
  143360. 10,
  143361. 9,
  143362. 11,
  143363. 8,
  143364. 12,
  143365. 7,
  143366. 13,
  143367. 6,
  143368. 14,
  143369. 5,
  143370. 15,
  143371. 4,
  143372. 16,
  143373. 3,
  143374. 17,
  143375. 2,
  143376. 18,
  143377. 1,
  143378. 19,
  143379. 0,
  143380. 20,
  143381. };
  143382. static long _vq_lengthlist__16u0__p7_2[] = {
  143383. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143384. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143385. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143386. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143387. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143388. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143389. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143390. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143391. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143392. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143393. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143394. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143395. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143396. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143397. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143398. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143399. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143400. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143401. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143402. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143403. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143404. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143405. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143406. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143407. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143408. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143409. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143410. 10,10,12,11,10,11,11,11,10,
  143411. };
  143412. static float _vq_quantthresh__16u0__p7_2[] = {
  143413. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143414. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143415. 6.5, 7.5, 8.5, 9.5,
  143416. };
  143417. static long _vq_quantmap__16u0__p7_2[] = {
  143418. 19, 17, 15, 13, 11, 9, 7, 5,
  143419. 3, 1, 0, 2, 4, 6, 8, 10,
  143420. 12, 14, 16, 18, 20,
  143421. };
  143422. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143423. _vq_quantthresh__16u0__p7_2,
  143424. _vq_quantmap__16u0__p7_2,
  143425. 21,
  143426. 21
  143427. };
  143428. static static_codebook _16u0__p7_2 = {
  143429. 2, 441,
  143430. _vq_lengthlist__16u0__p7_2,
  143431. 1, -529268736, 1611661312, 5, 0,
  143432. _vq_quantlist__16u0__p7_2,
  143433. NULL,
  143434. &_vq_auxt__16u0__p7_2,
  143435. NULL,
  143436. 0
  143437. };
  143438. static long _huff_lengthlist__16u0__single[] = {
  143439. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143440. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143441. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143442. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143443. };
  143444. static static_codebook _huff_book__16u0__single = {
  143445. 2, 64,
  143446. _huff_lengthlist__16u0__single,
  143447. 0, 0, 0, 0, 0,
  143448. NULL,
  143449. NULL,
  143450. NULL,
  143451. NULL,
  143452. 0
  143453. };
  143454. static long _huff_lengthlist__16u1__long[] = {
  143455. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143456. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143457. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143458. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143459. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143460. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143461. 16,13,16,18,
  143462. };
  143463. static static_codebook _huff_book__16u1__long = {
  143464. 2, 100,
  143465. _huff_lengthlist__16u1__long,
  143466. 0, 0, 0, 0, 0,
  143467. NULL,
  143468. NULL,
  143469. NULL,
  143470. NULL,
  143471. 0
  143472. };
  143473. static long _vq_quantlist__16u1__p1_0[] = {
  143474. 1,
  143475. 0,
  143476. 2,
  143477. };
  143478. static long _vq_lengthlist__16u1__p1_0[] = {
  143479. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143480. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143481. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143482. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143483. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143484. 11,
  143485. };
  143486. static float _vq_quantthresh__16u1__p1_0[] = {
  143487. -0.5, 0.5,
  143488. };
  143489. static long _vq_quantmap__16u1__p1_0[] = {
  143490. 1, 0, 2,
  143491. };
  143492. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143493. _vq_quantthresh__16u1__p1_0,
  143494. _vq_quantmap__16u1__p1_0,
  143495. 3,
  143496. 3
  143497. };
  143498. static static_codebook _16u1__p1_0 = {
  143499. 4, 81,
  143500. _vq_lengthlist__16u1__p1_0,
  143501. 1, -535822336, 1611661312, 2, 0,
  143502. _vq_quantlist__16u1__p1_0,
  143503. NULL,
  143504. &_vq_auxt__16u1__p1_0,
  143505. NULL,
  143506. 0
  143507. };
  143508. static long _vq_quantlist__16u1__p2_0[] = {
  143509. 1,
  143510. 0,
  143511. 2,
  143512. };
  143513. static long _vq_lengthlist__16u1__p2_0[] = {
  143514. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143515. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143516. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143517. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143518. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143519. 8,
  143520. };
  143521. static float _vq_quantthresh__16u1__p2_0[] = {
  143522. -0.5, 0.5,
  143523. };
  143524. static long _vq_quantmap__16u1__p2_0[] = {
  143525. 1, 0, 2,
  143526. };
  143527. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143528. _vq_quantthresh__16u1__p2_0,
  143529. _vq_quantmap__16u1__p2_0,
  143530. 3,
  143531. 3
  143532. };
  143533. static static_codebook _16u1__p2_0 = {
  143534. 4, 81,
  143535. _vq_lengthlist__16u1__p2_0,
  143536. 1, -535822336, 1611661312, 2, 0,
  143537. _vq_quantlist__16u1__p2_0,
  143538. NULL,
  143539. &_vq_auxt__16u1__p2_0,
  143540. NULL,
  143541. 0
  143542. };
  143543. static long _vq_quantlist__16u1__p3_0[] = {
  143544. 2,
  143545. 1,
  143546. 3,
  143547. 0,
  143548. 4,
  143549. };
  143550. static long _vq_lengthlist__16u1__p3_0[] = {
  143551. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143552. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143553. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143554. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143555. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143556. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143557. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143558. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143559. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143560. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143561. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143562. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143563. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143564. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143565. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143566. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143567. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143568. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143569. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143570. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143571. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143572. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143573. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143574. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143575. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143576. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143577. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143578. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143579. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143580. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143581. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143582. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143583. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143584. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143585. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143586. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143587. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143588. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143589. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143590. 16,
  143591. };
  143592. static float _vq_quantthresh__16u1__p3_0[] = {
  143593. -1.5, -0.5, 0.5, 1.5,
  143594. };
  143595. static long _vq_quantmap__16u1__p3_0[] = {
  143596. 3, 1, 0, 2, 4,
  143597. };
  143598. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143599. _vq_quantthresh__16u1__p3_0,
  143600. _vq_quantmap__16u1__p3_0,
  143601. 5,
  143602. 5
  143603. };
  143604. static static_codebook _16u1__p3_0 = {
  143605. 4, 625,
  143606. _vq_lengthlist__16u1__p3_0,
  143607. 1, -533725184, 1611661312, 3, 0,
  143608. _vq_quantlist__16u1__p3_0,
  143609. NULL,
  143610. &_vq_auxt__16u1__p3_0,
  143611. NULL,
  143612. 0
  143613. };
  143614. static long _vq_quantlist__16u1__p4_0[] = {
  143615. 2,
  143616. 1,
  143617. 3,
  143618. 0,
  143619. 4,
  143620. };
  143621. static long _vq_lengthlist__16u1__p4_0[] = {
  143622. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143623. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143624. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143625. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143626. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143627. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143628. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143629. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143630. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143631. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143632. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143633. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143634. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143635. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143636. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143637. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143638. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143639. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143640. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143641. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143642. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143643. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143644. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143645. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143646. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143647. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143648. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143649. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143650. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143651. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143652. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143653. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143654. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143655. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143656. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143657. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143658. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143659. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143660. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143661. 11,
  143662. };
  143663. static float _vq_quantthresh__16u1__p4_0[] = {
  143664. -1.5, -0.5, 0.5, 1.5,
  143665. };
  143666. static long _vq_quantmap__16u1__p4_0[] = {
  143667. 3, 1, 0, 2, 4,
  143668. };
  143669. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143670. _vq_quantthresh__16u1__p4_0,
  143671. _vq_quantmap__16u1__p4_0,
  143672. 5,
  143673. 5
  143674. };
  143675. static static_codebook _16u1__p4_0 = {
  143676. 4, 625,
  143677. _vq_lengthlist__16u1__p4_0,
  143678. 1, -533725184, 1611661312, 3, 0,
  143679. _vq_quantlist__16u1__p4_0,
  143680. NULL,
  143681. &_vq_auxt__16u1__p4_0,
  143682. NULL,
  143683. 0
  143684. };
  143685. static long _vq_quantlist__16u1__p5_0[] = {
  143686. 4,
  143687. 3,
  143688. 5,
  143689. 2,
  143690. 6,
  143691. 1,
  143692. 7,
  143693. 0,
  143694. 8,
  143695. };
  143696. static long _vq_lengthlist__16u1__p5_0[] = {
  143697. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143698. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143699. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143700. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143701. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143702. 13,
  143703. };
  143704. static float _vq_quantthresh__16u1__p5_0[] = {
  143705. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143706. };
  143707. static long _vq_quantmap__16u1__p5_0[] = {
  143708. 7, 5, 3, 1, 0, 2, 4, 6,
  143709. 8,
  143710. };
  143711. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143712. _vq_quantthresh__16u1__p5_0,
  143713. _vq_quantmap__16u1__p5_0,
  143714. 9,
  143715. 9
  143716. };
  143717. static static_codebook _16u1__p5_0 = {
  143718. 2, 81,
  143719. _vq_lengthlist__16u1__p5_0,
  143720. 1, -531628032, 1611661312, 4, 0,
  143721. _vq_quantlist__16u1__p5_0,
  143722. NULL,
  143723. &_vq_auxt__16u1__p5_0,
  143724. NULL,
  143725. 0
  143726. };
  143727. static long _vq_quantlist__16u1__p6_0[] = {
  143728. 4,
  143729. 3,
  143730. 5,
  143731. 2,
  143732. 6,
  143733. 1,
  143734. 7,
  143735. 0,
  143736. 8,
  143737. };
  143738. static long _vq_lengthlist__16u1__p6_0[] = {
  143739. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143740. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143741. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143742. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143743. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143744. 11,
  143745. };
  143746. static float _vq_quantthresh__16u1__p6_0[] = {
  143747. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143748. };
  143749. static long _vq_quantmap__16u1__p6_0[] = {
  143750. 7, 5, 3, 1, 0, 2, 4, 6,
  143751. 8,
  143752. };
  143753. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143754. _vq_quantthresh__16u1__p6_0,
  143755. _vq_quantmap__16u1__p6_0,
  143756. 9,
  143757. 9
  143758. };
  143759. static static_codebook _16u1__p6_0 = {
  143760. 2, 81,
  143761. _vq_lengthlist__16u1__p6_0,
  143762. 1, -531628032, 1611661312, 4, 0,
  143763. _vq_quantlist__16u1__p6_0,
  143764. NULL,
  143765. &_vq_auxt__16u1__p6_0,
  143766. NULL,
  143767. 0
  143768. };
  143769. static long _vq_quantlist__16u1__p7_0[] = {
  143770. 1,
  143771. 0,
  143772. 2,
  143773. };
  143774. static long _vq_lengthlist__16u1__p7_0[] = {
  143775. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143776. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143777. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143778. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143779. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143780. 13,
  143781. };
  143782. static float _vq_quantthresh__16u1__p7_0[] = {
  143783. -5.5, 5.5,
  143784. };
  143785. static long _vq_quantmap__16u1__p7_0[] = {
  143786. 1, 0, 2,
  143787. };
  143788. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143789. _vq_quantthresh__16u1__p7_0,
  143790. _vq_quantmap__16u1__p7_0,
  143791. 3,
  143792. 3
  143793. };
  143794. static static_codebook _16u1__p7_0 = {
  143795. 4, 81,
  143796. _vq_lengthlist__16u1__p7_0,
  143797. 1, -529137664, 1618345984, 2, 0,
  143798. _vq_quantlist__16u1__p7_0,
  143799. NULL,
  143800. &_vq_auxt__16u1__p7_0,
  143801. NULL,
  143802. 0
  143803. };
  143804. static long _vq_quantlist__16u1__p7_1[] = {
  143805. 5,
  143806. 4,
  143807. 6,
  143808. 3,
  143809. 7,
  143810. 2,
  143811. 8,
  143812. 1,
  143813. 9,
  143814. 0,
  143815. 10,
  143816. };
  143817. static long _vq_lengthlist__16u1__p7_1[] = {
  143818. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143819. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143820. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143821. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143822. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143823. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143824. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143825. 8, 9, 9,10,10,10,10,10,10,
  143826. };
  143827. static float _vq_quantthresh__16u1__p7_1[] = {
  143828. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143829. 3.5, 4.5,
  143830. };
  143831. static long _vq_quantmap__16u1__p7_1[] = {
  143832. 9, 7, 5, 3, 1, 0, 2, 4,
  143833. 6, 8, 10,
  143834. };
  143835. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143836. _vq_quantthresh__16u1__p7_1,
  143837. _vq_quantmap__16u1__p7_1,
  143838. 11,
  143839. 11
  143840. };
  143841. static static_codebook _16u1__p7_1 = {
  143842. 2, 121,
  143843. _vq_lengthlist__16u1__p7_1,
  143844. 1, -531365888, 1611661312, 4, 0,
  143845. _vq_quantlist__16u1__p7_1,
  143846. NULL,
  143847. &_vq_auxt__16u1__p7_1,
  143848. NULL,
  143849. 0
  143850. };
  143851. static long _vq_quantlist__16u1__p8_0[] = {
  143852. 5,
  143853. 4,
  143854. 6,
  143855. 3,
  143856. 7,
  143857. 2,
  143858. 8,
  143859. 1,
  143860. 9,
  143861. 0,
  143862. 10,
  143863. };
  143864. static long _vq_lengthlist__16u1__p8_0[] = {
  143865. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143866. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143867. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143868. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143869. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143870. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143871. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143872. 13,14,14,15,15,16,16,15,16,
  143873. };
  143874. static float _vq_quantthresh__16u1__p8_0[] = {
  143875. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143876. 38.5, 49.5,
  143877. };
  143878. static long _vq_quantmap__16u1__p8_0[] = {
  143879. 9, 7, 5, 3, 1, 0, 2, 4,
  143880. 6, 8, 10,
  143881. };
  143882. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143883. _vq_quantthresh__16u1__p8_0,
  143884. _vq_quantmap__16u1__p8_0,
  143885. 11,
  143886. 11
  143887. };
  143888. static static_codebook _16u1__p8_0 = {
  143889. 2, 121,
  143890. _vq_lengthlist__16u1__p8_0,
  143891. 1, -524582912, 1618345984, 4, 0,
  143892. _vq_quantlist__16u1__p8_0,
  143893. NULL,
  143894. &_vq_auxt__16u1__p8_0,
  143895. NULL,
  143896. 0
  143897. };
  143898. static long _vq_quantlist__16u1__p8_1[] = {
  143899. 5,
  143900. 4,
  143901. 6,
  143902. 3,
  143903. 7,
  143904. 2,
  143905. 8,
  143906. 1,
  143907. 9,
  143908. 0,
  143909. 10,
  143910. };
  143911. static long _vq_lengthlist__16u1__p8_1[] = {
  143912. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143913. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143914. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143915. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143916. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143917. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143918. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143919. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143920. };
  143921. static float _vq_quantthresh__16u1__p8_1[] = {
  143922. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143923. 3.5, 4.5,
  143924. };
  143925. static long _vq_quantmap__16u1__p8_1[] = {
  143926. 9, 7, 5, 3, 1, 0, 2, 4,
  143927. 6, 8, 10,
  143928. };
  143929. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143930. _vq_quantthresh__16u1__p8_1,
  143931. _vq_quantmap__16u1__p8_1,
  143932. 11,
  143933. 11
  143934. };
  143935. static static_codebook _16u1__p8_1 = {
  143936. 2, 121,
  143937. _vq_lengthlist__16u1__p8_1,
  143938. 1, -531365888, 1611661312, 4, 0,
  143939. _vq_quantlist__16u1__p8_1,
  143940. NULL,
  143941. &_vq_auxt__16u1__p8_1,
  143942. NULL,
  143943. 0
  143944. };
  143945. static long _vq_quantlist__16u1__p9_0[] = {
  143946. 7,
  143947. 6,
  143948. 8,
  143949. 5,
  143950. 9,
  143951. 4,
  143952. 10,
  143953. 3,
  143954. 11,
  143955. 2,
  143956. 12,
  143957. 1,
  143958. 13,
  143959. 0,
  143960. 14,
  143961. };
  143962. static long _vq_lengthlist__16u1__p9_0[] = {
  143963. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143964. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143965. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143966. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143967. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143968. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143969. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143970. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143971. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143972. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143973. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143974. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143975. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143976. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143977. 8,
  143978. };
  143979. static float _vq_quantthresh__16u1__p9_0[] = {
  143980. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143981. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143982. };
  143983. static long _vq_quantmap__16u1__p9_0[] = {
  143984. 13, 11, 9, 7, 5, 3, 1, 0,
  143985. 2, 4, 6, 8, 10, 12, 14,
  143986. };
  143987. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143988. _vq_quantthresh__16u1__p9_0,
  143989. _vq_quantmap__16u1__p9_0,
  143990. 15,
  143991. 15
  143992. };
  143993. static static_codebook _16u1__p9_0 = {
  143994. 2, 225,
  143995. _vq_lengthlist__16u1__p9_0,
  143996. 1, -514071552, 1627381760, 4, 0,
  143997. _vq_quantlist__16u1__p9_0,
  143998. NULL,
  143999. &_vq_auxt__16u1__p9_0,
  144000. NULL,
  144001. 0
  144002. };
  144003. static long _vq_quantlist__16u1__p9_1[] = {
  144004. 7,
  144005. 6,
  144006. 8,
  144007. 5,
  144008. 9,
  144009. 4,
  144010. 10,
  144011. 3,
  144012. 11,
  144013. 2,
  144014. 12,
  144015. 1,
  144016. 13,
  144017. 0,
  144018. 14,
  144019. };
  144020. static long _vq_lengthlist__16u1__p9_1[] = {
  144021. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  144022. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  144023. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  144024. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  144025. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144026. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  144027. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  144028. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  144029. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  144030. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144031. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  144032. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144033. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144034. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144035. 9,
  144036. };
  144037. static float _vq_quantthresh__16u1__p9_1[] = {
  144038. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144039. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144040. };
  144041. static long _vq_quantmap__16u1__p9_1[] = {
  144042. 13, 11, 9, 7, 5, 3, 1, 0,
  144043. 2, 4, 6, 8, 10, 12, 14,
  144044. };
  144045. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144046. _vq_quantthresh__16u1__p9_1,
  144047. _vq_quantmap__16u1__p9_1,
  144048. 15,
  144049. 15
  144050. };
  144051. static static_codebook _16u1__p9_1 = {
  144052. 2, 225,
  144053. _vq_lengthlist__16u1__p9_1,
  144054. 1, -522338304, 1620115456, 4, 0,
  144055. _vq_quantlist__16u1__p9_1,
  144056. NULL,
  144057. &_vq_auxt__16u1__p9_1,
  144058. NULL,
  144059. 0
  144060. };
  144061. static long _vq_quantlist__16u1__p9_2[] = {
  144062. 8,
  144063. 7,
  144064. 9,
  144065. 6,
  144066. 10,
  144067. 5,
  144068. 11,
  144069. 4,
  144070. 12,
  144071. 3,
  144072. 13,
  144073. 2,
  144074. 14,
  144075. 1,
  144076. 15,
  144077. 0,
  144078. 16,
  144079. };
  144080. static long _vq_lengthlist__16u1__p9_2[] = {
  144081. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144082. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144083. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144084. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144085. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144086. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144087. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144088. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144089. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144090. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144091. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144092. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144093. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144094. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144095. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144096. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144097. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144098. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144099. 10,
  144100. };
  144101. static float _vq_quantthresh__16u1__p9_2[] = {
  144102. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144103. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144104. };
  144105. static long _vq_quantmap__16u1__p9_2[] = {
  144106. 15, 13, 11, 9, 7, 5, 3, 1,
  144107. 0, 2, 4, 6, 8, 10, 12, 14,
  144108. 16,
  144109. };
  144110. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144111. _vq_quantthresh__16u1__p9_2,
  144112. _vq_quantmap__16u1__p9_2,
  144113. 17,
  144114. 17
  144115. };
  144116. static static_codebook _16u1__p9_2 = {
  144117. 2, 289,
  144118. _vq_lengthlist__16u1__p9_2,
  144119. 1, -529530880, 1611661312, 5, 0,
  144120. _vq_quantlist__16u1__p9_2,
  144121. NULL,
  144122. &_vq_auxt__16u1__p9_2,
  144123. NULL,
  144124. 0
  144125. };
  144126. static long _huff_lengthlist__16u1__short[] = {
  144127. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144128. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144129. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144130. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144131. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144132. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144133. 16,16,16,16,
  144134. };
  144135. static static_codebook _huff_book__16u1__short = {
  144136. 2, 100,
  144137. _huff_lengthlist__16u1__short,
  144138. 0, 0, 0, 0, 0,
  144139. NULL,
  144140. NULL,
  144141. NULL,
  144142. NULL,
  144143. 0
  144144. };
  144145. static long _huff_lengthlist__16u2__long[] = {
  144146. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144147. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144148. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144149. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144150. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144151. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144152. 13,14,18,18,
  144153. };
  144154. static static_codebook _huff_book__16u2__long = {
  144155. 2, 100,
  144156. _huff_lengthlist__16u2__long,
  144157. 0, 0, 0, 0, 0,
  144158. NULL,
  144159. NULL,
  144160. NULL,
  144161. NULL,
  144162. 0
  144163. };
  144164. static long _huff_lengthlist__16u2__short[] = {
  144165. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144166. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144167. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144168. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144169. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144170. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144171. 16,16,16,16,
  144172. };
  144173. static static_codebook _huff_book__16u2__short = {
  144174. 2, 100,
  144175. _huff_lengthlist__16u2__short,
  144176. 0, 0, 0, 0, 0,
  144177. NULL,
  144178. NULL,
  144179. NULL,
  144180. NULL,
  144181. 0
  144182. };
  144183. static long _vq_quantlist__16u2_p1_0[] = {
  144184. 1,
  144185. 0,
  144186. 2,
  144187. };
  144188. static long _vq_lengthlist__16u2_p1_0[] = {
  144189. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144190. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144191. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144192. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144193. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144194. 10,
  144195. };
  144196. static float _vq_quantthresh__16u2_p1_0[] = {
  144197. -0.5, 0.5,
  144198. };
  144199. static long _vq_quantmap__16u2_p1_0[] = {
  144200. 1, 0, 2,
  144201. };
  144202. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144203. _vq_quantthresh__16u2_p1_0,
  144204. _vq_quantmap__16u2_p1_0,
  144205. 3,
  144206. 3
  144207. };
  144208. static static_codebook _16u2_p1_0 = {
  144209. 4, 81,
  144210. _vq_lengthlist__16u2_p1_0,
  144211. 1, -535822336, 1611661312, 2, 0,
  144212. _vq_quantlist__16u2_p1_0,
  144213. NULL,
  144214. &_vq_auxt__16u2_p1_0,
  144215. NULL,
  144216. 0
  144217. };
  144218. static long _vq_quantlist__16u2_p2_0[] = {
  144219. 2,
  144220. 1,
  144221. 3,
  144222. 0,
  144223. 4,
  144224. };
  144225. static long _vq_lengthlist__16u2_p2_0[] = {
  144226. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144227. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144228. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144229. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144230. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144231. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144232. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144233. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144234. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144235. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144236. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144237. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144238. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144239. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144240. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144241. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144242. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144243. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144244. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144245. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144246. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144247. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144248. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144249. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144250. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144251. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144252. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144253. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144254. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144255. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144256. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144257. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144258. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144259. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144260. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144261. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144262. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144263. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144264. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144265. 13,
  144266. };
  144267. static float _vq_quantthresh__16u2_p2_0[] = {
  144268. -1.5, -0.5, 0.5, 1.5,
  144269. };
  144270. static long _vq_quantmap__16u2_p2_0[] = {
  144271. 3, 1, 0, 2, 4,
  144272. };
  144273. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144274. _vq_quantthresh__16u2_p2_0,
  144275. _vq_quantmap__16u2_p2_0,
  144276. 5,
  144277. 5
  144278. };
  144279. static static_codebook _16u2_p2_0 = {
  144280. 4, 625,
  144281. _vq_lengthlist__16u2_p2_0,
  144282. 1, -533725184, 1611661312, 3, 0,
  144283. _vq_quantlist__16u2_p2_0,
  144284. NULL,
  144285. &_vq_auxt__16u2_p2_0,
  144286. NULL,
  144287. 0
  144288. };
  144289. static long _vq_quantlist__16u2_p3_0[] = {
  144290. 4,
  144291. 3,
  144292. 5,
  144293. 2,
  144294. 6,
  144295. 1,
  144296. 7,
  144297. 0,
  144298. 8,
  144299. };
  144300. static long _vq_lengthlist__16u2_p3_0[] = {
  144301. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144302. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144303. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144304. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144305. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144306. 11,
  144307. };
  144308. static float _vq_quantthresh__16u2_p3_0[] = {
  144309. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144310. };
  144311. static long _vq_quantmap__16u2_p3_0[] = {
  144312. 7, 5, 3, 1, 0, 2, 4, 6,
  144313. 8,
  144314. };
  144315. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144316. _vq_quantthresh__16u2_p3_0,
  144317. _vq_quantmap__16u2_p3_0,
  144318. 9,
  144319. 9
  144320. };
  144321. static static_codebook _16u2_p3_0 = {
  144322. 2, 81,
  144323. _vq_lengthlist__16u2_p3_0,
  144324. 1, -531628032, 1611661312, 4, 0,
  144325. _vq_quantlist__16u2_p3_0,
  144326. NULL,
  144327. &_vq_auxt__16u2_p3_0,
  144328. NULL,
  144329. 0
  144330. };
  144331. static long _vq_quantlist__16u2_p4_0[] = {
  144332. 8,
  144333. 7,
  144334. 9,
  144335. 6,
  144336. 10,
  144337. 5,
  144338. 11,
  144339. 4,
  144340. 12,
  144341. 3,
  144342. 13,
  144343. 2,
  144344. 14,
  144345. 1,
  144346. 15,
  144347. 0,
  144348. 16,
  144349. };
  144350. static long _vq_lengthlist__16u2_p4_0[] = {
  144351. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144352. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144353. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144354. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144355. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144356. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144357. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144358. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144359. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144360. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144361. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144362. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144363. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144364. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144365. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144366. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144367. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144368. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144369. 14,
  144370. };
  144371. static float _vq_quantthresh__16u2_p4_0[] = {
  144372. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144373. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144374. };
  144375. static long _vq_quantmap__16u2_p4_0[] = {
  144376. 15, 13, 11, 9, 7, 5, 3, 1,
  144377. 0, 2, 4, 6, 8, 10, 12, 14,
  144378. 16,
  144379. };
  144380. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144381. _vq_quantthresh__16u2_p4_0,
  144382. _vq_quantmap__16u2_p4_0,
  144383. 17,
  144384. 17
  144385. };
  144386. static static_codebook _16u2_p4_0 = {
  144387. 2, 289,
  144388. _vq_lengthlist__16u2_p4_0,
  144389. 1, -529530880, 1611661312, 5, 0,
  144390. _vq_quantlist__16u2_p4_0,
  144391. NULL,
  144392. &_vq_auxt__16u2_p4_0,
  144393. NULL,
  144394. 0
  144395. };
  144396. static long _vq_quantlist__16u2_p5_0[] = {
  144397. 1,
  144398. 0,
  144399. 2,
  144400. };
  144401. static long _vq_lengthlist__16u2_p5_0[] = {
  144402. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144403. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144404. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144405. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144406. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144407. 10,
  144408. };
  144409. static float _vq_quantthresh__16u2_p5_0[] = {
  144410. -5.5, 5.5,
  144411. };
  144412. static long _vq_quantmap__16u2_p5_0[] = {
  144413. 1, 0, 2,
  144414. };
  144415. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144416. _vq_quantthresh__16u2_p5_0,
  144417. _vq_quantmap__16u2_p5_0,
  144418. 3,
  144419. 3
  144420. };
  144421. static static_codebook _16u2_p5_0 = {
  144422. 4, 81,
  144423. _vq_lengthlist__16u2_p5_0,
  144424. 1, -529137664, 1618345984, 2, 0,
  144425. _vq_quantlist__16u2_p5_0,
  144426. NULL,
  144427. &_vq_auxt__16u2_p5_0,
  144428. NULL,
  144429. 0
  144430. };
  144431. static long _vq_quantlist__16u2_p5_1[] = {
  144432. 5,
  144433. 4,
  144434. 6,
  144435. 3,
  144436. 7,
  144437. 2,
  144438. 8,
  144439. 1,
  144440. 9,
  144441. 0,
  144442. 10,
  144443. };
  144444. static long _vq_lengthlist__16u2_p5_1[] = {
  144445. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144446. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144447. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144448. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144449. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144450. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144451. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144452. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144453. };
  144454. static float _vq_quantthresh__16u2_p5_1[] = {
  144455. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144456. 3.5, 4.5,
  144457. };
  144458. static long _vq_quantmap__16u2_p5_1[] = {
  144459. 9, 7, 5, 3, 1, 0, 2, 4,
  144460. 6, 8, 10,
  144461. };
  144462. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144463. _vq_quantthresh__16u2_p5_1,
  144464. _vq_quantmap__16u2_p5_1,
  144465. 11,
  144466. 11
  144467. };
  144468. static static_codebook _16u2_p5_1 = {
  144469. 2, 121,
  144470. _vq_lengthlist__16u2_p5_1,
  144471. 1, -531365888, 1611661312, 4, 0,
  144472. _vq_quantlist__16u2_p5_1,
  144473. NULL,
  144474. &_vq_auxt__16u2_p5_1,
  144475. NULL,
  144476. 0
  144477. };
  144478. static long _vq_quantlist__16u2_p6_0[] = {
  144479. 6,
  144480. 5,
  144481. 7,
  144482. 4,
  144483. 8,
  144484. 3,
  144485. 9,
  144486. 2,
  144487. 10,
  144488. 1,
  144489. 11,
  144490. 0,
  144491. 12,
  144492. };
  144493. static long _vq_lengthlist__16u2_p6_0[] = {
  144494. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144495. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144496. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144497. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144498. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144499. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144500. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144501. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144502. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144503. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144504. 12,13,13,14,14,14,14,15,15,
  144505. };
  144506. static float _vq_quantthresh__16u2_p6_0[] = {
  144507. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144508. 12.5, 17.5, 22.5, 27.5,
  144509. };
  144510. static long _vq_quantmap__16u2_p6_0[] = {
  144511. 11, 9, 7, 5, 3, 1, 0, 2,
  144512. 4, 6, 8, 10, 12,
  144513. };
  144514. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144515. _vq_quantthresh__16u2_p6_0,
  144516. _vq_quantmap__16u2_p6_0,
  144517. 13,
  144518. 13
  144519. };
  144520. static static_codebook _16u2_p6_0 = {
  144521. 2, 169,
  144522. _vq_lengthlist__16u2_p6_0,
  144523. 1, -526516224, 1616117760, 4, 0,
  144524. _vq_quantlist__16u2_p6_0,
  144525. NULL,
  144526. &_vq_auxt__16u2_p6_0,
  144527. NULL,
  144528. 0
  144529. };
  144530. static long _vq_quantlist__16u2_p6_1[] = {
  144531. 2,
  144532. 1,
  144533. 3,
  144534. 0,
  144535. 4,
  144536. };
  144537. static long _vq_lengthlist__16u2_p6_1[] = {
  144538. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144539. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144540. };
  144541. static float _vq_quantthresh__16u2_p6_1[] = {
  144542. -1.5, -0.5, 0.5, 1.5,
  144543. };
  144544. static long _vq_quantmap__16u2_p6_1[] = {
  144545. 3, 1, 0, 2, 4,
  144546. };
  144547. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144548. _vq_quantthresh__16u2_p6_1,
  144549. _vq_quantmap__16u2_p6_1,
  144550. 5,
  144551. 5
  144552. };
  144553. static static_codebook _16u2_p6_1 = {
  144554. 2, 25,
  144555. _vq_lengthlist__16u2_p6_1,
  144556. 1, -533725184, 1611661312, 3, 0,
  144557. _vq_quantlist__16u2_p6_1,
  144558. NULL,
  144559. &_vq_auxt__16u2_p6_1,
  144560. NULL,
  144561. 0
  144562. };
  144563. static long _vq_quantlist__16u2_p7_0[] = {
  144564. 6,
  144565. 5,
  144566. 7,
  144567. 4,
  144568. 8,
  144569. 3,
  144570. 9,
  144571. 2,
  144572. 10,
  144573. 1,
  144574. 11,
  144575. 0,
  144576. 12,
  144577. };
  144578. static long _vq_lengthlist__16u2_p7_0[] = {
  144579. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144580. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144581. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144582. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144583. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144584. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144585. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144586. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144587. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144588. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144589. 12,13,13,13,14,14,14,15,14,
  144590. };
  144591. static float _vq_quantthresh__16u2_p7_0[] = {
  144592. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144593. 27.5, 38.5, 49.5, 60.5,
  144594. };
  144595. static long _vq_quantmap__16u2_p7_0[] = {
  144596. 11, 9, 7, 5, 3, 1, 0, 2,
  144597. 4, 6, 8, 10, 12,
  144598. };
  144599. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144600. _vq_quantthresh__16u2_p7_0,
  144601. _vq_quantmap__16u2_p7_0,
  144602. 13,
  144603. 13
  144604. };
  144605. static static_codebook _16u2_p7_0 = {
  144606. 2, 169,
  144607. _vq_lengthlist__16u2_p7_0,
  144608. 1, -523206656, 1618345984, 4, 0,
  144609. _vq_quantlist__16u2_p7_0,
  144610. NULL,
  144611. &_vq_auxt__16u2_p7_0,
  144612. NULL,
  144613. 0
  144614. };
  144615. static long _vq_quantlist__16u2_p7_1[] = {
  144616. 5,
  144617. 4,
  144618. 6,
  144619. 3,
  144620. 7,
  144621. 2,
  144622. 8,
  144623. 1,
  144624. 9,
  144625. 0,
  144626. 10,
  144627. };
  144628. static long _vq_lengthlist__16u2_p7_1[] = {
  144629. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144630. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144631. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144632. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144633. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144634. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144635. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144636. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144637. };
  144638. static float _vq_quantthresh__16u2_p7_1[] = {
  144639. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144640. 3.5, 4.5,
  144641. };
  144642. static long _vq_quantmap__16u2_p7_1[] = {
  144643. 9, 7, 5, 3, 1, 0, 2, 4,
  144644. 6, 8, 10,
  144645. };
  144646. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144647. _vq_quantthresh__16u2_p7_1,
  144648. _vq_quantmap__16u2_p7_1,
  144649. 11,
  144650. 11
  144651. };
  144652. static static_codebook _16u2_p7_1 = {
  144653. 2, 121,
  144654. _vq_lengthlist__16u2_p7_1,
  144655. 1, -531365888, 1611661312, 4, 0,
  144656. _vq_quantlist__16u2_p7_1,
  144657. NULL,
  144658. &_vq_auxt__16u2_p7_1,
  144659. NULL,
  144660. 0
  144661. };
  144662. static long _vq_quantlist__16u2_p8_0[] = {
  144663. 7,
  144664. 6,
  144665. 8,
  144666. 5,
  144667. 9,
  144668. 4,
  144669. 10,
  144670. 3,
  144671. 11,
  144672. 2,
  144673. 12,
  144674. 1,
  144675. 13,
  144676. 0,
  144677. 14,
  144678. };
  144679. static long _vq_lengthlist__16u2_p8_0[] = {
  144680. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144681. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144682. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144683. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144684. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144685. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144686. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144687. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144688. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144689. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144690. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144691. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144692. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144693. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144694. 14,
  144695. };
  144696. static float _vq_quantthresh__16u2_p8_0[] = {
  144697. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144698. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144699. };
  144700. static long _vq_quantmap__16u2_p8_0[] = {
  144701. 13, 11, 9, 7, 5, 3, 1, 0,
  144702. 2, 4, 6, 8, 10, 12, 14,
  144703. };
  144704. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144705. _vq_quantthresh__16u2_p8_0,
  144706. _vq_quantmap__16u2_p8_0,
  144707. 15,
  144708. 15
  144709. };
  144710. static static_codebook _16u2_p8_0 = {
  144711. 2, 225,
  144712. _vq_lengthlist__16u2_p8_0,
  144713. 1, -520986624, 1620377600, 4, 0,
  144714. _vq_quantlist__16u2_p8_0,
  144715. NULL,
  144716. &_vq_auxt__16u2_p8_0,
  144717. NULL,
  144718. 0
  144719. };
  144720. static long _vq_quantlist__16u2_p8_1[] = {
  144721. 10,
  144722. 9,
  144723. 11,
  144724. 8,
  144725. 12,
  144726. 7,
  144727. 13,
  144728. 6,
  144729. 14,
  144730. 5,
  144731. 15,
  144732. 4,
  144733. 16,
  144734. 3,
  144735. 17,
  144736. 2,
  144737. 18,
  144738. 1,
  144739. 19,
  144740. 0,
  144741. 20,
  144742. };
  144743. static long _vq_lengthlist__16u2_p8_1[] = {
  144744. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144745. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144746. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144747. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144748. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144749. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144750. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144751. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144752. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144753. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144754. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144755. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144756. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144757. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144758. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144759. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144760. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144761. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144762. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144763. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144764. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144765. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144766. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144767. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144768. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144769. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144770. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144771. 11,11,10,11,11,11,10,11,11,
  144772. };
  144773. static float _vq_quantthresh__16u2_p8_1[] = {
  144774. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144775. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144776. 6.5, 7.5, 8.5, 9.5,
  144777. };
  144778. static long _vq_quantmap__16u2_p8_1[] = {
  144779. 19, 17, 15, 13, 11, 9, 7, 5,
  144780. 3, 1, 0, 2, 4, 6, 8, 10,
  144781. 12, 14, 16, 18, 20,
  144782. };
  144783. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144784. _vq_quantthresh__16u2_p8_1,
  144785. _vq_quantmap__16u2_p8_1,
  144786. 21,
  144787. 21
  144788. };
  144789. static static_codebook _16u2_p8_1 = {
  144790. 2, 441,
  144791. _vq_lengthlist__16u2_p8_1,
  144792. 1, -529268736, 1611661312, 5, 0,
  144793. _vq_quantlist__16u2_p8_1,
  144794. NULL,
  144795. &_vq_auxt__16u2_p8_1,
  144796. NULL,
  144797. 0
  144798. };
  144799. static long _vq_quantlist__16u2_p9_0[] = {
  144800. 5586,
  144801. 4655,
  144802. 6517,
  144803. 3724,
  144804. 7448,
  144805. 2793,
  144806. 8379,
  144807. 1862,
  144808. 9310,
  144809. 931,
  144810. 10241,
  144811. 0,
  144812. 11172,
  144813. 5521,
  144814. 5651,
  144815. };
  144816. static long _vq_lengthlist__16u2_p9_0[] = {
  144817. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144818. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144819. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144820. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144821. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144822. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144823. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144824. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144825. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144826. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144827. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144828. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144829. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144830. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144831. 5,
  144832. };
  144833. static float _vq_quantthresh__16u2_p9_0[] = {
  144834. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144835. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144836. };
  144837. static long _vq_quantmap__16u2_p9_0[] = {
  144838. 11, 9, 7, 5, 3, 1, 13, 0,
  144839. 14, 2, 4, 6, 8, 10, 12,
  144840. };
  144841. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144842. _vq_quantthresh__16u2_p9_0,
  144843. _vq_quantmap__16u2_p9_0,
  144844. 15,
  144845. 15
  144846. };
  144847. static static_codebook _16u2_p9_0 = {
  144848. 2, 225,
  144849. _vq_lengthlist__16u2_p9_0,
  144850. 1, -510275072, 1611661312, 14, 0,
  144851. _vq_quantlist__16u2_p9_0,
  144852. NULL,
  144853. &_vq_auxt__16u2_p9_0,
  144854. NULL,
  144855. 0
  144856. };
  144857. static long _vq_quantlist__16u2_p9_1[] = {
  144858. 392,
  144859. 343,
  144860. 441,
  144861. 294,
  144862. 490,
  144863. 245,
  144864. 539,
  144865. 196,
  144866. 588,
  144867. 147,
  144868. 637,
  144869. 98,
  144870. 686,
  144871. 49,
  144872. 735,
  144873. 0,
  144874. 784,
  144875. 388,
  144876. 396,
  144877. };
  144878. static long _vq_lengthlist__16u2_p9_1[] = {
  144879. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144880. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144881. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144882. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144883. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144884. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144885. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144886. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144887. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144888. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144889. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144890. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144891. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144892. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144893. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144894. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144895. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144896. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144897. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144898. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144899. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144900. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144901. 11,11,11,11,11,11,11, 5, 4,
  144902. };
  144903. static float _vq_quantthresh__16u2_p9_1[] = {
  144904. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144905. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144906. 318.5, 367.5,
  144907. };
  144908. static long _vq_quantmap__16u2_p9_1[] = {
  144909. 15, 13, 11, 9, 7, 5, 3, 1,
  144910. 17, 0, 18, 2, 4, 6, 8, 10,
  144911. 12, 14, 16,
  144912. };
  144913. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144914. _vq_quantthresh__16u2_p9_1,
  144915. _vq_quantmap__16u2_p9_1,
  144916. 19,
  144917. 19
  144918. };
  144919. static static_codebook _16u2_p9_1 = {
  144920. 2, 361,
  144921. _vq_lengthlist__16u2_p9_1,
  144922. 1, -518488064, 1611661312, 10, 0,
  144923. _vq_quantlist__16u2_p9_1,
  144924. NULL,
  144925. &_vq_auxt__16u2_p9_1,
  144926. NULL,
  144927. 0
  144928. };
  144929. static long _vq_quantlist__16u2_p9_2[] = {
  144930. 24,
  144931. 23,
  144932. 25,
  144933. 22,
  144934. 26,
  144935. 21,
  144936. 27,
  144937. 20,
  144938. 28,
  144939. 19,
  144940. 29,
  144941. 18,
  144942. 30,
  144943. 17,
  144944. 31,
  144945. 16,
  144946. 32,
  144947. 15,
  144948. 33,
  144949. 14,
  144950. 34,
  144951. 13,
  144952. 35,
  144953. 12,
  144954. 36,
  144955. 11,
  144956. 37,
  144957. 10,
  144958. 38,
  144959. 9,
  144960. 39,
  144961. 8,
  144962. 40,
  144963. 7,
  144964. 41,
  144965. 6,
  144966. 42,
  144967. 5,
  144968. 43,
  144969. 4,
  144970. 44,
  144971. 3,
  144972. 45,
  144973. 2,
  144974. 46,
  144975. 1,
  144976. 47,
  144977. 0,
  144978. 48,
  144979. };
  144980. static long _vq_lengthlist__16u2_p9_2[] = {
  144981. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144982. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144983. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144984. 11,
  144985. };
  144986. static float _vq_quantthresh__16u2_p9_2[] = {
  144987. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144988. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144989. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144990. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144991. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144992. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144993. };
  144994. static long _vq_quantmap__16u2_p9_2[] = {
  144995. 47, 45, 43, 41, 39, 37, 35, 33,
  144996. 31, 29, 27, 25, 23, 21, 19, 17,
  144997. 15, 13, 11, 9, 7, 5, 3, 1,
  144998. 0, 2, 4, 6, 8, 10, 12, 14,
  144999. 16, 18, 20, 22, 24, 26, 28, 30,
  145000. 32, 34, 36, 38, 40, 42, 44, 46,
  145001. 48,
  145002. };
  145003. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  145004. _vq_quantthresh__16u2_p9_2,
  145005. _vq_quantmap__16u2_p9_2,
  145006. 49,
  145007. 49
  145008. };
  145009. static static_codebook _16u2_p9_2 = {
  145010. 1, 49,
  145011. _vq_lengthlist__16u2_p9_2,
  145012. 1, -526909440, 1611661312, 6, 0,
  145013. _vq_quantlist__16u2_p9_2,
  145014. NULL,
  145015. &_vq_auxt__16u2_p9_2,
  145016. NULL,
  145017. 0
  145018. };
  145019. static long _vq_quantlist__8u0__p1_0[] = {
  145020. 1,
  145021. 0,
  145022. 2,
  145023. };
  145024. static long _vq_lengthlist__8u0__p1_0[] = {
  145025. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145026. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  145027. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  145028. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  145029. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  145030. 11,
  145031. };
  145032. static float _vq_quantthresh__8u0__p1_0[] = {
  145033. -0.5, 0.5,
  145034. };
  145035. static long _vq_quantmap__8u0__p1_0[] = {
  145036. 1, 0, 2,
  145037. };
  145038. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  145039. _vq_quantthresh__8u0__p1_0,
  145040. _vq_quantmap__8u0__p1_0,
  145041. 3,
  145042. 3
  145043. };
  145044. static static_codebook _8u0__p1_0 = {
  145045. 4, 81,
  145046. _vq_lengthlist__8u0__p1_0,
  145047. 1, -535822336, 1611661312, 2, 0,
  145048. _vq_quantlist__8u0__p1_0,
  145049. NULL,
  145050. &_vq_auxt__8u0__p1_0,
  145051. NULL,
  145052. 0
  145053. };
  145054. static long _vq_quantlist__8u0__p2_0[] = {
  145055. 1,
  145056. 0,
  145057. 2,
  145058. };
  145059. static long _vq_lengthlist__8u0__p2_0[] = {
  145060. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145061. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145062. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145063. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145064. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145065. 8,
  145066. };
  145067. static float _vq_quantthresh__8u0__p2_0[] = {
  145068. -0.5, 0.5,
  145069. };
  145070. static long _vq_quantmap__8u0__p2_0[] = {
  145071. 1, 0, 2,
  145072. };
  145073. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145074. _vq_quantthresh__8u0__p2_0,
  145075. _vq_quantmap__8u0__p2_0,
  145076. 3,
  145077. 3
  145078. };
  145079. static static_codebook _8u0__p2_0 = {
  145080. 4, 81,
  145081. _vq_lengthlist__8u0__p2_0,
  145082. 1, -535822336, 1611661312, 2, 0,
  145083. _vq_quantlist__8u0__p2_0,
  145084. NULL,
  145085. &_vq_auxt__8u0__p2_0,
  145086. NULL,
  145087. 0
  145088. };
  145089. static long _vq_quantlist__8u0__p3_0[] = {
  145090. 2,
  145091. 1,
  145092. 3,
  145093. 0,
  145094. 4,
  145095. };
  145096. static long _vq_lengthlist__8u0__p3_0[] = {
  145097. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145098. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145099. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145100. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145101. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145102. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145103. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145104. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145105. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145106. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145107. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145108. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145109. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145110. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145111. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145112. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145113. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145114. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145115. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145116. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145117. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145118. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145119. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145120. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145121. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145122. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145123. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145124. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145125. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145126. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145127. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145128. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145129. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145130. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145131. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145132. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145133. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145134. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145135. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145136. 16,
  145137. };
  145138. static float _vq_quantthresh__8u0__p3_0[] = {
  145139. -1.5, -0.5, 0.5, 1.5,
  145140. };
  145141. static long _vq_quantmap__8u0__p3_0[] = {
  145142. 3, 1, 0, 2, 4,
  145143. };
  145144. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145145. _vq_quantthresh__8u0__p3_0,
  145146. _vq_quantmap__8u0__p3_0,
  145147. 5,
  145148. 5
  145149. };
  145150. static static_codebook _8u0__p3_0 = {
  145151. 4, 625,
  145152. _vq_lengthlist__8u0__p3_0,
  145153. 1, -533725184, 1611661312, 3, 0,
  145154. _vq_quantlist__8u0__p3_0,
  145155. NULL,
  145156. &_vq_auxt__8u0__p3_0,
  145157. NULL,
  145158. 0
  145159. };
  145160. static long _vq_quantlist__8u0__p4_0[] = {
  145161. 2,
  145162. 1,
  145163. 3,
  145164. 0,
  145165. 4,
  145166. };
  145167. static long _vq_lengthlist__8u0__p4_0[] = {
  145168. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145169. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145170. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145171. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145172. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145173. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145174. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145175. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145176. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145177. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145178. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145179. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145180. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145181. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145182. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145183. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145184. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145185. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145186. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145187. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145188. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145189. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145190. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145191. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145192. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145193. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145194. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145195. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145196. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145197. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145198. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145199. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145200. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145201. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145202. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145203. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145204. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145205. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145206. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145207. 12,
  145208. };
  145209. static float _vq_quantthresh__8u0__p4_0[] = {
  145210. -1.5, -0.5, 0.5, 1.5,
  145211. };
  145212. static long _vq_quantmap__8u0__p4_0[] = {
  145213. 3, 1, 0, 2, 4,
  145214. };
  145215. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145216. _vq_quantthresh__8u0__p4_0,
  145217. _vq_quantmap__8u0__p4_0,
  145218. 5,
  145219. 5
  145220. };
  145221. static static_codebook _8u0__p4_0 = {
  145222. 4, 625,
  145223. _vq_lengthlist__8u0__p4_0,
  145224. 1, -533725184, 1611661312, 3, 0,
  145225. _vq_quantlist__8u0__p4_0,
  145226. NULL,
  145227. &_vq_auxt__8u0__p4_0,
  145228. NULL,
  145229. 0
  145230. };
  145231. static long _vq_quantlist__8u0__p5_0[] = {
  145232. 4,
  145233. 3,
  145234. 5,
  145235. 2,
  145236. 6,
  145237. 1,
  145238. 7,
  145239. 0,
  145240. 8,
  145241. };
  145242. static long _vq_lengthlist__8u0__p5_0[] = {
  145243. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145244. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145245. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145246. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145247. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145248. 12,
  145249. };
  145250. static float _vq_quantthresh__8u0__p5_0[] = {
  145251. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145252. };
  145253. static long _vq_quantmap__8u0__p5_0[] = {
  145254. 7, 5, 3, 1, 0, 2, 4, 6,
  145255. 8,
  145256. };
  145257. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145258. _vq_quantthresh__8u0__p5_0,
  145259. _vq_quantmap__8u0__p5_0,
  145260. 9,
  145261. 9
  145262. };
  145263. static static_codebook _8u0__p5_0 = {
  145264. 2, 81,
  145265. _vq_lengthlist__8u0__p5_0,
  145266. 1, -531628032, 1611661312, 4, 0,
  145267. _vq_quantlist__8u0__p5_0,
  145268. NULL,
  145269. &_vq_auxt__8u0__p5_0,
  145270. NULL,
  145271. 0
  145272. };
  145273. static long _vq_quantlist__8u0__p6_0[] = {
  145274. 6,
  145275. 5,
  145276. 7,
  145277. 4,
  145278. 8,
  145279. 3,
  145280. 9,
  145281. 2,
  145282. 10,
  145283. 1,
  145284. 11,
  145285. 0,
  145286. 12,
  145287. };
  145288. static long _vq_lengthlist__8u0__p6_0[] = {
  145289. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145290. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145291. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145292. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145293. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145294. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145295. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145296. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145297. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145298. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145299. 16, 0,15, 0,17, 0, 0, 0, 0,
  145300. };
  145301. static float _vq_quantthresh__8u0__p6_0[] = {
  145302. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145303. 12.5, 17.5, 22.5, 27.5,
  145304. };
  145305. static long _vq_quantmap__8u0__p6_0[] = {
  145306. 11, 9, 7, 5, 3, 1, 0, 2,
  145307. 4, 6, 8, 10, 12,
  145308. };
  145309. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145310. _vq_quantthresh__8u0__p6_0,
  145311. _vq_quantmap__8u0__p6_0,
  145312. 13,
  145313. 13
  145314. };
  145315. static static_codebook _8u0__p6_0 = {
  145316. 2, 169,
  145317. _vq_lengthlist__8u0__p6_0,
  145318. 1, -526516224, 1616117760, 4, 0,
  145319. _vq_quantlist__8u0__p6_0,
  145320. NULL,
  145321. &_vq_auxt__8u0__p6_0,
  145322. NULL,
  145323. 0
  145324. };
  145325. static long _vq_quantlist__8u0__p6_1[] = {
  145326. 2,
  145327. 1,
  145328. 3,
  145329. 0,
  145330. 4,
  145331. };
  145332. static long _vq_lengthlist__8u0__p6_1[] = {
  145333. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145334. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145335. };
  145336. static float _vq_quantthresh__8u0__p6_1[] = {
  145337. -1.5, -0.5, 0.5, 1.5,
  145338. };
  145339. static long _vq_quantmap__8u0__p6_1[] = {
  145340. 3, 1, 0, 2, 4,
  145341. };
  145342. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145343. _vq_quantthresh__8u0__p6_1,
  145344. _vq_quantmap__8u0__p6_1,
  145345. 5,
  145346. 5
  145347. };
  145348. static static_codebook _8u0__p6_1 = {
  145349. 2, 25,
  145350. _vq_lengthlist__8u0__p6_1,
  145351. 1, -533725184, 1611661312, 3, 0,
  145352. _vq_quantlist__8u0__p6_1,
  145353. NULL,
  145354. &_vq_auxt__8u0__p6_1,
  145355. NULL,
  145356. 0
  145357. };
  145358. static long _vq_quantlist__8u0__p7_0[] = {
  145359. 1,
  145360. 0,
  145361. 2,
  145362. };
  145363. static long _vq_lengthlist__8u0__p7_0[] = {
  145364. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145365. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145366. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145367. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145368. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145369. 7,
  145370. };
  145371. static float _vq_quantthresh__8u0__p7_0[] = {
  145372. -157.5, 157.5,
  145373. };
  145374. static long _vq_quantmap__8u0__p7_0[] = {
  145375. 1, 0, 2,
  145376. };
  145377. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145378. _vq_quantthresh__8u0__p7_0,
  145379. _vq_quantmap__8u0__p7_0,
  145380. 3,
  145381. 3
  145382. };
  145383. static static_codebook _8u0__p7_0 = {
  145384. 4, 81,
  145385. _vq_lengthlist__8u0__p7_0,
  145386. 1, -518803456, 1628680192, 2, 0,
  145387. _vq_quantlist__8u0__p7_0,
  145388. NULL,
  145389. &_vq_auxt__8u0__p7_0,
  145390. NULL,
  145391. 0
  145392. };
  145393. static long _vq_quantlist__8u0__p7_1[] = {
  145394. 7,
  145395. 6,
  145396. 8,
  145397. 5,
  145398. 9,
  145399. 4,
  145400. 10,
  145401. 3,
  145402. 11,
  145403. 2,
  145404. 12,
  145405. 1,
  145406. 13,
  145407. 0,
  145408. 14,
  145409. };
  145410. static long _vq_lengthlist__8u0__p7_1[] = {
  145411. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145412. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145413. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145414. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145415. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145416. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145417. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145418. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145419. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145420. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145421. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145422. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145423. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145424. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145425. 10,
  145426. };
  145427. static float _vq_quantthresh__8u0__p7_1[] = {
  145428. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145429. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145430. };
  145431. static long _vq_quantmap__8u0__p7_1[] = {
  145432. 13, 11, 9, 7, 5, 3, 1, 0,
  145433. 2, 4, 6, 8, 10, 12, 14,
  145434. };
  145435. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145436. _vq_quantthresh__8u0__p7_1,
  145437. _vq_quantmap__8u0__p7_1,
  145438. 15,
  145439. 15
  145440. };
  145441. static static_codebook _8u0__p7_1 = {
  145442. 2, 225,
  145443. _vq_lengthlist__8u0__p7_1,
  145444. 1, -520986624, 1620377600, 4, 0,
  145445. _vq_quantlist__8u0__p7_1,
  145446. NULL,
  145447. &_vq_auxt__8u0__p7_1,
  145448. NULL,
  145449. 0
  145450. };
  145451. static long _vq_quantlist__8u0__p7_2[] = {
  145452. 10,
  145453. 9,
  145454. 11,
  145455. 8,
  145456. 12,
  145457. 7,
  145458. 13,
  145459. 6,
  145460. 14,
  145461. 5,
  145462. 15,
  145463. 4,
  145464. 16,
  145465. 3,
  145466. 17,
  145467. 2,
  145468. 18,
  145469. 1,
  145470. 19,
  145471. 0,
  145472. 20,
  145473. };
  145474. static long _vq_lengthlist__8u0__p7_2[] = {
  145475. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145476. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145477. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145478. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145479. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145480. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145481. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145482. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145483. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145484. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145485. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145486. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145487. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145488. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145489. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145490. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145491. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145492. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145493. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145494. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145495. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145496. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145497. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145498. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145499. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145500. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145501. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145502. 11,12,11,11,11,10,10,11,11,
  145503. };
  145504. static float _vq_quantthresh__8u0__p7_2[] = {
  145505. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145506. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145507. 6.5, 7.5, 8.5, 9.5,
  145508. };
  145509. static long _vq_quantmap__8u0__p7_2[] = {
  145510. 19, 17, 15, 13, 11, 9, 7, 5,
  145511. 3, 1, 0, 2, 4, 6, 8, 10,
  145512. 12, 14, 16, 18, 20,
  145513. };
  145514. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145515. _vq_quantthresh__8u0__p7_2,
  145516. _vq_quantmap__8u0__p7_2,
  145517. 21,
  145518. 21
  145519. };
  145520. static static_codebook _8u0__p7_2 = {
  145521. 2, 441,
  145522. _vq_lengthlist__8u0__p7_2,
  145523. 1, -529268736, 1611661312, 5, 0,
  145524. _vq_quantlist__8u0__p7_2,
  145525. NULL,
  145526. &_vq_auxt__8u0__p7_2,
  145527. NULL,
  145528. 0
  145529. };
  145530. static long _huff_lengthlist__8u0__single[] = {
  145531. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145532. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145533. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145534. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145535. };
  145536. static static_codebook _huff_book__8u0__single = {
  145537. 2, 64,
  145538. _huff_lengthlist__8u0__single,
  145539. 0, 0, 0, 0, 0,
  145540. NULL,
  145541. NULL,
  145542. NULL,
  145543. NULL,
  145544. 0
  145545. };
  145546. static long _vq_quantlist__8u1__p1_0[] = {
  145547. 1,
  145548. 0,
  145549. 2,
  145550. };
  145551. static long _vq_lengthlist__8u1__p1_0[] = {
  145552. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145553. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145554. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145555. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145556. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145557. 10,
  145558. };
  145559. static float _vq_quantthresh__8u1__p1_0[] = {
  145560. -0.5, 0.5,
  145561. };
  145562. static long _vq_quantmap__8u1__p1_0[] = {
  145563. 1, 0, 2,
  145564. };
  145565. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145566. _vq_quantthresh__8u1__p1_0,
  145567. _vq_quantmap__8u1__p1_0,
  145568. 3,
  145569. 3
  145570. };
  145571. static static_codebook _8u1__p1_0 = {
  145572. 4, 81,
  145573. _vq_lengthlist__8u1__p1_0,
  145574. 1, -535822336, 1611661312, 2, 0,
  145575. _vq_quantlist__8u1__p1_0,
  145576. NULL,
  145577. &_vq_auxt__8u1__p1_0,
  145578. NULL,
  145579. 0
  145580. };
  145581. static long _vq_quantlist__8u1__p2_0[] = {
  145582. 1,
  145583. 0,
  145584. 2,
  145585. };
  145586. static long _vq_lengthlist__8u1__p2_0[] = {
  145587. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145588. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145589. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145590. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145591. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145592. 7,
  145593. };
  145594. static float _vq_quantthresh__8u1__p2_0[] = {
  145595. -0.5, 0.5,
  145596. };
  145597. static long _vq_quantmap__8u1__p2_0[] = {
  145598. 1, 0, 2,
  145599. };
  145600. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145601. _vq_quantthresh__8u1__p2_0,
  145602. _vq_quantmap__8u1__p2_0,
  145603. 3,
  145604. 3
  145605. };
  145606. static static_codebook _8u1__p2_0 = {
  145607. 4, 81,
  145608. _vq_lengthlist__8u1__p2_0,
  145609. 1, -535822336, 1611661312, 2, 0,
  145610. _vq_quantlist__8u1__p2_0,
  145611. NULL,
  145612. &_vq_auxt__8u1__p2_0,
  145613. NULL,
  145614. 0
  145615. };
  145616. static long _vq_quantlist__8u1__p3_0[] = {
  145617. 2,
  145618. 1,
  145619. 3,
  145620. 0,
  145621. 4,
  145622. };
  145623. static long _vq_lengthlist__8u1__p3_0[] = {
  145624. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145625. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145626. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145627. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145628. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145629. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145630. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145631. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145632. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145633. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145634. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145635. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145636. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145637. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145638. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145639. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145640. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145641. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145642. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145643. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145644. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145645. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145646. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145647. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145648. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145649. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145650. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145651. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145652. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145653. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145654. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145655. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145656. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145657. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145658. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145659. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145660. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145661. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145662. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145663. 16,
  145664. };
  145665. static float _vq_quantthresh__8u1__p3_0[] = {
  145666. -1.5, -0.5, 0.5, 1.5,
  145667. };
  145668. static long _vq_quantmap__8u1__p3_0[] = {
  145669. 3, 1, 0, 2, 4,
  145670. };
  145671. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145672. _vq_quantthresh__8u1__p3_0,
  145673. _vq_quantmap__8u1__p3_0,
  145674. 5,
  145675. 5
  145676. };
  145677. static static_codebook _8u1__p3_0 = {
  145678. 4, 625,
  145679. _vq_lengthlist__8u1__p3_0,
  145680. 1, -533725184, 1611661312, 3, 0,
  145681. _vq_quantlist__8u1__p3_0,
  145682. NULL,
  145683. &_vq_auxt__8u1__p3_0,
  145684. NULL,
  145685. 0
  145686. };
  145687. static long _vq_quantlist__8u1__p4_0[] = {
  145688. 2,
  145689. 1,
  145690. 3,
  145691. 0,
  145692. 4,
  145693. };
  145694. static long _vq_lengthlist__8u1__p4_0[] = {
  145695. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145696. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145697. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145698. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145699. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145700. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145701. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145702. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145703. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145704. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145705. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145706. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145707. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145708. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145709. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145710. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145711. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145712. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145713. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145714. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145715. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145716. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145717. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145718. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145719. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145720. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145721. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145722. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145723. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145724. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145725. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145726. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145727. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145728. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145729. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145730. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145731. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145732. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145733. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145734. 10,
  145735. };
  145736. static float _vq_quantthresh__8u1__p4_0[] = {
  145737. -1.5, -0.5, 0.5, 1.5,
  145738. };
  145739. static long _vq_quantmap__8u1__p4_0[] = {
  145740. 3, 1, 0, 2, 4,
  145741. };
  145742. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145743. _vq_quantthresh__8u1__p4_0,
  145744. _vq_quantmap__8u1__p4_0,
  145745. 5,
  145746. 5
  145747. };
  145748. static static_codebook _8u1__p4_0 = {
  145749. 4, 625,
  145750. _vq_lengthlist__8u1__p4_0,
  145751. 1, -533725184, 1611661312, 3, 0,
  145752. _vq_quantlist__8u1__p4_0,
  145753. NULL,
  145754. &_vq_auxt__8u1__p4_0,
  145755. NULL,
  145756. 0
  145757. };
  145758. static long _vq_quantlist__8u1__p5_0[] = {
  145759. 4,
  145760. 3,
  145761. 5,
  145762. 2,
  145763. 6,
  145764. 1,
  145765. 7,
  145766. 0,
  145767. 8,
  145768. };
  145769. static long _vq_lengthlist__8u1__p5_0[] = {
  145770. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145771. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145772. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145773. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145774. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145775. 13,
  145776. };
  145777. static float _vq_quantthresh__8u1__p5_0[] = {
  145778. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145779. };
  145780. static long _vq_quantmap__8u1__p5_0[] = {
  145781. 7, 5, 3, 1, 0, 2, 4, 6,
  145782. 8,
  145783. };
  145784. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145785. _vq_quantthresh__8u1__p5_0,
  145786. _vq_quantmap__8u1__p5_0,
  145787. 9,
  145788. 9
  145789. };
  145790. static static_codebook _8u1__p5_0 = {
  145791. 2, 81,
  145792. _vq_lengthlist__8u1__p5_0,
  145793. 1, -531628032, 1611661312, 4, 0,
  145794. _vq_quantlist__8u1__p5_0,
  145795. NULL,
  145796. &_vq_auxt__8u1__p5_0,
  145797. NULL,
  145798. 0
  145799. };
  145800. static long _vq_quantlist__8u1__p6_0[] = {
  145801. 4,
  145802. 3,
  145803. 5,
  145804. 2,
  145805. 6,
  145806. 1,
  145807. 7,
  145808. 0,
  145809. 8,
  145810. };
  145811. static long _vq_lengthlist__8u1__p6_0[] = {
  145812. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145813. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145814. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145815. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145816. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145817. 10,
  145818. };
  145819. static float _vq_quantthresh__8u1__p6_0[] = {
  145820. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145821. };
  145822. static long _vq_quantmap__8u1__p6_0[] = {
  145823. 7, 5, 3, 1, 0, 2, 4, 6,
  145824. 8,
  145825. };
  145826. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145827. _vq_quantthresh__8u1__p6_0,
  145828. _vq_quantmap__8u1__p6_0,
  145829. 9,
  145830. 9
  145831. };
  145832. static static_codebook _8u1__p6_0 = {
  145833. 2, 81,
  145834. _vq_lengthlist__8u1__p6_0,
  145835. 1, -531628032, 1611661312, 4, 0,
  145836. _vq_quantlist__8u1__p6_0,
  145837. NULL,
  145838. &_vq_auxt__8u1__p6_0,
  145839. NULL,
  145840. 0
  145841. };
  145842. static long _vq_quantlist__8u1__p7_0[] = {
  145843. 1,
  145844. 0,
  145845. 2,
  145846. };
  145847. static long _vq_lengthlist__8u1__p7_0[] = {
  145848. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145849. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145850. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145851. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145852. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145853. 11,
  145854. };
  145855. static float _vq_quantthresh__8u1__p7_0[] = {
  145856. -5.5, 5.5,
  145857. };
  145858. static long _vq_quantmap__8u1__p7_0[] = {
  145859. 1, 0, 2,
  145860. };
  145861. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145862. _vq_quantthresh__8u1__p7_0,
  145863. _vq_quantmap__8u1__p7_0,
  145864. 3,
  145865. 3
  145866. };
  145867. static static_codebook _8u1__p7_0 = {
  145868. 4, 81,
  145869. _vq_lengthlist__8u1__p7_0,
  145870. 1, -529137664, 1618345984, 2, 0,
  145871. _vq_quantlist__8u1__p7_0,
  145872. NULL,
  145873. &_vq_auxt__8u1__p7_0,
  145874. NULL,
  145875. 0
  145876. };
  145877. static long _vq_quantlist__8u1__p7_1[] = {
  145878. 5,
  145879. 4,
  145880. 6,
  145881. 3,
  145882. 7,
  145883. 2,
  145884. 8,
  145885. 1,
  145886. 9,
  145887. 0,
  145888. 10,
  145889. };
  145890. static long _vq_lengthlist__8u1__p7_1[] = {
  145891. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145892. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145893. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145894. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145895. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145896. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145897. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145898. 9, 9, 9, 9, 9,10,10,10,10,
  145899. };
  145900. static float _vq_quantthresh__8u1__p7_1[] = {
  145901. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145902. 3.5, 4.5,
  145903. };
  145904. static long _vq_quantmap__8u1__p7_1[] = {
  145905. 9, 7, 5, 3, 1, 0, 2, 4,
  145906. 6, 8, 10,
  145907. };
  145908. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145909. _vq_quantthresh__8u1__p7_1,
  145910. _vq_quantmap__8u1__p7_1,
  145911. 11,
  145912. 11
  145913. };
  145914. static static_codebook _8u1__p7_1 = {
  145915. 2, 121,
  145916. _vq_lengthlist__8u1__p7_1,
  145917. 1, -531365888, 1611661312, 4, 0,
  145918. _vq_quantlist__8u1__p7_1,
  145919. NULL,
  145920. &_vq_auxt__8u1__p7_1,
  145921. NULL,
  145922. 0
  145923. };
  145924. static long _vq_quantlist__8u1__p8_0[] = {
  145925. 5,
  145926. 4,
  145927. 6,
  145928. 3,
  145929. 7,
  145930. 2,
  145931. 8,
  145932. 1,
  145933. 9,
  145934. 0,
  145935. 10,
  145936. };
  145937. static long _vq_lengthlist__8u1__p8_0[] = {
  145938. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145939. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145940. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145941. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145942. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145943. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145944. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145945. 12,13,13,14,14,15,15,15,15,
  145946. };
  145947. static float _vq_quantthresh__8u1__p8_0[] = {
  145948. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145949. 38.5, 49.5,
  145950. };
  145951. static long _vq_quantmap__8u1__p8_0[] = {
  145952. 9, 7, 5, 3, 1, 0, 2, 4,
  145953. 6, 8, 10,
  145954. };
  145955. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145956. _vq_quantthresh__8u1__p8_0,
  145957. _vq_quantmap__8u1__p8_0,
  145958. 11,
  145959. 11
  145960. };
  145961. static static_codebook _8u1__p8_0 = {
  145962. 2, 121,
  145963. _vq_lengthlist__8u1__p8_0,
  145964. 1, -524582912, 1618345984, 4, 0,
  145965. _vq_quantlist__8u1__p8_0,
  145966. NULL,
  145967. &_vq_auxt__8u1__p8_0,
  145968. NULL,
  145969. 0
  145970. };
  145971. static long _vq_quantlist__8u1__p8_1[] = {
  145972. 5,
  145973. 4,
  145974. 6,
  145975. 3,
  145976. 7,
  145977. 2,
  145978. 8,
  145979. 1,
  145980. 9,
  145981. 0,
  145982. 10,
  145983. };
  145984. static long _vq_lengthlist__8u1__p8_1[] = {
  145985. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145986. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145987. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145988. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145989. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145990. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145991. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145992. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145993. };
  145994. static float _vq_quantthresh__8u1__p8_1[] = {
  145995. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145996. 3.5, 4.5,
  145997. };
  145998. static long _vq_quantmap__8u1__p8_1[] = {
  145999. 9, 7, 5, 3, 1, 0, 2, 4,
  146000. 6, 8, 10,
  146001. };
  146002. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  146003. _vq_quantthresh__8u1__p8_1,
  146004. _vq_quantmap__8u1__p8_1,
  146005. 11,
  146006. 11
  146007. };
  146008. static static_codebook _8u1__p8_1 = {
  146009. 2, 121,
  146010. _vq_lengthlist__8u1__p8_1,
  146011. 1, -531365888, 1611661312, 4, 0,
  146012. _vq_quantlist__8u1__p8_1,
  146013. NULL,
  146014. &_vq_auxt__8u1__p8_1,
  146015. NULL,
  146016. 0
  146017. };
  146018. static long _vq_quantlist__8u1__p9_0[] = {
  146019. 7,
  146020. 6,
  146021. 8,
  146022. 5,
  146023. 9,
  146024. 4,
  146025. 10,
  146026. 3,
  146027. 11,
  146028. 2,
  146029. 12,
  146030. 1,
  146031. 13,
  146032. 0,
  146033. 14,
  146034. };
  146035. static long _vq_lengthlist__8u1__p9_0[] = {
  146036. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  146037. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  146038. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146039. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146040. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146041. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146042. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146043. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146044. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146045. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146046. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146047. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146048. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146049. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146050. 10,
  146051. };
  146052. static float _vq_quantthresh__8u1__p9_0[] = {
  146053. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146054. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146055. };
  146056. static long _vq_quantmap__8u1__p9_0[] = {
  146057. 13, 11, 9, 7, 5, 3, 1, 0,
  146058. 2, 4, 6, 8, 10, 12, 14,
  146059. };
  146060. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146061. _vq_quantthresh__8u1__p9_0,
  146062. _vq_quantmap__8u1__p9_0,
  146063. 15,
  146064. 15
  146065. };
  146066. static static_codebook _8u1__p9_0 = {
  146067. 2, 225,
  146068. _vq_lengthlist__8u1__p9_0,
  146069. 1, -514071552, 1627381760, 4, 0,
  146070. _vq_quantlist__8u1__p9_0,
  146071. NULL,
  146072. &_vq_auxt__8u1__p9_0,
  146073. NULL,
  146074. 0
  146075. };
  146076. static long _vq_quantlist__8u1__p9_1[] = {
  146077. 7,
  146078. 6,
  146079. 8,
  146080. 5,
  146081. 9,
  146082. 4,
  146083. 10,
  146084. 3,
  146085. 11,
  146086. 2,
  146087. 12,
  146088. 1,
  146089. 13,
  146090. 0,
  146091. 14,
  146092. };
  146093. static long _vq_lengthlist__8u1__p9_1[] = {
  146094. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146095. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146096. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146097. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146098. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146099. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146100. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146101. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146102. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146103. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146104. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146105. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146106. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146107. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146108. 13,
  146109. };
  146110. static float _vq_quantthresh__8u1__p9_1[] = {
  146111. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146112. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146113. };
  146114. static long _vq_quantmap__8u1__p9_1[] = {
  146115. 13, 11, 9, 7, 5, 3, 1, 0,
  146116. 2, 4, 6, 8, 10, 12, 14,
  146117. };
  146118. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146119. _vq_quantthresh__8u1__p9_1,
  146120. _vq_quantmap__8u1__p9_1,
  146121. 15,
  146122. 15
  146123. };
  146124. static static_codebook _8u1__p9_1 = {
  146125. 2, 225,
  146126. _vq_lengthlist__8u1__p9_1,
  146127. 1, -522338304, 1620115456, 4, 0,
  146128. _vq_quantlist__8u1__p9_1,
  146129. NULL,
  146130. &_vq_auxt__8u1__p9_1,
  146131. NULL,
  146132. 0
  146133. };
  146134. static long _vq_quantlist__8u1__p9_2[] = {
  146135. 8,
  146136. 7,
  146137. 9,
  146138. 6,
  146139. 10,
  146140. 5,
  146141. 11,
  146142. 4,
  146143. 12,
  146144. 3,
  146145. 13,
  146146. 2,
  146147. 14,
  146148. 1,
  146149. 15,
  146150. 0,
  146151. 16,
  146152. };
  146153. static long _vq_lengthlist__8u1__p9_2[] = {
  146154. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146155. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146156. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146157. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146158. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146159. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146160. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146161. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146162. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146163. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146164. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146165. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146166. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146167. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146168. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146169. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146170. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146171. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146172. 10,
  146173. };
  146174. static float _vq_quantthresh__8u1__p9_2[] = {
  146175. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146176. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146177. };
  146178. static long _vq_quantmap__8u1__p9_2[] = {
  146179. 15, 13, 11, 9, 7, 5, 3, 1,
  146180. 0, 2, 4, 6, 8, 10, 12, 14,
  146181. 16,
  146182. };
  146183. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146184. _vq_quantthresh__8u1__p9_2,
  146185. _vq_quantmap__8u1__p9_2,
  146186. 17,
  146187. 17
  146188. };
  146189. static static_codebook _8u1__p9_2 = {
  146190. 2, 289,
  146191. _vq_lengthlist__8u1__p9_2,
  146192. 1, -529530880, 1611661312, 5, 0,
  146193. _vq_quantlist__8u1__p9_2,
  146194. NULL,
  146195. &_vq_auxt__8u1__p9_2,
  146196. NULL,
  146197. 0
  146198. };
  146199. static long _huff_lengthlist__8u1__single[] = {
  146200. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146201. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146202. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146203. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146204. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146205. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146206. 13, 8, 8,15,
  146207. };
  146208. static static_codebook _huff_book__8u1__single = {
  146209. 2, 100,
  146210. _huff_lengthlist__8u1__single,
  146211. 0, 0, 0, 0, 0,
  146212. NULL,
  146213. NULL,
  146214. NULL,
  146215. NULL,
  146216. 0
  146217. };
  146218. static long _huff_lengthlist__44u0__long[] = {
  146219. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146220. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146221. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146222. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146223. };
  146224. static static_codebook _huff_book__44u0__long = {
  146225. 2, 64,
  146226. _huff_lengthlist__44u0__long,
  146227. 0, 0, 0, 0, 0,
  146228. NULL,
  146229. NULL,
  146230. NULL,
  146231. NULL,
  146232. 0
  146233. };
  146234. static long _vq_quantlist__44u0__p1_0[] = {
  146235. 1,
  146236. 0,
  146237. 2,
  146238. };
  146239. static long _vq_lengthlist__44u0__p1_0[] = {
  146240. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146241. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146242. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146243. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146244. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146245. 13,
  146246. };
  146247. static float _vq_quantthresh__44u0__p1_0[] = {
  146248. -0.5, 0.5,
  146249. };
  146250. static long _vq_quantmap__44u0__p1_0[] = {
  146251. 1, 0, 2,
  146252. };
  146253. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146254. _vq_quantthresh__44u0__p1_0,
  146255. _vq_quantmap__44u0__p1_0,
  146256. 3,
  146257. 3
  146258. };
  146259. static static_codebook _44u0__p1_0 = {
  146260. 4, 81,
  146261. _vq_lengthlist__44u0__p1_0,
  146262. 1, -535822336, 1611661312, 2, 0,
  146263. _vq_quantlist__44u0__p1_0,
  146264. NULL,
  146265. &_vq_auxt__44u0__p1_0,
  146266. NULL,
  146267. 0
  146268. };
  146269. static long _vq_quantlist__44u0__p2_0[] = {
  146270. 1,
  146271. 0,
  146272. 2,
  146273. };
  146274. static long _vq_lengthlist__44u0__p2_0[] = {
  146275. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146276. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146277. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146278. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146279. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146280. 9,
  146281. };
  146282. static float _vq_quantthresh__44u0__p2_0[] = {
  146283. -0.5, 0.5,
  146284. };
  146285. static long _vq_quantmap__44u0__p2_0[] = {
  146286. 1, 0, 2,
  146287. };
  146288. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146289. _vq_quantthresh__44u0__p2_0,
  146290. _vq_quantmap__44u0__p2_0,
  146291. 3,
  146292. 3
  146293. };
  146294. static static_codebook _44u0__p2_0 = {
  146295. 4, 81,
  146296. _vq_lengthlist__44u0__p2_0,
  146297. 1, -535822336, 1611661312, 2, 0,
  146298. _vq_quantlist__44u0__p2_0,
  146299. NULL,
  146300. &_vq_auxt__44u0__p2_0,
  146301. NULL,
  146302. 0
  146303. };
  146304. static long _vq_quantlist__44u0__p3_0[] = {
  146305. 2,
  146306. 1,
  146307. 3,
  146308. 0,
  146309. 4,
  146310. };
  146311. static long _vq_lengthlist__44u0__p3_0[] = {
  146312. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146313. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146314. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146315. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146316. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146317. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146318. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146319. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146320. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146321. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146322. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146323. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146324. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146325. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146326. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146327. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146328. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146329. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146330. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146331. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146332. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146333. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146334. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146335. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146336. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146337. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146338. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146339. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146340. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146341. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146342. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146343. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146344. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146345. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146346. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146347. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146348. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146349. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146350. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146351. 19,
  146352. };
  146353. static float _vq_quantthresh__44u0__p3_0[] = {
  146354. -1.5, -0.5, 0.5, 1.5,
  146355. };
  146356. static long _vq_quantmap__44u0__p3_0[] = {
  146357. 3, 1, 0, 2, 4,
  146358. };
  146359. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146360. _vq_quantthresh__44u0__p3_0,
  146361. _vq_quantmap__44u0__p3_0,
  146362. 5,
  146363. 5
  146364. };
  146365. static static_codebook _44u0__p3_0 = {
  146366. 4, 625,
  146367. _vq_lengthlist__44u0__p3_0,
  146368. 1, -533725184, 1611661312, 3, 0,
  146369. _vq_quantlist__44u0__p3_0,
  146370. NULL,
  146371. &_vq_auxt__44u0__p3_0,
  146372. NULL,
  146373. 0
  146374. };
  146375. static long _vq_quantlist__44u0__p4_0[] = {
  146376. 2,
  146377. 1,
  146378. 3,
  146379. 0,
  146380. 4,
  146381. };
  146382. static long _vq_lengthlist__44u0__p4_0[] = {
  146383. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146384. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146385. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146386. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146387. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146388. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146389. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146390. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146391. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146392. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146393. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146394. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146395. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146396. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146397. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146398. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146399. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146400. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146401. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146402. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146403. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146404. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146405. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146406. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146407. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146408. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146409. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146410. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146411. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146412. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146413. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146414. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146415. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146416. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146417. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146418. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146419. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146420. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146421. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146422. 12,
  146423. };
  146424. static float _vq_quantthresh__44u0__p4_0[] = {
  146425. -1.5, -0.5, 0.5, 1.5,
  146426. };
  146427. static long _vq_quantmap__44u0__p4_0[] = {
  146428. 3, 1, 0, 2, 4,
  146429. };
  146430. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146431. _vq_quantthresh__44u0__p4_0,
  146432. _vq_quantmap__44u0__p4_0,
  146433. 5,
  146434. 5
  146435. };
  146436. static static_codebook _44u0__p4_0 = {
  146437. 4, 625,
  146438. _vq_lengthlist__44u0__p4_0,
  146439. 1, -533725184, 1611661312, 3, 0,
  146440. _vq_quantlist__44u0__p4_0,
  146441. NULL,
  146442. &_vq_auxt__44u0__p4_0,
  146443. NULL,
  146444. 0
  146445. };
  146446. static long _vq_quantlist__44u0__p5_0[] = {
  146447. 4,
  146448. 3,
  146449. 5,
  146450. 2,
  146451. 6,
  146452. 1,
  146453. 7,
  146454. 0,
  146455. 8,
  146456. };
  146457. static long _vq_lengthlist__44u0__p5_0[] = {
  146458. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146459. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146460. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146461. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146462. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146463. 12,
  146464. };
  146465. static float _vq_quantthresh__44u0__p5_0[] = {
  146466. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146467. };
  146468. static long _vq_quantmap__44u0__p5_0[] = {
  146469. 7, 5, 3, 1, 0, 2, 4, 6,
  146470. 8,
  146471. };
  146472. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146473. _vq_quantthresh__44u0__p5_0,
  146474. _vq_quantmap__44u0__p5_0,
  146475. 9,
  146476. 9
  146477. };
  146478. static static_codebook _44u0__p5_0 = {
  146479. 2, 81,
  146480. _vq_lengthlist__44u0__p5_0,
  146481. 1, -531628032, 1611661312, 4, 0,
  146482. _vq_quantlist__44u0__p5_0,
  146483. NULL,
  146484. &_vq_auxt__44u0__p5_0,
  146485. NULL,
  146486. 0
  146487. };
  146488. static long _vq_quantlist__44u0__p6_0[] = {
  146489. 6,
  146490. 5,
  146491. 7,
  146492. 4,
  146493. 8,
  146494. 3,
  146495. 9,
  146496. 2,
  146497. 10,
  146498. 1,
  146499. 11,
  146500. 0,
  146501. 12,
  146502. };
  146503. static long _vq_lengthlist__44u0__p6_0[] = {
  146504. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146505. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146506. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146507. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146508. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146509. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146510. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146511. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146512. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146513. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146514. 15,17,16,17,18,17,17,18, 0,
  146515. };
  146516. static float _vq_quantthresh__44u0__p6_0[] = {
  146517. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146518. 12.5, 17.5, 22.5, 27.5,
  146519. };
  146520. static long _vq_quantmap__44u0__p6_0[] = {
  146521. 11, 9, 7, 5, 3, 1, 0, 2,
  146522. 4, 6, 8, 10, 12,
  146523. };
  146524. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146525. _vq_quantthresh__44u0__p6_0,
  146526. _vq_quantmap__44u0__p6_0,
  146527. 13,
  146528. 13
  146529. };
  146530. static static_codebook _44u0__p6_0 = {
  146531. 2, 169,
  146532. _vq_lengthlist__44u0__p6_0,
  146533. 1, -526516224, 1616117760, 4, 0,
  146534. _vq_quantlist__44u0__p6_0,
  146535. NULL,
  146536. &_vq_auxt__44u0__p6_0,
  146537. NULL,
  146538. 0
  146539. };
  146540. static long _vq_quantlist__44u0__p6_1[] = {
  146541. 2,
  146542. 1,
  146543. 3,
  146544. 0,
  146545. 4,
  146546. };
  146547. static long _vq_lengthlist__44u0__p6_1[] = {
  146548. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146549. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146550. };
  146551. static float _vq_quantthresh__44u0__p6_1[] = {
  146552. -1.5, -0.5, 0.5, 1.5,
  146553. };
  146554. static long _vq_quantmap__44u0__p6_1[] = {
  146555. 3, 1, 0, 2, 4,
  146556. };
  146557. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146558. _vq_quantthresh__44u0__p6_1,
  146559. _vq_quantmap__44u0__p6_1,
  146560. 5,
  146561. 5
  146562. };
  146563. static static_codebook _44u0__p6_1 = {
  146564. 2, 25,
  146565. _vq_lengthlist__44u0__p6_1,
  146566. 1, -533725184, 1611661312, 3, 0,
  146567. _vq_quantlist__44u0__p6_1,
  146568. NULL,
  146569. &_vq_auxt__44u0__p6_1,
  146570. NULL,
  146571. 0
  146572. };
  146573. static long _vq_quantlist__44u0__p7_0[] = {
  146574. 2,
  146575. 1,
  146576. 3,
  146577. 0,
  146578. 4,
  146579. };
  146580. static long _vq_lengthlist__44u0__p7_0[] = {
  146581. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146582. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146583. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146584. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146585. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146586. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146587. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146588. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146589. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146590. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146591. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146592. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146593. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146594. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146595. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146596. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146597. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146598. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146599. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146602. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146603. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146604. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146605. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146606. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146607. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146608. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146609. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146610. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146611. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146612. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146613. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146614. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146615. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146616. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146617. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146618. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146619. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146620. 10,
  146621. };
  146622. static float _vq_quantthresh__44u0__p7_0[] = {
  146623. -253.5, -84.5, 84.5, 253.5,
  146624. };
  146625. static long _vq_quantmap__44u0__p7_0[] = {
  146626. 3, 1, 0, 2, 4,
  146627. };
  146628. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146629. _vq_quantthresh__44u0__p7_0,
  146630. _vq_quantmap__44u0__p7_0,
  146631. 5,
  146632. 5
  146633. };
  146634. static static_codebook _44u0__p7_0 = {
  146635. 4, 625,
  146636. _vq_lengthlist__44u0__p7_0,
  146637. 1, -518709248, 1626677248, 3, 0,
  146638. _vq_quantlist__44u0__p7_0,
  146639. NULL,
  146640. &_vq_auxt__44u0__p7_0,
  146641. NULL,
  146642. 0
  146643. };
  146644. static long _vq_quantlist__44u0__p7_1[] = {
  146645. 6,
  146646. 5,
  146647. 7,
  146648. 4,
  146649. 8,
  146650. 3,
  146651. 9,
  146652. 2,
  146653. 10,
  146654. 1,
  146655. 11,
  146656. 0,
  146657. 12,
  146658. };
  146659. static long _vq_lengthlist__44u0__p7_1[] = {
  146660. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146661. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146662. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146663. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146664. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146665. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146666. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146667. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146668. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146669. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146670. 15,15,15,15,15,15,15,15,15,
  146671. };
  146672. static float _vq_quantthresh__44u0__p7_1[] = {
  146673. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146674. 32.5, 45.5, 58.5, 71.5,
  146675. };
  146676. static long _vq_quantmap__44u0__p7_1[] = {
  146677. 11, 9, 7, 5, 3, 1, 0, 2,
  146678. 4, 6, 8, 10, 12,
  146679. };
  146680. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146681. _vq_quantthresh__44u0__p7_1,
  146682. _vq_quantmap__44u0__p7_1,
  146683. 13,
  146684. 13
  146685. };
  146686. static static_codebook _44u0__p7_1 = {
  146687. 2, 169,
  146688. _vq_lengthlist__44u0__p7_1,
  146689. 1, -523010048, 1618608128, 4, 0,
  146690. _vq_quantlist__44u0__p7_1,
  146691. NULL,
  146692. &_vq_auxt__44u0__p7_1,
  146693. NULL,
  146694. 0
  146695. };
  146696. static long _vq_quantlist__44u0__p7_2[] = {
  146697. 6,
  146698. 5,
  146699. 7,
  146700. 4,
  146701. 8,
  146702. 3,
  146703. 9,
  146704. 2,
  146705. 10,
  146706. 1,
  146707. 11,
  146708. 0,
  146709. 12,
  146710. };
  146711. static long _vq_lengthlist__44u0__p7_2[] = {
  146712. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146713. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146714. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146715. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146716. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146717. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146718. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146719. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146720. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146721. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146722. 9, 9, 9,10, 9, 9,10,10, 9,
  146723. };
  146724. static float _vq_quantthresh__44u0__p7_2[] = {
  146725. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146726. 2.5, 3.5, 4.5, 5.5,
  146727. };
  146728. static long _vq_quantmap__44u0__p7_2[] = {
  146729. 11, 9, 7, 5, 3, 1, 0, 2,
  146730. 4, 6, 8, 10, 12,
  146731. };
  146732. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146733. _vq_quantthresh__44u0__p7_2,
  146734. _vq_quantmap__44u0__p7_2,
  146735. 13,
  146736. 13
  146737. };
  146738. static static_codebook _44u0__p7_2 = {
  146739. 2, 169,
  146740. _vq_lengthlist__44u0__p7_2,
  146741. 1, -531103744, 1611661312, 4, 0,
  146742. _vq_quantlist__44u0__p7_2,
  146743. NULL,
  146744. &_vq_auxt__44u0__p7_2,
  146745. NULL,
  146746. 0
  146747. };
  146748. static long _huff_lengthlist__44u0__short[] = {
  146749. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146750. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146751. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146752. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146753. };
  146754. static static_codebook _huff_book__44u0__short = {
  146755. 2, 64,
  146756. _huff_lengthlist__44u0__short,
  146757. 0, 0, 0, 0, 0,
  146758. NULL,
  146759. NULL,
  146760. NULL,
  146761. NULL,
  146762. 0
  146763. };
  146764. static long _huff_lengthlist__44u1__long[] = {
  146765. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146766. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146767. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146768. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146769. };
  146770. static static_codebook _huff_book__44u1__long = {
  146771. 2, 64,
  146772. _huff_lengthlist__44u1__long,
  146773. 0, 0, 0, 0, 0,
  146774. NULL,
  146775. NULL,
  146776. NULL,
  146777. NULL,
  146778. 0
  146779. };
  146780. static long _vq_quantlist__44u1__p1_0[] = {
  146781. 1,
  146782. 0,
  146783. 2,
  146784. };
  146785. static long _vq_lengthlist__44u1__p1_0[] = {
  146786. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146787. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146788. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146789. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146790. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146791. 13,
  146792. };
  146793. static float _vq_quantthresh__44u1__p1_0[] = {
  146794. -0.5, 0.5,
  146795. };
  146796. static long _vq_quantmap__44u1__p1_0[] = {
  146797. 1, 0, 2,
  146798. };
  146799. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146800. _vq_quantthresh__44u1__p1_0,
  146801. _vq_quantmap__44u1__p1_0,
  146802. 3,
  146803. 3
  146804. };
  146805. static static_codebook _44u1__p1_0 = {
  146806. 4, 81,
  146807. _vq_lengthlist__44u1__p1_0,
  146808. 1, -535822336, 1611661312, 2, 0,
  146809. _vq_quantlist__44u1__p1_0,
  146810. NULL,
  146811. &_vq_auxt__44u1__p1_0,
  146812. NULL,
  146813. 0
  146814. };
  146815. static long _vq_quantlist__44u1__p2_0[] = {
  146816. 1,
  146817. 0,
  146818. 2,
  146819. };
  146820. static long _vq_lengthlist__44u1__p2_0[] = {
  146821. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146822. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146823. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146824. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146825. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146826. 9,
  146827. };
  146828. static float _vq_quantthresh__44u1__p2_0[] = {
  146829. -0.5, 0.5,
  146830. };
  146831. static long _vq_quantmap__44u1__p2_0[] = {
  146832. 1, 0, 2,
  146833. };
  146834. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146835. _vq_quantthresh__44u1__p2_0,
  146836. _vq_quantmap__44u1__p2_0,
  146837. 3,
  146838. 3
  146839. };
  146840. static static_codebook _44u1__p2_0 = {
  146841. 4, 81,
  146842. _vq_lengthlist__44u1__p2_0,
  146843. 1, -535822336, 1611661312, 2, 0,
  146844. _vq_quantlist__44u1__p2_0,
  146845. NULL,
  146846. &_vq_auxt__44u1__p2_0,
  146847. NULL,
  146848. 0
  146849. };
  146850. static long _vq_quantlist__44u1__p3_0[] = {
  146851. 2,
  146852. 1,
  146853. 3,
  146854. 0,
  146855. 4,
  146856. };
  146857. static long _vq_lengthlist__44u1__p3_0[] = {
  146858. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146859. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146860. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146861. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146862. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146863. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146864. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146865. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146866. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146867. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146868. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146869. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146870. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146871. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146872. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146873. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146874. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146875. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146876. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146877. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146878. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146879. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146880. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146881. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146882. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146883. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146884. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146885. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146886. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146887. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146888. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146889. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146890. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146891. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146892. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146893. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146894. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146895. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146896. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146897. 19,
  146898. };
  146899. static float _vq_quantthresh__44u1__p3_0[] = {
  146900. -1.5, -0.5, 0.5, 1.5,
  146901. };
  146902. static long _vq_quantmap__44u1__p3_0[] = {
  146903. 3, 1, 0, 2, 4,
  146904. };
  146905. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146906. _vq_quantthresh__44u1__p3_0,
  146907. _vq_quantmap__44u1__p3_0,
  146908. 5,
  146909. 5
  146910. };
  146911. static static_codebook _44u1__p3_0 = {
  146912. 4, 625,
  146913. _vq_lengthlist__44u1__p3_0,
  146914. 1, -533725184, 1611661312, 3, 0,
  146915. _vq_quantlist__44u1__p3_0,
  146916. NULL,
  146917. &_vq_auxt__44u1__p3_0,
  146918. NULL,
  146919. 0
  146920. };
  146921. static long _vq_quantlist__44u1__p4_0[] = {
  146922. 2,
  146923. 1,
  146924. 3,
  146925. 0,
  146926. 4,
  146927. };
  146928. static long _vq_lengthlist__44u1__p4_0[] = {
  146929. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146930. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146931. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146932. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146933. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146934. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146935. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146936. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146937. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146938. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146939. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146940. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146941. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146942. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146943. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146944. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146945. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146946. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146947. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146948. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146949. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146950. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146951. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146952. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146953. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146954. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146955. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146956. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146957. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146958. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146959. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146960. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146961. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146962. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146963. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146964. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146965. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146966. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146967. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146968. 12,
  146969. };
  146970. static float _vq_quantthresh__44u1__p4_0[] = {
  146971. -1.5, -0.5, 0.5, 1.5,
  146972. };
  146973. static long _vq_quantmap__44u1__p4_0[] = {
  146974. 3, 1, 0, 2, 4,
  146975. };
  146976. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146977. _vq_quantthresh__44u1__p4_0,
  146978. _vq_quantmap__44u1__p4_0,
  146979. 5,
  146980. 5
  146981. };
  146982. static static_codebook _44u1__p4_0 = {
  146983. 4, 625,
  146984. _vq_lengthlist__44u1__p4_0,
  146985. 1, -533725184, 1611661312, 3, 0,
  146986. _vq_quantlist__44u1__p4_0,
  146987. NULL,
  146988. &_vq_auxt__44u1__p4_0,
  146989. NULL,
  146990. 0
  146991. };
  146992. static long _vq_quantlist__44u1__p5_0[] = {
  146993. 4,
  146994. 3,
  146995. 5,
  146996. 2,
  146997. 6,
  146998. 1,
  146999. 7,
  147000. 0,
  147001. 8,
  147002. };
  147003. static long _vq_lengthlist__44u1__p5_0[] = {
  147004. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  147005. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  147006. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  147007. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147008. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  147009. 12,
  147010. };
  147011. static float _vq_quantthresh__44u1__p5_0[] = {
  147012. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147013. };
  147014. static long _vq_quantmap__44u1__p5_0[] = {
  147015. 7, 5, 3, 1, 0, 2, 4, 6,
  147016. 8,
  147017. };
  147018. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  147019. _vq_quantthresh__44u1__p5_0,
  147020. _vq_quantmap__44u1__p5_0,
  147021. 9,
  147022. 9
  147023. };
  147024. static static_codebook _44u1__p5_0 = {
  147025. 2, 81,
  147026. _vq_lengthlist__44u1__p5_0,
  147027. 1, -531628032, 1611661312, 4, 0,
  147028. _vq_quantlist__44u1__p5_0,
  147029. NULL,
  147030. &_vq_auxt__44u1__p5_0,
  147031. NULL,
  147032. 0
  147033. };
  147034. static long _vq_quantlist__44u1__p6_0[] = {
  147035. 6,
  147036. 5,
  147037. 7,
  147038. 4,
  147039. 8,
  147040. 3,
  147041. 9,
  147042. 2,
  147043. 10,
  147044. 1,
  147045. 11,
  147046. 0,
  147047. 12,
  147048. };
  147049. static long _vq_lengthlist__44u1__p6_0[] = {
  147050. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147051. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147052. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147053. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147054. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147055. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147056. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147057. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147058. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147059. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147060. 15,17,16,17,18,17,17,18, 0,
  147061. };
  147062. static float _vq_quantthresh__44u1__p6_0[] = {
  147063. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147064. 12.5, 17.5, 22.5, 27.5,
  147065. };
  147066. static long _vq_quantmap__44u1__p6_0[] = {
  147067. 11, 9, 7, 5, 3, 1, 0, 2,
  147068. 4, 6, 8, 10, 12,
  147069. };
  147070. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147071. _vq_quantthresh__44u1__p6_0,
  147072. _vq_quantmap__44u1__p6_0,
  147073. 13,
  147074. 13
  147075. };
  147076. static static_codebook _44u1__p6_0 = {
  147077. 2, 169,
  147078. _vq_lengthlist__44u1__p6_0,
  147079. 1, -526516224, 1616117760, 4, 0,
  147080. _vq_quantlist__44u1__p6_0,
  147081. NULL,
  147082. &_vq_auxt__44u1__p6_0,
  147083. NULL,
  147084. 0
  147085. };
  147086. static long _vq_quantlist__44u1__p6_1[] = {
  147087. 2,
  147088. 1,
  147089. 3,
  147090. 0,
  147091. 4,
  147092. };
  147093. static long _vq_lengthlist__44u1__p6_1[] = {
  147094. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147095. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147096. };
  147097. static float _vq_quantthresh__44u1__p6_1[] = {
  147098. -1.5, -0.5, 0.5, 1.5,
  147099. };
  147100. static long _vq_quantmap__44u1__p6_1[] = {
  147101. 3, 1, 0, 2, 4,
  147102. };
  147103. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147104. _vq_quantthresh__44u1__p6_1,
  147105. _vq_quantmap__44u1__p6_1,
  147106. 5,
  147107. 5
  147108. };
  147109. static static_codebook _44u1__p6_1 = {
  147110. 2, 25,
  147111. _vq_lengthlist__44u1__p6_1,
  147112. 1, -533725184, 1611661312, 3, 0,
  147113. _vq_quantlist__44u1__p6_1,
  147114. NULL,
  147115. &_vq_auxt__44u1__p6_1,
  147116. NULL,
  147117. 0
  147118. };
  147119. static long _vq_quantlist__44u1__p7_0[] = {
  147120. 3,
  147121. 2,
  147122. 4,
  147123. 1,
  147124. 5,
  147125. 0,
  147126. 6,
  147127. };
  147128. static long _vq_lengthlist__44u1__p7_0[] = {
  147129. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147130. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147131. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147132. 8,
  147133. };
  147134. static float _vq_quantthresh__44u1__p7_0[] = {
  147135. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147136. };
  147137. static long _vq_quantmap__44u1__p7_0[] = {
  147138. 5, 3, 1, 0, 2, 4, 6,
  147139. };
  147140. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147141. _vq_quantthresh__44u1__p7_0,
  147142. _vq_quantmap__44u1__p7_0,
  147143. 7,
  147144. 7
  147145. };
  147146. static static_codebook _44u1__p7_0 = {
  147147. 2, 49,
  147148. _vq_lengthlist__44u1__p7_0,
  147149. 1, -518017024, 1626677248, 3, 0,
  147150. _vq_quantlist__44u1__p7_0,
  147151. NULL,
  147152. &_vq_auxt__44u1__p7_0,
  147153. NULL,
  147154. 0
  147155. };
  147156. static long _vq_quantlist__44u1__p7_1[] = {
  147157. 6,
  147158. 5,
  147159. 7,
  147160. 4,
  147161. 8,
  147162. 3,
  147163. 9,
  147164. 2,
  147165. 10,
  147166. 1,
  147167. 11,
  147168. 0,
  147169. 12,
  147170. };
  147171. static long _vq_lengthlist__44u1__p7_1[] = {
  147172. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147173. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147174. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147175. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147176. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147177. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147178. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147179. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147180. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147181. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147182. 15,15,15,15,15,15,15,15,15,
  147183. };
  147184. static float _vq_quantthresh__44u1__p7_1[] = {
  147185. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147186. 32.5, 45.5, 58.5, 71.5,
  147187. };
  147188. static long _vq_quantmap__44u1__p7_1[] = {
  147189. 11, 9, 7, 5, 3, 1, 0, 2,
  147190. 4, 6, 8, 10, 12,
  147191. };
  147192. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147193. _vq_quantthresh__44u1__p7_1,
  147194. _vq_quantmap__44u1__p7_1,
  147195. 13,
  147196. 13
  147197. };
  147198. static static_codebook _44u1__p7_1 = {
  147199. 2, 169,
  147200. _vq_lengthlist__44u1__p7_1,
  147201. 1, -523010048, 1618608128, 4, 0,
  147202. _vq_quantlist__44u1__p7_1,
  147203. NULL,
  147204. &_vq_auxt__44u1__p7_1,
  147205. NULL,
  147206. 0
  147207. };
  147208. static long _vq_quantlist__44u1__p7_2[] = {
  147209. 6,
  147210. 5,
  147211. 7,
  147212. 4,
  147213. 8,
  147214. 3,
  147215. 9,
  147216. 2,
  147217. 10,
  147218. 1,
  147219. 11,
  147220. 0,
  147221. 12,
  147222. };
  147223. static long _vq_lengthlist__44u1__p7_2[] = {
  147224. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147225. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147226. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147227. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147228. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147229. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147230. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147231. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147232. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147233. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147234. 9, 9, 9,10, 9, 9,10,10, 9,
  147235. };
  147236. static float _vq_quantthresh__44u1__p7_2[] = {
  147237. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147238. 2.5, 3.5, 4.5, 5.5,
  147239. };
  147240. static long _vq_quantmap__44u1__p7_2[] = {
  147241. 11, 9, 7, 5, 3, 1, 0, 2,
  147242. 4, 6, 8, 10, 12,
  147243. };
  147244. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147245. _vq_quantthresh__44u1__p7_2,
  147246. _vq_quantmap__44u1__p7_2,
  147247. 13,
  147248. 13
  147249. };
  147250. static static_codebook _44u1__p7_2 = {
  147251. 2, 169,
  147252. _vq_lengthlist__44u1__p7_2,
  147253. 1, -531103744, 1611661312, 4, 0,
  147254. _vq_quantlist__44u1__p7_2,
  147255. NULL,
  147256. &_vq_auxt__44u1__p7_2,
  147257. NULL,
  147258. 0
  147259. };
  147260. static long _huff_lengthlist__44u1__short[] = {
  147261. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147262. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147263. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147264. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147265. };
  147266. static static_codebook _huff_book__44u1__short = {
  147267. 2, 64,
  147268. _huff_lengthlist__44u1__short,
  147269. 0, 0, 0, 0, 0,
  147270. NULL,
  147271. NULL,
  147272. NULL,
  147273. NULL,
  147274. 0
  147275. };
  147276. static long _huff_lengthlist__44u2__long[] = {
  147277. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147278. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147279. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147280. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147281. };
  147282. static static_codebook _huff_book__44u2__long = {
  147283. 2, 64,
  147284. _huff_lengthlist__44u2__long,
  147285. 0, 0, 0, 0, 0,
  147286. NULL,
  147287. NULL,
  147288. NULL,
  147289. NULL,
  147290. 0
  147291. };
  147292. static long _vq_quantlist__44u2__p1_0[] = {
  147293. 1,
  147294. 0,
  147295. 2,
  147296. };
  147297. static long _vq_lengthlist__44u2__p1_0[] = {
  147298. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147299. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147300. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147301. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147302. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147303. 13,
  147304. };
  147305. static float _vq_quantthresh__44u2__p1_0[] = {
  147306. -0.5, 0.5,
  147307. };
  147308. static long _vq_quantmap__44u2__p1_0[] = {
  147309. 1, 0, 2,
  147310. };
  147311. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147312. _vq_quantthresh__44u2__p1_0,
  147313. _vq_quantmap__44u2__p1_0,
  147314. 3,
  147315. 3
  147316. };
  147317. static static_codebook _44u2__p1_0 = {
  147318. 4, 81,
  147319. _vq_lengthlist__44u2__p1_0,
  147320. 1, -535822336, 1611661312, 2, 0,
  147321. _vq_quantlist__44u2__p1_0,
  147322. NULL,
  147323. &_vq_auxt__44u2__p1_0,
  147324. NULL,
  147325. 0
  147326. };
  147327. static long _vq_quantlist__44u2__p2_0[] = {
  147328. 1,
  147329. 0,
  147330. 2,
  147331. };
  147332. static long _vq_lengthlist__44u2__p2_0[] = {
  147333. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147334. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147335. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147336. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147337. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147338. 9,
  147339. };
  147340. static float _vq_quantthresh__44u2__p2_0[] = {
  147341. -0.5, 0.5,
  147342. };
  147343. static long _vq_quantmap__44u2__p2_0[] = {
  147344. 1, 0, 2,
  147345. };
  147346. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147347. _vq_quantthresh__44u2__p2_0,
  147348. _vq_quantmap__44u2__p2_0,
  147349. 3,
  147350. 3
  147351. };
  147352. static static_codebook _44u2__p2_0 = {
  147353. 4, 81,
  147354. _vq_lengthlist__44u2__p2_0,
  147355. 1, -535822336, 1611661312, 2, 0,
  147356. _vq_quantlist__44u2__p2_0,
  147357. NULL,
  147358. &_vq_auxt__44u2__p2_0,
  147359. NULL,
  147360. 0
  147361. };
  147362. static long _vq_quantlist__44u2__p3_0[] = {
  147363. 2,
  147364. 1,
  147365. 3,
  147366. 0,
  147367. 4,
  147368. };
  147369. static long _vq_lengthlist__44u2__p3_0[] = {
  147370. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147371. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147372. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147373. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147374. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147375. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147376. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147377. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147378. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147379. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147380. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147381. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147382. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147383. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147384. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147385. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147386. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147387. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147388. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147389. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147390. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147391. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147392. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147393. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147394. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147395. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147396. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147397. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147398. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147399. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147400. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147401. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147402. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147403. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147404. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147405. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147406. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147407. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147408. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147409. 0,
  147410. };
  147411. static float _vq_quantthresh__44u2__p3_0[] = {
  147412. -1.5, -0.5, 0.5, 1.5,
  147413. };
  147414. static long _vq_quantmap__44u2__p3_0[] = {
  147415. 3, 1, 0, 2, 4,
  147416. };
  147417. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147418. _vq_quantthresh__44u2__p3_0,
  147419. _vq_quantmap__44u2__p3_0,
  147420. 5,
  147421. 5
  147422. };
  147423. static static_codebook _44u2__p3_0 = {
  147424. 4, 625,
  147425. _vq_lengthlist__44u2__p3_0,
  147426. 1, -533725184, 1611661312, 3, 0,
  147427. _vq_quantlist__44u2__p3_0,
  147428. NULL,
  147429. &_vq_auxt__44u2__p3_0,
  147430. NULL,
  147431. 0
  147432. };
  147433. static long _vq_quantlist__44u2__p4_0[] = {
  147434. 2,
  147435. 1,
  147436. 3,
  147437. 0,
  147438. 4,
  147439. };
  147440. static long _vq_lengthlist__44u2__p4_0[] = {
  147441. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147442. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147443. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147444. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147445. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147446. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147447. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147448. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147449. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147450. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147451. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147452. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147453. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147454. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147455. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147456. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147457. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147458. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147459. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147460. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147461. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147462. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147463. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147464. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147465. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147466. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147467. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147468. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147469. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147470. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147471. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147472. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147473. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147474. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147475. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147476. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147477. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147478. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147479. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147480. 13,
  147481. };
  147482. static float _vq_quantthresh__44u2__p4_0[] = {
  147483. -1.5, -0.5, 0.5, 1.5,
  147484. };
  147485. static long _vq_quantmap__44u2__p4_0[] = {
  147486. 3, 1, 0, 2, 4,
  147487. };
  147488. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147489. _vq_quantthresh__44u2__p4_0,
  147490. _vq_quantmap__44u2__p4_0,
  147491. 5,
  147492. 5
  147493. };
  147494. static static_codebook _44u2__p4_0 = {
  147495. 4, 625,
  147496. _vq_lengthlist__44u2__p4_0,
  147497. 1, -533725184, 1611661312, 3, 0,
  147498. _vq_quantlist__44u2__p4_0,
  147499. NULL,
  147500. &_vq_auxt__44u2__p4_0,
  147501. NULL,
  147502. 0
  147503. };
  147504. static long _vq_quantlist__44u2__p5_0[] = {
  147505. 4,
  147506. 3,
  147507. 5,
  147508. 2,
  147509. 6,
  147510. 1,
  147511. 7,
  147512. 0,
  147513. 8,
  147514. };
  147515. static long _vq_lengthlist__44u2__p5_0[] = {
  147516. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147517. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147518. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147519. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147520. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147521. 13,
  147522. };
  147523. static float _vq_quantthresh__44u2__p5_0[] = {
  147524. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147525. };
  147526. static long _vq_quantmap__44u2__p5_0[] = {
  147527. 7, 5, 3, 1, 0, 2, 4, 6,
  147528. 8,
  147529. };
  147530. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147531. _vq_quantthresh__44u2__p5_0,
  147532. _vq_quantmap__44u2__p5_0,
  147533. 9,
  147534. 9
  147535. };
  147536. static static_codebook _44u2__p5_0 = {
  147537. 2, 81,
  147538. _vq_lengthlist__44u2__p5_0,
  147539. 1, -531628032, 1611661312, 4, 0,
  147540. _vq_quantlist__44u2__p5_0,
  147541. NULL,
  147542. &_vq_auxt__44u2__p5_0,
  147543. NULL,
  147544. 0
  147545. };
  147546. static long _vq_quantlist__44u2__p6_0[] = {
  147547. 6,
  147548. 5,
  147549. 7,
  147550. 4,
  147551. 8,
  147552. 3,
  147553. 9,
  147554. 2,
  147555. 10,
  147556. 1,
  147557. 11,
  147558. 0,
  147559. 12,
  147560. };
  147561. static long _vq_lengthlist__44u2__p6_0[] = {
  147562. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147563. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147564. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147565. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147566. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147567. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147568. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147569. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147570. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147571. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147572. 15,17,17,16,18,17,18, 0, 0,
  147573. };
  147574. static float _vq_quantthresh__44u2__p6_0[] = {
  147575. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147576. 12.5, 17.5, 22.5, 27.5,
  147577. };
  147578. static long _vq_quantmap__44u2__p6_0[] = {
  147579. 11, 9, 7, 5, 3, 1, 0, 2,
  147580. 4, 6, 8, 10, 12,
  147581. };
  147582. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147583. _vq_quantthresh__44u2__p6_0,
  147584. _vq_quantmap__44u2__p6_0,
  147585. 13,
  147586. 13
  147587. };
  147588. static static_codebook _44u2__p6_0 = {
  147589. 2, 169,
  147590. _vq_lengthlist__44u2__p6_0,
  147591. 1, -526516224, 1616117760, 4, 0,
  147592. _vq_quantlist__44u2__p6_0,
  147593. NULL,
  147594. &_vq_auxt__44u2__p6_0,
  147595. NULL,
  147596. 0
  147597. };
  147598. static long _vq_quantlist__44u2__p6_1[] = {
  147599. 2,
  147600. 1,
  147601. 3,
  147602. 0,
  147603. 4,
  147604. };
  147605. static long _vq_lengthlist__44u2__p6_1[] = {
  147606. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147607. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147608. };
  147609. static float _vq_quantthresh__44u2__p6_1[] = {
  147610. -1.5, -0.5, 0.5, 1.5,
  147611. };
  147612. static long _vq_quantmap__44u2__p6_1[] = {
  147613. 3, 1, 0, 2, 4,
  147614. };
  147615. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147616. _vq_quantthresh__44u2__p6_1,
  147617. _vq_quantmap__44u2__p6_1,
  147618. 5,
  147619. 5
  147620. };
  147621. static static_codebook _44u2__p6_1 = {
  147622. 2, 25,
  147623. _vq_lengthlist__44u2__p6_1,
  147624. 1, -533725184, 1611661312, 3, 0,
  147625. _vq_quantlist__44u2__p6_1,
  147626. NULL,
  147627. &_vq_auxt__44u2__p6_1,
  147628. NULL,
  147629. 0
  147630. };
  147631. static long _vq_quantlist__44u2__p7_0[] = {
  147632. 4,
  147633. 3,
  147634. 5,
  147635. 2,
  147636. 6,
  147637. 1,
  147638. 7,
  147639. 0,
  147640. 8,
  147641. };
  147642. static long _vq_lengthlist__44u2__p7_0[] = {
  147643. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147644. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147645. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147646. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147647. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147648. 11,
  147649. };
  147650. static float _vq_quantthresh__44u2__p7_0[] = {
  147651. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147652. };
  147653. static long _vq_quantmap__44u2__p7_0[] = {
  147654. 7, 5, 3, 1, 0, 2, 4, 6,
  147655. 8,
  147656. };
  147657. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147658. _vq_quantthresh__44u2__p7_0,
  147659. _vq_quantmap__44u2__p7_0,
  147660. 9,
  147661. 9
  147662. };
  147663. static static_codebook _44u2__p7_0 = {
  147664. 2, 81,
  147665. _vq_lengthlist__44u2__p7_0,
  147666. 1, -516612096, 1626677248, 4, 0,
  147667. _vq_quantlist__44u2__p7_0,
  147668. NULL,
  147669. &_vq_auxt__44u2__p7_0,
  147670. NULL,
  147671. 0
  147672. };
  147673. static long _vq_quantlist__44u2__p7_1[] = {
  147674. 6,
  147675. 5,
  147676. 7,
  147677. 4,
  147678. 8,
  147679. 3,
  147680. 9,
  147681. 2,
  147682. 10,
  147683. 1,
  147684. 11,
  147685. 0,
  147686. 12,
  147687. };
  147688. static long _vq_lengthlist__44u2__p7_1[] = {
  147689. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147690. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147691. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147692. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147693. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147694. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147695. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147696. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147697. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147698. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147699. 14,14,14,17,15,17,17,17,17,
  147700. };
  147701. static float _vq_quantthresh__44u2__p7_1[] = {
  147702. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147703. 32.5, 45.5, 58.5, 71.5,
  147704. };
  147705. static long _vq_quantmap__44u2__p7_1[] = {
  147706. 11, 9, 7, 5, 3, 1, 0, 2,
  147707. 4, 6, 8, 10, 12,
  147708. };
  147709. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147710. _vq_quantthresh__44u2__p7_1,
  147711. _vq_quantmap__44u2__p7_1,
  147712. 13,
  147713. 13
  147714. };
  147715. static static_codebook _44u2__p7_1 = {
  147716. 2, 169,
  147717. _vq_lengthlist__44u2__p7_1,
  147718. 1, -523010048, 1618608128, 4, 0,
  147719. _vq_quantlist__44u2__p7_1,
  147720. NULL,
  147721. &_vq_auxt__44u2__p7_1,
  147722. NULL,
  147723. 0
  147724. };
  147725. static long _vq_quantlist__44u2__p7_2[] = {
  147726. 6,
  147727. 5,
  147728. 7,
  147729. 4,
  147730. 8,
  147731. 3,
  147732. 9,
  147733. 2,
  147734. 10,
  147735. 1,
  147736. 11,
  147737. 0,
  147738. 12,
  147739. };
  147740. static long _vq_lengthlist__44u2__p7_2[] = {
  147741. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147742. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147743. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147744. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147745. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147746. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147747. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147748. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147749. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147750. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147751. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147752. };
  147753. static float _vq_quantthresh__44u2__p7_2[] = {
  147754. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147755. 2.5, 3.5, 4.5, 5.5,
  147756. };
  147757. static long _vq_quantmap__44u2__p7_2[] = {
  147758. 11, 9, 7, 5, 3, 1, 0, 2,
  147759. 4, 6, 8, 10, 12,
  147760. };
  147761. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147762. _vq_quantthresh__44u2__p7_2,
  147763. _vq_quantmap__44u2__p7_2,
  147764. 13,
  147765. 13
  147766. };
  147767. static static_codebook _44u2__p7_2 = {
  147768. 2, 169,
  147769. _vq_lengthlist__44u2__p7_2,
  147770. 1, -531103744, 1611661312, 4, 0,
  147771. _vq_quantlist__44u2__p7_2,
  147772. NULL,
  147773. &_vq_auxt__44u2__p7_2,
  147774. NULL,
  147775. 0
  147776. };
  147777. static long _huff_lengthlist__44u2__short[] = {
  147778. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147779. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147780. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147781. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147782. };
  147783. static static_codebook _huff_book__44u2__short = {
  147784. 2, 64,
  147785. _huff_lengthlist__44u2__short,
  147786. 0, 0, 0, 0, 0,
  147787. NULL,
  147788. NULL,
  147789. NULL,
  147790. NULL,
  147791. 0
  147792. };
  147793. static long _huff_lengthlist__44u3__long[] = {
  147794. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147795. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147796. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147797. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147798. };
  147799. static static_codebook _huff_book__44u3__long = {
  147800. 2, 64,
  147801. _huff_lengthlist__44u3__long,
  147802. 0, 0, 0, 0, 0,
  147803. NULL,
  147804. NULL,
  147805. NULL,
  147806. NULL,
  147807. 0
  147808. };
  147809. static long _vq_quantlist__44u3__p1_0[] = {
  147810. 1,
  147811. 0,
  147812. 2,
  147813. };
  147814. static long _vq_lengthlist__44u3__p1_0[] = {
  147815. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147816. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147817. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147818. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147819. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147820. 13,
  147821. };
  147822. static float _vq_quantthresh__44u3__p1_0[] = {
  147823. -0.5, 0.5,
  147824. };
  147825. static long _vq_quantmap__44u3__p1_0[] = {
  147826. 1, 0, 2,
  147827. };
  147828. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147829. _vq_quantthresh__44u3__p1_0,
  147830. _vq_quantmap__44u3__p1_0,
  147831. 3,
  147832. 3
  147833. };
  147834. static static_codebook _44u3__p1_0 = {
  147835. 4, 81,
  147836. _vq_lengthlist__44u3__p1_0,
  147837. 1, -535822336, 1611661312, 2, 0,
  147838. _vq_quantlist__44u3__p1_0,
  147839. NULL,
  147840. &_vq_auxt__44u3__p1_0,
  147841. NULL,
  147842. 0
  147843. };
  147844. static long _vq_quantlist__44u3__p2_0[] = {
  147845. 1,
  147846. 0,
  147847. 2,
  147848. };
  147849. static long _vq_lengthlist__44u3__p2_0[] = {
  147850. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147851. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147852. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147853. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147854. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147855. 9,
  147856. };
  147857. static float _vq_quantthresh__44u3__p2_0[] = {
  147858. -0.5, 0.5,
  147859. };
  147860. static long _vq_quantmap__44u3__p2_0[] = {
  147861. 1, 0, 2,
  147862. };
  147863. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147864. _vq_quantthresh__44u3__p2_0,
  147865. _vq_quantmap__44u3__p2_0,
  147866. 3,
  147867. 3
  147868. };
  147869. static static_codebook _44u3__p2_0 = {
  147870. 4, 81,
  147871. _vq_lengthlist__44u3__p2_0,
  147872. 1, -535822336, 1611661312, 2, 0,
  147873. _vq_quantlist__44u3__p2_0,
  147874. NULL,
  147875. &_vq_auxt__44u3__p2_0,
  147876. NULL,
  147877. 0
  147878. };
  147879. static long _vq_quantlist__44u3__p3_0[] = {
  147880. 2,
  147881. 1,
  147882. 3,
  147883. 0,
  147884. 4,
  147885. };
  147886. static long _vq_lengthlist__44u3__p3_0[] = {
  147887. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147888. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147889. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147890. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147891. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147892. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147893. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147894. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147895. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147896. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147897. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147898. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147899. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147900. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147901. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147902. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147903. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147904. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147905. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147906. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147907. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147908. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147909. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147910. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147911. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147912. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147913. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147914. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147915. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147916. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147917. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147918. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147919. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147920. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147921. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147922. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147923. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147924. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147925. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147926. 0,
  147927. };
  147928. static float _vq_quantthresh__44u3__p3_0[] = {
  147929. -1.5, -0.5, 0.5, 1.5,
  147930. };
  147931. static long _vq_quantmap__44u3__p3_0[] = {
  147932. 3, 1, 0, 2, 4,
  147933. };
  147934. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147935. _vq_quantthresh__44u3__p3_0,
  147936. _vq_quantmap__44u3__p3_0,
  147937. 5,
  147938. 5
  147939. };
  147940. static static_codebook _44u3__p3_0 = {
  147941. 4, 625,
  147942. _vq_lengthlist__44u3__p3_0,
  147943. 1, -533725184, 1611661312, 3, 0,
  147944. _vq_quantlist__44u3__p3_0,
  147945. NULL,
  147946. &_vq_auxt__44u3__p3_0,
  147947. NULL,
  147948. 0
  147949. };
  147950. static long _vq_quantlist__44u3__p4_0[] = {
  147951. 2,
  147952. 1,
  147953. 3,
  147954. 0,
  147955. 4,
  147956. };
  147957. static long _vq_lengthlist__44u3__p4_0[] = {
  147958. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147959. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147960. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147961. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147962. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147963. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147964. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147965. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147966. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147967. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147968. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147969. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147970. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147971. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147972. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147973. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147974. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147975. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147976. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147977. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147978. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147979. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147980. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147981. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147982. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147983. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147984. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147985. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147986. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147987. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147988. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147989. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147990. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147991. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147992. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147993. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147994. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147995. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147996. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147997. 13,
  147998. };
  147999. static float _vq_quantthresh__44u3__p4_0[] = {
  148000. -1.5, -0.5, 0.5, 1.5,
  148001. };
  148002. static long _vq_quantmap__44u3__p4_0[] = {
  148003. 3, 1, 0, 2, 4,
  148004. };
  148005. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  148006. _vq_quantthresh__44u3__p4_0,
  148007. _vq_quantmap__44u3__p4_0,
  148008. 5,
  148009. 5
  148010. };
  148011. static static_codebook _44u3__p4_0 = {
  148012. 4, 625,
  148013. _vq_lengthlist__44u3__p4_0,
  148014. 1, -533725184, 1611661312, 3, 0,
  148015. _vq_quantlist__44u3__p4_0,
  148016. NULL,
  148017. &_vq_auxt__44u3__p4_0,
  148018. NULL,
  148019. 0
  148020. };
  148021. static long _vq_quantlist__44u3__p5_0[] = {
  148022. 4,
  148023. 3,
  148024. 5,
  148025. 2,
  148026. 6,
  148027. 1,
  148028. 7,
  148029. 0,
  148030. 8,
  148031. };
  148032. static long _vq_lengthlist__44u3__p5_0[] = {
  148033. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148034. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148035. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  148036. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148037. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  148038. 12,
  148039. };
  148040. static float _vq_quantthresh__44u3__p5_0[] = {
  148041. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148042. };
  148043. static long _vq_quantmap__44u3__p5_0[] = {
  148044. 7, 5, 3, 1, 0, 2, 4, 6,
  148045. 8,
  148046. };
  148047. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148048. _vq_quantthresh__44u3__p5_0,
  148049. _vq_quantmap__44u3__p5_0,
  148050. 9,
  148051. 9
  148052. };
  148053. static static_codebook _44u3__p5_0 = {
  148054. 2, 81,
  148055. _vq_lengthlist__44u3__p5_0,
  148056. 1, -531628032, 1611661312, 4, 0,
  148057. _vq_quantlist__44u3__p5_0,
  148058. NULL,
  148059. &_vq_auxt__44u3__p5_0,
  148060. NULL,
  148061. 0
  148062. };
  148063. static long _vq_quantlist__44u3__p6_0[] = {
  148064. 6,
  148065. 5,
  148066. 7,
  148067. 4,
  148068. 8,
  148069. 3,
  148070. 9,
  148071. 2,
  148072. 10,
  148073. 1,
  148074. 11,
  148075. 0,
  148076. 12,
  148077. };
  148078. static long _vq_lengthlist__44u3__p6_0[] = {
  148079. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148080. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148081. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148082. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148083. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148084. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148085. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148086. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148087. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148088. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148089. 15,16,16,16,17,18,16,20,18,
  148090. };
  148091. static float _vq_quantthresh__44u3__p6_0[] = {
  148092. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148093. 12.5, 17.5, 22.5, 27.5,
  148094. };
  148095. static long _vq_quantmap__44u3__p6_0[] = {
  148096. 11, 9, 7, 5, 3, 1, 0, 2,
  148097. 4, 6, 8, 10, 12,
  148098. };
  148099. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148100. _vq_quantthresh__44u3__p6_0,
  148101. _vq_quantmap__44u3__p6_0,
  148102. 13,
  148103. 13
  148104. };
  148105. static static_codebook _44u3__p6_0 = {
  148106. 2, 169,
  148107. _vq_lengthlist__44u3__p6_0,
  148108. 1, -526516224, 1616117760, 4, 0,
  148109. _vq_quantlist__44u3__p6_0,
  148110. NULL,
  148111. &_vq_auxt__44u3__p6_0,
  148112. NULL,
  148113. 0
  148114. };
  148115. static long _vq_quantlist__44u3__p6_1[] = {
  148116. 2,
  148117. 1,
  148118. 3,
  148119. 0,
  148120. 4,
  148121. };
  148122. static long _vq_lengthlist__44u3__p6_1[] = {
  148123. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148124. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148125. };
  148126. static float _vq_quantthresh__44u3__p6_1[] = {
  148127. -1.5, -0.5, 0.5, 1.5,
  148128. };
  148129. static long _vq_quantmap__44u3__p6_1[] = {
  148130. 3, 1, 0, 2, 4,
  148131. };
  148132. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148133. _vq_quantthresh__44u3__p6_1,
  148134. _vq_quantmap__44u3__p6_1,
  148135. 5,
  148136. 5
  148137. };
  148138. static static_codebook _44u3__p6_1 = {
  148139. 2, 25,
  148140. _vq_lengthlist__44u3__p6_1,
  148141. 1, -533725184, 1611661312, 3, 0,
  148142. _vq_quantlist__44u3__p6_1,
  148143. NULL,
  148144. &_vq_auxt__44u3__p6_1,
  148145. NULL,
  148146. 0
  148147. };
  148148. static long _vq_quantlist__44u3__p7_0[] = {
  148149. 4,
  148150. 3,
  148151. 5,
  148152. 2,
  148153. 6,
  148154. 1,
  148155. 7,
  148156. 0,
  148157. 8,
  148158. };
  148159. static long _vq_lengthlist__44u3__p7_0[] = {
  148160. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148161. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148162. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148163. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148164. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148165. 9,
  148166. };
  148167. static float _vq_quantthresh__44u3__p7_0[] = {
  148168. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148169. };
  148170. static long _vq_quantmap__44u3__p7_0[] = {
  148171. 7, 5, 3, 1, 0, 2, 4, 6,
  148172. 8,
  148173. };
  148174. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148175. _vq_quantthresh__44u3__p7_0,
  148176. _vq_quantmap__44u3__p7_0,
  148177. 9,
  148178. 9
  148179. };
  148180. static static_codebook _44u3__p7_0 = {
  148181. 2, 81,
  148182. _vq_lengthlist__44u3__p7_0,
  148183. 1, -515907584, 1627381760, 4, 0,
  148184. _vq_quantlist__44u3__p7_0,
  148185. NULL,
  148186. &_vq_auxt__44u3__p7_0,
  148187. NULL,
  148188. 0
  148189. };
  148190. static long _vq_quantlist__44u3__p7_1[] = {
  148191. 7,
  148192. 6,
  148193. 8,
  148194. 5,
  148195. 9,
  148196. 4,
  148197. 10,
  148198. 3,
  148199. 11,
  148200. 2,
  148201. 12,
  148202. 1,
  148203. 13,
  148204. 0,
  148205. 14,
  148206. };
  148207. static long _vq_lengthlist__44u3__p7_1[] = {
  148208. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148209. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148210. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148211. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148212. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148213. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148214. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148215. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148216. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148217. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148218. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148219. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148220. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148221. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148222. 17,
  148223. };
  148224. static float _vq_quantthresh__44u3__p7_1[] = {
  148225. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148226. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148227. };
  148228. static long _vq_quantmap__44u3__p7_1[] = {
  148229. 13, 11, 9, 7, 5, 3, 1, 0,
  148230. 2, 4, 6, 8, 10, 12, 14,
  148231. };
  148232. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148233. _vq_quantthresh__44u3__p7_1,
  148234. _vq_quantmap__44u3__p7_1,
  148235. 15,
  148236. 15
  148237. };
  148238. static static_codebook _44u3__p7_1 = {
  148239. 2, 225,
  148240. _vq_lengthlist__44u3__p7_1,
  148241. 1, -522338304, 1620115456, 4, 0,
  148242. _vq_quantlist__44u3__p7_1,
  148243. NULL,
  148244. &_vq_auxt__44u3__p7_1,
  148245. NULL,
  148246. 0
  148247. };
  148248. static long _vq_quantlist__44u3__p7_2[] = {
  148249. 8,
  148250. 7,
  148251. 9,
  148252. 6,
  148253. 10,
  148254. 5,
  148255. 11,
  148256. 4,
  148257. 12,
  148258. 3,
  148259. 13,
  148260. 2,
  148261. 14,
  148262. 1,
  148263. 15,
  148264. 0,
  148265. 16,
  148266. };
  148267. static long _vq_lengthlist__44u3__p7_2[] = {
  148268. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148269. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148270. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148271. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148272. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148273. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148274. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148275. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148276. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148277. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148278. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148279. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148280. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148281. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148282. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148283. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148284. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148285. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148286. 11,
  148287. };
  148288. static float _vq_quantthresh__44u3__p7_2[] = {
  148289. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148290. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148291. };
  148292. static long _vq_quantmap__44u3__p7_2[] = {
  148293. 15, 13, 11, 9, 7, 5, 3, 1,
  148294. 0, 2, 4, 6, 8, 10, 12, 14,
  148295. 16,
  148296. };
  148297. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148298. _vq_quantthresh__44u3__p7_2,
  148299. _vq_quantmap__44u3__p7_2,
  148300. 17,
  148301. 17
  148302. };
  148303. static static_codebook _44u3__p7_2 = {
  148304. 2, 289,
  148305. _vq_lengthlist__44u3__p7_2,
  148306. 1, -529530880, 1611661312, 5, 0,
  148307. _vq_quantlist__44u3__p7_2,
  148308. NULL,
  148309. &_vq_auxt__44u3__p7_2,
  148310. NULL,
  148311. 0
  148312. };
  148313. static long _huff_lengthlist__44u3__short[] = {
  148314. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148315. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148316. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148317. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148318. };
  148319. static static_codebook _huff_book__44u3__short = {
  148320. 2, 64,
  148321. _huff_lengthlist__44u3__short,
  148322. 0, 0, 0, 0, 0,
  148323. NULL,
  148324. NULL,
  148325. NULL,
  148326. NULL,
  148327. 0
  148328. };
  148329. static long _huff_lengthlist__44u4__long[] = {
  148330. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148331. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148332. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148333. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148334. };
  148335. static static_codebook _huff_book__44u4__long = {
  148336. 2, 64,
  148337. _huff_lengthlist__44u4__long,
  148338. 0, 0, 0, 0, 0,
  148339. NULL,
  148340. NULL,
  148341. NULL,
  148342. NULL,
  148343. 0
  148344. };
  148345. static long _vq_quantlist__44u4__p1_0[] = {
  148346. 1,
  148347. 0,
  148348. 2,
  148349. };
  148350. static long _vq_lengthlist__44u4__p1_0[] = {
  148351. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148352. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148353. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148354. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148355. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148356. 13,
  148357. };
  148358. static float _vq_quantthresh__44u4__p1_0[] = {
  148359. -0.5, 0.5,
  148360. };
  148361. static long _vq_quantmap__44u4__p1_0[] = {
  148362. 1, 0, 2,
  148363. };
  148364. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148365. _vq_quantthresh__44u4__p1_0,
  148366. _vq_quantmap__44u4__p1_0,
  148367. 3,
  148368. 3
  148369. };
  148370. static static_codebook _44u4__p1_0 = {
  148371. 4, 81,
  148372. _vq_lengthlist__44u4__p1_0,
  148373. 1, -535822336, 1611661312, 2, 0,
  148374. _vq_quantlist__44u4__p1_0,
  148375. NULL,
  148376. &_vq_auxt__44u4__p1_0,
  148377. NULL,
  148378. 0
  148379. };
  148380. static long _vq_quantlist__44u4__p2_0[] = {
  148381. 1,
  148382. 0,
  148383. 2,
  148384. };
  148385. static long _vq_lengthlist__44u4__p2_0[] = {
  148386. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148387. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148388. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148389. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148390. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148391. 9,
  148392. };
  148393. static float _vq_quantthresh__44u4__p2_0[] = {
  148394. -0.5, 0.5,
  148395. };
  148396. static long _vq_quantmap__44u4__p2_0[] = {
  148397. 1, 0, 2,
  148398. };
  148399. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148400. _vq_quantthresh__44u4__p2_0,
  148401. _vq_quantmap__44u4__p2_0,
  148402. 3,
  148403. 3
  148404. };
  148405. static static_codebook _44u4__p2_0 = {
  148406. 4, 81,
  148407. _vq_lengthlist__44u4__p2_0,
  148408. 1, -535822336, 1611661312, 2, 0,
  148409. _vq_quantlist__44u4__p2_0,
  148410. NULL,
  148411. &_vq_auxt__44u4__p2_0,
  148412. NULL,
  148413. 0
  148414. };
  148415. static long _vq_quantlist__44u4__p3_0[] = {
  148416. 2,
  148417. 1,
  148418. 3,
  148419. 0,
  148420. 4,
  148421. };
  148422. static long _vq_lengthlist__44u4__p3_0[] = {
  148423. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148424. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148425. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148426. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148427. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148428. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148429. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148430. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148431. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148432. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148433. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148434. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148435. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148436. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148437. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148438. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148439. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148440. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148441. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148442. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148443. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148444. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148445. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148446. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148447. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148448. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148449. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148450. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148451. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148452. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148453. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148454. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148455. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148456. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148457. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148458. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148459. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148460. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148461. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148462. 0,
  148463. };
  148464. static float _vq_quantthresh__44u4__p3_0[] = {
  148465. -1.5, -0.5, 0.5, 1.5,
  148466. };
  148467. static long _vq_quantmap__44u4__p3_0[] = {
  148468. 3, 1, 0, 2, 4,
  148469. };
  148470. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148471. _vq_quantthresh__44u4__p3_0,
  148472. _vq_quantmap__44u4__p3_0,
  148473. 5,
  148474. 5
  148475. };
  148476. static static_codebook _44u4__p3_0 = {
  148477. 4, 625,
  148478. _vq_lengthlist__44u4__p3_0,
  148479. 1, -533725184, 1611661312, 3, 0,
  148480. _vq_quantlist__44u4__p3_0,
  148481. NULL,
  148482. &_vq_auxt__44u4__p3_0,
  148483. NULL,
  148484. 0
  148485. };
  148486. static long _vq_quantlist__44u4__p4_0[] = {
  148487. 2,
  148488. 1,
  148489. 3,
  148490. 0,
  148491. 4,
  148492. };
  148493. static long _vq_lengthlist__44u4__p4_0[] = {
  148494. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148495. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148496. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148497. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148498. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148499. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148500. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148501. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148502. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148503. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148504. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148505. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148506. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148507. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148508. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148509. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148510. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148511. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148512. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148513. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148514. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148515. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148516. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148517. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148518. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148519. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148520. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148521. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148522. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148523. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148524. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148525. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148526. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148527. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148528. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148529. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148530. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148531. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148532. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148533. 13,
  148534. };
  148535. static float _vq_quantthresh__44u4__p4_0[] = {
  148536. -1.5, -0.5, 0.5, 1.5,
  148537. };
  148538. static long _vq_quantmap__44u4__p4_0[] = {
  148539. 3, 1, 0, 2, 4,
  148540. };
  148541. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148542. _vq_quantthresh__44u4__p4_0,
  148543. _vq_quantmap__44u4__p4_0,
  148544. 5,
  148545. 5
  148546. };
  148547. static static_codebook _44u4__p4_0 = {
  148548. 4, 625,
  148549. _vq_lengthlist__44u4__p4_0,
  148550. 1, -533725184, 1611661312, 3, 0,
  148551. _vq_quantlist__44u4__p4_0,
  148552. NULL,
  148553. &_vq_auxt__44u4__p4_0,
  148554. NULL,
  148555. 0
  148556. };
  148557. static long _vq_quantlist__44u4__p5_0[] = {
  148558. 4,
  148559. 3,
  148560. 5,
  148561. 2,
  148562. 6,
  148563. 1,
  148564. 7,
  148565. 0,
  148566. 8,
  148567. };
  148568. static long _vq_lengthlist__44u4__p5_0[] = {
  148569. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148570. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148571. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148572. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148573. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148574. 12,
  148575. };
  148576. static float _vq_quantthresh__44u4__p5_0[] = {
  148577. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148578. };
  148579. static long _vq_quantmap__44u4__p5_0[] = {
  148580. 7, 5, 3, 1, 0, 2, 4, 6,
  148581. 8,
  148582. };
  148583. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148584. _vq_quantthresh__44u4__p5_0,
  148585. _vq_quantmap__44u4__p5_0,
  148586. 9,
  148587. 9
  148588. };
  148589. static static_codebook _44u4__p5_0 = {
  148590. 2, 81,
  148591. _vq_lengthlist__44u4__p5_0,
  148592. 1, -531628032, 1611661312, 4, 0,
  148593. _vq_quantlist__44u4__p5_0,
  148594. NULL,
  148595. &_vq_auxt__44u4__p5_0,
  148596. NULL,
  148597. 0
  148598. };
  148599. static long _vq_quantlist__44u4__p6_0[] = {
  148600. 6,
  148601. 5,
  148602. 7,
  148603. 4,
  148604. 8,
  148605. 3,
  148606. 9,
  148607. 2,
  148608. 10,
  148609. 1,
  148610. 11,
  148611. 0,
  148612. 12,
  148613. };
  148614. static long _vq_lengthlist__44u4__p6_0[] = {
  148615. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148616. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148617. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148618. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148619. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148620. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148621. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148622. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148623. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148624. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148625. 16,16,16,17,17,18,17,20,21,
  148626. };
  148627. static float _vq_quantthresh__44u4__p6_0[] = {
  148628. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148629. 12.5, 17.5, 22.5, 27.5,
  148630. };
  148631. static long _vq_quantmap__44u4__p6_0[] = {
  148632. 11, 9, 7, 5, 3, 1, 0, 2,
  148633. 4, 6, 8, 10, 12,
  148634. };
  148635. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148636. _vq_quantthresh__44u4__p6_0,
  148637. _vq_quantmap__44u4__p6_0,
  148638. 13,
  148639. 13
  148640. };
  148641. static static_codebook _44u4__p6_0 = {
  148642. 2, 169,
  148643. _vq_lengthlist__44u4__p6_0,
  148644. 1, -526516224, 1616117760, 4, 0,
  148645. _vq_quantlist__44u4__p6_0,
  148646. NULL,
  148647. &_vq_auxt__44u4__p6_0,
  148648. NULL,
  148649. 0
  148650. };
  148651. static long _vq_quantlist__44u4__p6_1[] = {
  148652. 2,
  148653. 1,
  148654. 3,
  148655. 0,
  148656. 4,
  148657. };
  148658. static long _vq_lengthlist__44u4__p6_1[] = {
  148659. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148660. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148661. };
  148662. static float _vq_quantthresh__44u4__p6_1[] = {
  148663. -1.5, -0.5, 0.5, 1.5,
  148664. };
  148665. static long _vq_quantmap__44u4__p6_1[] = {
  148666. 3, 1, 0, 2, 4,
  148667. };
  148668. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148669. _vq_quantthresh__44u4__p6_1,
  148670. _vq_quantmap__44u4__p6_1,
  148671. 5,
  148672. 5
  148673. };
  148674. static static_codebook _44u4__p6_1 = {
  148675. 2, 25,
  148676. _vq_lengthlist__44u4__p6_1,
  148677. 1, -533725184, 1611661312, 3, 0,
  148678. _vq_quantlist__44u4__p6_1,
  148679. NULL,
  148680. &_vq_auxt__44u4__p6_1,
  148681. NULL,
  148682. 0
  148683. };
  148684. static long _vq_quantlist__44u4__p7_0[] = {
  148685. 6,
  148686. 5,
  148687. 7,
  148688. 4,
  148689. 8,
  148690. 3,
  148691. 9,
  148692. 2,
  148693. 10,
  148694. 1,
  148695. 11,
  148696. 0,
  148697. 12,
  148698. };
  148699. static long _vq_lengthlist__44u4__p7_0[] = {
  148700. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148701. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148702. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148703. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148704. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148705. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148707. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148708. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148710. 11,11,11,11,11,11,11,11,11,
  148711. };
  148712. static float _vq_quantthresh__44u4__p7_0[] = {
  148713. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148714. 637.5, 892.5, 1147.5, 1402.5,
  148715. };
  148716. static long _vq_quantmap__44u4__p7_0[] = {
  148717. 11, 9, 7, 5, 3, 1, 0, 2,
  148718. 4, 6, 8, 10, 12,
  148719. };
  148720. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148721. _vq_quantthresh__44u4__p7_0,
  148722. _vq_quantmap__44u4__p7_0,
  148723. 13,
  148724. 13
  148725. };
  148726. static static_codebook _44u4__p7_0 = {
  148727. 2, 169,
  148728. _vq_lengthlist__44u4__p7_0,
  148729. 1, -514332672, 1627381760, 4, 0,
  148730. _vq_quantlist__44u4__p7_0,
  148731. NULL,
  148732. &_vq_auxt__44u4__p7_0,
  148733. NULL,
  148734. 0
  148735. };
  148736. static long _vq_quantlist__44u4__p7_1[] = {
  148737. 7,
  148738. 6,
  148739. 8,
  148740. 5,
  148741. 9,
  148742. 4,
  148743. 10,
  148744. 3,
  148745. 11,
  148746. 2,
  148747. 12,
  148748. 1,
  148749. 13,
  148750. 0,
  148751. 14,
  148752. };
  148753. static long _vq_lengthlist__44u4__p7_1[] = {
  148754. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148755. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148756. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148757. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148758. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148759. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148760. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148761. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148762. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148763. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148764. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148765. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148766. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148767. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148768. 16,
  148769. };
  148770. static float _vq_quantthresh__44u4__p7_1[] = {
  148771. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148772. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148773. };
  148774. static long _vq_quantmap__44u4__p7_1[] = {
  148775. 13, 11, 9, 7, 5, 3, 1, 0,
  148776. 2, 4, 6, 8, 10, 12, 14,
  148777. };
  148778. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148779. _vq_quantthresh__44u4__p7_1,
  148780. _vq_quantmap__44u4__p7_1,
  148781. 15,
  148782. 15
  148783. };
  148784. static static_codebook _44u4__p7_1 = {
  148785. 2, 225,
  148786. _vq_lengthlist__44u4__p7_1,
  148787. 1, -522338304, 1620115456, 4, 0,
  148788. _vq_quantlist__44u4__p7_1,
  148789. NULL,
  148790. &_vq_auxt__44u4__p7_1,
  148791. NULL,
  148792. 0
  148793. };
  148794. static long _vq_quantlist__44u4__p7_2[] = {
  148795. 8,
  148796. 7,
  148797. 9,
  148798. 6,
  148799. 10,
  148800. 5,
  148801. 11,
  148802. 4,
  148803. 12,
  148804. 3,
  148805. 13,
  148806. 2,
  148807. 14,
  148808. 1,
  148809. 15,
  148810. 0,
  148811. 16,
  148812. };
  148813. static long _vq_lengthlist__44u4__p7_2[] = {
  148814. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148815. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148816. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148817. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148818. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148819. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148820. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148821. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148822. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148823. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148824. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148825. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148826. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148827. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148828. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148829. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148830. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148831. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148832. 10,
  148833. };
  148834. static float _vq_quantthresh__44u4__p7_2[] = {
  148835. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148836. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148837. };
  148838. static long _vq_quantmap__44u4__p7_2[] = {
  148839. 15, 13, 11, 9, 7, 5, 3, 1,
  148840. 0, 2, 4, 6, 8, 10, 12, 14,
  148841. 16,
  148842. };
  148843. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148844. _vq_quantthresh__44u4__p7_2,
  148845. _vq_quantmap__44u4__p7_2,
  148846. 17,
  148847. 17
  148848. };
  148849. static static_codebook _44u4__p7_2 = {
  148850. 2, 289,
  148851. _vq_lengthlist__44u4__p7_2,
  148852. 1, -529530880, 1611661312, 5, 0,
  148853. _vq_quantlist__44u4__p7_2,
  148854. NULL,
  148855. &_vq_auxt__44u4__p7_2,
  148856. NULL,
  148857. 0
  148858. };
  148859. static long _huff_lengthlist__44u4__short[] = {
  148860. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148861. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148862. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148863. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148864. };
  148865. static static_codebook _huff_book__44u4__short = {
  148866. 2, 64,
  148867. _huff_lengthlist__44u4__short,
  148868. 0, 0, 0, 0, 0,
  148869. NULL,
  148870. NULL,
  148871. NULL,
  148872. NULL,
  148873. 0
  148874. };
  148875. static long _huff_lengthlist__44u5__long[] = {
  148876. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148877. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148878. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148879. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148880. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148881. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148882. 14, 8, 7, 8,
  148883. };
  148884. static static_codebook _huff_book__44u5__long = {
  148885. 2, 100,
  148886. _huff_lengthlist__44u5__long,
  148887. 0, 0, 0, 0, 0,
  148888. NULL,
  148889. NULL,
  148890. NULL,
  148891. NULL,
  148892. 0
  148893. };
  148894. static long _vq_quantlist__44u5__p1_0[] = {
  148895. 1,
  148896. 0,
  148897. 2,
  148898. };
  148899. static long _vq_lengthlist__44u5__p1_0[] = {
  148900. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148901. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148902. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148903. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148904. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148905. 12,
  148906. };
  148907. static float _vq_quantthresh__44u5__p1_0[] = {
  148908. -0.5, 0.5,
  148909. };
  148910. static long _vq_quantmap__44u5__p1_0[] = {
  148911. 1, 0, 2,
  148912. };
  148913. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148914. _vq_quantthresh__44u5__p1_0,
  148915. _vq_quantmap__44u5__p1_0,
  148916. 3,
  148917. 3
  148918. };
  148919. static static_codebook _44u5__p1_0 = {
  148920. 4, 81,
  148921. _vq_lengthlist__44u5__p1_0,
  148922. 1, -535822336, 1611661312, 2, 0,
  148923. _vq_quantlist__44u5__p1_0,
  148924. NULL,
  148925. &_vq_auxt__44u5__p1_0,
  148926. NULL,
  148927. 0
  148928. };
  148929. static long _vq_quantlist__44u5__p2_0[] = {
  148930. 1,
  148931. 0,
  148932. 2,
  148933. };
  148934. static long _vq_lengthlist__44u5__p2_0[] = {
  148935. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148936. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148937. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148938. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148939. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148940. 9,
  148941. };
  148942. static float _vq_quantthresh__44u5__p2_0[] = {
  148943. -0.5, 0.5,
  148944. };
  148945. static long _vq_quantmap__44u5__p2_0[] = {
  148946. 1, 0, 2,
  148947. };
  148948. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148949. _vq_quantthresh__44u5__p2_0,
  148950. _vq_quantmap__44u5__p2_0,
  148951. 3,
  148952. 3
  148953. };
  148954. static static_codebook _44u5__p2_0 = {
  148955. 4, 81,
  148956. _vq_lengthlist__44u5__p2_0,
  148957. 1, -535822336, 1611661312, 2, 0,
  148958. _vq_quantlist__44u5__p2_0,
  148959. NULL,
  148960. &_vq_auxt__44u5__p2_0,
  148961. NULL,
  148962. 0
  148963. };
  148964. static long _vq_quantlist__44u5__p3_0[] = {
  148965. 2,
  148966. 1,
  148967. 3,
  148968. 0,
  148969. 4,
  148970. };
  148971. static long _vq_lengthlist__44u5__p3_0[] = {
  148972. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148973. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148974. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148975. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148976. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148977. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148978. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148979. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148980. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148981. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148982. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148983. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148984. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148985. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148986. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148987. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148988. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148989. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148990. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148991. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148992. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148993. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148994. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148995. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148996. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148997. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148998. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148999. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  149000. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  149001. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  149002. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  149003. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  149004. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  149005. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  149006. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  149007. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  149008. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  149009. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  149010. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  149011. 0,
  149012. };
  149013. static float _vq_quantthresh__44u5__p3_0[] = {
  149014. -1.5, -0.5, 0.5, 1.5,
  149015. };
  149016. static long _vq_quantmap__44u5__p3_0[] = {
  149017. 3, 1, 0, 2, 4,
  149018. };
  149019. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  149020. _vq_quantthresh__44u5__p3_0,
  149021. _vq_quantmap__44u5__p3_0,
  149022. 5,
  149023. 5
  149024. };
  149025. static static_codebook _44u5__p3_0 = {
  149026. 4, 625,
  149027. _vq_lengthlist__44u5__p3_0,
  149028. 1, -533725184, 1611661312, 3, 0,
  149029. _vq_quantlist__44u5__p3_0,
  149030. NULL,
  149031. &_vq_auxt__44u5__p3_0,
  149032. NULL,
  149033. 0
  149034. };
  149035. static long _vq_quantlist__44u5__p4_0[] = {
  149036. 2,
  149037. 1,
  149038. 3,
  149039. 0,
  149040. 4,
  149041. };
  149042. static long _vq_lengthlist__44u5__p4_0[] = {
  149043. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149044. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149045. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149046. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149047. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149048. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149049. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149050. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149051. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149052. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149053. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149054. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149055. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149056. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149057. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149058. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149059. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149060. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149061. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149062. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149063. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149064. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149065. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149066. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149067. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149068. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149069. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149070. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149071. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149072. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149073. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149074. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149075. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149076. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149077. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149078. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149079. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149080. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149081. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149082. 12,
  149083. };
  149084. static float _vq_quantthresh__44u5__p4_0[] = {
  149085. -1.5, -0.5, 0.5, 1.5,
  149086. };
  149087. static long _vq_quantmap__44u5__p4_0[] = {
  149088. 3, 1, 0, 2, 4,
  149089. };
  149090. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149091. _vq_quantthresh__44u5__p4_0,
  149092. _vq_quantmap__44u5__p4_0,
  149093. 5,
  149094. 5
  149095. };
  149096. static static_codebook _44u5__p4_0 = {
  149097. 4, 625,
  149098. _vq_lengthlist__44u5__p4_0,
  149099. 1, -533725184, 1611661312, 3, 0,
  149100. _vq_quantlist__44u5__p4_0,
  149101. NULL,
  149102. &_vq_auxt__44u5__p4_0,
  149103. NULL,
  149104. 0
  149105. };
  149106. static long _vq_quantlist__44u5__p5_0[] = {
  149107. 4,
  149108. 3,
  149109. 5,
  149110. 2,
  149111. 6,
  149112. 1,
  149113. 7,
  149114. 0,
  149115. 8,
  149116. };
  149117. static long _vq_lengthlist__44u5__p5_0[] = {
  149118. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149119. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149120. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149121. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149122. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149123. 14,
  149124. };
  149125. static float _vq_quantthresh__44u5__p5_0[] = {
  149126. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149127. };
  149128. static long _vq_quantmap__44u5__p5_0[] = {
  149129. 7, 5, 3, 1, 0, 2, 4, 6,
  149130. 8,
  149131. };
  149132. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149133. _vq_quantthresh__44u5__p5_0,
  149134. _vq_quantmap__44u5__p5_0,
  149135. 9,
  149136. 9
  149137. };
  149138. static static_codebook _44u5__p5_0 = {
  149139. 2, 81,
  149140. _vq_lengthlist__44u5__p5_0,
  149141. 1, -531628032, 1611661312, 4, 0,
  149142. _vq_quantlist__44u5__p5_0,
  149143. NULL,
  149144. &_vq_auxt__44u5__p5_0,
  149145. NULL,
  149146. 0
  149147. };
  149148. static long _vq_quantlist__44u5__p6_0[] = {
  149149. 4,
  149150. 3,
  149151. 5,
  149152. 2,
  149153. 6,
  149154. 1,
  149155. 7,
  149156. 0,
  149157. 8,
  149158. };
  149159. static long _vq_lengthlist__44u5__p6_0[] = {
  149160. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149161. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149162. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149163. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149164. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149165. 11,
  149166. };
  149167. static float _vq_quantthresh__44u5__p6_0[] = {
  149168. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149169. };
  149170. static long _vq_quantmap__44u5__p6_0[] = {
  149171. 7, 5, 3, 1, 0, 2, 4, 6,
  149172. 8,
  149173. };
  149174. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149175. _vq_quantthresh__44u5__p6_0,
  149176. _vq_quantmap__44u5__p6_0,
  149177. 9,
  149178. 9
  149179. };
  149180. static static_codebook _44u5__p6_0 = {
  149181. 2, 81,
  149182. _vq_lengthlist__44u5__p6_0,
  149183. 1, -531628032, 1611661312, 4, 0,
  149184. _vq_quantlist__44u5__p6_0,
  149185. NULL,
  149186. &_vq_auxt__44u5__p6_0,
  149187. NULL,
  149188. 0
  149189. };
  149190. static long _vq_quantlist__44u5__p7_0[] = {
  149191. 1,
  149192. 0,
  149193. 2,
  149194. };
  149195. static long _vq_lengthlist__44u5__p7_0[] = {
  149196. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149197. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149198. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149199. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149200. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149201. 12,
  149202. };
  149203. static float _vq_quantthresh__44u5__p7_0[] = {
  149204. -5.5, 5.5,
  149205. };
  149206. static long _vq_quantmap__44u5__p7_0[] = {
  149207. 1, 0, 2,
  149208. };
  149209. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149210. _vq_quantthresh__44u5__p7_0,
  149211. _vq_quantmap__44u5__p7_0,
  149212. 3,
  149213. 3
  149214. };
  149215. static static_codebook _44u5__p7_0 = {
  149216. 4, 81,
  149217. _vq_lengthlist__44u5__p7_0,
  149218. 1, -529137664, 1618345984, 2, 0,
  149219. _vq_quantlist__44u5__p7_0,
  149220. NULL,
  149221. &_vq_auxt__44u5__p7_0,
  149222. NULL,
  149223. 0
  149224. };
  149225. static long _vq_quantlist__44u5__p7_1[] = {
  149226. 5,
  149227. 4,
  149228. 6,
  149229. 3,
  149230. 7,
  149231. 2,
  149232. 8,
  149233. 1,
  149234. 9,
  149235. 0,
  149236. 10,
  149237. };
  149238. static long _vq_lengthlist__44u5__p7_1[] = {
  149239. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149240. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149241. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149242. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149243. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149244. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149245. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149246. 9, 9, 9, 9, 9,10,10,10,10,
  149247. };
  149248. static float _vq_quantthresh__44u5__p7_1[] = {
  149249. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149250. 3.5, 4.5,
  149251. };
  149252. static long _vq_quantmap__44u5__p7_1[] = {
  149253. 9, 7, 5, 3, 1, 0, 2, 4,
  149254. 6, 8, 10,
  149255. };
  149256. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149257. _vq_quantthresh__44u5__p7_1,
  149258. _vq_quantmap__44u5__p7_1,
  149259. 11,
  149260. 11
  149261. };
  149262. static static_codebook _44u5__p7_1 = {
  149263. 2, 121,
  149264. _vq_lengthlist__44u5__p7_1,
  149265. 1, -531365888, 1611661312, 4, 0,
  149266. _vq_quantlist__44u5__p7_1,
  149267. NULL,
  149268. &_vq_auxt__44u5__p7_1,
  149269. NULL,
  149270. 0
  149271. };
  149272. static long _vq_quantlist__44u5__p8_0[] = {
  149273. 5,
  149274. 4,
  149275. 6,
  149276. 3,
  149277. 7,
  149278. 2,
  149279. 8,
  149280. 1,
  149281. 9,
  149282. 0,
  149283. 10,
  149284. };
  149285. static long _vq_lengthlist__44u5__p8_0[] = {
  149286. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149287. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149288. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149289. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149290. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149291. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149292. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149293. 12,13,13,14,14,14,14,15,15,
  149294. };
  149295. static float _vq_quantthresh__44u5__p8_0[] = {
  149296. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149297. 38.5, 49.5,
  149298. };
  149299. static long _vq_quantmap__44u5__p8_0[] = {
  149300. 9, 7, 5, 3, 1, 0, 2, 4,
  149301. 6, 8, 10,
  149302. };
  149303. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149304. _vq_quantthresh__44u5__p8_0,
  149305. _vq_quantmap__44u5__p8_0,
  149306. 11,
  149307. 11
  149308. };
  149309. static static_codebook _44u5__p8_0 = {
  149310. 2, 121,
  149311. _vq_lengthlist__44u5__p8_0,
  149312. 1, -524582912, 1618345984, 4, 0,
  149313. _vq_quantlist__44u5__p8_0,
  149314. NULL,
  149315. &_vq_auxt__44u5__p8_0,
  149316. NULL,
  149317. 0
  149318. };
  149319. static long _vq_quantlist__44u5__p8_1[] = {
  149320. 5,
  149321. 4,
  149322. 6,
  149323. 3,
  149324. 7,
  149325. 2,
  149326. 8,
  149327. 1,
  149328. 9,
  149329. 0,
  149330. 10,
  149331. };
  149332. static long _vq_lengthlist__44u5__p8_1[] = {
  149333. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149334. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149335. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149336. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149337. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149338. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149339. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149340. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149341. };
  149342. static float _vq_quantthresh__44u5__p8_1[] = {
  149343. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149344. 3.5, 4.5,
  149345. };
  149346. static long _vq_quantmap__44u5__p8_1[] = {
  149347. 9, 7, 5, 3, 1, 0, 2, 4,
  149348. 6, 8, 10,
  149349. };
  149350. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149351. _vq_quantthresh__44u5__p8_1,
  149352. _vq_quantmap__44u5__p8_1,
  149353. 11,
  149354. 11
  149355. };
  149356. static static_codebook _44u5__p8_1 = {
  149357. 2, 121,
  149358. _vq_lengthlist__44u5__p8_1,
  149359. 1, -531365888, 1611661312, 4, 0,
  149360. _vq_quantlist__44u5__p8_1,
  149361. NULL,
  149362. &_vq_auxt__44u5__p8_1,
  149363. NULL,
  149364. 0
  149365. };
  149366. static long _vq_quantlist__44u5__p9_0[] = {
  149367. 6,
  149368. 5,
  149369. 7,
  149370. 4,
  149371. 8,
  149372. 3,
  149373. 9,
  149374. 2,
  149375. 10,
  149376. 1,
  149377. 11,
  149378. 0,
  149379. 12,
  149380. };
  149381. static long _vq_lengthlist__44u5__p9_0[] = {
  149382. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149383. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149384. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149385. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149386. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149387. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149388. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149389. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149390. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149391. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149392. 12,12,12,12,12,12,12,12,12,
  149393. };
  149394. static float _vq_quantthresh__44u5__p9_0[] = {
  149395. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149396. 637.5, 892.5, 1147.5, 1402.5,
  149397. };
  149398. static long _vq_quantmap__44u5__p9_0[] = {
  149399. 11, 9, 7, 5, 3, 1, 0, 2,
  149400. 4, 6, 8, 10, 12,
  149401. };
  149402. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149403. _vq_quantthresh__44u5__p9_0,
  149404. _vq_quantmap__44u5__p9_0,
  149405. 13,
  149406. 13
  149407. };
  149408. static static_codebook _44u5__p9_0 = {
  149409. 2, 169,
  149410. _vq_lengthlist__44u5__p9_0,
  149411. 1, -514332672, 1627381760, 4, 0,
  149412. _vq_quantlist__44u5__p9_0,
  149413. NULL,
  149414. &_vq_auxt__44u5__p9_0,
  149415. NULL,
  149416. 0
  149417. };
  149418. static long _vq_quantlist__44u5__p9_1[] = {
  149419. 7,
  149420. 6,
  149421. 8,
  149422. 5,
  149423. 9,
  149424. 4,
  149425. 10,
  149426. 3,
  149427. 11,
  149428. 2,
  149429. 12,
  149430. 1,
  149431. 13,
  149432. 0,
  149433. 14,
  149434. };
  149435. static long _vq_lengthlist__44u5__p9_1[] = {
  149436. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149437. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149438. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149439. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149440. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149441. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149442. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149443. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149444. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149445. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149446. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149447. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149448. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149449. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149450. 14,
  149451. };
  149452. static float _vq_quantthresh__44u5__p9_1[] = {
  149453. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149454. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149455. };
  149456. static long _vq_quantmap__44u5__p9_1[] = {
  149457. 13, 11, 9, 7, 5, 3, 1, 0,
  149458. 2, 4, 6, 8, 10, 12, 14,
  149459. };
  149460. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149461. _vq_quantthresh__44u5__p9_1,
  149462. _vq_quantmap__44u5__p9_1,
  149463. 15,
  149464. 15
  149465. };
  149466. static static_codebook _44u5__p9_1 = {
  149467. 2, 225,
  149468. _vq_lengthlist__44u5__p9_1,
  149469. 1, -522338304, 1620115456, 4, 0,
  149470. _vq_quantlist__44u5__p9_1,
  149471. NULL,
  149472. &_vq_auxt__44u5__p9_1,
  149473. NULL,
  149474. 0
  149475. };
  149476. static long _vq_quantlist__44u5__p9_2[] = {
  149477. 8,
  149478. 7,
  149479. 9,
  149480. 6,
  149481. 10,
  149482. 5,
  149483. 11,
  149484. 4,
  149485. 12,
  149486. 3,
  149487. 13,
  149488. 2,
  149489. 14,
  149490. 1,
  149491. 15,
  149492. 0,
  149493. 16,
  149494. };
  149495. static long _vq_lengthlist__44u5__p9_2[] = {
  149496. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149497. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149498. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149499. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149500. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149501. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149502. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149503. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149504. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149505. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149506. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149507. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149508. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149509. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149510. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149511. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149512. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149513. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149514. 10,
  149515. };
  149516. static float _vq_quantthresh__44u5__p9_2[] = {
  149517. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149518. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149519. };
  149520. static long _vq_quantmap__44u5__p9_2[] = {
  149521. 15, 13, 11, 9, 7, 5, 3, 1,
  149522. 0, 2, 4, 6, 8, 10, 12, 14,
  149523. 16,
  149524. };
  149525. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149526. _vq_quantthresh__44u5__p9_2,
  149527. _vq_quantmap__44u5__p9_2,
  149528. 17,
  149529. 17
  149530. };
  149531. static static_codebook _44u5__p9_2 = {
  149532. 2, 289,
  149533. _vq_lengthlist__44u5__p9_2,
  149534. 1, -529530880, 1611661312, 5, 0,
  149535. _vq_quantlist__44u5__p9_2,
  149536. NULL,
  149537. &_vq_auxt__44u5__p9_2,
  149538. NULL,
  149539. 0
  149540. };
  149541. static long _huff_lengthlist__44u5__short[] = {
  149542. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149543. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149544. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149545. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149546. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149547. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149548. 6, 8,15,17,
  149549. };
  149550. static static_codebook _huff_book__44u5__short = {
  149551. 2, 100,
  149552. _huff_lengthlist__44u5__short,
  149553. 0, 0, 0, 0, 0,
  149554. NULL,
  149555. NULL,
  149556. NULL,
  149557. NULL,
  149558. 0
  149559. };
  149560. static long _huff_lengthlist__44u6__long[] = {
  149561. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149562. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149563. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149564. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149565. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149566. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149567. 13, 8, 7, 7,
  149568. };
  149569. static static_codebook _huff_book__44u6__long = {
  149570. 2, 100,
  149571. _huff_lengthlist__44u6__long,
  149572. 0, 0, 0, 0, 0,
  149573. NULL,
  149574. NULL,
  149575. NULL,
  149576. NULL,
  149577. 0
  149578. };
  149579. static long _vq_quantlist__44u6__p1_0[] = {
  149580. 1,
  149581. 0,
  149582. 2,
  149583. };
  149584. static long _vq_lengthlist__44u6__p1_0[] = {
  149585. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149586. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149587. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149588. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149589. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149590. 12,
  149591. };
  149592. static float _vq_quantthresh__44u6__p1_0[] = {
  149593. -0.5, 0.5,
  149594. };
  149595. static long _vq_quantmap__44u6__p1_0[] = {
  149596. 1, 0, 2,
  149597. };
  149598. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149599. _vq_quantthresh__44u6__p1_0,
  149600. _vq_quantmap__44u6__p1_0,
  149601. 3,
  149602. 3
  149603. };
  149604. static static_codebook _44u6__p1_0 = {
  149605. 4, 81,
  149606. _vq_lengthlist__44u6__p1_0,
  149607. 1, -535822336, 1611661312, 2, 0,
  149608. _vq_quantlist__44u6__p1_0,
  149609. NULL,
  149610. &_vq_auxt__44u6__p1_0,
  149611. NULL,
  149612. 0
  149613. };
  149614. static long _vq_quantlist__44u6__p2_0[] = {
  149615. 1,
  149616. 0,
  149617. 2,
  149618. };
  149619. static long _vq_lengthlist__44u6__p2_0[] = {
  149620. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149621. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149622. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149623. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149624. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149625. 9,
  149626. };
  149627. static float _vq_quantthresh__44u6__p2_0[] = {
  149628. -0.5, 0.5,
  149629. };
  149630. static long _vq_quantmap__44u6__p2_0[] = {
  149631. 1, 0, 2,
  149632. };
  149633. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149634. _vq_quantthresh__44u6__p2_0,
  149635. _vq_quantmap__44u6__p2_0,
  149636. 3,
  149637. 3
  149638. };
  149639. static static_codebook _44u6__p2_0 = {
  149640. 4, 81,
  149641. _vq_lengthlist__44u6__p2_0,
  149642. 1, -535822336, 1611661312, 2, 0,
  149643. _vq_quantlist__44u6__p2_0,
  149644. NULL,
  149645. &_vq_auxt__44u6__p2_0,
  149646. NULL,
  149647. 0
  149648. };
  149649. static long _vq_quantlist__44u6__p3_0[] = {
  149650. 2,
  149651. 1,
  149652. 3,
  149653. 0,
  149654. 4,
  149655. };
  149656. static long _vq_lengthlist__44u6__p3_0[] = {
  149657. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149658. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149659. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149660. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149661. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149662. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149663. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149664. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149665. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149666. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149667. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149668. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149669. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149670. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149671. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149672. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149673. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149674. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149675. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149676. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149677. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149678. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149679. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149680. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149681. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149682. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149683. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149684. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149685. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149686. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149687. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149688. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149689. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149690. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149691. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149692. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149693. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149694. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149695. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149696. 19,
  149697. };
  149698. static float _vq_quantthresh__44u6__p3_0[] = {
  149699. -1.5, -0.5, 0.5, 1.5,
  149700. };
  149701. static long _vq_quantmap__44u6__p3_0[] = {
  149702. 3, 1, 0, 2, 4,
  149703. };
  149704. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149705. _vq_quantthresh__44u6__p3_0,
  149706. _vq_quantmap__44u6__p3_0,
  149707. 5,
  149708. 5
  149709. };
  149710. static static_codebook _44u6__p3_0 = {
  149711. 4, 625,
  149712. _vq_lengthlist__44u6__p3_0,
  149713. 1, -533725184, 1611661312, 3, 0,
  149714. _vq_quantlist__44u6__p3_0,
  149715. NULL,
  149716. &_vq_auxt__44u6__p3_0,
  149717. NULL,
  149718. 0
  149719. };
  149720. static long _vq_quantlist__44u6__p4_0[] = {
  149721. 2,
  149722. 1,
  149723. 3,
  149724. 0,
  149725. 4,
  149726. };
  149727. static long _vq_lengthlist__44u6__p4_0[] = {
  149728. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149729. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149730. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149731. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149732. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149733. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149734. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149735. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149736. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149737. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149738. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149739. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149740. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149741. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149742. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149743. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149744. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149745. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149746. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149747. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149748. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149749. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149750. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149751. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149752. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149753. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149754. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149755. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149756. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149757. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149758. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149759. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149760. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149761. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149762. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149763. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149764. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149765. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149766. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149767. 13,
  149768. };
  149769. static float _vq_quantthresh__44u6__p4_0[] = {
  149770. -1.5, -0.5, 0.5, 1.5,
  149771. };
  149772. static long _vq_quantmap__44u6__p4_0[] = {
  149773. 3, 1, 0, 2, 4,
  149774. };
  149775. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149776. _vq_quantthresh__44u6__p4_0,
  149777. _vq_quantmap__44u6__p4_0,
  149778. 5,
  149779. 5
  149780. };
  149781. static static_codebook _44u6__p4_0 = {
  149782. 4, 625,
  149783. _vq_lengthlist__44u6__p4_0,
  149784. 1, -533725184, 1611661312, 3, 0,
  149785. _vq_quantlist__44u6__p4_0,
  149786. NULL,
  149787. &_vq_auxt__44u6__p4_0,
  149788. NULL,
  149789. 0
  149790. };
  149791. static long _vq_quantlist__44u6__p5_0[] = {
  149792. 4,
  149793. 3,
  149794. 5,
  149795. 2,
  149796. 6,
  149797. 1,
  149798. 7,
  149799. 0,
  149800. 8,
  149801. };
  149802. static long _vq_lengthlist__44u6__p5_0[] = {
  149803. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149804. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149805. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149806. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149807. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149808. 14,
  149809. };
  149810. static float _vq_quantthresh__44u6__p5_0[] = {
  149811. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149812. };
  149813. static long _vq_quantmap__44u6__p5_0[] = {
  149814. 7, 5, 3, 1, 0, 2, 4, 6,
  149815. 8,
  149816. };
  149817. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149818. _vq_quantthresh__44u6__p5_0,
  149819. _vq_quantmap__44u6__p5_0,
  149820. 9,
  149821. 9
  149822. };
  149823. static static_codebook _44u6__p5_0 = {
  149824. 2, 81,
  149825. _vq_lengthlist__44u6__p5_0,
  149826. 1, -531628032, 1611661312, 4, 0,
  149827. _vq_quantlist__44u6__p5_0,
  149828. NULL,
  149829. &_vq_auxt__44u6__p5_0,
  149830. NULL,
  149831. 0
  149832. };
  149833. static long _vq_quantlist__44u6__p6_0[] = {
  149834. 4,
  149835. 3,
  149836. 5,
  149837. 2,
  149838. 6,
  149839. 1,
  149840. 7,
  149841. 0,
  149842. 8,
  149843. };
  149844. static long _vq_lengthlist__44u6__p6_0[] = {
  149845. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149846. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149847. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149848. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149849. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149850. 12,
  149851. };
  149852. static float _vq_quantthresh__44u6__p6_0[] = {
  149853. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149854. };
  149855. static long _vq_quantmap__44u6__p6_0[] = {
  149856. 7, 5, 3, 1, 0, 2, 4, 6,
  149857. 8,
  149858. };
  149859. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149860. _vq_quantthresh__44u6__p6_0,
  149861. _vq_quantmap__44u6__p6_0,
  149862. 9,
  149863. 9
  149864. };
  149865. static static_codebook _44u6__p6_0 = {
  149866. 2, 81,
  149867. _vq_lengthlist__44u6__p6_0,
  149868. 1, -531628032, 1611661312, 4, 0,
  149869. _vq_quantlist__44u6__p6_0,
  149870. NULL,
  149871. &_vq_auxt__44u6__p6_0,
  149872. NULL,
  149873. 0
  149874. };
  149875. static long _vq_quantlist__44u6__p7_0[] = {
  149876. 1,
  149877. 0,
  149878. 2,
  149879. };
  149880. static long _vq_lengthlist__44u6__p7_0[] = {
  149881. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149882. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149883. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149884. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149885. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149886. 10,
  149887. };
  149888. static float _vq_quantthresh__44u6__p7_0[] = {
  149889. -5.5, 5.5,
  149890. };
  149891. static long _vq_quantmap__44u6__p7_0[] = {
  149892. 1, 0, 2,
  149893. };
  149894. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149895. _vq_quantthresh__44u6__p7_0,
  149896. _vq_quantmap__44u6__p7_0,
  149897. 3,
  149898. 3
  149899. };
  149900. static static_codebook _44u6__p7_0 = {
  149901. 4, 81,
  149902. _vq_lengthlist__44u6__p7_0,
  149903. 1, -529137664, 1618345984, 2, 0,
  149904. _vq_quantlist__44u6__p7_0,
  149905. NULL,
  149906. &_vq_auxt__44u6__p7_0,
  149907. NULL,
  149908. 0
  149909. };
  149910. static long _vq_quantlist__44u6__p7_1[] = {
  149911. 5,
  149912. 4,
  149913. 6,
  149914. 3,
  149915. 7,
  149916. 2,
  149917. 8,
  149918. 1,
  149919. 9,
  149920. 0,
  149921. 10,
  149922. };
  149923. static long _vq_lengthlist__44u6__p7_1[] = {
  149924. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149925. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149926. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149927. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149928. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149929. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149930. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149931. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149932. };
  149933. static float _vq_quantthresh__44u6__p7_1[] = {
  149934. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149935. 3.5, 4.5,
  149936. };
  149937. static long _vq_quantmap__44u6__p7_1[] = {
  149938. 9, 7, 5, 3, 1, 0, 2, 4,
  149939. 6, 8, 10,
  149940. };
  149941. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149942. _vq_quantthresh__44u6__p7_1,
  149943. _vq_quantmap__44u6__p7_1,
  149944. 11,
  149945. 11
  149946. };
  149947. static static_codebook _44u6__p7_1 = {
  149948. 2, 121,
  149949. _vq_lengthlist__44u6__p7_1,
  149950. 1, -531365888, 1611661312, 4, 0,
  149951. _vq_quantlist__44u6__p7_1,
  149952. NULL,
  149953. &_vq_auxt__44u6__p7_1,
  149954. NULL,
  149955. 0
  149956. };
  149957. static long _vq_quantlist__44u6__p8_0[] = {
  149958. 5,
  149959. 4,
  149960. 6,
  149961. 3,
  149962. 7,
  149963. 2,
  149964. 8,
  149965. 1,
  149966. 9,
  149967. 0,
  149968. 10,
  149969. };
  149970. static long _vq_lengthlist__44u6__p8_0[] = {
  149971. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149972. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149973. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149974. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149975. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149976. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149977. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149978. 12,13,13,14,14,14,15,15,15,
  149979. };
  149980. static float _vq_quantthresh__44u6__p8_0[] = {
  149981. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149982. 38.5, 49.5,
  149983. };
  149984. static long _vq_quantmap__44u6__p8_0[] = {
  149985. 9, 7, 5, 3, 1, 0, 2, 4,
  149986. 6, 8, 10,
  149987. };
  149988. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149989. _vq_quantthresh__44u6__p8_0,
  149990. _vq_quantmap__44u6__p8_0,
  149991. 11,
  149992. 11
  149993. };
  149994. static static_codebook _44u6__p8_0 = {
  149995. 2, 121,
  149996. _vq_lengthlist__44u6__p8_0,
  149997. 1, -524582912, 1618345984, 4, 0,
  149998. _vq_quantlist__44u6__p8_0,
  149999. NULL,
  150000. &_vq_auxt__44u6__p8_0,
  150001. NULL,
  150002. 0
  150003. };
  150004. static long _vq_quantlist__44u6__p8_1[] = {
  150005. 5,
  150006. 4,
  150007. 6,
  150008. 3,
  150009. 7,
  150010. 2,
  150011. 8,
  150012. 1,
  150013. 9,
  150014. 0,
  150015. 10,
  150016. };
  150017. static long _vq_lengthlist__44u6__p8_1[] = {
  150018. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  150019. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  150020. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  150021. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150022. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  150023. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150024. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150025. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150026. };
  150027. static float _vq_quantthresh__44u6__p8_1[] = {
  150028. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150029. 3.5, 4.5,
  150030. };
  150031. static long _vq_quantmap__44u6__p8_1[] = {
  150032. 9, 7, 5, 3, 1, 0, 2, 4,
  150033. 6, 8, 10,
  150034. };
  150035. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  150036. _vq_quantthresh__44u6__p8_1,
  150037. _vq_quantmap__44u6__p8_1,
  150038. 11,
  150039. 11
  150040. };
  150041. static static_codebook _44u6__p8_1 = {
  150042. 2, 121,
  150043. _vq_lengthlist__44u6__p8_1,
  150044. 1, -531365888, 1611661312, 4, 0,
  150045. _vq_quantlist__44u6__p8_1,
  150046. NULL,
  150047. &_vq_auxt__44u6__p8_1,
  150048. NULL,
  150049. 0
  150050. };
  150051. static long _vq_quantlist__44u6__p9_0[] = {
  150052. 7,
  150053. 6,
  150054. 8,
  150055. 5,
  150056. 9,
  150057. 4,
  150058. 10,
  150059. 3,
  150060. 11,
  150061. 2,
  150062. 12,
  150063. 1,
  150064. 13,
  150065. 0,
  150066. 14,
  150067. };
  150068. static long _vq_lengthlist__44u6__p9_0[] = {
  150069. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150070. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150071. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150072. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150073. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150074. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150075. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150076. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150077. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150078. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150079. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150080. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150081. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150082. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150083. 14,
  150084. };
  150085. static float _vq_quantthresh__44u6__p9_0[] = {
  150086. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150087. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150088. };
  150089. static long _vq_quantmap__44u6__p9_0[] = {
  150090. 13, 11, 9, 7, 5, 3, 1, 0,
  150091. 2, 4, 6, 8, 10, 12, 14,
  150092. };
  150093. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150094. _vq_quantthresh__44u6__p9_0,
  150095. _vq_quantmap__44u6__p9_0,
  150096. 15,
  150097. 15
  150098. };
  150099. static static_codebook _44u6__p9_0 = {
  150100. 2, 225,
  150101. _vq_lengthlist__44u6__p9_0,
  150102. 1, -514071552, 1627381760, 4, 0,
  150103. _vq_quantlist__44u6__p9_0,
  150104. NULL,
  150105. &_vq_auxt__44u6__p9_0,
  150106. NULL,
  150107. 0
  150108. };
  150109. static long _vq_quantlist__44u6__p9_1[] = {
  150110. 7,
  150111. 6,
  150112. 8,
  150113. 5,
  150114. 9,
  150115. 4,
  150116. 10,
  150117. 3,
  150118. 11,
  150119. 2,
  150120. 12,
  150121. 1,
  150122. 13,
  150123. 0,
  150124. 14,
  150125. };
  150126. static long _vq_lengthlist__44u6__p9_1[] = {
  150127. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150128. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150129. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150130. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150131. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150132. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150133. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150134. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150135. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150136. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150137. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150138. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150139. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150140. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150141. 13,
  150142. };
  150143. static float _vq_quantthresh__44u6__p9_1[] = {
  150144. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150145. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150146. };
  150147. static long _vq_quantmap__44u6__p9_1[] = {
  150148. 13, 11, 9, 7, 5, 3, 1, 0,
  150149. 2, 4, 6, 8, 10, 12, 14,
  150150. };
  150151. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150152. _vq_quantthresh__44u6__p9_1,
  150153. _vq_quantmap__44u6__p9_1,
  150154. 15,
  150155. 15
  150156. };
  150157. static static_codebook _44u6__p9_1 = {
  150158. 2, 225,
  150159. _vq_lengthlist__44u6__p9_1,
  150160. 1, -522338304, 1620115456, 4, 0,
  150161. _vq_quantlist__44u6__p9_1,
  150162. NULL,
  150163. &_vq_auxt__44u6__p9_1,
  150164. NULL,
  150165. 0
  150166. };
  150167. static long _vq_quantlist__44u6__p9_2[] = {
  150168. 8,
  150169. 7,
  150170. 9,
  150171. 6,
  150172. 10,
  150173. 5,
  150174. 11,
  150175. 4,
  150176. 12,
  150177. 3,
  150178. 13,
  150179. 2,
  150180. 14,
  150181. 1,
  150182. 15,
  150183. 0,
  150184. 16,
  150185. };
  150186. static long _vq_lengthlist__44u6__p9_2[] = {
  150187. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150188. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150189. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150190. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150191. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150192. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150193. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150194. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150195. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150196. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150197. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150198. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150199. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150200. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150201. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150202. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150203. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150204. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150205. 10,
  150206. };
  150207. static float _vq_quantthresh__44u6__p9_2[] = {
  150208. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150209. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150210. };
  150211. static long _vq_quantmap__44u6__p9_2[] = {
  150212. 15, 13, 11, 9, 7, 5, 3, 1,
  150213. 0, 2, 4, 6, 8, 10, 12, 14,
  150214. 16,
  150215. };
  150216. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150217. _vq_quantthresh__44u6__p9_2,
  150218. _vq_quantmap__44u6__p9_2,
  150219. 17,
  150220. 17
  150221. };
  150222. static static_codebook _44u6__p9_2 = {
  150223. 2, 289,
  150224. _vq_lengthlist__44u6__p9_2,
  150225. 1, -529530880, 1611661312, 5, 0,
  150226. _vq_quantlist__44u6__p9_2,
  150227. NULL,
  150228. &_vq_auxt__44u6__p9_2,
  150229. NULL,
  150230. 0
  150231. };
  150232. static long _huff_lengthlist__44u6__short[] = {
  150233. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150234. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150235. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150236. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150237. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150238. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150239. 7, 6, 9,16,
  150240. };
  150241. static static_codebook _huff_book__44u6__short = {
  150242. 2, 100,
  150243. _huff_lengthlist__44u6__short,
  150244. 0, 0, 0, 0, 0,
  150245. NULL,
  150246. NULL,
  150247. NULL,
  150248. NULL,
  150249. 0
  150250. };
  150251. static long _huff_lengthlist__44u7__long[] = {
  150252. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150253. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150254. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150255. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150256. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150257. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150258. 12, 8, 6, 7,
  150259. };
  150260. static static_codebook _huff_book__44u7__long = {
  150261. 2, 100,
  150262. _huff_lengthlist__44u7__long,
  150263. 0, 0, 0, 0, 0,
  150264. NULL,
  150265. NULL,
  150266. NULL,
  150267. NULL,
  150268. 0
  150269. };
  150270. static long _vq_quantlist__44u7__p1_0[] = {
  150271. 1,
  150272. 0,
  150273. 2,
  150274. };
  150275. static long _vq_lengthlist__44u7__p1_0[] = {
  150276. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150277. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150278. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150279. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150280. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150281. 12,
  150282. };
  150283. static float _vq_quantthresh__44u7__p1_0[] = {
  150284. -0.5, 0.5,
  150285. };
  150286. static long _vq_quantmap__44u7__p1_0[] = {
  150287. 1, 0, 2,
  150288. };
  150289. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150290. _vq_quantthresh__44u7__p1_0,
  150291. _vq_quantmap__44u7__p1_0,
  150292. 3,
  150293. 3
  150294. };
  150295. static static_codebook _44u7__p1_0 = {
  150296. 4, 81,
  150297. _vq_lengthlist__44u7__p1_0,
  150298. 1, -535822336, 1611661312, 2, 0,
  150299. _vq_quantlist__44u7__p1_0,
  150300. NULL,
  150301. &_vq_auxt__44u7__p1_0,
  150302. NULL,
  150303. 0
  150304. };
  150305. static long _vq_quantlist__44u7__p2_0[] = {
  150306. 1,
  150307. 0,
  150308. 2,
  150309. };
  150310. static long _vq_lengthlist__44u7__p2_0[] = {
  150311. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150312. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150313. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150314. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150315. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150316. 9,
  150317. };
  150318. static float _vq_quantthresh__44u7__p2_0[] = {
  150319. -0.5, 0.5,
  150320. };
  150321. static long _vq_quantmap__44u7__p2_0[] = {
  150322. 1, 0, 2,
  150323. };
  150324. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150325. _vq_quantthresh__44u7__p2_0,
  150326. _vq_quantmap__44u7__p2_0,
  150327. 3,
  150328. 3
  150329. };
  150330. static static_codebook _44u7__p2_0 = {
  150331. 4, 81,
  150332. _vq_lengthlist__44u7__p2_0,
  150333. 1, -535822336, 1611661312, 2, 0,
  150334. _vq_quantlist__44u7__p2_0,
  150335. NULL,
  150336. &_vq_auxt__44u7__p2_0,
  150337. NULL,
  150338. 0
  150339. };
  150340. static long _vq_quantlist__44u7__p3_0[] = {
  150341. 2,
  150342. 1,
  150343. 3,
  150344. 0,
  150345. 4,
  150346. };
  150347. static long _vq_lengthlist__44u7__p3_0[] = {
  150348. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150349. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150350. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150351. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150352. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150353. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150354. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150355. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150356. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150357. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150358. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150359. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150360. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150361. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150362. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150363. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150364. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150365. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150366. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150367. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150368. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150369. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150370. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150371. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150372. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150373. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150374. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150375. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150376. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150377. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150378. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150379. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150380. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150381. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150382. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150383. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150384. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150385. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150386. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150387. 0,
  150388. };
  150389. static float _vq_quantthresh__44u7__p3_0[] = {
  150390. -1.5, -0.5, 0.5, 1.5,
  150391. };
  150392. static long _vq_quantmap__44u7__p3_0[] = {
  150393. 3, 1, 0, 2, 4,
  150394. };
  150395. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150396. _vq_quantthresh__44u7__p3_0,
  150397. _vq_quantmap__44u7__p3_0,
  150398. 5,
  150399. 5
  150400. };
  150401. static static_codebook _44u7__p3_0 = {
  150402. 4, 625,
  150403. _vq_lengthlist__44u7__p3_0,
  150404. 1, -533725184, 1611661312, 3, 0,
  150405. _vq_quantlist__44u7__p3_0,
  150406. NULL,
  150407. &_vq_auxt__44u7__p3_0,
  150408. NULL,
  150409. 0
  150410. };
  150411. static long _vq_quantlist__44u7__p4_0[] = {
  150412. 2,
  150413. 1,
  150414. 3,
  150415. 0,
  150416. 4,
  150417. };
  150418. static long _vq_lengthlist__44u7__p4_0[] = {
  150419. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150420. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150421. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150422. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150423. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150424. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150425. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150426. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150427. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150428. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150429. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150430. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150431. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150432. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150433. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150434. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150435. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150436. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150437. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150438. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150439. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150440. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150441. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150442. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150443. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150444. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150445. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150446. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150447. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150448. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150449. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150450. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150451. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150452. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150453. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150454. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150455. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150456. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150457. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150458. 14,
  150459. };
  150460. static float _vq_quantthresh__44u7__p4_0[] = {
  150461. -1.5, -0.5, 0.5, 1.5,
  150462. };
  150463. static long _vq_quantmap__44u7__p4_0[] = {
  150464. 3, 1, 0, 2, 4,
  150465. };
  150466. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150467. _vq_quantthresh__44u7__p4_0,
  150468. _vq_quantmap__44u7__p4_0,
  150469. 5,
  150470. 5
  150471. };
  150472. static static_codebook _44u7__p4_0 = {
  150473. 4, 625,
  150474. _vq_lengthlist__44u7__p4_0,
  150475. 1, -533725184, 1611661312, 3, 0,
  150476. _vq_quantlist__44u7__p4_0,
  150477. NULL,
  150478. &_vq_auxt__44u7__p4_0,
  150479. NULL,
  150480. 0
  150481. };
  150482. static long _vq_quantlist__44u7__p5_0[] = {
  150483. 4,
  150484. 3,
  150485. 5,
  150486. 2,
  150487. 6,
  150488. 1,
  150489. 7,
  150490. 0,
  150491. 8,
  150492. };
  150493. static long _vq_lengthlist__44u7__p5_0[] = {
  150494. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150495. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150496. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150497. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150498. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150499. 14,
  150500. };
  150501. static float _vq_quantthresh__44u7__p5_0[] = {
  150502. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150503. };
  150504. static long _vq_quantmap__44u7__p5_0[] = {
  150505. 7, 5, 3, 1, 0, 2, 4, 6,
  150506. 8,
  150507. };
  150508. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150509. _vq_quantthresh__44u7__p5_0,
  150510. _vq_quantmap__44u7__p5_0,
  150511. 9,
  150512. 9
  150513. };
  150514. static static_codebook _44u7__p5_0 = {
  150515. 2, 81,
  150516. _vq_lengthlist__44u7__p5_0,
  150517. 1, -531628032, 1611661312, 4, 0,
  150518. _vq_quantlist__44u7__p5_0,
  150519. NULL,
  150520. &_vq_auxt__44u7__p5_0,
  150521. NULL,
  150522. 0
  150523. };
  150524. static long _vq_quantlist__44u7__p6_0[] = {
  150525. 4,
  150526. 3,
  150527. 5,
  150528. 2,
  150529. 6,
  150530. 1,
  150531. 7,
  150532. 0,
  150533. 8,
  150534. };
  150535. static long _vq_lengthlist__44u7__p6_0[] = {
  150536. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150537. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150538. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150539. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150540. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150541. 12,
  150542. };
  150543. static float _vq_quantthresh__44u7__p6_0[] = {
  150544. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150545. };
  150546. static long _vq_quantmap__44u7__p6_0[] = {
  150547. 7, 5, 3, 1, 0, 2, 4, 6,
  150548. 8,
  150549. };
  150550. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150551. _vq_quantthresh__44u7__p6_0,
  150552. _vq_quantmap__44u7__p6_0,
  150553. 9,
  150554. 9
  150555. };
  150556. static static_codebook _44u7__p6_0 = {
  150557. 2, 81,
  150558. _vq_lengthlist__44u7__p6_0,
  150559. 1, -531628032, 1611661312, 4, 0,
  150560. _vq_quantlist__44u7__p6_0,
  150561. NULL,
  150562. &_vq_auxt__44u7__p6_0,
  150563. NULL,
  150564. 0
  150565. };
  150566. static long _vq_quantlist__44u7__p7_0[] = {
  150567. 1,
  150568. 0,
  150569. 2,
  150570. };
  150571. static long _vq_lengthlist__44u7__p7_0[] = {
  150572. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150573. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150574. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150575. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150576. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150577. 10,
  150578. };
  150579. static float _vq_quantthresh__44u7__p7_0[] = {
  150580. -5.5, 5.5,
  150581. };
  150582. static long _vq_quantmap__44u7__p7_0[] = {
  150583. 1, 0, 2,
  150584. };
  150585. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150586. _vq_quantthresh__44u7__p7_0,
  150587. _vq_quantmap__44u7__p7_0,
  150588. 3,
  150589. 3
  150590. };
  150591. static static_codebook _44u7__p7_0 = {
  150592. 4, 81,
  150593. _vq_lengthlist__44u7__p7_0,
  150594. 1, -529137664, 1618345984, 2, 0,
  150595. _vq_quantlist__44u7__p7_0,
  150596. NULL,
  150597. &_vq_auxt__44u7__p7_0,
  150598. NULL,
  150599. 0
  150600. };
  150601. static long _vq_quantlist__44u7__p7_1[] = {
  150602. 5,
  150603. 4,
  150604. 6,
  150605. 3,
  150606. 7,
  150607. 2,
  150608. 8,
  150609. 1,
  150610. 9,
  150611. 0,
  150612. 10,
  150613. };
  150614. static long _vq_lengthlist__44u7__p7_1[] = {
  150615. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150616. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150617. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150618. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150619. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150620. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150621. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150622. 8, 9, 9, 9, 9, 9,10,10,10,
  150623. };
  150624. static float _vq_quantthresh__44u7__p7_1[] = {
  150625. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150626. 3.5, 4.5,
  150627. };
  150628. static long _vq_quantmap__44u7__p7_1[] = {
  150629. 9, 7, 5, 3, 1, 0, 2, 4,
  150630. 6, 8, 10,
  150631. };
  150632. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150633. _vq_quantthresh__44u7__p7_1,
  150634. _vq_quantmap__44u7__p7_1,
  150635. 11,
  150636. 11
  150637. };
  150638. static static_codebook _44u7__p7_1 = {
  150639. 2, 121,
  150640. _vq_lengthlist__44u7__p7_1,
  150641. 1, -531365888, 1611661312, 4, 0,
  150642. _vq_quantlist__44u7__p7_1,
  150643. NULL,
  150644. &_vq_auxt__44u7__p7_1,
  150645. NULL,
  150646. 0
  150647. };
  150648. static long _vq_quantlist__44u7__p8_0[] = {
  150649. 5,
  150650. 4,
  150651. 6,
  150652. 3,
  150653. 7,
  150654. 2,
  150655. 8,
  150656. 1,
  150657. 9,
  150658. 0,
  150659. 10,
  150660. };
  150661. static long _vq_lengthlist__44u7__p8_0[] = {
  150662. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150663. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150664. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150665. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150666. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150667. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150668. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150669. 12,13,13,14,14,15,15,15,16,
  150670. };
  150671. static float _vq_quantthresh__44u7__p8_0[] = {
  150672. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150673. 38.5, 49.5,
  150674. };
  150675. static long _vq_quantmap__44u7__p8_0[] = {
  150676. 9, 7, 5, 3, 1, 0, 2, 4,
  150677. 6, 8, 10,
  150678. };
  150679. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150680. _vq_quantthresh__44u7__p8_0,
  150681. _vq_quantmap__44u7__p8_0,
  150682. 11,
  150683. 11
  150684. };
  150685. static static_codebook _44u7__p8_0 = {
  150686. 2, 121,
  150687. _vq_lengthlist__44u7__p8_0,
  150688. 1, -524582912, 1618345984, 4, 0,
  150689. _vq_quantlist__44u7__p8_0,
  150690. NULL,
  150691. &_vq_auxt__44u7__p8_0,
  150692. NULL,
  150693. 0
  150694. };
  150695. static long _vq_quantlist__44u7__p8_1[] = {
  150696. 5,
  150697. 4,
  150698. 6,
  150699. 3,
  150700. 7,
  150701. 2,
  150702. 8,
  150703. 1,
  150704. 9,
  150705. 0,
  150706. 10,
  150707. };
  150708. static long _vq_lengthlist__44u7__p8_1[] = {
  150709. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150710. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150711. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150712. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150713. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150714. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150715. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150716. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150717. };
  150718. static float _vq_quantthresh__44u7__p8_1[] = {
  150719. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150720. 3.5, 4.5,
  150721. };
  150722. static long _vq_quantmap__44u7__p8_1[] = {
  150723. 9, 7, 5, 3, 1, 0, 2, 4,
  150724. 6, 8, 10,
  150725. };
  150726. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150727. _vq_quantthresh__44u7__p8_1,
  150728. _vq_quantmap__44u7__p8_1,
  150729. 11,
  150730. 11
  150731. };
  150732. static static_codebook _44u7__p8_1 = {
  150733. 2, 121,
  150734. _vq_lengthlist__44u7__p8_1,
  150735. 1, -531365888, 1611661312, 4, 0,
  150736. _vq_quantlist__44u7__p8_1,
  150737. NULL,
  150738. &_vq_auxt__44u7__p8_1,
  150739. NULL,
  150740. 0
  150741. };
  150742. static long _vq_quantlist__44u7__p9_0[] = {
  150743. 5,
  150744. 4,
  150745. 6,
  150746. 3,
  150747. 7,
  150748. 2,
  150749. 8,
  150750. 1,
  150751. 9,
  150752. 0,
  150753. 10,
  150754. };
  150755. static long _vq_lengthlist__44u7__p9_0[] = {
  150756. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150757. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150758. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150759. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150760. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150761. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150762. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150763. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150764. };
  150765. static float _vq_quantthresh__44u7__p9_0[] = {
  150766. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150767. 2229.5, 2866.5,
  150768. };
  150769. static long _vq_quantmap__44u7__p9_0[] = {
  150770. 9, 7, 5, 3, 1, 0, 2, 4,
  150771. 6, 8, 10,
  150772. };
  150773. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150774. _vq_quantthresh__44u7__p9_0,
  150775. _vq_quantmap__44u7__p9_0,
  150776. 11,
  150777. 11
  150778. };
  150779. static static_codebook _44u7__p9_0 = {
  150780. 2, 121,
  150781. _vq_lengthlist__44u7__p9_0,
  150782. 1, -512171520, 1630791680, 4, 0,
  150783. _vq_quantlist__44u7__p9_0,
  150784. NULL,
  150785. &_vq_auxt__44u7__p9_0,
  150786. NULL,
  150787. 0
  150788. };
  150789. static long _vq_quantlist__44u7__p9_1[] = {
  150790. 6,
  150791. 5,
  150792. 7,
  150793. 4,
  150794. 8,
  150795. 3,
  150796. 9,
  150797. 2,
  150798. 10,
  150799. 1,
  150800. 11,
  150801. 0,
  150802. 12,
  150803. };
  150804. static long _vq_lengthlist__44u7__p9_1[] = {
  150805. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150806. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150807. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150808. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150809. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150810. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150811. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150812. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150813. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150814. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150815. 15,15,15,15,17,17,16,17,16,
  150816. };
  150817. static float _vq_quantthresh__44u7__p9_1[] = {
  150818. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150819. 122.5, 171.5, 220.5, 269.5,
  150820. };
  150821. static long _vq_quantmap__44u7__p9_1[] = {
  150822. 11, 9, 7, 5, 3, 1, 0, 2,
  150823. 4, 6, 8, 10, 12,
  150824. };
  150825. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150826. _vq_quantthresh__44u7__p9_1,
  150827. _vq_quantmap__44u7__p9_1,
  150828. 13,
  150829. 13
  150830. };
  150831. static static_codebook _44u7__p9_1 = {
  150832. 2, 169,
  150833. _vq_lengthlist__44u7__p9_1,
  150834. 1, -518889472, 1622704128, 4, 0,
  150835. _vq_quantlist__44u7__p9_1,
  150836. NULL,
  150837. &_vq_auxt__44u7__p9_1,
  150838. NULL,
  150839. 0
  150840. };
  150841. static long _vq_quantlist__44u7__p9_2[] = {
  150842. 24,
  150843. 23,
  150844. 25,
  150845. 22,
  150846. 26,
  150847. 21,
  150848. 27,
  150849. 20,
  150850. 28,
  150851. 19,
  150852. 29,
  150853. 18,
  150854. 30,
  150855. 17,
  150856. 31,
  150857. 16,
  150858. 32,
  150859. 15,
  150860. 33,
  150861. 14,
  150862. 34,
  150863. 13,
  150864. 35,
  150865. 12,
  150866. 36,
  150867. 11,
  150868. 37,
  150869. 10,
  150870. 38,
  150871. 9,
  150872. 39,
  150873. 8,
  150874. 40,
  150875. 7,
  150876. 41,
  150877. 6,
  150878. 42,
  150879. 5,
  150880. 43,
  150881. 4,
  150882. 44,
  150883. 3,
  150884. 45,
  150885. 2,
  150886. 46,
  150887. 1,
  150888. 47,
  150889. 0,
  150890. 48,
  150891. };
  150892. static long _vq_lengthlist__44u7__p9_2[] = {
  150893. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150894. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150895. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150896. 8,
  150897. };
  150898. static float _vq_quantthresh__44u7__p9_2[] = {
  150899. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150900. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150901. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150902. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150903. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150904. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150905. };
  150906. static long _vq_quantmap__44u7__p9_2[] = {
  150907. 47, 45, 43, 41, 39, 37, 35, 33,
  150908. 31, 29, 27, 25, 23, 21, 19, 17,
  150909. 15, 13, 11, 9, 7, 5, 3, 1,
  150910. 0, 2, 4, 6, 8, 10, 12, 14,
  150911. 16, 18, 20, 22, 24, 26, 28, 30,
  150912. 32, 34, 36, 38, 40, 42, 44, 46,
  150913. 48,
  150914. };
  150915. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150916. _vq_quantthresh__44u7__p9_2,
  150917. _vq_quantmap__44u7__p9_2,
  150918. 49,
  150919. 49
  150920. };
  150921. static static_codebook _44u7__p9_2 = {
  150922. 1, 49,
  150923. _vq_lengthlist__44u7__p9_2,
  150924. 1, -526909440, 1611661312, 6, 0,
  150925. _vq_quantlist__44u7__p9_2,
  150926. NULL,
  150927. &_vq_auxt__44u7__p9_2,
  150928. NULL,
  150929. 0
  150930. };
  150931. static long _huff_lengthlist__44u7__short[] = {
  150932. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150933. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150934. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150935. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150936. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150937. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150938. 6, 8, 5, 9,
  150939. };
  150940. static static_codebook _huff_book__44u7__short = {
  150941. 2, 100,
  150942. _huff_lengthlist__44u7__short,
  150943. 0, 0, 0, 0, 0,
  150944. NULL,
  150945. NULL,
  150946. NULL,
  150947. NULL,
  150948. 0
  150949. };
  150950. static long _huff_lengthlist__44u8__long[] = {
  150951. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150952. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150953. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150954. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150955. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150956. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150957. 10, 8, 8, 9,
  150958. };
  150959. static static_codebook _huff_book__44u8__long = {
  150960. 2, 100,
  150961. _huff_lengthlist__44u8__long,
  150962. 0, 0, 0, 0, 0,
  150963. NULL,
  150964. NULL,
  150965. NULL,
  150966. NULL,
  150967. 0
  150968. };
  150969. static long _huff_lengthlist__44u8__short[] = {
  150970. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150971. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150972. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150973. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150974. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150975. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150976. 10,10,15,17,
  150977. };
  150978. static static_codebook _huff_book__44u8__short = {
  150979. 2, 100,
  150980. _huff_lengthlist__44u8__short,
  150981. 0, 0, 0, 0, 0,
  150982. NULL,
  150983. NULL,
  150984. NULL,
  150985. NULL,
  150986. 0
  150987. };
  150988. static long _vq_quantlist__44u8_p1_0[] = {
  150989. 1,
  150990. 0,
  150991. 2,
  150992. };
  150993. static long _vq_lengthlist__44u8_p1_0[] = {
  150994. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150995. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150996. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150997. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150998. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150999. 10,
  151000. };
  151001. static float _vq_quantthresh__44u8_p1_0[] = {
  151002. -0.5, 0.5,
  151003. };
  151004. static long _vq_quantmap__44u8_p1_0[] = {
  151005. 1, 0, 2,
  151006. };
  151007. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  151008. _vq_quantthresh__44u8_p1_0,
  151009. _vq_quantmap__44u8_p1_0,
  151010. 3,
  151011. 3
  151012. };
  151013. static static_codebook _44u8_p1_0 = {
  151014. 4, 81,
  151015. _vq_lengthlist__44u8_p1_0,
  151016. 1, -535822336, 1611661312, 2, 0,
  151017. _vq_quantlist__44u8_p1_0,
  151018. NULL,
  151019. &_vq_auxt__44u8_p1_0,
  151020. NULL,
  151021. 0
  151022. };
  151023. static long _vq_quantlist__44u8_p2_0[] = {
  151024. 2,
  151025. 1,
  151026. 3,
  151027. 0,
  151028. 4,
  151029. };
  151030. static long _vq_lengthlist__44u8_p2_0[] = {
  151031. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151032. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  151033. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  151034. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  151035. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  151036. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  151037. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151038. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  151039. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151040. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151041. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  151042. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  151043. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  151044. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  151045. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151046. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151047. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151048. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151049. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151050. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151051. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151052. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151053. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151054. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151055. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151056. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151057. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151058. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151059. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151060. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151061. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151062. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151063. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151064. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151065. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151066. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151067. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151068. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151069. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151070. 14,
  151071. };
  151072. static float _vq_quantthresh__44u8_p2_0[] = {
  151073. -1.5, -0.5, 0.5, 1.5,
  151074. };
  151075. static long _vq_quantmap__44u8_p2_0[] = {
  151076. 3, 1, 0, 2, 4,
  151077. };
  151078. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151079. _vq_quantthresh__44u8_p2_0,
  151080. _vq_quantmap__44u8_p2_0,
  151081. 5,
  151082. 5
  151083. };
  151084. static static_codebook _44u8_p2_0 = {
  151085. 4, 625,
  151086. _vq_lengthlist__44u8_p2_0,
  151087. 1, -533725184, 1611661312, 3, 0,
  151088. _vq_quantlist__44u8_p2_0,
  151089. NULL,
  151090. &_vq_auxt__44u8_p2_0,
  151091. NULL,
  151092. 0
  151093. };
  151094. static long _vq_quantlist__44u8_p3_0[] = {
  151095. 4,
  151096. 3,
  151097. 5,
  151098. 2,
  151099. 6,
  151100. 1,
  151101. 7,
  151102. 0,
  151103. 8,
  151104. };
  151105. static long _vq_lengthlist__44u8_p3_0[] = {
  151106. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151107. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151108. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151109. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151110. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151111. 12,
  151112. };
  151113. static float _vq_quantthresh__44u8_p3_0[] = {
  151114. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151115. };
  151116. static long _vq_quantmap__44u8_p3_0[] = {
  151117. 7, 5, 3, 1, 0, 2, 4, 6,
  151118. 8,
  151119. };
  151120. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151121. _vq_quantthresh__44u8_p3_0,
  151122. _vq_quantmap__44u8_p3_0,
  151123. 9,
  151124. 9
  151125. };
  151126. static static_codebook _44u8_p3_0 = {
  151127. 2, 81,
  151128. _vq_lengthlist__44u8_p3_0,
  151129. 1, -531628032, 1611661312, 4, 0,
  151130. _vq_quantlist__44u8_p3_0,
  151131. NULL,
  151132. &_vq_auxt__44u8_p3_0,
  151133. NULL,
  151134. 0
  151135. };
  151136. static long _vq_quantlist__44u8_p4_0[] = {
  151137. 8,
  151138. 7,
  151139. 9,
  151140. 6,
  151141. 10,
  151142. 5,
  151143. 11,
  151144. 4,
  151145. 12,
  151146. 3,
  151147. 13,
  151148. 2,
  151149. 14,
  151150. 1,
  151151. 15,
  151152. 0,
  151153. 16,
  151154. };
  151155. static long _vq_lengthlist__44u8_p4_0[] = {
  151156. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151157. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151158. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151159. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151160. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151161. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151162. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151163. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151164. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151165. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151166. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151167. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151168. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151169. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151170. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151171. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151172. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151173. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151174. 14,
  151175. };
  151176. static float _vq_quantthresh__44u8_p4_0[] = {
  151177. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151178. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151179. };
  151180. static long _vq_quantmap__44u8_p4_0[] = {
  151181. 15, 13, 11, 9, 7, 5, 3, 1,
  151182. 0, 2, 4, 6, 8, 10, 12, 14,
  151183. 16,
  151184. };
  151185. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151186. _vq_quantthresh__44u8_p4_0,
  151187. _vq_quantmap__44u8_p4_0,
  151188. 17,
  151189. 17
  151190. };
  151191. static static_codebook _44u8_p4_0 = {
  151192. 2, 289,
  151193. _vq_lengthlist__44u8_p4_0,
  151194. 1, -529530880, 1611661312, 5, 0,
  151195. _vq_quantlist__44u8_p4_0,
  151196. NULL,
  151197. &_vq_auxt__44u8_p4_0,
  151198. NULL,
  151199. 0
  151200. };
  151201. static long _vq_quantlist__44u8_p5_0[] = {
  151202. 1,
  151203. 0,
  151204. 2,
  151205. };
  151206. static long _vq_lengthlist__44u8_p5_0[] = {
  151207. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151208. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151209. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151210. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151211. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151212. 10,
  151213. };
  151214. static float _vq_quantthresh__44u8_p5_0[] = {
  151215. -5.5, 5.5,
  151216. };
  151217. static long _vq_quantmap__44u8_p5_0[] = {
  151218. 1, 0, 2,
  151219. };
  151220. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151221. _vq_quantthresh__44u8_p5_0,
  151222. _vq_quantmap__44u8_p5_0,
  151223. 3,
  151224. 3
  151225. };
  151226. static static_codebook _44u8_p5_0 = {
  151227. 4, 81,
  151228. _vq_lengthlist__44u8_p5_0,
  151229. 1, -529137664, 1618345984, 2, 0,
  151230. _vq_quantlist__44u8_p5_0,
  151231. NULL,
  151232. &_vq_auxt__44u8_p5_0,
  151233. NULL,
  151234. 0
  151235. };
  151236. static long _vq_quantlist__44u8_p5_1[] = {
  151237. 5,
  151238. 4,
  151239. 6,
  151240. 3,
  151241. 7,
  151242. 2,
  151243. 8,
  151244. 1,
  151245. 9,
  151246. 0,
  151247. 10,
  151248. };
  151249. static long _vq_lengthlist__44u8_p5_1[] = {
  151250. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151251. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151252. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151253. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151254. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151255. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151256. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151257. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151258. };
  151259. static float _vq_quantthresh__44u8_p5_1[] = {
  151260. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151261. 3.5, 4.5,
  151262. };
  151263. static long _vq_quantmap__44u8_p5_1[] = {
  151264. 9, 7, 5, 3, 1, 0, 2, 4,
  151265. 6, 8, 10,
  151266. };
  151267. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151268. _vq_quantthresh__44u8_p5_1,
  151269. _vq_quantmap__44u8_p5_1,
  151270. 11,
  151271. 11
  151272. };
  151273. static static_codebook _44u8_p5_1 = {
  151274. 2, 121,
  151275. _vq_lengthlist__44u8_p5_1,
  151276. 1, -531365888, 1611661312, 4, 0,
  151277. _vq_quantlist__44u8_p5_1,
  151278. NULL,
  151279. &_vq_auxt__44u8_p5_1,
  151280. NULL,
  151281. 0
  151282. };
  151283. static long _vq_quantlist__44u8_p6_0[] = {
  151284. 6,
  151285. 5,
  151286. 7,
  151287. 4,
  151288. 8,
  151289. 3,
  151290. 9,
  151291. 2,
  151292. 10,
  151293. 1,
  151294. 11,
  151295. 0,
  151296. 12,
  151297. };
  151298. static long _vq_lengthlist__44u8_p6_0[] = {
  151299. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151300. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151301. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151302. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151303. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151304. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151305. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151306. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151307. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151308. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151309. 11,11,11,11,11,12,11,12,12,
  151310. };
  151311. static float _vq_quantthresh__44u8_p6_0[] = {
  151312. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151313. 12.5, 17.5, 22.5, 27.5,
  151314. };
  151315. static long _vq_quantmap__44u8_p6_0[] = {
  151316. 11, 9, 7, 5, 3, 1, 0, 2,
  151317. 4, 6, 8, 10, 12,
  151318. };
  151319. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151320. _vq_quantthresh__44u8_p6_0,
  151321. _vq_quantmap__44u8_p6_0,
  151322. 13,
  151323. 13
  151324. };
  151325. static static_codebook _44u8_p6_0 = {
  151326. 2, 169,
  151327. _vq_lengthlist__44u8_p6_0,
  151328. 1, -526516224, 1616117760, 4, 0,
  151329. _vq_quantlist__44u8_p6_0,
  151330. NULL,
  151331. &_vq_auxt__44u8_p6_0,
  151332. NULL,
  151333. 0
  151334. };
  151335. static long _vq_quantlist__44u8_p6_1[] = {
  151336. 2,
  151337. 1,
  151338. 3,
  151339. 0,
  151340. 4,
  151341. };
  151342. static long _vq_lengthlist__44u8_p6_1[] = {
  151343. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151344. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151345. };
  151346. static float _vq_quantthresh__44u8_p6_1[] = {
  151347. -1.5, -0.5, 0.5, 1.5,
  151348. };
  151349. static long _vq_quantmap__44u8_p6_1[] = {
  151350. 3, 1, 0, 2, 4,
  151351. };
  151352. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151353. _vq_quantthresh__44u8_p6_1,
  151354. _vq_quantmap__44u8_p6_1,
  151355. 5,
  151356. 5
  151357. };
  151358. static static_codebook _44u8_p6_1 = {
  151359. 2, 25,
  151360. _vq_lengthlist__44u8_p6_1,
  151361. 1, -533725184, 1611661312, 3, 0,
  151362. _vq_quantlist__44u8_p6_1,
  151363. NULL,
  151364. &_vq_auxt__44u8_p6_1,
  151365. NULL,
  151366. 0
  151367. };
  151368. static long _vq_quantlist__44u8_p7_0[] = {
  151369. 6,
  151370. 5,
  151371. 7,
  151372. 4,
  151373. 8,
  151374. 3,
  151375. 9,
  151376. 2,
  151377. 10,
  151378. 1,
  151379. 11,
  151380. 0,
  151381. 12,
  151382. };
  151383. static long _vq_lengthlist__44u8_p7_0[] = {
  151384. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151385. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151386. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151387. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151388. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151389. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151390. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151391. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151392. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151393. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151394. 13,13,14,14,14,15,15,15,16,
  151395. };
  151396. static float _vq_quantthresh__44u8_p7_0[] = {
  151397. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151398. 27.5, 38.5, 49.5, 60.5,
  151399. };
  151400. static long _vq_quantmap__44u8_p7_0[] = {
  151401. 11, 9, 7, 5, 3, 1, 0, 2,
  151402. 4, 6, 8, 10, 12,
  151403. };
  151404. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151405. _vq_quantthresh__44u8_p7_0,
  151406. _vq_quantmap__44u8_p7_0,
  151407. 13,
  151408. 13
  151409. };
  151410. static static_codebook _44u8_p7_0 = {
  151411. 2, 169,
  151412. _vq_lengthlist__44u8_p7_0,
  151413. 1, -523206656, 1618345984, 4, 0,
  151414. _vq_quantlist__44u8_p7_0,
  151415. NULL,
  151416. &_vq_auxt__44u8_p7_0,
  151417. NULL,
  151418. 0
  151419. };
  151420. static long _vq_quantlist__44u8_p7_1[] = {
  151421. 5,
  151422. 4,
  151423. 6,
  151424. 3,
  151425. 7,
  151426. 2,
  151427. 8,
  151428. 1,
  151429. 9,
  151430. 0,
  151431. 10,
  151432. };
  151433. static long _vq_lengthlist__44u8_p7_1[] = {
  151434. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151435. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151436. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151437. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151438. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151439. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151440. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151441. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151442. };
  151443. static float _vq_quantthresh__44u8_p7_1[] = {
  151444. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151445. 3.5, 4.5,
  151446. };
  151447. static long _vq_quantmap__44u8_p7_1[] = {
  151448. 9, 7, 5, 3, 1, 0, 2, 4,
  151449. 6, 8, 10,
  151450. };
  151451. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151452. _vq_quantthresh__44u8_p7_1,
  151453. _vq_quantmap__44u8_p7_1,
  151454. 11,
  151455. 11
  151456. };
  151457. static static_codebook _44u8_p7_1 = {
  151458. 2, 121,
  151459. _vq_lengthlist__44u8_p7_1,
  151460. 1, -531365888, 1611661312, 4, 0,
  151461. _vq_quantlist__44u8_p7_1,
  151462. NULL,
  151463. &_vq_auxt__44u8_p7_1,
  151464. NULL,
  151465. 0
  151466. };
  151467. static long _vq_quantlist__44u8_p8_0[] = {
  151468. 7,
  151469. 6,
  151470. 8,
  151471. 5,
  151472. 9,
  151473. 4,
  151474. 10,
  151475. 3,
  151476. 11,
  151477. 2,
  151478. 12,
  151479. 1,
  151480. 13,
  151481. 0,
  151482. 14,
  151483. };
  151484. static long _vq_lengthlist__44u8_p8_0[] = {
  151485. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151486. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151487. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151488. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151489. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151490. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151491. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151492. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151493. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151494. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151495. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151496. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151497. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151498. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151499. 17,
  151500. };
  151501. static float _vq_quantthresh__44u8_p8_0[] = {
  151502. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151503. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151504. };
  151505. static long _vq_quantmap__44u8_p8_0[] = {
  151506. 13, 11, 9, 7, 5, 3, 1, 0,
  151507. 2, 4, 6, 8, 10, 12, 14,
  151508. };
  151509. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151510. _vq_quantthresh__44u8_p8_0,
  151511. _vq_quantmap__44u8_p8_0,
  151512. 15,
  151513. 15
  151514. };
  151515. static static_codebook _44u8_p8_0 = {
  151516. 2, 225,
  151517. _vq_lengthlist__44u8_p8_0,
  151518. 1, -520986624, 1620377600, 4, 0,
  151519. _vq_quantlist__44u8_p8_0,
  151520. NULL,
  151521. &_vq_auxt__44u8_p8_0,
  151522. NULL,
  151523. 0
  151524. };
  151525. static long _vq_quantlist__44u8_p8_1[] = {
  151526. 10,
  151527. 9,
  151528. 11,
  151529. 8,
  151530. 12,
  151531. 7,
  151532. 13,
  151533. 6,
  151534. 14,
  151535. 5,
  151536. 15,
  151537. 4,
  151538. 16,
  151539. 3,
  151540. 17,
  151541. 2,
  151542. 18,
  151543. 1,
  151544. 19,
  151545. 0,
  151546. 20,
  151547. };
  151548. static long _vq_lengthlist__44u8_p8_1[] = {
  151549. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151550. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151551. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151552. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151553. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151554. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151555. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151556. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151557. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151558. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151559. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151560. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151561. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151562. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151563. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151564. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151565. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151566. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151567. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151568. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151569. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151570. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151571. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151572. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151573. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151574. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151575. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151576. 10,10,10,10,10,10,10,10,10,
  151577. };
  151578. static float _vq_quantthresh__44u8_p8_1[] = {
  151579. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151580. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151581. 6.5, 7.5, 8.5, 9.5,
  151582. };
  151583. static long _vq_quantmap__44u8_p8_1[] = {
  151584. 19, 17, 15, 13, 11, 9, 7, 5,
  151585. 3, 1, 0, 2, 4, 6, 8, 10,
  151586. 12, 14, 16, 18, 20,
  151587. };
  151588. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151589. _vq_quantthresh__44u8_p8_1,
  151590. _vq_quantmap__44u8_p8_1,
  151591. 21,
  151592. 21
  151593. };
  151594. static static_codebook _44u8_p8_1 = {
  151595. 2, 441,
  151596. _vq_lengthlist__44u8_p8_1,
  151597. 1, -529268736, 1611661312, 5, 0,
  151598. _vq_quantlist__44u8_p8_1,
  151599. NULL,
  151600. &_vq_auxt__44u8_p8_1,
  151601. NULL,
  151602. 0
  151603. };
  151604. static long _vq_quantlist__44u8_p9_0[] = {
  151605. 4,
  151606. 3,
  151607. 5,
  151608. 2,
  151609. 6,
  151610. 1,
  151611. 7,
  151612. 0,
  151613. 8,
  151614. };
  151615. static long _vq_lengthlist__44u8_p9_0[] = {
  151616. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151617. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151618. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151619. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151620. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151621. 8,
  151622. };
  151623. static float _vq_quantthresh__44u8_p9_0[] = {
  151624. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151625. };
  151626. static long _vq_quantmap__44u8_p9_0[] = {
  151627. 7, 5, 3, 1, 0, 2, 4, 6,
  151628. 8,
  151629. };
  151630. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151631. _vq_quantthresh__44u8_p9_0,
  151632. _vq_quantmap__44u8_p9_0,
  151633. 9,
  151634. 9
  151635. };
  151636. static static_codebook _44u8_p9_0 = {
  151637. 2, 81,
  151638. _vq_lengthlist__44u8_p9_0,
  151639. 1, -511895552, 1631393792, 4, 0,
  151640. _vq_quantlist__44u8_p9_0,
  151641. NULL,
  151642. &_vq_auxt__44u8_p9_0,
  151643. NULL,
  151644. 0
  151645. };
  151646. static long _vq_quantlist__44u8_p9_1[] = {
  151647. 9,
  151648. 8,
  151649. 10,
  151650. 7,
  151651. 11,
  151652. 6,
  151653. 12,
  151654. 5,
  151655. 13,
  151656. 4,
  151657. 14,
  151658. 3,
  151659. 15,
  151660. 2,
  151661. 16,
  151662. 1,
  151663. 17,
  151664. 0,
  151665. 18,
  151666. };
  151667. static long _vq_lengthlist__44u8_p9_1[] = {
  151668. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151669. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151670. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151671. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151672. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151673. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151674. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151675. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151676. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151677. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151678. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151679. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151680. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151681. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151682. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151683. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151684. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151685. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151686. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151687. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151688. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151689. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151690. 16,15,16,16,16,16,16,16,16,
  151691. };
  151692. static float _vq_quantthresh__44u8_p9_1[] = {
  151693. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151694. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151695. 367.5, 416.5,
  151696. };
  151697. static long _vq_quantmap__44u8_p9_1[] = {
  151698. 17, 15, 13, 11, 9, 7, 5, 3,
  151699. 1, 0, 2, 4, 6, 8, 10, 12,
  151700. 14, 16, 18,
  151701. };
  151702. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151703. _vq_quantthresh__44u8_p9_1,
  151704. _vq_quantmap__44u8_p9_1,
  151705. 19,
  151706. 19
  151707. };
  151708. static static_codebook _44u8_p9_1 = {
  151709. 2, 361,
  151710. _vq_lengthlist__44u8_p9_1,
  151711. 1, -518287360, 1622704128, 5, 0,
  151712. _vq_quantlist__44u8_p9_1,
  151713. NULL,
  151714. &_vq_auxt__44u8_p9_1,
  151715. NULL,
  151716. 0
  151717. };
  151718. static long _vq_quantlist__44u8_p9_2[] = {
  151719. 24,
  151720. 23,
  151721. 25,
  151722. 22,
  151723. 26,
  151724. 21,
  151725. 27,
  151726. 20,
  151727. 28,
  151728. 19,
  151729. 29,
  151730. 18,
  151731. 30,
  151732. 17,
  151733. 31,
  151734. 16,
  151735. 32,
  151736. 15,
  151737. 33,
  151738. 14,
  151739. 34,
  151740. 13,
  151741. 35,
  151742. 12,
  151743. 36,
  151744. 11,
  151745. 37,
  151746. 10,
  151747. 38,
  151748. 9,
  151749. 39,
  151750. 8,
  151751. 40,
  151752. 7,
  151753. 41,
  151754. 6,
  151755. 42,
  151756. 5,
  151757. 43,
  151758. 4,
  151759. 44,
  151760. 3,
  151761. 45,
  151762. 2,
  151763. 46,
  151764. 1,
  151765. 47,
  151766. 0,
  151767. 48,
  151768. };
  151769. static long _vq_lengthlist__44u8_p9_2[] = {
  151770. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151771. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151772. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151773. 7,
  151774. };
  151775. static float _vq_quantthresh__44u8_p9_2[] = {
  151776. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151777. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151778. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151779. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151780. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151781. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151782. };
  151783. static long _vq_quantmap__44u8_p9_2[] = {
  151784. 47, 45, 43, 41, 39, 37, 35, 33,
  151785. 31, 29, 27, 25, 23, 21, 19, 17,
  151786. 15, 13, 11, 9, 7, 5, 3, 1,
  151787. 0, 2, 4, 6, 8, 10, 12, 14,
  151788. 16, 18, 20, 22, 24, 26, 28, 30,
  151789. 32, 34, 36, 38, 40, 42, 44, 46,
  151790. 48,
  151791. };
  151792. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151793. _vq_quantthresh__44u8_p9_2,
  151794. _vq_quantmap__44u8_p9_2,
  151795. 49,
  151796. 49
  151797. };
  151798. static static_codebook _44u8_p9_2 = {
  151799. 1, 49,
  151800. _vq_lengthlist__44u8_p9_2,
  151801. 1, -526909440, 1611661312, 6, 0,
  151802. _vq_quantlist__44u8_p9_2,
  151803. NULL,
  151804. &_vq_auxt__44u8_p9_2,
  151805. NULL,
  151806. 0
  151807. };
  151808. static long _huff_lengthlist__44u9__long[] = {
  151809. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151810. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151811. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151812. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151813. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151814. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151815. 10, 8, 8, 9,
  151816. };
  151817. static static_codebook _huff_book__44u9__long = {
  151818. 2, 100,
  151819. _huff_lengthlist__44u9__long,
  151820. 0, 0, 0, 0, 0,
  151821. NULL,
  151822. NULL,
  151823. NULL,
  151824. NULL,
  151825. 0
  151826. };
  151827. static long _huff_lengthlist__44u9__short[] = {
  151828. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151829. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151830. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151831. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151832. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151833. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151834. 9, 9,12,15,
  151835. };
  151836. static static_codebook _huff_book__44u9__short = {
  151837. 2, 100,
  151838. _huff_lengthlist__44u9__short,
  151839. 0, 0, 0, 0, 0,
  151840. NULL,
  151841. NULL,
  151842. NULL,
  151843. NULL,
  151844. 0
  151845. };
  151846. static long _vq_quantlist__44u9_p1_0[] = {
  151847. 1,
  151848. 0,
  151849. 2,
  151850. };
  151851. static long _vq_lengthlist__44u9_p1_0[] = {
  151852. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151853. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151854. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151855. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151856. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151857. 10,
  151858. };
  151859. static float _vq_quantthresh__44u9_p1_0[] = {
  151860. -0.5, 0.5,
  151861. };
  151862. static long _vq_quantmap__44u9_p1_0[] = {
  151863. 1, 0, 2,
  151864. };
  151865. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151866. _vq_quantthresh__44u9_p1_0,
  151867. _vq_quantmap__44u9_p1_0,
  151868. 3,
  151869. 3
  151870. };
  151871. static static_codebook _44u9_p1_0 = {
  151872. 4, 81,
  151873. _vq_lengthlist__44u9_p1_0,
  151874. 1, -535822336, 1611661312, 2, 0,
  151875. _vq_quantlist__44u9_p1_0,
  151876. NULL,
  151877. &_vq_auxt__44u9_p1_0,
  151878. NULL,
  151879. 0
  151880. };
  151881. static long _vq_quantlist__44u9_p2_0[] = {
  151882. 2,
  151883. 1,
  151884. 3,
  151885. 0,
  151886. 4,
  151887. };
  151888. static long _vq_lengthlist__44u9_p2_0[] = {
  151889. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151890. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151891. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151892. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151893. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151894. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151895. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151896. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151897. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151898. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151899. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151900. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151901. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151902. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151903. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151904. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151905. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151906. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151907. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151908. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151909. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151910. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151911. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151912. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151913. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151914. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151915. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151916. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151917. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151918. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151919. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151920. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151921. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151922. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151923. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151924. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151925. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151926. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151927. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151928. 14,
  151929. };
  151930. static float _vq_quantthresh__44u9_p2_0[] = {
  151931. -1.5, -0.5, 0.5, 1.5,
  151932. };
  151933. static long _vq_quantmap__44u9_p2_0[] = {
  151934. 3, 1, 0, 2, 4,
  151935. };
  151936. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151937. _vq_quantthresh__44u9_p2_0,
  151938. _vq_quantmap__44u9_p2_0,
  151939. 5,
  151940. 5
  151941. };
  151942. static static_codebook _44u9_p2_0 = {
  151943. 4, 625,
  151944. _vq_lengthlist__44u9_p2_0,
  151945. 1, -533725184, 1611661312, 3, 0,
  151946. _vq_quantlist__44u9_p2_0,
  151947. NULL,
  151948. &_vq_auxt__44u9_p2_0,
  151949. NULL,
  151950. 0
  151951. };
  151952. static long _vq_quantlist__44u9_p3_0[] = {
  151953. 4,
  151954. 3,
  151955. 5,
  151956. 2,
  151957. 6,
  151958. 1,
  151959. 7,
  151960. 0,
  151961. 8,
  151962. };
  151963. static long _vq_lengthlist__44u9_p3_0[] = {
  151964. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151965. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151966. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151967. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151968. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151969. 11,
  151970. };
  151971. static float _vq_quantthresh__44u9_p3_0[] = {
  151972. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151973. };
  151974. static long _vq_quantmap__44u9_p3_0[] = {
  151975. 7, 5, 3, 1, 0, 2, 4, 6,
  151976. 8,
  151977. };
  151978. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151979. _vq_quantthresh__44u9_p3_0,
  151980. _vq_quantmap__44u9_p3_0,
  151981. 9,
  151982. 9
  151983. };
  151984. static static_codebook _44u9_p3_0 = {
  151985. 2, 81,
  151986. _vq_lengthlist__44u9_p3_0,
  151987. 1, -531628032, 1611661312, 4, 0,
  151988. _vq_quantlist__44u9_p3_0,
  151989. NULL,
  151990. &_vq_auxt__44u9_p3_0,
  151991. NULL,
  151992. 0
  151993. };
  151994. static long _vq_quantlist__44u9_p4_0[] = {
  151995. 8,
  151996. 7,
  151997. 9,
  151998. 6,
  151999. 10,
  152000. 5,
  152001. 11,
  152002. 4,
  152003. 12,
  152004. 3,
  152005. 13,
  152006. 2,
  152007. 14,
  152008. 1,
  152009. 15,
  152010. 0,
  152011. 16,
  152012. };
  152013. static long _vq_lengthlist__44u9_p4_0[] = {
  152014. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  152015. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  152016. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  152017. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  152018. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  152019. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  152020. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  152021. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  152022. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  152023. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  152024. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  152025. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  152026. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  152027. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  152028. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  152029. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  152030. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  152031. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  152032. 14,
  152033. };
  152034. static float _vq_quantthresh__44u9_p4_0[] = {
  152035. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152036. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152037. };
  152038. static long _vq_quantmap__44u9_p4_0[] = {
  152039. 15, 13, 11, 9, 7, 5, 3, 1,
  152040. 0, 2, 4, 6, 8, 10, 12, 14,
  152041. 16,
  152042. };
  152043. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  152044. _vq_quantthresh__44u9_p4_0,
  152045. _vq_quantmap__44u9_p4_0,
  152046. 17,
  152047. 17
  152048. };
  152049. static static_codebook _44u9_p4_0 = {
  152050. 2, 289,
  152051. _vq_lengthlist__44u9_p4_0,
  152052. 1, -529530880, 1611661312, 5, 0,
  152053. _vq_quantlist__44u9_p4_0,
  152054. NULL,
  152055. &_vq_auxt__44u9_p4_0,
  152056. NULL,
  152057. 0
  152058. };
  152059. static long _vq_quantlist__44u9_p5_0[] = {
  152060. 1,
  152061. 0,
  152062. 2,
  152063. };
  152064. static long _vq_lengthlist__44u9_p5_0[] = {
  152065. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152066. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152067. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152068. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152069. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152070. 10,
  152071. };
  152072. static float _vq_quantthresh__44u9_p5_0[] = {
  152073. -5.5, 5.5,
  152074. };
  152075. static long _vq_quantmap__44u9_p5_0[] = {
  152076. 1, 0, 2,
  152077. };
  152078. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152079. _vq_quantthresh__44u9_p5_0,
  152080. _vq_quantmap__44u9_p5_0,
  152081. 3,
  152082. 3
  152083. };
  152084. static static_codebook _44u9_p5_0 = {
  152085. 4, 81,
  152086. _vq_lengthlist__44u9_p5_0,
  152087. 1, -529137664, 1618345984, 2, 0,
  152088. _vq_quantlist__44u9_p5_0,
  152089. NULL,
  152090. &_vq_auxt__44u9_p5_0,
  152091. NULL,
  152092. 0
  152093. };
  152094. static long _vq_quantlist__44u9_p5_1[] = {
  152095. 5,
  152096. 4,
  152097. 6,
  152098. 3,
  152099. 7,
  152100. 2,
  152101. 8,
  152102. 1,
  152103. 9,
  152104. 0,
  152105. 10,
  152106. };
  152107. static long _vq_lengthlist__44u9_p5_1[] = {
  152108. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152109. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152110. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152111. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152112. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152113. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152114. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152115. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152116. };
  152117. static float _vq_quantthresh__44u9_p5_1[] = {
  152118. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152119. 3.5, 4.5,
  152120. };
  152121. static long _vq_quantmap__44u9_p5_1[] = {
  152122. 9, 7, 5, 3, 1, 0, 2, 4,
  152123. 6, 8, 10,
  152124. };
  152125. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152126. _vq_quantthresh__44u9_p5_1,
  152127. _vq_quantmap__44u9_p5_1,
  152128. 11,
  152129. 11
  152130. };
  152131. static static_codebook _44u9_p5_1 = {
  152132. 2, 121,
  152133. _vq_lengthlist__44u9_p5_1,
  152134. 1, -531365888, 1611661312, 4, 0,
  152135. _vq_quantlist__44u9_p5_1,
  152136. NULL,
  152137. &_vq_auxt__44u9_p5_1,
  152138. NULL,
  152139. 0
  152140. };
  152141. static long _vq_quantlist__44u9_p6_0[] = {
  152142. 6,
  152143. 5,
  152144. 7,
  152145. 4,
  152146. 8,
  152147. 3,
  152148. 9,
  152149. 2,
  152150. 10,
  152151. 1,
  152152. 11,
  152153. 0,
  152154. 12,
  152155. };
  152156. static long _vq_lengthlist__44u9_p6_0[] = {
  152157. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152158. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152159. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152160. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152161. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152162. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152163. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152164. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152165. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152166. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152167. 10,11,11,11,11,12,11,12,12,
  152168. };
  152169. static float _vq_quantthresh__44u9_p6_0[] = {
  152170. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152171. 12.5, 17.5, 22.5, 27.5,
  152172. };
  152173. static long _vq_quantmap__44u9_p6_0[] = {
  152174. 11, 9, 7, 5, 3, 1, 0, 2,
  152175. 4, 6, 8, 10, 12,
  152176. };
  152177. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152178. _vq_quantthresh__44u9_p6_0,
  152179. _vq_quantmap__44u9_p6_0,
  152180. 13,
  152181. 13
  152182. };
  152183. static static_codebook _44u9_p6_0 = {
  152184. 2, 169,
  152185. _vq_lengthlist__44u9_p6_0,
  152186. 1, -526516224, 1616117760, 4, 0,
  152187. _vq_quantlist__44u9_p6_0,
  152188. NULL,
  152189. &_vq_auxt__44u9_p6_0,
  152190. NULL,
  152191. 0
  152192. };
  152193. static long _vq_quantlist__44u9_p6_1[] = {
  152194. 2,
  152195. 1,
  152196. 3,
  152197. 0,
  152198. 4,
  152199. };
  152200. static long _vq_lengthlist__44u9_p6_1[] = {
  152201. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152202. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152203. };
  152204. static float _vq_quantthresh__44u9_p6_1[] = {
  152205. -1.5, -0.5, 0.5, 1.5,
  152206. };
  152207. static long _vq_quantmap__44u9_p6_1[] = {
  152208. 3, 1, 0, 2, 4,
  152209. };
  152210. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152211. _vq_quantthresh__44u9_p6_1,
  152212. _vq_quantmap__44u9_p6_1,
  152213. 5,
  152214. 5
  152215. };
  152216. static static_codebook _44u9_p6_1 = {
  152217. 2, 25,
  152218. _vq_lengthlist__44u9_p6_1,
  152219. 1, -533725184, 1611661312, 3, 0,
  152220. _vq_quantlist__44u9_p6_1,
  152221. NULL,
  152222. &_vq_auxt__44u9_p6_1,
  152223. NULL,
  152224. 0
  152225. };
  152226. static long _vq_quantlist__44u9_p7_0[] = {
  152227. 6,
  152228. 5,
  152229. 7,
  152230. 4,
  152231. 8,
  152232. 3,
  152233. 9,
  152234. 2,
  152235. 10,
  152236. 1,
  152237. 11,
  152238. 0,
  152239. 12,
  152240. };
  152241. static long _vq_lengthlist__44u9_p7_0[] = {
  152242. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152243. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152244. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152245. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152246. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152247. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152248. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152249. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152250. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152251. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152252. 12,13,13,14,14,14,15,15,15,
  152253. };
  152254. static float _vq_quantthresh__44u9_p7_0[] = {
  152255. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152256. 27.5, 38.5, 49.5, 60.5,
  152257. };
  152258. static long _vq_quantmap__44u9_p7_0[] = {
  152259. 11, 9, 7, 5, 3, 1, 0, 2,
  152260. 4, 6, 8, 10, 12,
  152261. };
  152262. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152263. _vq_quantthresh__44u9_p7_0,
  152264. _vq_quantmap__44u9_p7_0,
  152265. 13,
  152266. 13
  152267. };
  152268. static static_codebook _44u9_p7_0 = {
  152269. 2, 169,
  152270. _vq_lengthlist__44u9_p7_0,
  152271. 1, -523206656, 1618345984, 4, 0,
  152272. _vq_quantlist__44u9_p7_0,
  152273. NULL,
  152274. &_vq_auxt__44u9_p7_0,
  152275. NULL,
  152276. 0
  152277. };
  152278. static long _vq_quantlist__44u9_p7_1[] = {
  152279. 5,
  152280. 4,
  152281. 6,
  152282. 3,
  152283. 7,
  152284. 2,
  152285. 8,
  152286. 1,
  152287. 9,
  152288. 0,
  152289. 10,
  152290. };
  152291. static long _vq_lengthlist__44u9_p7_1[] = {
  152292. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152293. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152294. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152295. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152296. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152297. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152298. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152299. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152300. };
  152301. static float _vq_quantthresh__44u9_p7_1[] = {
  152302. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152303. 3.5, 4.5,
  152304. };
  152305. static long _vq_quantmap__44u9_p7_1[] = {
  152306. 9, 7, 5, 3, 1, 0, 2, 4,
  152307. 6, 8, 10,
  152308. };
  152309. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152310. _vq_quantthresh__44u9_p7_1,
  152311. _vq_quantmap__44u9_p7_1,
  152312. 11,
  152313. 11
  152314. };
  152315. static static_codebook _44u9_p7_1 = {
  152316. 2, 121,
  152317. _vq_lengthlist__44u9_p7_1,
  152318. 1, -531365888, 1611661312, 4, 0,
  152319. _vq_quantlist__44u9_p7_1,
  152320. NULL,
  152321. &_vq_auxt__44u9_p7_1,
  152322. NULL,
  152323. 0
  152324. };
  152325. static long _vq_quantlist__44u9_p8_0[] = {
  152326. 7,
  152327. 6,
  152328. 8,
  152329. 5,
  152330. 9,
  152331. 4,
  152332. 10,
  152333. 3,
  152334. 11,
  152335. 2,
  152336. 12,
  152337. 1,
  152338. 13,
  152339. 0,
  152340. 14,
  152341. };
  152342. static long _vq_lengthlist__44u9_p8_0[] = {
  152343. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152344. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152345. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152346. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152347. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152348. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152349. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152350. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152351. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152352. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152353. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152354. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152355. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152356. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152357. 15,
  152358. };
  152359. static float _vq_quantthresh__44u9_p8_0[] = {
  152360. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152361. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152362. };
  152363. static long _vq_quantmap__44u9_p8_0[] = {
  152364. 13, 11, 9, 7, 5, 3, 1, 0,
  152365. 2, 4, 6, 8, 10, 12, 14,
  152366. };
  152367. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152368. _vq_quantthresh__44u9_p8_0,
  152369. _vq_quantmap__44u9_p8_0,
  152370. 15,
  152371. 15
  152372. };
  152373. static static_codebook _44u9_p8_0 = {
  152374. 2, 225,
  152375. _vq_lengthlist__44u9_p8_0,
  152376. 1, -520986624, 1620377600, 4, 0,
  152377. _vq_quantlist__44u9_p8_0,
  152378. NULL,
  152379. &_vq_auxt__44u9_p8_0,
  152380. NULL,
  152381. 0
  152382. };
  152383. static long _vq_quantlist__44u9_p8_1[] = {
  152384. 10,
  152385. 9,
  152386. 11,
  152387. 8,
  152388. 12,
  152389. 7,
  152390. 13,
  152391. 6,
  152392. 14,
  152393. 5,
  152394. 15,
  152395. 4,
  152396. 16,
  152397. 3,
  152398. 17,
  152399. 2,
  152400. 18,
  152401. 1,
  152402. 19,
  152403. 0,
  152404. 20,
  152405. };
  152406. static long _vq_lengthlist__44u9_p8_1[] = {
  152407. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152408. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152409. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152410. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152411. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152412. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152413. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152414. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152415. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152416. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152417. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152418. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152419. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152420. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152421. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152422. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152423. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152424. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152425. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152426. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152427. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152428. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152429. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152430. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152431. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152432. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152433. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152434. 10,10,10,10,10,10,10,10,10,
  152435. };
  152436. static float _vq_quantthresh__44u9_p8_1[] = {
  152437. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152438. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152439. 6.5, 7.5, 8.5, 9.5,
  152440. };
  152441. static long _vq_quantmap__44u9_p8_1[] = {
  152442. 19, 17, 15, 13, 11, 9, 7, 5,
  152443. 3, 1, 0, 2, 4, 6, 8, 10,
  152444. 12, 14, 16, 18, 20,
  152445. };
  152446. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152447. _vq_quantthresh__44u9_p8_1,
  152448. _vq_quantmap__44u9_p8_1,
  152449. 21,
  152450. 21
  152451. };
  152452. static static_codebook _44u9_p8_1 = {
  152453. 2, 441,
  152454. _vq_lengthlist__44u9_p8_1,
  152455. 1, -529268736, 1611661312, 5, 0,
  152456. _vq_quantlist__44u9_p8_1,
  152457. NULL,
  152458. &_vq_auxt__44u9_p8_1,
  152459. NULL,
  152460. 0
  152461. };
  152462. static long _vq_quantlist__44u9_p9_0[] = {
  152463. 7,
  152464. 6,
  152465. 8,
  152466. 5,
  152467. 9,
  152468. 4,
  152469. 10,
  152470. 3,
  152471. 11,
  152472. 2,
  152473. 12,
  152474. 1,
  152475. 13,
  152476. 0,
  152477. 14,
  152478. };
  152479. static long _vq_lengthlist__44u9_p9_0[] = {
  152480. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152481. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152482. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152483. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152484. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152485. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152486. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152487. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152488. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152489. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152490. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152491. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152492. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152493. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152494. 10,
  152495. };
  152496. static float _vq_quantthresh__44u9_p9_0[] = {
  152497. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152498. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152499. };
  152500. static long _vq_quantmap__44u9_p9_0[] = {
  152501. 13, 11, 9, 7, 5, 3, 1, 0,
  152502. 2, 4, 6, 8, 10, 12, 14,
  152503. };
  152504. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152505. _vq_quantthresh__44u9_p9_0,
  152506. _vq_quantmap__44u9_p9_0,
  152507. 15,
  152508. 15
  152509. };
  152510. static static_codebook _44u9_p9_0 = {
  152511. 2, 225,
  152512. _vq_lengthlist__44u9_p9_0,
  152513. 1, -510036736, 1631393792, 4, 0,
  152514. _vq_quantlist__44u9_p9_0,
  152515. NULL,
  152516. &_vq_auxt__44u9_p9_0,
  152517. NULL,
  152518. 0
  152519. };
  152520. static long _vq_quantlist__44u9_p9_1[] = {
  152521. 9,
  152522. 8,
  152523. 10,
  152524. 7,
  152525. 11,
  152526. 6,
  152527. 12,
  152528. 5,
  152529. 13,
  152530. 4,
  152531. 14,
  152532. 3,
  152533. 15,
  152534. 2,
  152535. 16,
  152536. 1,
  152537. 17,
  152538. 0,
  152539. 18,
  152540. };
  152541. static long _vq_lengthlist__44u9_p9_1[] = {
  152542. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152543. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152544. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152545. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152546. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152547. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152548. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152549. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152550. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152551. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152552. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152553. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152554. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152555. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152556. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152557. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152558. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152559. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152560. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152561. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152562. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152563. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152564. 17,17,15,17,15,17,16,16,17,
  152565. };
  152566. static float _vq_quantthresh__44u9_p9_1[] = {
  152567. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152568. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152569. 367.5, 416.5,
  152570. };
  152571. static long _vq_quantmap__44u9_p9_1[] = {
  152572. 17, 15, 13, 11, 9, 7, 5, 3,
  152573. 1, 0, 2, 4, 6, 8, 10, 12,
  152574. 14, 16, 18,
  152575. };
  152576. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152577. _vq_quantthresh__44u9_p9_1,
  152578. _vq_quantmap__44u9_p9_1,
  152579. 19,
  152580. 19
  152581. };
  152582. static static_codebook _44u9_p9_1 = {
  152583. 2, 361,
  152584. _vq_lengthlist__44u9_p9_1,
  152585. 1, -518287360, 1622704128, 5, 0,
  152586. _vq_quantlist__44u9_p9_1,
  152587. NULL,
  152588. &_vq_auxt__44u9_p9_1,
  152589. NULL,
  152590. 0
  152591. };
  152592. static long _vq_quantlist__44u9_p9_2[] = {
  152593. 24,
  152594. 23,
  152595. 25,
  152596. 22,
  152597. 26,
  152598. 21,
  152599. 27,
  152600. 20,
  152601. 28,
  152602. 19,
  152603. 29,
  152604. 18,
  152605. 30,
  152606. 17,
  152607. 31,
  152608. 16,
  152609. 32,
  152610. 15,
  152611. 33,
  152612. 14,
  152613. 34,
  152614. 13,
  152615. 35,
  152616. 12,
  152617. 36,
  152618. 11,
  152619. 37,
  152620. 10,
  152621. 38,
  152622. 9,
  152623. 39,
  152624. 8,
  152625. 40,
  152626. 7,
  152627. 41,
  152628. 6,
  152629. 42,
  152630. 5,
  152631. 43,
  152632. 4,
  152633. 44,
  152634. 3,
  152635. 45,
  152636. 2,
  152637. 46,
  152638. 1,
  152639. 47,
  152640. 0,
  152641. 48,
  152642. };
  152643. static long _vq_lengthlist__44u9_p9_2[] = {
  152644. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152645. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152646. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152647. 7,
  152648. };
  152649. static float _vq_quantthresh__44u9_p9_2[] = {
  152650. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152651. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152652. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152653. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152654. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152655. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152656. };
  152657. static long _vq_quantmap__44u9_p9_2[] = {
  152658. 47, 45, 43, 41, 39, 37, 35, 33,
  152659. 31, 29, 27, 25, 23, 21, 19, 17,
  152660. 15, 13, 11, 9, 7, 5, 3, 1,
  152661. 0, 2, 4, 6, 8, 10, 12, 14,
  152662. 16, 18, 20, 22, 24, 26, 28, 30,
  152663. 32, 34, 36, 38, 40, 42, 44, 46,
  152664. 48,
  152665. };
  152666. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152667. _vq_quantthresh__44u9_p9_2,
  152668. _vq_quantmap__44u9_p9_2,
  152669. 49,
  152670. 49
  152671. };
  152672. static static_codebook _44u9_p9_2 = {
  152673. 1, 49,
  152674. _vq_lengthlist__44u9_p9_2,
  152675. 1, -526909440, 1611661312, 6, 0,
  152676. _vq_quantlist__44u9_p9_2,
  152677. NULL,
  152678. &_vq_auxt__44u9_p9_2,
  152679. NULL,
  152680. 0
  152681. };
  152682. static long _huff_lengthlist__44un1__long[] = {
  152683. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152684. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152685. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152686. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152687. };
  152688. static static_codebook _huff_book__44un1__long = {
  152689. 2, 64,
  152690. _huff_lengthlist__44un1__long,
  152691. 0, 0, 0, 0, 0,
  152692. NULL,
  152693. NULL,
  152694. NULL,
  152695. NULL,
  152696. 0
  152697. };
  152698. static long _vq_quantlist__44un1__p1_0[] = {
  152699. 1,
  152700. 0,
  152701. 2,
  152702. };
  152703. static long _vq_lengthlist__44un1__p1_0[] = {
  152704. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152705. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152706. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152707. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152708. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152709. 12,
  152710. };
  152711. static float _vq_quantthresh__44un1__p1_0[] = {
  152712. -0.5, 0.5,
  152713. };
  152714. static long _vq_quantmap__44un1__p1_0[] = {
  152715. 1, 0, 2,
  152716. };
  152717. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152718. _vq_quantthresh__44un1__p1_0,
  152719. _vq_quantmap__44un1__p1_0,
  152720. 3,
  152721. 3
  152722. };
  152723. static static_codebook _44un1__p1_0 = {
  152724. 4, 81,
  152725. _vq_lengthlist__44un1__p1_0,
  152726. 1, -535822336, 1611661312, 2, 0,
  152727. _vq_quantlist__44un1__p1_0,
  152728. NULL,
  152729. &_vq_auxt__44un1__p1_0,
  152730. NULL,
  152731. 0
  152732. };
  152733. static long _vq_quantlist__44un1__p2_0[] = {
  152734. 1,
  152735. 0,
  152736. 2,
  152737. };
  152738. static long _vq_lengthlist__44un1__p2_0[] = {
  152739. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152740. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152741. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152742. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152743. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152744. 8,
  152745. };
  152746. static float _vq_quantthresh__44un1__p2_0[] = {
  152747. -0.5, 0.5,
  152748. };
  152749. static long _vq_quantmap__44un1__p2_0[] = {
  152750. 1, 0, 2,
  152751. };
  152752. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152753. _vq_quantthresh__44un1__p2_0,
  152754. _vq_quantmap__44un1__p2_0,
  152755. 3,
  152756. 3
  152757. };
  152758. static static_codebook _44un1__p2_0 = {
  152759. 4, 81,
  152760. _vq_lengthlist__44un1__p2_0,
  152761. 1, -535822336, 1611661312, 2, 0,
  152762. _vq_quantlist__44un1__p2_0,
  152763. NULL,
  152764. &_vq_auxt__44un1__p2_0,
  152765. NULL,
  152766. 0
  152767. };
  152768. static long _vq_quantlist__44un1__p3_0[] = {
  152769. 2,
  152770. 1,
  152771. 3,
  152772. 0,
  152773. 4,
  152774. };
  152775. static long _vq_lengthlist__44un1__p3_0[] = {
  152776. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152777. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152778. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152779. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152780. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152781. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152782. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152783. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152784. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152785. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152786. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152787. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152788. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152789. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152790. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152791. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152792. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152793. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152794. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152795. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152796. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152797. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152798. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152799. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152800. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152801. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152802. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152803. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152804. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152805. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152806. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152807. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152808. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152809. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152810. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152811. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152812. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152813. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152814. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152815. 17,
  152816. };
  152817. static float _vq_quantthresh__44un1__p3_0[] = {
  152818. -1.5, -0.5, 0.5, 1.5,
  152819. };
  152820. static long _vq_quantmap__44un1__p3_0[] = {
  152821. 3, 1, 0, 2, 4,
  152822. };
  152823. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152824. _vq_quantthresh__44un1__p3_0,
  152825. _vq_quantmap__44un1__p3_0,
  152826. 5,
  152827. 5
  152828. };
  152829. static static_codebook _44un1__p3_0 = {
  152830. 4, 625,
  152831. _vq_lengthlist__44un1__p3_0,
  152832. 1, -533725184, 1611661312, 3, 0,
  152833. _vq_quantlist__44un1__p3_0,
  152834. NULL,
  152835. &_vq_auxt__44un1__p3_0,
  152836. NULL,
  152837. 0
  152838. };
  152839. static long _vq_quantlist__44un1__p4_0[] = {
  152840. 2,
  152841. 1,
  152842. 3,
  152843. 0,
  152844. 4,
  152845. };
  152846. static long _vq_lengthlist__44un1__p4_0[] = {
  152847. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152848. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152849. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152850. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152851. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152852. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152853. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152854. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152855. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152856. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152857. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152858. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152859. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152860. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152861. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152862. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152863. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152864. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152865. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152866. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152867. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152868. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152869. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152870. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152871. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152872. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152873. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152874. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152875. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152876. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152877. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152878. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152879. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152880. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152881. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152882. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152883. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152884. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152885. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152886. 12,
  152887. };
  152888. static float _vq_quantthresh__44un1__p4_0[] = {
  152889. -1.5, -0.5, 0.5, 1.5,
  152890. };
  152891. static long _vq_quantmap__44un1__p4_0[] = {
  152892. 3, 1, 0, 2, 4,
  152893. };
  152894. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152895. _vq_quantthresh__44un1__p4_0,
  152896. _vq_quantmap__44un1__p4_0,
  152897. 5,
  152898. 5
  152899. };
  152900. static static_codebook _44un1__p4_0 = {
  152901. 4, 625,
  152902. _vq_lengthlist__44un1__p4_0,
  152903. 1, -533725184, 1611661312, 3, 0,
  152904. _vq_quantlist__44un1__p4_0,
  152905. NULL,
  152906. &_vq_auxt__44un1__p4_0,
  152907. NULL,
  152908. 0
  152909. };
  152910. static long _vq_quantlist__44un1__p5_0[] = {
  152911. 4,
  152912. 3,
  152913. 5,
  152914. 2,
  152915. 6,
  152916. 1,
  152917. 7,
  152918. 0,
  152919. 8,
  152920. };
  152921. static long _vq_lengthlist__44un1__p5_0[] = {
  152922. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152923. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152924. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152925. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152926. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152927. 12,
  152928. };
  152929. static float _vq_quantthresh__44un1__p5_0[] = {
  152930. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152931. };
  152932. static long _vq_quantmap__44un1__p5_0[] = {
  152933. 7, 5, 3, 1, 0, 2, 4, 6,
  152934. 8,
  152935. };
  152936. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152937. _vq_quantthresh__44un1__p5_0,
  152938. _vq_quantmap__44un1__p5_0,
  152939. 9,
  152940. 9
  152941. };
  152942. static static_codebook _44un1__p5_0 = {
  152943. 2, 81,
  152944. _vq_lengthlist__44un1__p5_0,
  152945. 1, -531628032, 1611661312, 4, 0,
  152946. _vq_quantlist__44un1__p5_0,
  152947. NULL,
  152948. &_vq_auxt__44un1__p5_0,
  152949. NULL,
  152950. 0
  152951. };
  152952. static long _vq_quantlist__44un1__p6_0[] = {
  152953. 6,
  152954. 5,
  152955. 7,
  152956. 4,
  152957. 8,
  152958. 3,
  152959. 9,
  152960. 2,
  152961. 10,
  152962. 1,
  152963. 11,
  152964. 0,
  152965. 12,
  152966. };
  152967. static long _vq_lengthlist__44un1__p6_0[] = {
  152968. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152969. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152970. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152971. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152972. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152973. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152974. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152975. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152976. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152977. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152978. 16, 0,15,18,18, 0,16, 0, 0,
  152979. };
  152980. static float _vq_quantthresh__44un1__p6_0[] = {
  152981. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152982. 12.5, 17.5, 22.5, 27.5,
  152983. };
  152984. static long _vq_quantmap__44un1__p6_0[] = {
  152985. 11, 9, 7, 5, 3, 1, 0, 2,
  152986. 4, 6, 8, 10, 12,
  152987. };
  152988. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152989. _vq_quantthresh__44un1__p6_0,
  152990. _vq_quantmap__44un1__p6_0,
  152991. 13,
  152992. 13
  152993. };
  152994. static static_codebook _44un1__p6_0 = {
  152995. 2, 169,
  152996. _vq_lengthlist__44un1__p6_0,
  152997. 1, -526516224, 1616117760, 4, 0,
  152998. _vq_quantlist__44un1__p6_0,
  152999. NULL,
  153000. &_vq_auxt__44un1__p6_0,
  153001. NULL,
  153002. 0
  153003. };
  153004. static long _vq_quantlist__44un1__p6_1[] = {
  153005. 2,
  153006. 1,
  153007. 3,
  153008. 0,
  153009. 4,
  153010. };
  153011. static long _vq_lengthlist__44un1__p6_1[] = {
  153012. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  153013. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  153014. };
  153015. static float _vq_quantthresh__44un1__p6_1[] = {
  153016. -1.5, -0.5, 0.5, 1.5,
  153017. };
  153018. static long _vq_quantmap__44un1__p6_1[] = {
  153019. 3, 1, 0, 2, 4,
  153020. };
  153021. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  153022. _vq_quantthresh__44un1__p6_1,
  153023. _vq_quantmap__44un1__p6_1,
  153024. 5,
  153025. 5
  153026. };
  153027. static static_codebook _44un1__p6_1 = {
  153028. 2, 25,
  153029. _vq_lengthlist__44un1__p6_1,
  153030. 1, -533725184, 1611661312, 3, 0,
  153031. _vq_quantlist__44un1__p6_1,
  153032. NULL,
  153033. &_vq_auxt__44un1__p6_1,
  153034. NULL,
  153035. 0
  153036. };
  153037. static long _vq_quantlist__44un1__p7_0[] = {
  153038. 2,
  153039. 1,
  153040. 3,
  153041. 0,
  153042. 4,
  153043. };
  153044. static long _vq_lengthlist__44un1__p7_0[] = {
  153045. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153046. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153047. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153048. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153049. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153050. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153051. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153052. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  153053. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153054. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153055. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  153056. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153057. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153058. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153059. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153060. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  153061. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153062. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  153063. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153064. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153065. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153066. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153067. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153068. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153069. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153070. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153071. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153072. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153073. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153074. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153075. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153076. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153077. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153078. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153079. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153080. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153081. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153082. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153083. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153084. 10,
  153085. };
  153086. static float _vq_quantthresh__44un1__p7_0[] = {
  153087. -253.5, -84.5, 84.5, 253.5,
  153088. };
  153089. static long _vq_quantmap__44un1__p7_0[] = {
  153090. 3, 1, 0, 2, 4,
  153091. };
  153092. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153093. _vq_quantthresh__44un1__p7_0,
  153094. _vq_quantmap__44un1__p7_0,
  153095. 5,
  153096. 5
  153097. };
  153098. static static_codebook _44un1__p7_0 = {
  153099. 4, 625,
  153100. _vq_lengthlist__44un1__p7_0,
  153101. 1, -518709248, 1626677248, 3, 0,
  153102. _vq_quantlist__44un1__p7_0,
  153103. NULL,
  153104. &_vq_auxt__44un1__p7_0,
  153105. NULL,
  153106. 0
  153107. };
  153108. static long _vq_quantlist__44un1__p7_1[] = {
  153109. 6,
  153110. 5,
  153111. 7,
  153112. 4,
  153113. 8,
  153114. 3,
  153115. 9,
  153116. 2,
  153117. 10,
  153118. 1,
  153119. 11,
  153120. 0,
  153121. 12,
  153122. };
  153123. static long _vq_lengthlist__44un1__p7_1[] = {
  153124. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153125. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153126. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153127. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153128. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153129. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153130. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153131. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153132. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153133. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153134. 12,13,13,12,13,13,14,14,14,
  153135. };
  153136. static float _vq_quantthresh__44un1__p7_1[] = {
  153137. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153138. 32.5, 45.5, 58.5, 71.5,
  153139. };
  153140. static long _vq_quantmap__44un1__p7_1[] = {
  153141. 11, 9, 7, 5, 3, 1, 0, 2,
  153142. 4, 6, 8, 10, 12,
  153143. };
  153144. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153145. _vq_quantthresh__44un1__p7_1,
  153146. _vq_quantmap__44un1__p7_1,
  153147. 13,
  153148. 13
  153149. };
  153150. static static_codebook _44un1__p7_1 = {
  153151. 2, 169,
  153152. _vq_lengthlist__44un1__p7_1,
  153153. 1, -523010048, 1618608128, 4, 0,
  153154. _vq_quantlist__44un1__p7_1,
  153155. NULL,
  153156. &_vq_auxt__44un1__p7_1,
  153157. NULL,
  153158. 0
  153159. };
  153160. static long _vq_quantlist__44un1__p7_2[] = {
  153161. 6,
  153162. 5,
  153163. 7,
  153164. 4,
  153165. 8,
  153166. 3,
  153167. 9,
  153168. 2,
  153169. 10,
  153170. 1,
  153171. 11,
  153172. 0,
  153173. 12,
  153174. };
  153175. static long _vq_lengthlist__44un1__p7_2[] = {
  153176. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153177. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153178. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153179. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153180. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153181. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153182. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153183. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153184. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153185. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153186. 9, 9, 9,10,10,10,10,10,10,
  153187. };
  153188. static float _vq_quantthresh__44un1__p7_2[] = {
  153189. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153190. 2.5, 3.5, 4.5, 5.5,
  153191. };
  153192. static long _vq_quantmap__44un1__p7_2[] = {
  153193. 11, 9, 7, 5, 3, 1, 0, 2,
  153194. 4, 6, 8, 10, 12,
  153195. };
  153196. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153197. _vq_quantthresh__44un1__p7_2,
  153198. _vq_quantmap__44un1__p7_2,
  153199. 13,
  153200. 13
  153201. };
  153202. static static_codebook _44un1__p7_2 = {
  153203. 2, 169,
  153204. _vq_lengthlist__44un1__p7_2,
  153205. 1, -531103744, 1611661312, 4, 0,
  153206. _vq_quantlist__44un1__p7_2,
  153207. NULL,
  153208. &_vq_auxt__44un1__p7_2,
  153209. NULL,
  153210. 0
  153211. };
  153212. static long _huff_lengthlist__44un1__short[] = {
  153213. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153214. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153215. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153216. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153217. };
  153218. static static_codebook _huff_book__44un1__short = {
  153219. 2, 64,
  153220. _huff_lengthlist__44un1__short,
  153221. 0, 0, 0, 0, 0,
  153222. NULL,
  153223. NULL,
  153224. NULL,
  153225. NULL,
  153226. 0
  153227. };
  153228. /*** End of inlined file: res_books_uncoupled.h ***/
  153229. /***** residue backends *********************************************/
  153230. static vorbis_info_residue0 _residue_44_low_un={
  153231. 0,-1, -1, 8,-1,
  153232. {0},
  153233. {-1},
  153234. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153235. { -1, 25, -1, 45, -1, -1, -1}
  153236. };
  153237. static vorbis_info_residue0 _residue_44_mid_un={
  153238. 0,-1, -1, 10,-1,
  153239. /* 0 1 2 3 4 5 6 7 8 9 */
  153240. {0},
  153241. {-1},
  153242. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153243. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153244. };
  153245. static vorbis_info_residue0 _residue_44_hi_un={
  153246. 0,-1, -1, 10,-1,
  153247. /* 0 1 2 3 4 5 6 7 8 9 */
  153248. {0},
  153249. {-1},
  153250. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153251. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153252. };
  153253. /* mapping conventions:
  153254. only one submap (this would change for efficient 5.1 support for example)*/
  153255. /* Four psychoacoustic profiles are used, one for each blocktype */
  153256. static vorbis_info_mapping0 _map_nominal_u[2]={
  153257. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153258. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153259. };
  153260. static static_bookblock _resbook_44u_n1={
  153261. {
  153262. {0},
  153263. {0,0,&_44un1__p1_0},
  153264. {0,0,&_44un1__p2_0},
  153265. {0,0,&_44un1__p3_0},
  153266. {0,0,&_44un1__p4_0},
  153267. {0,0,&_44un1__p5_0},
  153268. {&_44un1__p6_0,&_44un1__p6_1},
  153269. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153270. }
  153271. };
  153272. static static_bookblock _resbook_44u_0={
  153273. {
  153274. {0},
  153275. {0,0,&_44u0__p1_0},
  153276. {0,0,&_44u0__p2_0},
  153277. {0,0,&_44u0__p3_0},
  153278. {0,0,&_44u0__p4_0},
  153279. {0,0,&_44u0__p5_0},
  153280. {&_44u0__p6_0,&_44u0__p6_1},
  153281. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153282. }
  153283. };
  153284. static static_bookblock _resbook_44u_1={
  153285. {
  153286. {0},
  153287. {0,0,&_44u1__p1_0},
  153288. {0,0,&_44u1__p2_0},
  153289. {0,0,&_44u1__p3_0},
  153290. {0,0,&_44u1__p4_0},
  153291. {0,0,&_44u1__p5_0},
  153292. {&_44u1__p6_0,&_44u1__p6_1},
  153293. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153294. }
  153295. };
  153296. static static_bookblock _resbook_44u_2={
  153297. {
  153298. {0},
  153299. {0,0,&_44u2__p1_0},
  153300. {0,0,&_44u2__p2_0},
  153301. {0,0,&_44u2__p3_0},
  153302. {0,0,&_44u2__p4_0},
  153303. {0,0,&_44u2__p5_0},
  153304. {&_44u2__p6_0,&_44u2__p6_1},
  153305. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153306. }
  153307. };
  153308. static static_bookblock _resbook_44u_3={
  153309. {
  153310. {0},
  153311. {0,0,&_44u3__p1_0},
  153312. {0,0,&_44u3__p2_0},
  153313. {0,0,&_44u3__p3_0},
  153314. {0,0,&_44u3__p4_0},
  153315. {0,0,&_44u3__p5_0},
  153316. {&_44u3__p6_0,&_44u3__p6_1},
  153317. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153318. }
  153319. };
  153320. static static_bookblock _resbook_44u_4={
  153321. {
  153322. {0},
  153323. {0,0,&_44u4__p1_0},
  153324. {0,0,&_44u4__p2_0},
  153325. {0,0,&_44u4__p3_0},
  153326. {0,0,&_44u4__p4_0},
  153327. {0,0,&_44u4__p5_0},
  153328. {&_44u4__p6_0,&_44u4__p6_1},
  153329. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153330. }
  153331. };
  153332. static static_bookblock _resbook_44u_5={
  153333. {
  153334. {0},
  153335. {0,0,&_44u5__p1_0},
  153336. {0,0,&_44u5__p2_0},
  153337. {0,0,&_44u5__p3_0},
  153338. {0,0,&_44u5__p4_0},
  153339. {0,0,&_44u5__p5_0},
  153340. {0,0,&_44u5__p6_0},
  153341. {&_44u5__p7_0,&_44u5__p7_1},
  153342. {&_44u5__p8_0,&_44u5__p8_1},
  153343. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153344. }
  153345. };
  153346. static static_bookblock _resbook_44u_6={
  153347. {
  153348. {0},
  153349. {0,0,&_44u6__p1_0},
  153350. {0,0,&_44u6__p2_0},
  153351. {0,0,&_44u6__p3_0},
  153352. {0,0,&_44u6__p4_0},
  153353. {0,0,&_44u6__p5_0},
  153354. {0,0,&_44u6__p6_0},
  153355. {&_44u6__p7_0,&_44u6__p7_1},
  153356. {&_44u6__p8_0,&_44u6__p8_1},
  153357. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153358. }
  153359. };
  153360. static static_bookblock _resbook_44u_7={
  153361. {
  153362. {0},
  153363. {0,0,&_44u7__p1_0},
  153364. {0,0,&_44u7__p2_0},
  153365. {0,0,&_44u7__p3_0},
  153366. {0,0,&_44u7__p4_0},
  153367. {0,0,&_44u7__p5_0},
  153368. {0,0,&_44u7__p6_0},
  153369. {&_44u7__p7_0,&_44u7__p7_1},
  153370. {&_44u7__p8_0,&_44u7__p8_1},
  153371. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153372. }
  153373. };
  153374. static static_bookblock _resbook_44u_8={
  153375. {
  153376. {0},
  153377. {0,0,&_44u8_p1_0},
  153378. {0,0,&_44u8_p2_0},
  153379. {0,0,&_44u8_p3_0},
  153380. {0,0,&_44u8_p4_0},
  153381. {&_44u8_p5_0,&_44u8_p5_1},
  153382. {&_44u8_p6_0,&_44u8_p6_1},
  153383. {&_44u8_p7_0,&_44u8_p7_1},
  153384. {&_44u8_p8_0,&_44u8_p8_1},
  153385. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153386. }
  153387. };
  153388. static static_bookblock _resbook_44u_9={
  153389. {
  153390. {0},
  153391. {0,0,&_44u9_p1_0},
  153392. {0,0,&_44u9_p2_0},
  153393. {0,0,&_44u9_p3_0},
  153394. {0,0,&_44u9_p4_0},
  153395. {&_44u9_p5_0,&_44u9_p5_1},
  153396. {&_44u9_p6_0,&_44u9_p6_1},
  153397. {&_44u9_p7_0,&_44u9_p7_1},
  153398. {&_44u9_p8_0,&_44u9_p8_1},
  153399. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153400. }
  153401. };
  153402. static vorbis_residue_template _res_44u_n1[]={
  153403. {1,0, &_residue_44_low_un,
  153404. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153405. &_resbook_44u_n1,&_resbook_44u_n1},
  153406. {1,0, &_residue_44_low_un,
  153407. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153408. &_resbook_44u_n1,&_resbook_44u_n1}
  153409. };
  153410. static vorbis_residue_template _res_44u_0[]={
  153411. {1,0, &_residue_44_low_un,
  153412. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153413. &_resbook_44u_0,&_resbook_44u_0},
  153414. {1,0, &_residue_44_low_un,
  153415. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153416. &_resbook_44u_0,&_resbook_44u_0}
  153417. };
  153418. static vorbis_residue_template _res_44u_1[]={
  153419. {1,0, &_residue_44_low_un,
  153420. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153421. &_resbook_44u_1,&_resbook_44u_1},
  153422. {1,0, &_residue_44_low_un,
  153423. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153424. &_resbook_44u_1,&_resbook_44u_1}
  153425. };
  153426. static vorbis_residue_template _res_44u_2[]={
  153427. {1,0, &_residue_44_low_un,
  153428. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153429. &_resbook_44u_2,&_resbook_44u_2},
  153430. {1,0, &_residue_44_low_un,
  153431. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153432. &_resbook_44u_2,&_resbook_44u_2}
  153433. };
  153434. static vorbis_residue_template _res_44u_3[]={
  153435. {1,0, &_residue_44_low_un,
  153436. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153437. &_resbook_44u_3,&_resbook_44u_3},
  153438. {1,0, &_residue_44_low_un,
  153439. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153440. &_resbook_44u_3,&_resbook_44u_3}
  153441. };
  153442. static vorbis_residue_template _res_44u_4[]={
  153443. {1,0, &_residue_44_low_un,
  153444. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153445. &_resbook_44u_4,&_resbook_44u_4},
  153446. {1,0, &_residue_44_low_un,
  153447. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153448. &_resbook_44u_4,&_resbook_44u_4}
  153449. };
  153450. static vorbis_residue_template _res_44u_5[]={
  153451. {1,0, &_residue_44_mid_un,
  153452. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153453. &_resbook_44u_5,&_resbook_44u_5},
  153454. {1,0, &_residue_44_mid_un,
  153455. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153456. &_resbook_44u_5,&_resbook_44u_5}
  153457. };
  153458. static vorbis_residue_template _res_44u_6[]={
  153459. {1,0, &_residue_44_mid_un,
  153460. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153461. &_resbook_44u_6,&_resbook_44u_6},
  153462. {1,0, &_residue_44_mid_un,
  153463. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153464. &_resbook_44u_6,&_resbook_44u_6}
  153465. };
  153466. static vorbis_residue_template _res_44u_7[]={
  153467. {1,0, &_residue_44_mid_un,
  153468. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153469. &_resbook_44u_7,&_resbook_44u_7},
  153470. {1,0, &_residue_44_mid_un,
  153471. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153472. &_resbook_44u_7,&_resbook_44u_7}
  153473. };
  153474. static vorbis_residue_template _res_44u_8[]={
  153475. {1,0, &_residue_44_hi_un,
  153476. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153477. &_resbook_44u_8,&_resbook_44u_8},
  153478. {1,0, &_residue_44_hi_un,
  153479. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153480. &_resbook_44u_8,&_resbook_44u_8}
  153481. };
  153482. static vorbis_residue_template _res_44u_9[]={
  153483. {1,0, &_residue_44_hi_un,
  153484. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153485. &_resbook_44u_9,&_resbook_44u_9},
  153486. {1,0, &_residue_44_hi_un,
  153487. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153488. &_resbook_44u_9,&_resbook_44u_9}
  153489. };
  153490. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153491. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153492. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153493. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153494. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153495. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153496. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153497. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153498. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153499. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153500. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153501. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153502. };
  153503. /*** End of inlined file: residue_44u.h ***/
  153504. static double rate_mapping_44_un[12]={
  153505. 32000.,48000.,60000.,70000.,80000.,86000.,
  153506. 96000.,110000.,120000.,140000.,160000.,240001.
  153507. };
  153508. ve_setup_data_template ve_setup_44_uncoupled={
  153509. 11,
  153510. rate_mapping_44_un,
  153511. quality_mapping_44,
  153512. -1,
  153513. 40000,
  153514. 50000,
  153515. blocksize_short_44,
  153516. blocksize_long_44,
  153517. _psy_tone_masteratt_44,
  153518. _psy_tone_0dB,
  153519. _psy_tone_suppress,
  153520. _vp_tonemask_adj_otherblock,
  153521. _vp_tonemask_adj_longblock,
  153522. _vp_tonemask_adj_otherblock,
  153523. _psy_noiseguards_44,
  153524. _psy_noisebias_impulse,
  153525. _psy_noisebias_padding,
  153526. _psy_noisebias_trans,
  153527. _psy_noisebias_long,
  153528. _psy_noise_suppress,
  153529. _psy_compand_44,
  153530. _psy_compand_short_mapping,
  153531. _psy_compand_long_mapping,
  153532. {_noise_start_short_44,_noise_start_long_44},
  153533. {_noise_part_short_44,_noise_part_long_44},
  153534. _noise_thresh_44,
  153535. _psy_ath_floater,
  153536. _psy_ath_abs,
  153537. _psy_lowpass_44,
  153538. _psy_global_44,
  153539. _global_mapping_44,
  153540. NULL,
  153541. _floor_books,
  153542. _floor,
  153543. _floor_short_mapping_44,
  153544. _floor_long_mapping_44,
  153545. _mapres_template_44_uncoupled
  153546. };
  153547. /*** End of inlined file: setup_44u.h ***/
  153548. /*** Start of inlined file: setup_32.h ***/
  153549. static double rate_mapping_32[12]={
  153550. 18000.,28000.,35000.,45000.,56000.,60000.,
  153551. 75000.,90000.,100000.,115000.,150000.,190000.,
  153552. };
  153553. static double rate_mapping_32_un[12]={
  153554. 30000.,42000.,52000.,64000.,72000.,78000.,
  153555. 86000.,92000.,110000.,120000.,140000.,190000.,
  153556. };
  153557. static double _psy_lowpass_32[12]={
  153558. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153559. };
  153560. ve_setup_data_template ve_setup_32_stereo={
  153561. 11,
  153562. rate_mapping_32,
  153563. quality_mapping_44,
  153564. 2,
  153565. 26000,
  153566. 40000,
  153567. blocksize_short_44,
  153568. blocksize_long_44,
  153569. _psy_tone_masteratt_44,
  153570. _psy_tone_0dB,
  153571. _psy_tone_suppress,
  153572. _vp_tonemask_adj_otherblock,
  153573. _vp_tonemask_adj_longblock,
  153574. _vp_tonemask_adj_otherblock,
  153575. _psy_noiseguards_44,
  153576. _psy_noisebias_impulse,
  153577. _psy_noisebias_padding,
  153578. _psy_noisebias_trans,
  153579. _psy_noisebias_long,
  153580. _psy_noise_suppress,
  153581. _psy_compand_44,
  153582. _psy_compand_short_mapping,
  153583. _psy_compand_long_mapping,
  153584. {_noise_start_short_44,_noise_start_long_44},
  153585. {_noise_part_short_44,_noise_part_long_44},
  153586. _noise_thresh_44,
  153587. _psy_ath_floater,
  153588. _psy_ath_abs,
  153589. _psy_lowpass_32,
  153590. _psy_global_44,
  153591. _global_mapping_44,
  153592. _psy_stereo_modes_44,
  153593. _floor_books,
  153594. _floor,
  153595. _floor_short_mapping_44,
  153596. _floor_long_mapping_44,
  153597. _mapres_template_44_stereo
  153598. };
  153599. ve_setup_data_template ve_setup_32_uncoupled={
  153600. 11,
  153601. rate_mapping_32_un,
  153602. quality_mapping_44,
  153603. -1,
  153604. 26000,
  153605. 40000,
  153606. blocksize_short_44,
  153607. blocksize_long_44,
  153608. _psy_tone_masteratt_44,
  153609. _psy_tone_0dB,
  153610. _psy_tone_suppress,
  153611. _vp_tonemask_adj_otherblock,
  153612. _vp_tonemask_adj_longblock,
  153613. _vp_tonemask_adj_otherblock,
  153614. _psy_noiseguards_44,
  153615. _psy_noisebias_impulse,
  153616. _psy_noisebias_padding,
  153617. _psy_noisebias_trans,
  153618. _psy_noisebias_long,
  153619. _psy_noise_suppress,
  153620. _psy_compand_44,
  153621. _psy_compand_short_mapping,
  153622. _psy_compand_long_mapping,
  153623. {_noise_start_short_44,_noise_start_long_44},
  153624. {_noise_part_short_44,_noise_part_long_44},
  153625. _noise_thresh_44,
  153626. _psy_ath_floater,
  153627. _psy_ath_abs,
  153628. _psy_lowpass_32,
  153629. _psy_global_44,
  153630. _global_mapping_44,
  153631. NULL,
  153632. _floor_books,
  153633. _floor,
  153634. _floor_short_mapping_44,
  153635. _floor_long_mapping_44,
  153636. _mapres_template_44_uncoupled
  153637. };
  153638. /*** End of inlined file: setup_32.h ***/
  153639. /*** Start of inlined file: setup_8.h ***/
  153640. /*** Start of inlined file: psych_8.h ***/
  153641. static att3 _psy_tone_masteratt_8[3]={
  153642. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153643. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153644. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153645. };
  153646. static vp_adjblock _vp_tonemask_adj_8[3]={
  153647. /* adjust for mode zero */
  153648. /* 63 125 250 500 1 2 4 8 16 */
  153649. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153650. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153651. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153652. };
  153653. static noise3 _psy_noisebias_8[3]={
  153654. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153655. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153656. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153657. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153658. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153659. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153660. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153661. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153662. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153663. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153664. };
  153665. /* stereo mode by base quality level */
  153666. static adj_stereo _psy_stereo_modes_8[3]={
  153667. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153668. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153669. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153670. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153671. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153672. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153673. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153674. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153675. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153676. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153677. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153678. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153679. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153680. };
  153681. static noiseguard _psy_noiseguards_8[2]={
  153682. {10,10,-1},
  153683. {10,10,-1},
  153684. };
  153685. static compandblock _psy_compand_8[2]={
  153686. {{
  153687. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153688. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153689. 12,12,13,13,14,14,15, 15, /* 23dB */
  153690. 16,16,17,17,17,18,18, 19, /* 31dB */
  153691. 19,19,20,21,22,23,24, 25, /* 39dB */
  153692. }},
  153693. {{
  153694. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153695. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153696. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153697. 9,10,11,12,13,14,15, 16, /* 31dB */
  153698. 17,18,19,20,21,22,23, 24, /* 39dB */
  153699. }},
  153700. };
  153701. static double _psy_lowpass_8[3]={3.,4.,4.};
  153702. static int _noise_start_8[2]={
  153703. 64,64,
  153704. };
  153705. static int _noise_part_8[2]={
  153706. 8,8,
  153707. };
  153708. static int _psy_ath_floater_8[3]={
  153709. -100,-100,-105,
  153710. };
  153711. static int _psy_ath_abs_8[3]={
  153712. -130,-130,-140,
  153713. };
  153714. /*** End of inlined file: psych_8.h ***/
  153715. /*** Start of inlined file: residue_8.h ***/
  153716. /***** residue backends *********************************************/
  153717. static static_bookblock _resbook_8s_0={
  153718. {
  153719. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153720. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153721. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153722. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153723. }
  153724. };
  153725. static static_bookblock _resbook_8s_1={
  153726. {
  153727. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153728. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153729. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153730. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153731. }
  153732. };
  153733. static vorbis_residue_template _res_8s_0[]={
  153734. {2,0, &_residue_44_mid,
  153735. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153736. &_resbook_8s_0,&_resbook_8s_0},
  153737. };
  153738. static vorbis_residue_template _res_8s_1[]={
  153739. {2,0, &_residue_44_mid,
  153740. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153741. &_resbook_8s_1,&_resbook_8s_1},
  153742. };
  153743. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153744. { _map_nominal, _res_8s_0 }, /* 0 */
  153745. { _map_nominal, _res_8s_1 }, /* 1 */
  153746. };
  153747. static static_bookblock _resbook_8u_0={
  153748. {
  153749. {0},
  153750. {0,0,&_8u0__p1_0},
  153751. {0,0,&_8u0__p2_0},
  153752. {0,0,&_8u0__p3_0},
  153753. {0,0,&_8u0__p4_0},
  153754. {0,0,&_8u0__p5_0},
  153755. {&_8u0__p6_0,&_8u0__p6_1},
  153756. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153757. }
  153758. };
  153759. static static_bookblock _resbook_8u_1={
  153760. {
  153761. {0},
  153762. {0,0,&_8u1__p1_0},
  153763. {0,0,&_8u1__p2_0},
  153764. {0,0,&_8u1__p3_0},
  153765. {0,0,&_8u1__p4_0},
  153766. {0,0,&_8u1__p5_0},
  153767. {0,0,&_8u1__p6_0},
  153768. {&_8u1__p7_0,&_8u1__p7_1},
  153769. {&_8u1__p8_0,&_8u1__p8_1},
  153770. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153771. }
  153772. };
  153773. static vorbis_residue_template _res_8u_0[]={
  153774. {1,0, &_residue_44_low_un,
  153775. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153776. &_resbook_8u_0,&_resbook_8u_0},
  153777. };
  153778. static vorbis_residue_template _res_8u_1[]={
  153779. {1,0, &_residue_44_mid_un,
  153780. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153781. &_resbook_8u_1,&_resbook_8u_1},
  153782. };
  153783. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153784. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153785. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153786. };
  153787. /*** End of inlined file: residue_8.h ***/
  153788. static int blocksize_8[2]={
  153789. 512,512
  153790. };
  153791. static int _floor_mapping_8[2]={
  153792. 6,6,
  153793. };
  153794. static double rate_mapping_8[3]={
  153795. 6000.,9000.,32000.,
  153796. };
  153797. static double rate_mapping_8_uncoupled[3]={
  153798. 8000.,14000.,42000.,
  153799. };
  153800. static double quality_mapping_8[3]={
  153801. -.1,.0,1.
  153802. };
  153803. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153804. static double _global_mapping_8[3]={ 1., 2., 3. };
  153805. ve_setup_data_template ve_setup_8_stereo={
  153806. 2,
  153807. rate_mapping_8,
  153808. quality_mapping_8,
  153809. 2,
  153810. 8000,
  153811. 9000,
  153812. blocksize_8,
  153813. blocksize_8,
  153814. _psy_tone_masteratt_8,
  153815. _psy_tone_0dB,
  153816. _psy_tone_suppress,
  153817. _vp_tonemask_adj_8,
  153818. NULL,
  153819. _vp_tonemask_adj_8,
  153820. _psy_noiseguards_8,
  153821. _psy_noisebias_8,
  153822. _psy_noisebias_8,
  153823. NULL,
  153824. NULL,
  153825. _psy_noise_suppress,
  153826. _psy_compand_8,
  153827. _psy_compand_8_mapping,
  153828. NULL,
  153829. {_noise_start_8,_noise_start_8},
  153830. {_noise_part_8,_noise_part_8},
  153831. _noise_thresh_5only,
  153832. _psy_ath_floater_8,
  153833. _psy_ath_abs_8,
  153834. _psy_lowpass_8,
  153835. _psy_global_44,
  153836. _global_mapping_8,
  153837. _psy_stereo_modes_8,
  153838. _floor_books,
  153839. _floor,
  153840. _floor_mapping_8,
  153841. NULL,
  153842. _mapres_template_8_stereo
  153843. };
  153844. ve_setup_data_template ve_setup_8_uncoupled={
  153845. 2,
  153846. rate_mapping_8_uncoupled,
  153847. quality_mapping_8,
  153848. -1,
  153849. 8000,
  153850. 9000,
  153851. blocksize_8,
  153852. blocksize_8,
  153853. _psy_tone_masteratt_8,
  153854. _psy_tone_0dB,
  153855. _psy_tone_suppress,
  153856. _vp_tonemask_adj_8,
  153857. NULL,
  153858. _vp_tonemask_adj_8,
  153859. _psy_noiseguards_8,
  153860. _psy_noisebias_8,
  153861. _psy_noisebias_8,
  153862. NULL,
  153863. NULL,
  153864. _psy_noise_suppress,
  153865. _psy_compand_8,
  153866. _psy_compand_8_mapping,
  153867. NULL,
  153868. {_noise_start_8,_noise_start_8},
  153869. {_noise_part_8,_noise_part_8},
  153870. _noise_thresh_5only,
  153871. _psy_ath_floater_8,
  153872. _psy_ath_abs_8,
  153873. _psy_lowpass_8,
  153874. _psy_global_44,
  153875. _global_mapping_8,
  153876. _psy_stereo_modes_8,
  153877. _floor_books,
  153878. _floor,
  153879. _floor_mapping_8,
  153880. NULL,
  153881. _mapres_template_8_uncoupled
  153882. };
  153883. /*** End of inlined file: setup_8.h ***/
  153884. /*** Start of inlined file: setup_11.h ***/
  153885. /*** Start of inlined file: psych_11.h ***/
  153886. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153887. static att3 _psy_tone_masteratt_11[3]={
  153888. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153889. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153890. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153891. };
  153892. static vp_adjblock _vp_tonemask_adj_11[3]={
  153893. /* adjust for mode zero */
  153894. /* 63 125 250 500 1 2 4 8 16 */
  153895. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153896. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153897. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153898. };
  153899. static noise3 _psy_noisebias_11[3]={
  153900. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153901. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153902. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153903. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153904. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153905. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153906. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153907. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153908. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153909. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153910. };
  153911. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153912. /*** End of inlined file: psych_11.h ***/
  153913. static int blocksize_11[2]={
  153914. 512,512
  153915. };
  153916. static int _floor_mapping_11[2]={
  153917. 6,6,
  153918. };
  153919. static double rate_mapping_11[3]={
  153920. 8000.,13000.,44000.,
  153921. };
  153922. static double rate_mapping_11_uncoupled[3]={
  153923. 12000.,20000.,50000.,
  153924. };
  153925. static double quality_mapping_11[3]={
  153926. -.1,.0,1.
  153927. };
  153928. ve_setup_data_template ve_setup_11_stereo={
  153929. 2,
  153930. rate_mapping_11,
  153931. quality_mapping_11,
  153932. 2,
  153933. 9000,
  153934. 15000,
  153935. blocksize_11,
  153936. blocksize_11,
  153937. _psy_tone_masteratt_11,
  153938. _psy_tone_0dB,
  153939. _psy_tone_suppress,
  153940. _vp_tonemask_adj_11,
  153941. NULL,
  153942. _vp_tonemask_adj_11,
  153943. _psy_noiseguards_8,
  153944. _psy_noisebias_11,
  153945. _psy_noisebias_11,
  153946. NULL,
  153947. NULL,
  153948. _psy_noise_suppress,
  153949. _psy_compand_8,
  153950. _psy_compand_8_mapping,
  153951. NULL,
  153952. {_noise_start_8,_noise_start_8},
  153953. {_noise_part_8,_noise_part_8},
  153954. _noise_thresh_11,
  153955. _psy_ath_floater_8,
  153956. _psy_ath_abs_8,
  153957. _psy_lowpass_11,
  153958. _psy_global_44,
  153959. _global_mapping_8,
  153960. _psy_stereo_modes_8,
  153961. _floor_books,
  153962. _floor,
  153963. _floor_mapping_11,
  153964. NULL,
  153965. _mapres_template_8_stereo
  153966. };
  153967. ve_setup_data_template ve_setup_11_uncoupled={
  153968. 2,
  153969. rate_mapping_11_uncoupled,
  153970. quality_mapping_11,
  153971. -1,
  153972. 9000,
  153973. 15000,
  153974. blocksize_11,
  153975. blocksize_11,
  153976. _psy_tone_masteratt_11,
  153977. _psy_tone_0dB,
  153978. _psy_tone_suppress,
  153979. _vp_tonemask_adj_11,
  153980. NULL,
  153981. _vp_tonemask_adj_11,
  153982. _psy_noiseguards_8,
  153983. _psy_noisebias_11,
  153984. _psy_noisebias_11,
  153985. NULL,
  153986. NULL,
  153987. _psy_noise_suppress,
  153988. _psy_compand_8,
  153989. _psy_compand_8_mapping,
  153990. NULL,
  153991. {_noise_start_8,_noise_start_8},
  153992. {_noise_part_8,_noise_part_8},
  153993. _noise_thresh_11,
  153994. _psy_ath_floater_8,
  153995. _psy_ath_abs_8,
  153996. _psy_lowpass_11,
  153997. _psy_global_44,
  153998. _global_mapping_8,
  153999. _psy_stereo_modes_8,
  154000. _floor_books,
  154001. _floor,
  154002. _floor_mapping_11,
  154003. NULL,
  154004. _mapres_template_8_uncoupled
  154005. };
  154006. /*** End of inlined file: setup_11.h ***/
  154007. /*** Start of inlined file: setup_16.h ***/
  154008. /*** Start of inlined file: psych_16.h ***/
  154009. /* stereo mode by base quality level */
  154010. static adj_stereo _psy_stereo_modes_16[4]={
  154011. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  154012. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154013. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154014. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  154015. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154016. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154017. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154018. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  154019. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154020. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154021. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154022. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154023. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154024. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154025. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154026. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  154027. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154028. };
  154029. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  154030. static att3 _psy_tone_masteratt_16[4]={
  154031. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154032. {{ 25, 22, 12}, 0, 0}, /* 0 */
  154033. {{ 20, 12, 0}, 0, 0}, /* 0 */
  154034. {{ 15, 0, -14}, 0, 0}, /* 0 */
  154035. };
  154036. static vp_adjblock _vp_tonemask_adj_16[4]={
  154037. /* adjust for mode zero */
  154038. /* 63 125 250 500 1 2 4 8 16 */
  154039. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  154040. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  154041. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154042. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154043. };
  154044. static noise3 _psy_noisebias_16_short[4]={
  154045. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154046. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154047. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154048. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154049. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154050. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  154051. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154052. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154053. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  154054. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154055. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154056. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154057. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154058. };
  154059. static noise3 _psy_noisebias_16_impulse[4]={
  154060. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154061. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154062. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154063. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154064. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154065. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154066. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154067. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154068. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  154069. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154070. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154071. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154072. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154073. };
  154074. static noise3 _psy_noisebias_16[4]={
  154075. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154076. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154077. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154078. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154079. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154080. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154081. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154082. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154083. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154084. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154085. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154086. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154087. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154088. };
  154089. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154090. static int _noise_start_16[3]={ 256,256,9999 };
  154091. static int _noise_part_16[4]={ 8,8,8,8 };
  154092. static int _psy_ath_floater_16[4]={
  154093. -100,-100,-100,-105,
  154094. };
  154095. static int _psy_ath_abs_16[4]={
  154096. -130,-130,-130,-140,
  154097. };
  154098. /*** End of inlined file: psych_16.h ***/
  154099. /*** Start of inlined file: residue_16.h ***/
  154100. /***** residue backends *********************************************/
  154101. static static_bookblock _resbook_16s_0={
  154102. {
  154103. {0},
  154104. {0,0,&_16c0_s_p1_0},
  154105. {0,0,&_16c0_s_p2_0},
  154106. {0,0,&_16c0_s_p3_0},
  154107. {0,0,&_16c0_s_p4_0},
  154108. {0,0,&_16c0_s_p5_0},
  154109. {0,0,&_16c0_s_p6_0},
  154110. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154111. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154112. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154113. }
  154114. };
  154115. static static_bookblock _resbook_16s_1={
  154116. {
  154117. {0},
  154118. {0,0,&_16c1_s_p1_0},
  154119. {0,0,&_16c1_s_p2_0},
  154120. {0,0,&_16c1_s_p3_0},
  154121. {0,0,&_16c1_s_p4_0},
  154122. {0,0,&_16c1_s_p5_0},
  154123. {0,0,&_16c1_s_p6_0},
  154124. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154125. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154126. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154127. }
  154128. };
  154129. static static_bookblock _resbook_16s_2={
  154130. {
  154131. {0},
  154132. {0,0,&_16c2_s_p1_0},
  154133. {0,0,&_16c2_s_p2_0},
  154134. {0,0,&_16c2_s_p3_0},
  154135. {0,0,&_16c2_s_p4_0},
  154136. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154137. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154138. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154139. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154140. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154141. }
  154142. };
  154143. static vorbis_residue_template _res_16s_0[]={
  154144. {2,0, &_residue_44_mid,
  154145. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154146. &_resbook_16s_0,&_resbook_16s_0},
  154147. };
  154148. static vorbis_residue_template _res_16s_1[]={
  154149. {2,0, &_residue_44_mid,
  154150. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154151. &_resbook_16s_1,&_resbook_16s_1},
  154152. {2,0, &_residue_44_mid,
  154153. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154154. &_resbook_16s_1,&_resbook_16s_1}
  154155. };
  154156. static vorbis_residue_template _res_16s_2[]={
  154157. {2,0, &_residue_44_high,
  154158. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154159. &_resbook_16s_2,&_resbook_16s_2},
  154160. {2,0, &_residue_44_high,
  154161. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154162. &_resbook_16s_2,&_resbook_16s_2}
  154163. };
  154164. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154165. { _map_nominal, _res_16s_0 }, /* 0 */
  154166. { _map_nominal, _res_16s_1 }, /* 1 */
  154167. { _map_nominal, _res_16s_2 }, /* 2 */
  154168. };
  154169. static static_bookblock _resbook_16u_0={
  154170. {
  154171. {0},
  154172. {0,0,&_16u0__p1_0},
  154173. {0,0,&_16u0__p2_0},
  154174. {0,0,&_16u0__p3_0},
  154175. {0,0,&_16u0__p4_0},
  154176. {0,0,&_16u0__p5_0},
  154177. {&_16u0__p6_0,&_16u0__p6_1},
  154178. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154179. }
  154180. };
  154181. static static_bookblock _resbook_16u_1={
  154182. {
  154183. {0},
  154184. {0,0,&_16u1__p1_0},
  154185. {0,0,&_16u1__p2_0},
  154186. {0,0,&_16u1__p3_0},
  154187. {0,0,&_16u1__p4_0},
  154188. {0,0,&_16u1__p5_0},
  154189. {0,0,&_16u1__p6_0},
  154190. {&_16u1__p7_0,&_16u1__p7_1},
  154191. {&_16u1__p8_0,&_16u1__p8_1},
  154192. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154193. }
  154194. };
  154195. static static_bookblock _resbook_16u_2={
  154196. {
  154197. {0},
  154198. {0,0,&_16u2_p1_0},
  154199. {0,0,&_16u2_p2_0},
  154200. {0,0,&_16u2_p3_0},
  154201. {0,0,&_16u2_p4_0},
  154202. {&_16u2_p5_0,&_16u2_p5_1},
  154203. {&_16u2_p6_0,&_16u2_p6_1},
  154204. {&_16u2_p7_0,&_16u2_p7_1},
  154205. {&_16u2_p8_0,&_16u2_p8_1},
  154206. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154207. }
  154208. };
  154209. static vorbis_residue_template _res_16u_0[]={
  154210. {1,0, &_residue_44_low_un,
  154211. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154212. &_resbook_16u_0,&_resbook_16u_0},
  154213. };
  154214. static vorbis_residue_template _res_16u_1[]={
  154215. {1,0, &_residue_44_mid_un,
  154216. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154217. &_resbook_16u_1,&_resbook_16u_1},
  154218. {1,0, &_residue_44_mid_un,
  154219. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154220. &_resbook_16u_1,&_resbook_16u_1}
  154221. };
  154222. static vorbis_residue_template _res_16u_2[]={
  154223. {1,0, &_residue_44_hi_un,
  154224. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154225. &_resbook_16u_2,&_resbook_16u_2},
  154226. {1,0, &_residue_44_hi_un,
  154227. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154228. &_resbook_16u_2,&_resbook_16u_2}
  154229. };
  154230. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154231. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154232. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154233. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154234. };
  154235. /*** End of inlined file: residue_16.h ***/
  154236. static int blocksize_16_short[3]={
  154237. 1024,512,512
  154238. };
  154239. static int blocksize_16_long[3]={
  154240. 1024,1024,1024
  154241. };
  154242. static int _floor_mapping_16_short[3]={
  154243. 9,3,3
  154244. };
  154245. static int _floor_mapping_16[3]={
  154246. 9,9,9
  154247. };
  154248. static double rate_mapping_16[4]={
  154249. 12000.,20000.,44000.,86000.
  154250. };
  154251. static double rate_mapping_16_uncoupled[4]={
  154252. 16000.,28000.,64000.,100000.
  154253. };
  154254. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154255. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154256. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154257. ve_setup_data_template ve_setup_16_stereo={
  154258. 3,
  154259. rate_mapping_16,
  154260. quality_mapping_16,
  154261. 2,
  154262. 15000,
  154263. 19000,
  154264. blocksize_16_short,
  154265. blocksize_16_long,
  154266. _psy_tone_masteratt_16,
  154267. _psy_tone_0dB,
  154268. _psy_tone_suppress,
  154269. _vp_tonemask_adj_16,
  154270. _vp_tonemask_adj_16,
  154271. _vp_tonemask_adj_16,
  154272. _psy_noiseguards_8,
  154273. _psy_noisebias_16_impulse,
  154274. _psy_noisebias_16_short,
  154275. _psy_noisebias_16_short,
  154276. _psy_noisebias_16,
  154277. _psy_noise_suppress,
  154278. _psy_compand_8,
  154279. _psy_compand_16_mapping,
  154280. _psy_compand_16_mapping,
  154281. {_noise_start_16,_noise_start_16},
  154282. { _noise_part_16, _noise_part_16},
  154283. _noise_thresh_16,
  154284. _psy_ath_floater_16,
  154285. _psy_ath_abs_16,
  154286. _psy_lowpass_16,
  154287. _psy_global_44,
  154288. _global_mapping_16,
  154289. _psy_stereo_modes_16,
  154290. _floor_books,
  154291. _floor,
  154292. _floor_mapping_16_short,
  154293. _floor_mapping_16,
  154294. _mapres_template_16_stereo
  154295. };
  154296. ve_setup_data_template ve_setup_16_uncoupled={
  154297. 3,
  154298. rate_mapping_16_uncoupled,
  154299. quality_mapping_16,
  154300. -1,
  154301. 15000,
  154302. 19000,
  154303. blocksize_16_short,
  154304. blocksize_16_long,
  154305. _psy_tone_masteratt_16,
  154306. _psy_tone_0dB,
  154307. _psy_tone_suppress,
  154308. _vp_tonemask_adj_16,
  154309. _vp_tonemask_adj_16,
  154310. _vp_tonemask_adj_16,
  154311. _psy_noiseguards_8,
  154312. _psy_noisebias_16_impulse,
  154313. _psy_noisebias_16_short,
  154314. _psy_noisebias_16_short,
  154315. _psy_noisebias_16,
  154316. _psy_noise_suppress,
  154317. _psy_compand_8,
  154318. _psy_compand_16_mapping,
  154319. _psy_compand_16_mapping,
  154320. {_noise_start_16,_noise_start_16},
  154321. { _noise_part_16, _noise_part_16},
  154322. _noise_thresh_16,
  154323. _psy_ath_floater_16,
  154324. _psy_ath_abs_16,
  154325. _psy_lowpass_16,
  154326. _psy_global_44,
  154327. _global_mapping_16,
  154328. _psy_stereo_modes_16,
  154329. _floor_books,
  154330. _floor,
  154331. _floor_mapping_16_short,
  154332. _floor_mapping_16,
  154333. _mapres_template_16_uncoupled
  154334. };
  154335. /*** End of inlined file: setup_16.h ***/
  154336. /*** Start of inlined file: setup_22.h ***/
  154337. static double rate_mapping_22[4]={
  154338. 15000.,20000.,44000.,86000.
  154339. };
  154340. static double rate_mapping_22_uncoupled[4]={
  154341. 16000.,28000.,50000.,90000.
  154342. };
  154343. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154344. ve_setup_data_template ve_setup_22_stereo={
  154345. 3,
  154346. rate_mapping_22,
  154347. quality_mapping_16,
  154348. 2,
  154349. 19000,
  154350. 26000,
  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_8_mapping,
  154367. _psy_compand_8_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_22,
  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_stereo
  154382. };
  154383. ve_setup_data_template ve_setup_22_uncoupled={
  154384. 3,
  154385. rate_mapping_22_uncoupled,
  154386. quality_mapping_16,
  154387. -1,
  154388. 19000,
  154389. 26000,
  154390. blocksize_16_short,
  154391. blocksize_16_long,
  154392. _psy_tone_masteratt_16,
  154393. _psy_tone_0dB,
  154394. _psy_tone_suppress,
  154395. _vp_tonemask_adj_16,
  154396. _vp_tonemask_adj_16,
  154397. _vp_tonemask_adj_16,
  154398. _psy_noiseguards_8,
  154399. _psy_noisebias_16_impulse,
  154400. _psy_noisebias_16_short,
  154401. _psy_noisebias_16_short,
  154402. _psy_noisebias_16,
  154403. _psy_noise_suppress,
  154404. _psy_compand_8,
  154405. _psy_compand_8_mapping,
  154406. _psy_compand_8_mapping,
  154407. {_noise_start_16,_noise_start_16},
  154408. { _noise_part_16, _noise_part_16},
  154409. _noise_thresh_16,
  154410. _psy_ath_floater_16,
  154411. _psy_ath_abs_16,
  154412. _psy_lowpass_22,
  154413. _psy_global_44,
  154414. _global_mapping_16,
  154415. _psy_stereo_modes_16,
  154416. _floor_books,
  154417. _floor,
  154418. _floor_mapping_16_short,
  154419. _floor_mapping_16,
  154420. _mapres_template_16_uncoupled
  154421. };
  154422. /*** End of inlined file: setup_22.h ***/
  154423. /*** Start of inlined file: setup_X.h ***/
  154424. static double rate_mapping_X[12]={
  154425. -1.,-1.,-1.,-1.,-1.,-1.,
  154426. -1.,-1.,-1.,-1.,-1.,-1.
  154427. };
  154428. ve_setup_data_template ve_setup_X_stereo={
  154429. 11,
  154430. rate_mapping_X,
  154431. quality_mapping_44,
  154432. 2,
  154433. 50000,
  154434. 200000,
  154435. blocksize_short_44,
  154436. blocksize_long_44,
  154437. _psy_tone_masteratt_44,
  154438. _psy_tone_0dB,
  154439. _psy_tone_suppress,
  154440. _vp_tonemask_adj_otherblock,
  154441. _vp_tonemask_adj_longblock,
  154442. _vp_tonemask_adj_otherblock,
  154443. _psy_noiseguards_44,
  154444. _psy_noisebias_impulse,
  154445. _psy_noisebias_padding,
  154446. _psy_noisebias_trans,
  154447. _psy_noisebias_long,
  154448. _psy_noise_suppress,
  154449. _psy_compand_44,
  154450. _psy_compand_short_mapping,
  154451. _psy_compand_long_mapping,
  154452. {_noise_start_short_44,_noise_start_long_44},
  154453. {_noise_part_short_44,_noise_part_long_44},
  154454. _noise_thresh_44,
  154455. _psy_ath_floater,
  154456. _psy_ath_abs,
  154457. _psy_lowpass_44,
  154458. _psy_global_44,
  154459. _global_mapping_44,
  154460. _psy_stereo_modes_44,
  154461. _floor_books,
  154462. _floor,
  154463. _floor_short_mapping_44,
  154464. _floor_long_mapping_44,
  154465. _mapres_template_44_stereo
  154466. };
  154467. ve_setup_data_template ve_setup_X_uncoupled={
  154468. 11,
  154469. rate_mapping_X,
  154470. quality_mapping_44,
  154471. -1,
  154472. 50000,
  154473. 200000,
  154474. blocksize_short_44,
  154475. blocksize_long_44,
  154476. _psy_tone_masteratt_44,
  154477. _psy_tone_0dB,
  154478. _psy_tone_suppress,
  154479. _vp_tonemask_adj_otherblock,
  154480. _vp_tonemask_adj_longblock,
  154481. _vp_tonemask_adj_otherblock,
  154482. _psy_noiseguards_44,
  154483. _psy_noisebias_impulse,
  154484. _psy_noisebias_padding,
  154485. _psy_noisebias_trans,
  154486. _psy_noisebias_long,
  154487. _psy_noise_suppress,
  154488. _psy_compand_44,
  154489. _psy_compand_short_mapping,
  154490. _psy_compand_long_mapping,
  154491. {_noise_start_short_44,_noise_start_long_44},
  154492. {_noise_part_short_44,_noise_part_long_44},
  154493. _noise_thresh_44,
  154494. _psy_ath_floater,
  154495. _psy_ath_abs,
  154496. _psy_lowpass_44,
  154497. _psy_global_44,
  154498. _global_mapping_44,
  154499. NULL,
  154500. _floor_books,
  154501. _floor,
  154502. _floor_short_mapping_44,
  154503. _floor_long_mapping_44,
  154504. _mapres_template_44_uncoupled
  154505. };
  154506. ve_setup_data_template ve_setup_XX_stereo={
  154507. 2,
  154508. rate_mapping_X,
  154509. quality_mapping_8,
  154510. 2,
  154511. 0,
  154512. 8000,
  154513. blocksize_8,
  154514. blocksize_8,
  154515. _psy_tone_masteratt_8,
  154516. _psy_tone_0dB,
  154517. _psy_tone_suppress,
  154518. _vp_tonemask_adj_8,
  154519. NULL,
  154520. _vp_tonemask_adj_8,
  154521. _psy_noiseguards_8,
  154522. _psy_noisebias_8,
  154523. _psy_noisebias_8,
  154524. NULL,
  154525. NULL,
  154526. _psy_noise_suppress,
  154527. _psy_compand_8,
  154528. _psy_compand_8_mapping,
  154529. NULL,
  154530. {_noise_start_8,_noise_start_8},
  154531. {_noise_part_8,_noise_part_8},
  154532. _noise_thresh_5only,
  154533. _psy_ath_floater_8,
  154534. _psy_ath_abs_8,
  154535. _psy_lowpass_8,
  154536. _psy_global_44,
  154537. _global_mapping_8,
  154538. _psy_stereo_modes_8,
  154539. _floor_books,
  154540. _floor,
  154541. _floor_mapping_8,
  154542. NULL,
  154543. _mapres_template_8_stereo
  154544. };
  154545. ve_setup_data_template ve_setup_XX_uncoupled={
  154546. 2,
  154547. rate_mapping_X,
  154548. quality_mapping_8,
  154549. -1,
  154550. 0,
  154551. 8000,
  154552. blocksize_8,
  154553. blocksize_8,
  154554. _psy_tone_masteratt_8,
  154555. _psy_tone_0dB,
  154556. _psy_tone_suppress,
  154557. _vp_tonemask_adj_8,
  154558. NULL,
  154559. _vp_tonemask_adj_8,
  154560. _psy_noiseguards_8,
  154561. _psy_noisebias_8,
  154562. _psy_noisebias_8,
  154563. NULL,
  154564. NULL,
  154565. _psy_noise_suppress,
  154566. _psy_compand_8,
  154567. _psy_compand_8_mapping,
  154568. NULL,
  154569. {_noise_start_8,_noise_start_8},
  154570. {_noise_part_8,_noise_part_8},
  154571. _noise_thresh_5only,
  154572. _psy_ath_floater_8,
  154573. _psy_ath_abs_8,
  154574. _psy_lowpass_8,
  154575. _psy_global_44,
  154576. _global_mapping_8,
  154577. _psy_stereo_modes_8,
  154578. _floor_books,
  154579. _floor,
  154580. _floor_mapping_8,
  154581. NULL,
  154582. _mapres_template_8_uncoupled
  154583. };
  154584. /*** End of inlined file: setup_X.h ***/
  154585. static ve_setup_data_template *setup_list[]={
  154586. &ve_setup_44_stereo,
  154587. &ve_setup_44_uncoupled,
  154588. &ve_setup_32_stereo,
  154589. &ve_setup_32_uncoupled,
  154590. &ve_setup_22_stereo,
  154591. &ve_setup_22_uncoupled,
  154592. &ve_setup_16_stereo,
  154593. &ve_setup_16_uncoupled,
  154594. &ve_setup_11_stereo,
  154595. &ve_setup_11_uncoupled,
  154596. &ve_setup_8_stereo,
  154597. &ve_setup_8_uncoupled,
  154598. &ve_setup_X_stereo,
  154599. &ve_setup_X_uncoupled,
  154600. &ve_setup_XX_stereo,
  154601. &ve_setup_XX_uncoupled,
  154602. 0
  154603. };
  154604. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154605. if(vi && vi->codec_setup){
  154606. vi->version=0;
  154607. vi->channels=ch;
  154608. vi->rate=rate;
  154609. return(0);
  154610. }
  154611. return(OV_EINVAL);
  154612. }
  154613. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154614. static_codebook ***books,
  154615. vorbis_info_floor1 *in,
  154616. int *x){
  154617. int i,k,is=s;
  154618. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154619. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154620. memcpy(f,in+x[is],sizeof(*f));
  154621. /* fill in the lowpass field, even if it's temporary */
  154622. f->n=ci->blocksizes[block]>>1;
  154623. /* books */
  154624. {
  154625. int partitions=f->partitions;
  154626. int maxclass=-1;
  154627. int maxbook=-1;
  154628. for(i=0;i<partitions;i++)
  154629. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154630. for(i=0;i<=maxclass;i++){
  154631. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154632. f->class_book[i]+=ci->books;
  154633. for(k=0;k<(1<<f->class_subs[i]);k++){
  154634. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154635. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154636. }
  154637. }
  154638. for(i=0;i<=maxbook;i++)
  154639. ci->book_param[ci->books++]=books[x[is]][i];
  154640. }
  154641. /* for now, we're only using floor 1 */
  154642. ci->floor_type[ci->floors]=1;
  154643. ci->floor_param[ci->floors]=f;
  154644. ci->floors++;
  154645. return;
  154646. }
  154647. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154648. vorbis_info_psy_global *in,
  154649. double *x){
  154650. int i,is=s;
  154651. double ds=s-is;
  154652. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154653. vorbis_info_psy_global *g=&ci->psy_g_param;
  154654. memcpy(g,in+(int)x[is],sizeof(*g));
  154655. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154656. is=(int)ds;
  154657. ds-=is;
  154658. if(ds==0 && is>0){
  154659. is--;
  154660. ds=1.;
  154661. }
  154662. /* interpolate the trigger threshholds */
  154663. for(i=0;i<4;i++){
  154664. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154665. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154666. }
  154667. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154668. return;
  154669. }
  154670. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154671. highlevel_encode_setup *hi,
  154672. adj_stereo *p){
  154673. float s=hi->stereo_point_setting;
  154674. int i,is=s;
  154675. double ds=s-is;
  154676. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154677. vorbis_info_psy_global *g=&ci->psy_g_param;
  154678. if(p){
  154679. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154680. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154681. if(hi->managed){
  154682. /* interpolate the kHz threshholds */
  154683. for(i=0;i<PACKETBLOBS;i++){
  154684. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154685. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154686. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154687. g->coupling_pkHz[i]=kHz;
  154688. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154689. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154690. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154691. }
  154692. }else{
  154693. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154694. for(i=0;i<PACKETBLOBS;i++){
  154695. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154696. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154697. g->coupling_pkHz[i]=kHz;
  154698. }
  154699. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154700. for(i=0;i<PACKETBLOBS;i++){
  154701. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154702. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154703. }
  154704. }
  154705. }else{
  154706. for(i=0;i<PACKETBLOBS;i++){
  154707. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154708. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154709. }
  154710. }
  154711. return;
  154712. }
  154713. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154714. int *nn_start,
  154715. int *nn_partition,
  154716. double *nn_thresh,
  154717. int block){
  154718. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154719. vorbis_info_psy *p=ci->psy_param[block];
  154720. highlevel_encode_setup *hi=&ci->hi;
  154721. int is=s;
  154722. if(block>=ci->psys)
  154723. ci->psys=block+1;
  154724. if(!p){
  154725. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154726. ci->psy_param[block]=p;
  154727. }
  154728. memcpy(p,&_psy_info_template,sizeof(*p));
  154729. p->blockflag=block>>1;
  154730. if(hi->noise_normalize_p){
  154731. p->normal_channel_p=1;
  154732. p->normal_point_p=1;
  154733. p->normal_start=nn_start[is];
  154734. p->normal_partition=nn_partition[is];
  154735. p->normal_thresh=nn_thresh[is];
  154736. }
  154737. return;
  154738. }
  154739. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154740. att3 *att,
  154741. int *max,
  154742. vp_adjblock *in){
  154743. int i,is=s;
  154744. double ds=s-is;
  154745. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154746. vorbis_info_psy *p=ci->psy_param[block];
  154747. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154748. filling the values in here */
  154749. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154750. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154751. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154752. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154753. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154754. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154755. for(i=0;i<P_BANDS;i++)
  154756. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154757. return;
  154758. }
  154759. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154760. compandblock *in, double *x){
  154761. int i,is=s;
  154762. double ds=s-is;
  154763. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154764. vorbis_info_psy *p=ci->psy_param[block];
  154765. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154766. is=(int)ds;
  154767. ds-=is;
  154768. if(ds==0 && is>0){
  154769. is--;
  154770. ds=1.;
  154771. }
  154772. /* interpolate the compander settings */
  154773. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154774. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154775. return;
  154776. }
  154777. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154778. int *suppress){
  154779. int is=s;
  154780. double ds=s-is;
  154781. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154782. vorbis_info_psy *p=ci->psy_param[block];
  154783. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154784. return;
  154785. }
  154786. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154787. int *suppress,
  154788. noise3 *in,
  154789. noiseguard *guard,
  154790. double userbias){
  154791. int i,is=s,j;
  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. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154796. p->noisewindowlomin=guard[block].lo;
  154797. p->noisewindowhimin=guard[block].hi;
  154798. p->noisewindowfixed=guard[block].fixed;
  154799. for(j=0;j<P_NOISECURVES;j++)
  154800. for(i=0;i<P_BANDS;i++)
  154801. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154802. /* impulse blocks may take a user specified bias to boost the
  154803. nominal/high noise encoding depth */
  154804. for(j=0;j<P_NOISECURVES;j++){
  154805. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154806. for(i=0;i<P_BANDS;i++){
  154807. p->noiseoff[j][i]+=userbias;
  154808. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154809. }
  154810. }
  154811. return;
  154812. }
  154813. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154814. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154815. vorbis_info_psy *p=ci->psy_param[block];
  154816. p->ath_adjatt=ci->hi.ath_floating_dB;
  154817. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154818. return;
  154819. }
  154820. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154821. int i;
  154822. for(i=0;i<ci->books;i++)
  154823. if(ci->book_param[i]==book)return(i);
  154824. return(ci->books++);
  154825. }
  154826. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154827. int *shortb,int *longb){
  154828. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154829. int is=s;
  154830. int blockshort=shortb[is];
  154831. int blocklong=longb[is];
  154832. ci->blocksizes[0]=blockshort;
  154833. ci->blocksizes[1]=blocklong;
  154834. }
  154835. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154836. int number, int block,
  154837. vorbis_residue_template *res){
  154838. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154839. int i,n;
  154840. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154841. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154842. memcpy(r,res->res,sizeof(*r));
  154843. if(ci->residues<=number)ci->residues=number+1;
  154844. switch(ci->blocksizes[block]){
  154845. case 64:case 128:case 256:
  154846. r->grouping=16;
  154847. break;
  154848. default:
  154849. r->grouping=32;
  154850. break;
  154851. }
  154852. ci->residue_type[number]=res->res_type;
  154853. /* to be adjusted by lowpass/pointlimit later */
  154854. n=r->end=ci->blocksizes[block]>>1;
  154855. if(res->res_type==2)
  154856. n=r->end*=vi->channels;
  154857. /* fill in all the books */
  154858. {
  154859. int booklist=0,k;
  154860. if(ci->hi.managed){
  154861. for(i=0;i<r->partitions;i++)
  154862. for(k=0;k<3;k++)
  154863. if(res->books_base_managed->books[i][k])
  154864. r->secondstages[i]|=(1<<k);
  154865. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154866. ci->book_param[r->groupbook]=res->book_aux_managed;
  154867. for(i=0;i<r->partitions;i++){
  154868. for(k=0;k<3;k++){
  154869. if(res->books_base_managed->books[i][k]){
  154870. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154871. r->booklist[booklist++]=bookid;
  154872. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154873. }
  154874. }
  154875. }
  154876. }else{
  154877. for(i=0;i<r->partitions;i++)
  154878. for(k=0;k<3;k++)
  154879. if(res->books_base->books[i][k])
  154880. r->secondstages[i]|=(1<<k);
  154881. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154882. ci->book_param[r->groupbook]=res->book_aux;
  154883. for(i=0;i<r->partitions;i++){
  154884. for(k=0;k<3;k++){
  154885. if(res->books_base->books[i][k]){
  154886. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154887. r->booklist[booklist++]=bookid;
  154888. ci->book_param[bookid]=res->books_base->books[i][k];
  154889. }
  154890. }
  154891. }
  154892. }
  154893. }
  154894. /* lowpass setup/pointlimit */
  154895. {
  154896. double freq=ci->hi.lowpass_kHz*1000.;
  154897. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154898. double nyq=vi->rate/2.;
  154899. long blocksize=ci->blocksizes[block]>>1;
  154900. /* lowpass needs to be set in the floor and the residue. */
  154901. if(freq>nyq)freq=nyq;
  154902. /* in the floor, the granularity can be very fine; it doesn't alter
  154903. the encoding structure, only the samples used to fit the floor
  154904. approximation */
  154905. f->n=freq/nyq*blocksize;
  154906. /* this res may by limited by the maximum pointlimit of the mode,
  154907. not the lowpass. the floor is always lowpass limited. */
  154908. if(res->limit_type){
  154909. if(ci->hi.managed)
  154910. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154911. else
  154912. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154913. if(freq>nyq)freq=nyq;
  154914. }
  154915. /* in the residue, we're constrained, physically, by partition
  154916. boundaries. We still lowpass 'wherever', but we have to round up
  154917. here to next boundary, or the vorbis spec will round it *down* to
  154918. previous boundary in encode/decode */
  154919. if(ci->residue_type[block]==2)
  154920. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154921. r->grouping;
  154922. else
  154923. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154924. r->grouping;
  154925. }
  154926. }
  154927. /* we assume two maps in this encoder */
  154928. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154929. vorbis_mapping_template *maps){
  154930. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154931. int i,j,is=s,modes=2;
  154932. vorbis_info_mapping0 *map=maps[is].map;
  154933. vorbis_info_mode *mode=_mode_template;
  154934. vorbis_residue_template *res=maps[is].res;
  154935. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154936. for(i=0;i<modes;i++){
  154937. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154938. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154939. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154940. if(i>=ci->modes)ci->modes=i+1;
  154941. ci->map_type[i]=0;
  154942. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154943. if(i>=ci->maps)ci->maps=i+1;
  154944. for(j=0;j<map[i].submaps;j++)
  154945. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154946. ,res+map[i].residuesubmap[j]);
  154947. }
  154948. }
  154949. static double setting_to_approx_bitrate(vorbis_info *vi){
  154950. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154951. highlevel_encode_setup *hi=&ci->hi;
  154952. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154953. int is=hi->base_setting;
  154954. double ds=hi->base_setting-is;
  154955. int ch=vi->channels;
  154956. double *r=setup->rate_mapping;
  154957. if(r==NULL)
  154958. return(-1);
  154959. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154960. }
  154961. static void get_setup_template(vorbis_info *vi,
  154962. long ch,long srate,
  154963. double req,int q_or_bitrate){
  154964. int i=0,j;
  154965. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154966. highlevel_encode_setup *hi=&ci->hi;
  154967. if(q_or_bitrate)req/=ch;
  154968. while(setup_list[i]){
  154969. if(setup_list[i]->coupling_restriction==-1 ||
  154970. setup_list[i]->coupling_restriction==ch){
  154971. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154972. srate<=setup_list[i]->samplerate_max_restriction){
  154973. int mappings=setup_list[i]->mappings;
  154974. double *map=(q_or_bitrate?
  154975. setup_list[i]->rate_mapping:
  154976. setup_list[i]->quality_mapping);
  154977. /* the template matches. Does the requested quality mode
  154978. fall within this template's modes? */
  154979. if(req<map[0]){++i;continue;}
  154980. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154981. for(j=0;j<mappings;j++)
  154982. if(req>=map[j] && req<map[j+1])break;
  154983. /* an all-points match */
  154984. hi->setup=setup_list[i];
  154985. if(j==mappings)
  154986. hi->base_setting=j-.001;
  154987. else{
  154988. float low=map[j];
  154989. float high=map[j+1];
  154990. float del=(req-low)/(high-low);
  154991. hi->base_setting=j+del;
  154992. }
  154993. return;
  154994. }
  154995. }
  154996. i++;
  154997. }
  154998. hi->setup=NULL;
  154999. }
  155000. /* encoders will need to use vorbis_info_init beforehand and call
  155001. vorbis_info clear when all done */
  155002. /* two interfaces; this, more detailed one, and later a convenience
  155003. layer on top */
  155004. /* the final setup call */
  155005. int vorbis_encode_setup_init(vorbis_info *vi){
  155006. int i0=0,singleblock=0;
  155007. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155008. ve_setup_data_template *setup=NULL;
  155009. highlevel_encode_setup *hi=&ci->hi;
  155010. if(ci==NULL)return(OV_EINVAL);
  155011. if(!hi->impulse_block_p)i0=1;
  155012. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  155013. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  155014. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  155015. /* again, bound this to avoid the app shooting itself int he foot
  155016. too badly */
  155017. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  155018. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  155019. /* get the appropriate setup template; matches the fetch in previous
  155020. stages */
  155021. setup=(ve_setup_data_template *)hi->setup;
  155022. if(setup==NULL)return(OV_EINVAL);
  155023. hi->set_in_stone=1;
  155024. /* choose block sizes from configured sizes as well as paying
  155025. attention to long_block_p and short_block_p. If the configured
  155026. short and long blocks are the same length, we set long_block_p
  155027. and unset short_block_p */
  155028. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  155029. setup->blocksize_short,
  155030. setup->blocksize_long);
  155031. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  155032. /* floor setup; choose proper floor params. Allocated on the floor
  155033. stack in order; if we alloc only long floor, it's 0 */
  155034. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  155035. setup->floor_books,
  155036. setup->floor_params,
  155037. setup->floor_short_mapping);
  155038. if(!singleblock)
  155039. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  155040. setup->floor_books,
  155041. setup->floor_params,
  155042. setup->floor_long_mapping);
  155043. /* setup of [mostly] short block detection and stereo*/
  155044. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  155045. setup->global_params,
  155046. setup->global_mapping);
  155047. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155048. /* basic psych setup and noise normalization */
  155049. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155050. setup->psy_noise_normal_start[0],
  155051. setup->psy_noise_normal_partition[0],
  155052. setup->psy_noise_normal_thresh,
  155053. 0);
  155054. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155055. setup->psy_noise_normal_start[0],
  155056. setup->psy_noise_normal_partition[0],
  155057. setup->psy_noise_normal_thresh,
  155058. 1);
  155059. if(!singleblock){
  155060. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155061. setup->psy_noise_normal_start[1],
  155062. setup->psy_noise_normal_partition[1],
  155063. setup->psy_noise_normal_thresh,
  155064. 2);
  155065. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155066. setup->psy_noise_normal_start[1],
  155067. setup->psy_noise_normal_partition[1],
  155068. setup->psy_noise_normal_thresh,
  155069. 3);
  155070. }
  155071. /* tone masking setup */
  155072. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155073. setup->psy_tone_masteratt,
  155074. setup->psy_tone_0dB,
  155075. setup->psy_tone_adj_impulse);
  155076. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155077. setup->psy_tone_masteratt,
  155078. setup->psy_tone_0dB,
  155079. setup->psy_tone_adj_other);
  155080. if(!singleblock){
  155081. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155082. setup->psy_tone_masteratt,
  155083. setup->psy_tone_0dB,
  155084. setup->psy_tone_adj_other);
  155085. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155086. setup->psy_tone_masteratt,
  155087. setup->psy_tone_0dB,
  155088. setup->psy_tone_adj_long);
  155089. }
  155090. /* noise companding setup */
  155091. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155092. setup->psy_noise_compand,
  155093. setup->psy_noise_compand_short_mapping);
  155094. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155095. setup->psy_noise_compand,
  155096. setup->psy_noise_compand_short_mapping);
  155097. if(!singleblock){
  155098. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155099. setup->psy_noise_compand,
  155100. setup->psy_noise_compand_long_mapping);
  155101. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155102. setup->psy_noise_compand,
  155103. setup->psy_noise_compand_long_mapping);
  155104. }
  155105. /* peak guarding setup */
  155106. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155107. setup->psy_tone_dBsuppress);
  155108. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155109. setup->psy_tone_dBsuppress);
  155110. if(!singleblock){
  155111. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155112. setup->psy_tone_dBsuppress);
  155113. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155114. setup->psy_tone_dBsuppress);
  155115. }
  155116. /* noise bias setup */
  155117. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155118. setup->psy_noise_dBsuppress,
  155119. setup->psy_noise_bias_impulse,
  155120. setup->psy_noiseguards,
  155121. (i0==0?hi->impulse_noisetune:0.));
  155122. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155123. setup->psy_noise_dBsuppress,
  155124. setup->psy_noise_bias_padding,
  155125. setup->psy_noiseguards,0.);
  155126. if(!singleblock){
  155127. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155128. setup->psy_noise_dBsuppress,
  155129. setup->psy_noise_bias_trans,
  155130. setup->psy_noiseguards,0.);
  155131. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155132. setup->psy_noise_dBsuppress,
  155133. setup->psy_noise_bias_long,
  155134. setup->psy_noiseguards,0.);
  155135. }
  155136. vorbis_encode_ath_setup(vi,0);
  155137. vorbis_encode_ath_setup(vi,1);
  155138. if(!singleblock){
  155139. vorbis_encode_ath_setup(vi,2);
  155140. vorbis_encode_ath_setup(vi,3);
  155141. }
  155142. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155143. /* set bitrate readonlies and management */
  155144. if(hi->bitrate_av>0)
  155145. vi->bitrate_nominal=hi->bitrate_av;
  155146. else{
  155147. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155148. }
  155149. vi->bitrate_lower=hi->bitrate_min;
  155150. vi->bitrate_upper=hi->bitrate_max;
  155151. if(hi->bitrate_av)
  155152. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155153. else
  155154. vi->bitrate_window=0.;
  155155. if(hi->managed){
  155156. ci->bi.avg_rate=hi->bitrate_av;
  155157. ci->bi.min_rate=hi->bitrate_min;
  155158. ci->bi.max_rate=hi->bitrate_max;
  155159. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155160. ci->bi.reservoir_bias=
  155161. hi->bitrate_reservoir_bias;
  155162. ci->bi.slew_damp=hi->bitrate_av_damp;
  155163. }
  155164. return(0);
  155165. }
  155166. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155167. long channels,
  155168. long rate){
  155169. int ret=0,i,is;
  155170. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155171. highlevel_encode_setup *hi=&ci->hi;
  155172. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155173. double ds;
  155174. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155175. if(ret)return(ret);
  155176. is=hi->base_setting;
  155177. ds=hi->base_setting-is;
  155178. hi->short_setting=hi->base_setting;
  155179. hi->long_setting=hi->base_setting;
  155180. hi->managed=0;
  155181. hi->impulse_block_p=1;
  155182. hi->noise_normalize_p=1;
  155183. hi->stereo_point_setting=hi->base_setting;
  155184. hi->lowpass_kHz=
  155185. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155186. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155187. setup->psy_ath_float[is+1]*ds;
  155188. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155189. setup->psy_ath_abs[is+1]*ds;
  155190. hi->amplitude_track_dBpersec=-6.;
  155191. hi->trigger_setting=hi->base_setting;
  155192. for(i=0;i<4;i++){
  155193. hi->block[i].tone_mask_setting=hi->base_setting;
  155194. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155195. hi->block[i].noise_bias_setting=hi->base_setting;
  155196. hi->block[i].noise_compand_setting=hi->base_setting;
  155197. }
  155198. return(ret);
  155199. }
  155200. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155201. long channels,
  155202. long rate,
  155203. float quality){
  155204. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155205. highlevel_encode_setup *hi=&ci->hi;
  155206. quality+=.0000001;
  155207. if(quality>=1.)quality=.9999;
  155208. get_setup_template(vi,channels,rate,quality,0);
  155209. if(!hi->setup)return OV_EIMPL;
  155210. return vorbis_encode_setup_setting(vi,channels,rate);
  155211. }
  155212. int vorbis_encode_init_vbr(vorbis_info *vi,
  155213. long channels,
  155214. long rate,
  155215. float base_quality /* 0. to 1. */
  155216. ){
  155217. int ret=0;
  155218. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155219. if(ret){
  155220. vorbis_info_clear(vi);
  155221. return ret;
  155222. }
  155223. ret=vorbis_encode_setup_init(vi);
  155224. if(ret)
  155225. vorbis_info_clear(vi);
  155226. return(ret);
  155227. }
  155228. int vorbis_encode_setup_managed(vorbis_info *vi,
  155229. long channels,
  155230. long rate,
  155231. long max_bitrate,
  155232. long nominal_bitrate,
  155233. long min_bitrate){
  155234. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155235. highlevel_encode_setup *hi=&ci->hi;
  155236. double tnominal=nominal_bitrate;
  155237. int ret=0;
  155238. if(nominal_bitrate<=0.){
  155239. if(max_bitrate>0.){
  155240. if(min_bitrate>0.)
  155241. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155242. else
  155243. nominal_bitrate=max_bitrate*.875;
  155244. }else{
  155245. if(min_bitrate>0.){
  155246. nominal_bitrate=min_bitrate;
  155247. }else{
  155248. return(OV_EINVAL);
  155249. }
  155250. }
  155251. }
  155252. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155253. if(!hi->setup)return OV_EIMPL;
  155254. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155255. if(ret){
  155256. vorbis_info_clear(vi);
  155257. return ret;
  155258. }
  155259. /* initialize management with sane defaults */
  155260. hi->managed=1;
  155261. hi->bitrate_min=min_bitrate;
  155262. hi->bitrate_max=max_bitrate;
  155263. hi->bitrate_av=tnominal;
  155264. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155265. hi->bitrate_reservoir=nominal_bitrate*2;
  155266. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155267. return(ret);
  155268. }
  155269. int vorbis_encode_init(vorbis_info *vi,
  155270. long channels,
  155271. long rate,
  155272. long max_bitrate,
  155273. long nominal_bitrate,
  155274. long min_bitrate){
  155275. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155276. max_bitrate,
  155277. nominal_bitrate,
  155278. min_bitrate);
  155279. if(ret){
  155280. vorbis_info_clear(vi);
  155281. return(ret);
  155282. }
  155283. ret=vorbis_encode_setup_init(vi);
  155284. if(ret)
  155285. vorbis_info_clear(vi);
  155286. return(ret);
  155287. }
  155288. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155289. if(vi){
  155290. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155291. highlevel_encode_setup *hi=&ci->hi;
  155292. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155293. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155294. switch(number){
  155295. /* now deprecated *****************/
  155296. case OV_ECTL_RATEMANAGE_GET:
  155297. {
  155298. struct ovectl_ratemanage_arg *ai=
  155299. (struct ovectl_ratemanage_arg *)arg;
  155300. ai->management_active=hi->managed;
  155301. ai->bitrate_hard_window=ai->bitrate_av_window=
  155302. (double)hi->bitrate_reservoir/vi->rate;
  155303. ai->bitrate_av_window_center=1.;
  155304. ai->bitrate_hard_min=hi->bitrate_min;
  155305. ai->bitrate_hard_max=hi->bitrate_max;
  155306. ai->bitrate_av_lo=hi->bitrate_av;
  155307. ai->bitrate_av_hi=hi->bitrate_av;
  155308. }
  155309. return(0);
  155310. /* now deprecated *****************/
  155311. case OV_ECTL_RATEMANAGE_SET:
  155312. {
  155313. struct ovectl_ratemanage_arg *ai=
  155314. (struct ovectl_ratemanage_arg *)arg;
  155315. if(ai==NULL){
  155316. hi->managed=0;
  155317. }else{
  155318. hi->managed=ai->management_active;
  155319. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155320. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155321. }
  155322. }
  155323. return 0;
  155324. /* now deprecated *****************/
  155325. case OV_ECTL_RATEMANAGE_AVG:
  155326. {
  155327. struct ovectl_ratemanage_arg *ai=
  155328. (struct ovectl_ratemanage_arg *)arg;
  155329. if(ai==NULL){
  155330. hi->bitrate_av=0;
  155331. }else{
  155332. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155333. }
  155334. }
  155335. return(0);
  155336. /* now deprecated *****************/
  155337. case OV_ECTL_RATEMANAGE_HARD:
  155338. {
  155339. struct ovectl_ratemanage_arg *ai=
  155340. (struct ovectl_ratemanage_arg *)arg;
  155341. if(ai==NULL){
  155342. hi->bitrate_min=0;
  155343. hi->bitrate_max=0;
  155344. }else{
  155345. hi->bitrate_min=ai->bitrate_hard_min;
  155346. hi->bitrate_max=ai->bitrate_hard_max;
  155347. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155348. (hi->bitrate_max+hi->bitrate_min)*.5;
  155349. }
  155350. if(hi->bitrate_reservoir<128.)
  155351. hi->bitrate_reservoir=128.;
  155352. }
  155353. return(0);
  155354. /* replacement ratemanage interface */
  155355. case OV_ECTL_RATEMANAGE2_GET:
  155356. {
  155357. struct ovectl_ratemanage2_arg *ai=
  155358. (struct ovectl_ratemanage2_arg *)arg;
  155359. if(ai==NULL)return OV_EINVAL;
  155360. ai->management_active=hi->managed;
  155361. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155362. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155363. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155364. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155365. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155366. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155367. }
  155368. return (0);
  155369. case OV_ECTL_RATEMANAGE2_SET:
  155370. {
  155371. struct ovectl_ratemanage2_arg *ai=
  155372. (struct ovectl_ratemanage2_arg *)arg;
  155373. if(ai==NULL){
  155374. hi->managed=0;
  155375. }else{
  155376. /* sanity check; only catch invariant violations */
  155377. if(ai->bitrate_limit_min_kbps>0 &&
  155378. ai->bitrate_average_kbps>0 &&
  155379. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155380. return OV_EINVAL;
  155381. if(ai->bitrate_limit_max_kbps>0 &&
  155382. ai->bitrate_average_kbps>0 &&
  155383. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155384. return OV_EINVAL;
  155385. if(ai->bitrate_limit_min_kbps>0 &&
  155386. ai->bitrate_limit_max_kbps>0 &&
  155387. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155388. return OV_EINVAL;
  155389. if(ai->bitrate_average_damping <= 0.)
  155390. return OV_EINVAL;
  155391. if(ai->bitrate_limit_reservoir_bits < 0)
  155392. return OV_EINVAL;
  155393. if(ai->bitrate_limit_reservoir_bias < 0.)
  155394. return OV_EINVAL;
  155395. if(ai->bitrate_limit_reservoir_bias > 1.)
  155396. return OV_EINVAL;
  155397. hi->managed=ai->management_active;
  155398. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155399. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155400. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155401. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155402. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155403. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155404. }
  155405. }
  155406. return 0;
  155407. case OV_ECTL_LOWPASS_GET:
  155408. {
  155409. double *farg=(double *)arg;
  155410. *farg=hi->lowpass_kHz;
  155411. }
  155412. return(0);
  155413. case OV_ECTL_LOWPASS_SET:
  155414. {
  155415. double *farg=(double *)arg;
  155416. hi->lowpass_kHz=*farg;
  155417. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155418. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155419. }
  155420. return(0);
  155421. case OV_ECTL_IBLOCK_GET:
  155422. {
  155423. double *farg=(double *)arg;
  155424. *farg=hi->impulse_noisetune;
  155425. }
  155426. return(0);
  155427. case OV_ECTL_IBLOCK_SET:
  155428. {
  155429. double *farg=(double *)arg;
  155430. hi->impulse_noisetune=*farg;
  155431. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155432. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155433. }
  155434. return(0);
  155435. }
  155436. return(OV_EIMPL);
  155437. }
  155438. return(OV_EINVAL);
  155439. }
  155440. #endif
  155441. /*** End of inlined file: vorbisenc.c ***/
  155442. /*** Start of inlined file: vorbisfile.c ***/
  155443. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155444. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155445. // tasks..
  155446. #if JUCE_MSVC
  155447. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155448. #endif
  155449. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155450. #if JUCE_USE_OGGVORBIS
  155451. #include <stdlib.h>
  155452. #include <stdio.h>
  155453. #include <errno.h>
  155454. #include <string.h>
  155455. #include <math.h>
  155456. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155457. one logical bitstream arranged end to end (the only form of Ogg
  155458. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155459. multiplexing] is not allowed in Vorbis) */
  155460. /* A Vorbis file can be played beginning to end (streamed) without
  155461. worrying ahead of time about chaining (see decoder_example.c). If
  155462. we have the whole file, however, and want random access
  155463. (seeking/scrubbing) or desire to know the total length/time of a
  155464. file, we need to account for the possibility of chaining. */
  155465. /* We can handle things a number of ways; we can determine the entire
  155466. bitstream structure right off the bat, or find pieces on demand.
  155467. This example determines and caches structure for the entire
  155468. bitstream, but builds a virtual decoder on the fly when moving
  155469. between links in the chain. */
  155470. /* There are also different ways to implement seeking. Enough
  155471. information exists in an Ogg bitstream to seek to
  155472. sample-granularity positions in the output. Or, one can seek by
  155473. picking some portion of the stream roughly in the desired area if
  155474. we only want coarse navigation through the stream. */
  155475. /*************************************************************************
  155476. * Many, many internal helpers. The intention is not to be confusing;
  155477. * rampant duplication and monolithic function implementation would be
  155478. * harder to understand anyway. The high level functions are last. Begin
  155479. * grokking near the end of the file */
  155480. /* read a little more data from the file/pipe into the ogg_sync framer
  155481. */
  155482. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155483. over 8k gets what they deserve */
  155484. static long _get_data(OggVorbis_File *vf){
  155485. errno=0;
  155486. if(vf->datasource){
  155487. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155488. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155489. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155490. if(bytes==0 && errno)return(-1);
  155491. return(bytes);
  155492. }else
  155493. return(0);
  155494. }
  155495. /* save a tiny smidge of verbosity to make the code more readable */
  155496. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155497. if(vf->datasource){
  155498. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155499. vf->offset=offset;
  155500. ogg_sync_reset(&vf->oy);
  155501. }else{
  155502. /* shouldn't happen unless someone writes a broken callback */
  155503. return;
  155504. }
  155505. }
  155506. /* The read/seek functions track absolute position within the stream */
  155507. /* from the head of the stream, get the next page. boundary specifies
  155508. if the function is allowed to fetch more data from the stream (and
  155509. how much) or only use internally buffered data.
  155510. boundary: -1) unbounded search
  155511. 0) read no additional data; use cached only
  155512. n) search for a new page beginning for n bytes
  155513. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155514. n) found a page at absolute offset n */
  155515. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155516. ogg_int64_t boundary){
  155517. if(boundary>0)boundary+=vf->offset;
  155518. while(1){
  155519. long more;
  155520. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155521. more=ogg_sync_pageseek(&vf->oy,og);
  155522. if(more<0){
  155523. /* skipped n bytes */
  155524. vf->offset-=more;
  155525. }else{
  155526. if(more==0){
  155527. /* send more paramedics */
  155528. if(!boundary)return(OV_FALSE);
  155529. {
  155530. long ret=_get_data(vf);
  155531. if(ret==0)return(OV_EOF);
  155532. if(ret<0)return(OV_EREAD);
  155533. }
  155534. }else{
  155535. /* got a page. Return the offset at the page beginning,
  155536. advance the internal offset past the page end */
  155537. ogg_int64_t ret=vf->offset;
  155538. vf->offset+=more;
  155539. return(ret);
  155540. }
  155541. }
  155542. }
  155543. }
  155544. /* find the latest page beginning before the current stream cursor
  155545. position. Much dirtier than the above as Ogg doesn't have any
  155546. backward search linkage. no 'readp' as it will certainly have to
  155547. read. */
  155548. /* returns offset or OV_EREAD, OV_FAULT */
  155549. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155550. ogg_int64_t begin=vf->offset;
  155551. ogg_int64_t end=begin;
  155552. ogg_int64_t ret;
  155553. ogg_int64_t offset=-1;
  155554. while(offset==-1){
  155555. begin-=CHUNKSIZE;
  155556. if(begin<0)
  155557. begin=0;
  155558. _seek_helper(vf,begin);
  155559. while(vf->offset<end){
  155560. ret=_get_next_page(vf,og,end-vf->offset);
  155561. if(ret==OV_EREAD)return(OV_EREAD);
  155562. if(ret<0){
  155563. break;
  155564. }else{
  155565. offset=ret;
  155566. }
  155567. }
  155568. }
  155569. /* we have the offset. Actually snork and hold the page now */
  155570. _seek_helper(vf,offset);
  155571. ret=_get_next_page(vf,og,CHUNKSIZE);
  155572. if(ret<0)
  155573. /* this shouldn't be possible */
  155574. return(OV_EFAULT);
  155575. return(offset);
  155576. }
  155577. /* finds each bitstream link one at a time using a bisection search
  155578. (has to begin by knowing the offset of the lb's initial page).
  155579. Recurses for each link so it can alloc the link storage after
  155580. finding them all, then unroll and fill the cache at the same time */
  155581. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155582. ogg_int64_t begin,
  155583. ogg_int64_t searched,
  155584. ogg_int64_t end,
  155585. long currentno,
  155586. long m){
  155587. ogg_int64_t endsearched=end;
  155588. ogg_int64_t next=end;
  155589. ogg_page og;
  155590. ogg_int64_t ret;
  155591. /* the below guards against garbage seperating the last and
  155592. first pages of two links. */
  155593. while(searched<endsearched){
  155594. ogg_int64_t bisect;
  155595. if(endsearched-searched<CHUNKSIZE){
  155596. bisect=searched;
  155597. }else{
  155598. bisect=(searched+endsearched)/2;
  155599. }
  155600. _seek_helper(vf,bisect);
  155601. ret=_get_next_page(vf,&og,-1);
  155602. if(ret==OV_EREAD)return(OV_EREAD);
  155603. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155604. endsearched=bisect;
  155605. if(ret>=0)next=ret;
  155606. }else{
  155607. searched=ret+og.header_len+og.body_len;
  155608. }
  155609. }
  155610. _seek_helper(vf,next);
  155611. ret=_get_next_page(vf,&og,-1);
  155612. if(ret==OV_EREAD)return(OV_EREAD);
  155613. if(searched>=end || ret<0){
  155614. vf->links=m+1;
  155615. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155616. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155617. vf->offsets[m+1]=searched;
  155618. }else{
  155619. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155620. end,ogg_page_serialno(&og),m+1);
  155621. if(ret==OV_EREAD)return(OV_EREAD);
  155622. }
  155623. vf->offsets[m]=begin;
  155624. vf->serialnos[m]=currentno;
  155625. return(0);
  155626. }
  155627. /* uses the local ogg_stream storage in vf; this is important for
  155628. non-streaming input sources */
  155629. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155630. long *serialno,ogg_page *og_ptr){
  155631. ogg_page og;
  155632. ogg_packet op;
  155633. int i,ret;
  155634. if(!og_ptr){
  155635. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155636. if(llret==OV_EREAD)return(OV_EREAD);
  155637. if(llret<0)return OV_ENOTVORBIS;
  155638. og_ptr=&og;
  155639. }
  155640. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155641. if(serialno)*serialno=vf->os.serialno;
  155642. vf->ready_state=STREAMSET;
  155643. /* extract the initial header from the first page and verify that the
  155644. Ogg bitstream is in fact Vorbis data */
  155645. vorbis_info_init(vi);
  155646. vorbis_comment_init(vc);
  155647. i=0;
  155648. while(i<3){
  155649. ogg_stream_pagein(&vf->os,og_ptr);
  155650. while(i<3){
  155651. int result=ogg_stream_packetout(&vf->os,&op);
  155652. if(result==0)break;
  155653. if(result==-1){
  155654. ret=OV_EBADHEADER;
  155655. goto bail_header;
  155656. }
  155657. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155658. goto bail_header;
  155659. }
  155660. i++;
  155661. }
  155662. if(i<3)
  155663. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155664. ret=OV_EBADHEADER;
  155665. goto bail_header;
  155666. }
  155667. }
  155668. return 0;
  155669. bail_header:
  155670. vorbis_info_clear(vi);
  155671. vorbis_comment_clear(vc);
  155672. vf->ready_state=OPENED;
  155673. return ret;
  155674. }
  155675. /* last step of the OggVorbis_File initialization; get all the
  155676. vorbis_info structs and PCM positions. Only called by the seekable
  155677. initialization (local stream storage is hacked slightly; pay
  155678. attention to how that's done) */
  155679. /* this is void and does not propogate errors up because we want to be
  155680. able to open and use damaged bitstreams as well as we can. Just
  155681. watch out for missing information for links in the OggVorbis_File
  155682. struct */
  155683. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155684. ogg_page og;
  155685. int i;
  155686. ogg_int64_t ret;
  155687. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155688. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155689. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155690. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155691. for(i=0;i<vf->links;i++){
  155692. if(i==0){
  155693. /* we already grabbed the initial header earlier. Just set the offset */
  155694. vf->dataoffsets[i]=dataoffset;
  155695. _seek_helper(vf,dataoffset);
  155696. }else{
  155697. /* seek to the location of the initial header */
  155698. _seek_helper(vf,vf->offsets[i]);
  155699. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155700. vf->dataoffsets[i]=-1;
  155701. }else{
  155702. vf->dataoffsets[i]=vf->offset;
  155703. }
  155704. }
  155705. /* fetch beginning PCM offset */
  155706. if(vf->dataoffsets[i]!=-1){
  155707. ogg_int64_t accumulated=0;
  155708. long lastblock=-1;
  155709. int result;
  155710. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155711. while(1){
  155712. ogg_packet op;
  155713. ret=_get_next_page(vf,&og,-1);
  155714. if(ret<0)
  155715. /* this should not be possible unless the file is
  155716. truncated/mangled */
  155717. break;
  155718. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155719. break;
  155720. /* count blocksizes of all frames in the page */
  155721. ogg_stream_pagein(&vf->os,&og);
  155722. while((result=ogg_stream_packetout(&vf->os,&op))){
  155723. if(result>0){ /* ignore holes */
  155724. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155725. if(lastblock!=-1)
  155726. accumulated+=(lastblock+thisblock)>>2;
  155727. lastblock=thisblock;
  155728. }
  155729. }
  155730. if(ogg_page_granulepos(&og)!=-1){
  155731. /* pcm offset of last packet on the first audio page */
  155732. accumulated= ogg_page_granulepos(&og)-accumulated;
  155733. break;
  155734. }
  155735. }
  155736. /* less than zero? This is a stream with samples trimmed off
  155737. the beginning, a normal occurrence; set the offset to zero */
  155738. if(accumulated<0)accumulated=0;
  155739. vf->pcmlengths[i*2]=accumulated;
  155740. }
  155741. /* get the PCM length of this link. To do this,
  155742. get the last page of the stream */
  155743. {
  155744. ogg_int64_t end=vf->offsets[i+1];
  155745. _seek_helper(vf,end);
  155746. while(1){
  155747. ret=_get_prev_page(vf,&og);
  155748. if(ret<0){
  155749. /* this should not be possible */
  155750. vorbis_info_clear(vf->vi+i);
  155751. vorbis_comment_clear(vf->vc+i);
  155752. break;
  155753. }
  155754. if(ogg_page_granulepos(&og)!=-1){
  155755. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155756. break;
  155757. }
  155758. vf->offset=ret;
  155759. }
  155760. }
  155761. }
  155762. }
  155763. static int _make_decode_ready(OggVorbis_File *vf){
  155764. if(vf->ready_state>STREAMSET)return 0;
  155765. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155766. if(vf->seekable){
  155767. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155768. return OV_EBADLINK;
  155769. }else{
  155770. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155771. return OV_EBADLINK;
  155772. }
  155773. vorbis_block_init(&vf->vd,&vf->vb);
  155774. vf->ready_state=INITSET;
  155775. vf->bittrack=0.f;
  155776. vf->samptrack=0.f;
  155777. return 0;
  155778. }
  155779. static int _open_seekable2(OggVorbis_File *vf){
  155780. long serialno=vf->current_serialno;
  155781. ogg_int64_t dataoffset=vf->offset, end;
  155782. ogg_page og;
  155783. /* we're partially open and have a first link header state in
  155784. storage in vf */
  155785. /* we can seek, so set out learning all about this file */
  155786. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155787. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155788. /* We get the offset for the last page of the physical bitstream.
  155789. Most OggVorbis files will contain a single logical bitstream */
  155790. end=_get_prev_page(vf,&og);
  155791. if(end<0)return(end);
  155792. /* more than one logical bitstream? */
  155793. if(ogg_page_serialno(&og)!=serialno){
  155794. /* Chained bitstream. Bisect-search each logical bitstream
  155795. section. Do so based on serial number only */
  155796. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155797. }else{
  155798. /* Only one logical bitstream */
  155799. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155800. }
  155801. /* the initial header memory is referenced by vf after; don't free it */
  155802. _prefetch_all_headers(vf,dataoffset);
  155803. return(ov_raw_seek(vf,0));
  155804. }
  155805. /* clear out the current logical bitstream decoder */
  155806. static void _decode_clear(OggVorbis_File *vf){
  155807. vorbis_dsp_clear(&vf->vd);
  155808. vorbis_block_clear(&vf->vb);
  155809. vf->ready_state=OPENED;
  155810. }
  155811. /* fetch and process a packet. Handles the case where we're at a
  155812. bitstream boundary and dumps the decoding machine. If the decoding
  155813. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155814. date (seek and read both use this. seek uses a special hack with
  155815. readp).
  155816. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155817. 0) need more data (only if readp==0)
  155818. 1) got a packet
  155819. */
  155820. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155821. ogg_packet *op_in,
  155822. int readp,
  155823. int spanp){
  155824. ogg_page og;
  155825. /* handle one packet. Try to fetch it from current stream state */
  155826. /* extract packets from page */
  155827. while(1){
  155828. /* process a packet if we can. If the machine isn't loaded,
  155829. neither is a page */
  155830. if(vf->ready_state==INITSET){
  155831. while(1) {
  155832. ogg_packet op;
  155833. ogg_packet *op_ptr=(op_in?op_in:&op);
  155834. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155835. ogg_int64_t granulepos;
  155836. op_in=NULL;
  155837. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155838. if(result>0){
  155839. /* got a packet. process it */
  155840. granulepos=op_ptr->granulepos;
  155841. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155842. header handling. The
  155843. header packets aren't
  155844. audio, so if/when we
  155845. submit them,
  155846. vorbis_synthesis will
  155847. reject them */
  155848. /* suck in the synthesis data and track bitrate */
  155849. {
  155850. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155851. /* for proper use of libvorbis within libvorbisfile,
  155852. oldsamples will always be zero. */
  155853. if(oldsamples)return(OV_EFAULT);
  155854. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155855. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155856. vf->bittrack+=op_ptr->bytes*8;
  155857. }
  155858. /* update the pcm offset. */
  155859. if(granulepos!=-1 && !op_ptr->e_o_s){
  155860. int link=(vf->seekable?vf->current_link:0);
  155861. int i,samples;
  155862. /* this packet has a pcm_offset on it (the last packet
  155863. completed on a page carries the offset) After processing
  155864. (above), we know the pcm position of the *last* sample
  155865. ready to be returned. Find the offset of the *first*
  155866. As an aside, this trick is inaccurate if we begin
  155867. reading anew right at the last page; the end-of-stream
  155868. granulepos declares the last frame in the stream, and the
  155869. last packet of the last page may be a partial frame.
  155870. So, we need a previous granulepos from an in-sequence page
  155871. to have a reference point. Thus the !op_ptr->e_o_s clause
  155872. above */
  155873. if(vf->seekable && link>0)
  155874. granulepos-=vf->pcmlengths[link*2];
  155875. if(granulepos<0)granulepos=0; /* actually, this
  155876. shouldn't be possible
  155877. here unless the stream
  155878. is very broken */
  155879. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155880. granulepos-=samples;
  155881. for(i=0;i<link;i++)
  155882. granulepos+=vf->pcmlengths[i*2+1];
  155883. vf->pcm_offset=granulepos;
  155884. }
  155885. return(1);
  155886. }
  155887. }
  155888. else
  155889. break;
  155890. }
  155891. }
  155892. if(vf->ready_state>=OPENED){
  155893. ogg_int64_t ret;
  155894. if(!readp)return(0);
  155895. if((ret=_get_next_page(vf,&og,-1))<0){
  155896. return(OV_EOF); /* eof.
  155897. leave unitialized */
  155898. }
  155899. /* bitrate tracking; add the header's bytes here, the body bytes
  155900. are done by packet above */
  155901. vf->bittrack+=og.header_len*8;
  155902. /* has our decoding just traversed a bitstream boundary? */
  155903. if(vf->ready_state==INITSET){
  155904. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155905. if(!spanp)
  155906. return(OV_EOF);
  155907. _decode_clear(vf);
  155908. if(!vf->seekable){
  155909. vorbis_info_clear(vf->vi);
  155910. vorbis_comment_clear(vf->vc);
  155911. }
  155912. }
  155913. }
  155914. }
  155915. /* Do we need to load a new machine before submitting the page? */
  155916. /* This is different in the seekable and non-seekable cases.
  155917. In the seekable case, we already have all the header
  155918. information loaded and cached; we just initialize the machine
  155919. with it and continue on our merry way.
  155920. In the non-seekable (streaming) case, we'll only be at a
  155921. boundary if we just left the previous logical bitstream and
  155922. we're now nominally at the header of the next bitstream
  155923. */
  155924. if(vf->ready_state!=INITSET){
  155925. int link;
  155926. if(vf->ready_state<STREAMSET){
  155927. if(vf->seekable){
  155928. vf->current_serialno=ogg_page_serialno(&og);
  155929. /* match the serialno to bitstream section. We use this rather than
  155930. offset positions to avoid problems near logical bitstream
  155931. boundaries */
  155932. for(link=0;link<vf->links;link++)
  155933. if(vf->serialnos[link]==vf->current_serialno)break;
  155934. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155935. stream. error out,
  155936. leave machine
  155937. uninitialized */
  155938. vf->current_link=link;
  155939. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155940. vf->ready_state=STREAMSET;
  155941. }else{
  155942. /* we're streaming */
  155943. /* fetch the three header packets, build the info struct */
  155944. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155945. if(ret)return(ret);
  155946. vf->current_link++;
  155947. link=0;
  155948. }
  155949. }
  155950. {
  155951. int ret=_make_decode_ready(vf);
  155952. if(ret<0)return ret;
  155953. }
  155954. }
  155955. ogg_stream_pagein(&vf->os,&og);
  155956. }
  155957. }
  155958. /* if, eg, 64 bit stdio is configured by default, this will build with
  155959. fseek64 */
  155960. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155961. if(f==NULL)return(-1);
  155962. return fseek(f,off,whence);
  155963. }
  155964. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155965. long ibytes, ov_callbacks callbacks){
  155966. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155967. int ret;
  155968. memset(vf,0,sizeof(*vf));
  155969. vf->datasource=f;
  155970. vf->callbacks = callbacks;
  155971. /* init the framing state */
  155972. ogg_sync_init(&vf->oy);
  155973. /* perhaps some data was previously read into a buffer for testing
  155974. against other stream types. Allow initialization from this
  155975. previously read data (as we may be reading from a non-seekable
  155976. stream) */
  155977. if(initial){
  155978. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155979. memcpy(buffer,initial,ibytes);
  155980. ogg_sync_wrote(&vf->oy,ibytes);
  155981. }
  155982. /* can we seek? Stevens suggests the seek test was portable */
  155983. if(offsettest!=-1)vf->seekable=1;
  155984. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155985. entry for partial open */
  155986. vf->links=1;
  155987. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155988. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155989. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155990. /* Try to fetch the headers, maintaining all the storage */
  155991. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155992. vf->datasource=NULL;
  155993. ov_clear(vf);
  155994. }else
  155995. vf->ready_state=PARTOPEN;
  155996. return(ret);
  155997. }
  155998. static int _ov_open2(OggVorbis_File *vf){
  155999. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  156000. vf->ready_state=OPENED;
  156001. if(vf->seekable){
  156002. int ret=_open_seekable2(vf);
  156003. if(ret){
  156004. vf->datasource=NULL;
  156005. ov_clear(vf);
  156006. }
  156007. return(ret);
  156008. }else
  156009. vf->ready_state=STREAMSET;
  156010. return 0;
  156011. }
  156012. /* clear out the OggVorbis_File struct */
  156013. int ov_clear(OggVorbis_File *vf){
  156014. if(vf){
  156015. vorbis_block_clear(&vf->vb);
  156016. vorbis_dsp_clear(&vf->vd);
  156017. ogg_stream_clear(&vf->os);
  156018. if(vf->vi && vf->links){
  156019. int i;
  156020. for(i=0;i<vf->links;i++){
  156021. vorbis_info_clear(vf->vi+i);
  156022. vorbis_comment_clear(vf->vc+i);
  156023. }
  156024. _ogg_free(vf->vi);
  156025. _ogg_free(vf->vc);
  156026. }
  156027. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  156028. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  156029. if(vf->serialnos)_ogg_free(vf->serialnos);
  156030. if(vf->offsets)_ogg_free(vf->offsets);
  156031. ogg_sync_clear(&vf->oy);
  156032. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  156033. memset(vf,0,sizeof(*vf));
  156034. }
  156035. #ifdef DEBUG_LEAKS
  156036. _VDBG_dump();
  156037. #endif
  156038. return(0);
  156039. }
  156040. /* inspects the OggVorbis file and finds/documents all the logical
  156041. bitstreams contained in it. Tries to be tolerant of logical
  156042. bitstream sections that are truncated/woogie.
  156043. return: -1) error
  156044. 0) OK
  156045. */
  156046. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156047. ov_callbacks callbacks){
  156048. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156049. if(ret)return ret;
  156050. return _ov_open2(vf);
  156051. }
  156052. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156053. ov_callbacks callbacks = {
  156054. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156055. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156056. (int (*)(void *)) fclose,
  156057. (long (*)(void *)) ftell
  156058. };
  156059. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156060. }
  156061. /* cheap hack for game usage where downsampling is desirable; there's
  156062. no need for SRC as we can just do it cheaply in libvorbis. */
  156063. int ov_halfrate(OggVorbis_File *vf,int flag){
  156064. int i;
  156065. if(vf->vi==NULL)return OV_EINVAL;
  156066. if(!vf->seekable)return OV_EINVAL;
  156067. if(vf->ready_state>=STREAMSET)
  156068. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156069. will be able to swap this on the fly, but
  156070. for now dumping the decode machine is needed
  156071. to reinit the MDCT lookups. 1.1 libvorbis
  156072. is planned to be able to switch on the fly */
  156073. for(i=0;i<vf->links;i++){
  156074. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156075. ov_halfrate(vf,0);
  156076. return OV_EINVAL;
  156077. }
  156078. }
  156079. return 0;
  156080. }
  156081. int ov_halfrate_p(OggVorbis_File *vf){
  156082. if(vf->vi==NULL)return OV_EINVAL;
  156083. return vorbis_synthesis_halfrate_p(vf->vi);
  156084. }
  156085. /* Only partially open the vorbis file; test for Vorbisness, and load
  156086. the headers for the first chain. Do not seek (although test for
  156087. seekability). Use ov_test_open to finish opening the file, else
  156088. ov_clear to close/free it. Same return codes as open. */
  156089. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156090. ov_callbacks callbacks)
  156091. {
  156092. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156093. }
  156094. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156095. ov_callbacks callbacks = {
  156096. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156097. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156098. (int (*)(void *)) fclose,
  156099. (long (*)(void *)) ftell
  156100. };
  156101. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156102. }
  156103. int ov_test_open(OggVorbis_File *vf){
  156104. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156105. return _ov_open2(vf);
  156106. }
  156107. /* How many logical bitstreams in this physical bitstream? */
  156108. long ov_streams(OggVorbis_File *vf){
  156109. return vf->links;
  156110. }
  156111. /* Is the FILE * associated with vf seekable? */
  156112. long ov_seekable(OggVorbis_File *vf){
  156113. return vf->seekable;
  156114. }
  156115. /* returns the bitrate for a given logical bitstream or the entire
  156116. physical bitstream. If the file is open for random access, it will
  156117. find the *actual* average bitrate. If the file is streaming, it
  156118. returns the nominal bitrate (if set) else the average of the
  156119. upper/lower bounds (if set) else -1 (unset).
  156120. If you want the actual bitrate field settings, get them from the
  156121. vorbis_info structs */
  156122. long ov_bitrate(OggVorbis_File *vf,int i){
  156123. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156124. if(i>=vf->links)return(OV_EINVAL);
  156125. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156126. if(i<0){
  156127. ogg_int64_t bits=0;
  156128. int i;
  156129. float br;
  156130. for(i=0;i<vf->links;i++)
  156131. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156132. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156133. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156134. * so this is slightly transformed to make it work.
  156135. */
  156136. br = bits/ov_time_total(vf,-1);
  156137. return(rint(br));
  156138. }else{
  156139. if(vf->seekable){
  156140. /* return the actual bitrate */
  156141. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156142. }else{
  156143. /* return nominal if set */
  156144. if(vf->vi[i].bitrate_nominal>0){
  156145. return vf->vi[i].bitrate_nominal;
  156146. }else{
  156147. if(vf->vi[i].bitrate_upper>0){
  156148. if(vf->vi[i].bitrate_lower>0){
  156149. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156150. }else{
  156151. return vf->vi[i].bitrate_upper;
  156152. }
  156153. }
  156154. return(OV_FALSE);
  156155. }
  156156. }
  156157. }
  156158. }
  156159. /* returns the actual bitrate since last call. returns -1 if no
  156160. additional data to offer since last call (or at beginning of stream),
  156161. EINVAL if stream is only partially open
  156162. */
  156163. long ov_bitrate_instant(OggVorbis_File *vf){
  156164. int link=(vf->seekable?vf->current_link:0);
  156165. long ret;
  156166. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156167. if(vf->samptrack==0)return(OV_FALSE);
  156168. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156169. vf->bittrack=0.f;
  156170. vf->samptrack=0.f;
  156171. return(ret);
  156172. }
  156173. /* Guess */
  156174. long ov_serialnumber(OggVorbis_File *vf,int i){
  156175. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156176. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156177. if(i<0){
  156178. return(vf->current_serialno);
  156179. }else{
  156180. return(vf->serialnos[i]);
  156181. }
  156182. }
  156183. /* returns: total raw (compressed) length of content if i==-1
  156184. raw (compressed) length of that logical bitstream for i==0 to n
  156185. OV_EINVAL if the stream is not seekable (we can't know the length)
  156186. or if stream is only partially open
  156187. */
  156188. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156189. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156190. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156191. if(i<0){
  156192. ogg_int64_t acc=0;
  156193. int i;
  156194. for(i=0;i<vf->links;i++)
  156195. acc+=ov_raw_total(vf,i);
  156196. return(acc);
  156197. }else{
  156198. return(vf->offsets[i+1]-vf->offsets[i]);
  156199. }
  156200. }
  156201. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156202. (samples) of that logical bitstream for i==0 to n
  156203. OV_EINVAL if the stream is not seekable (we can't know the
  156204. length) or only partially open
  156205. */
  156206. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156207. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156208. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156209. if(i<0){
  156210. ogg_int64_t acc=0;
  156211. int i;
  156212. for(i=0;i<vf->links;i++)
  156213. acc+=ov_pcm_total(vf,i);
  156214. return(acc);
  156215. }else{
  156216. return(vf->pcmlengths[i*2+1]);
  156217. }
  156218. }
  156219. /* returns: total seconds of content if i==-1
  156220. seconds in that logical bitstream for i==0 to n
  156221. OV_EINVAL if the stream is not seekable (we can't know the
  156222. length) or only partially open
  156223. */
  156224. double ov_time_total(OggVorbis_File *vf,int i){
  156225. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156226. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156227. if(i<0){
  156228. double acc=0;
  156229. int i;
  156230. for(i=0;i<vf->links;i++)
  156231. acc+=ov_time_total(vf,i);
  156232. return(acc);
  156233. }else{
  156234. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156235. }
  156236. }
  156237. /* seek to an offset relative to the *compressed* data. This also
  156238. scans packets to update the PCM cursor. It will cross a logical
  156239. bitstream boundary, but only if it can't get any packets out of the
  156240. tail of the bitstream we seek to (so no surprises).
  156241. returns zero on success, nonzero on failure */
  156242. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156243. ogg_stream_state work_os;
  156244. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156245. if(!vf->seekable)
  156246. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156247. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156248. /* don't yet clear out decoding machine (if it's initialized), in
  156249. the case we're in the same link. Restart the decode lapping, and
  156250. let _fetch_and_process_packet deal with a potential bitstream
  156251. boundary */
  156252. vf->pcm_offset=-1;
  156253. ogg_stream_reset_serialno(&vf->os,
  156254. vf->current_serialno); /* must set serialno */
  156255. vorbis_synthesis_restart(&vf->vd);
  156256. _seek_helper(vf,pos);
  156257. /* we need to make sure the pcm_offset is set, but we don't want to
  156258. advance the raw cursor past good packets just to get to the first
  156259. with a granulepos. That's not equivalent behavior to beginning
  156260. decoding as immediately after the seek position as possible.
  156261. So, a hack. We use two stream states; a local scratch state and
  156262. the shared vf->os stream state. We use the local state to
  156263. scan, and the shared state as a buffer for later decode.
  156264. Unfortuantely, on the last page we still advance to last packet
  156265. because the granulepos on the last page is not necessarily on a
  156266. packet boundary, and we need to make sure the granpos is
  156267. correct.
  156268. */
  156269. {
  156270. ogg_page og;
  156271. ogg_packet op;
  156272. int lastblock=0;
  156273. int accblock=0;
  156274. int thisblock;
  156275. int eosflag;
  156276. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156277. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156278. return from not necessarily
  156279. starting from the beginning */
  156280. while(1){
  156281. if(vf->ready_state>=STREAMSET){
  156282. /* snarf/scan a packet if we can */
  156283. int result=ogg_stream_packetout(&work_os,&op);
  156284. if(result>0){
  156285. if(vf->vi[vf->current_link].codec_setup){
  156286. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156287. if(thisblock<0){
  156288. ogg_stream_packetout(&vf->os,NULL);
  156289. thisblock=0;
  156290. }else{
  156291. if(eosflag)
  156292. ogg_stream_packetout(&vf->os,NULL);
  156293. else
  156294. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156295. }
  156296. if(op.granulepos!=-1){
  156297. int i,link=vf->current_link;
  156298. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156299. if(granulepos<0)granulepos=0;
  156300. for(i=0;i<link;i++)
  156301. granulepos+=vf->pcmlengths[i*2+1];
  156302. vf->pcm_offset=granulepos-accblock;
  156303. break;
  156304. }
  156305. lastblock=thisblock;
  156306. continue;
  156307. }else
  156308. ogg_stream_packetout(&vf->os,NULL);
  156309. }
  156310. }
  156311. if(!lastblock){
  156312. if(_get_next_page(vf,&og,-1)<0){
  156313. vf->pcm_offset=ov_pcm_total(vf,-1);
  156314. break;
  156315. }
  156316. }else{
  156317. /* huh? Bogus stream with packets but no granulepos */
  156318. vf->pcm_offset=-1;
  156319. break;
  156320. }
  156321. /* has our decoding just traversed a bitstream boundary? */
  156322. if(vf->ready_state>=STREAMSET)
  156323. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156324. _decode_clear(vf); /* clear out stream state */
  156325. ogg_stream_clear(&work_os);
  156326. }
  156327. if(vf->ready_state<STREAMSET){
  156328. int link;
  156329. vf->current_serialno=ogg_page_serialno(&og);
  156330. for(link=0;link<vf->links;link++)
  156331. if(vf->serialnos[link]==vf->current_serialno)break;
  156332. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156333. error out, leave
  156334. machine uninitialized */
  156335. vf->current_link=link;
  156336. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156337. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156338. vf->ready_state=STREAMSET;
  156339. }
  156340. ogg_stream_pagein(&vf->os,&og);
  156341. ogg_stream_pagein(&work_os,&og);
  156342. eosflag=ogg_page_eos(&og);
  156343. }
  156344. }
  156345. ogg_stream_clear(&work_os);
  156346. vf->bittrack=0.f;
  156347. vf->samptrack=0.f;
  156348. return(0);
  156349. seek_error:
  156350. /* dump the machine so we're in a known state */
  156351. vf->pcm_offset=-1;
  156352. ogg_stream_clear(&work_os);
  156353. _decode_clear(vf);
  156354. return OV_EBADLINK;
  156355. }
  156356. /* Page granularity seek (faster than sample granularity because we
  156357. don't do the last bit of decode to find a specific sample).
  156358. Seek to the last [granule marked] page preceeding the specified pos
  156359. location, such that decoding past the returned point will quickly
  156360. arrive at the requested position. */
  156361. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156362. int link=-1;
  156363. ogg_int64_t result=0;
  156364. ogg_int64_t total=ov_pcm_total(vf,-1);
  156365. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156366. if(!vf->seekable)return(OV_ENOSEEK);
  156367. if(pos<0 || pos>total)return(OV_EINVAL);
  156368. /* which bitstream section does this pcm offset occur in? */
  156369. for(link=vf->links-1;link>=0;link--){
  156370. total-=vf->pcmlengths[link*2+1];
  156371. if(pos>=total)break;
  156372. }
  156373. /* search within the logical bitstream for the page with the highest
  156374. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156375. missing pages or incorrect frame number information in the
  156376. bitstream could make our task impossible. Account for that (it
  156377. would be an error condition) */
  156378. /* new search algorithm by HB (Nicholas Vinen) */
  156379. {
  156380. ogg_int64_t end=vf->offsets[link+1];
  156381. ogg_int64_t begin=vf->offsets[link];
  156382. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156383. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156384. ogg_int64_t target=pos-total+begintime;
  156385. ogg_int64_t best=begin;
  156386. ogg_page og;
  156387. while(begin<end){
  156388. ogg_int64_t bisect;
  156389. if(end-begin<CHUNKSIZE){
  156390. bisect=begin;
  156391. }else{
  156392. /* take a (pretty decent) guess. */
  156393. bisect=begin +
  156394. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156395. if(bisect<=begin)
  156396. bisect=begin+1;
  156397. }
  156398. _seek_helper(vf,bisect);
  156399. while(begin<end){
  156400. result=_get_next_page(vf,&og,end-vf->offset);
  156401. if(result==OV_EREAD) goto seek_error;
  156402. if(result<0){
  156403. if(bisect<=begin+1)
  156404. end=begin; /* found it */
  156405. else{
  156406. if(bisect==0) goto seek_error;
  156407. bisect-=CHUNKSIZE;
  156408. if(bisect<=begin)bisect=begin+1;
  156409. _seek_helper(vf,bisect);
  156410. }
  156411. }else{
  156412. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156413. if(granulepos==-1)continue;
  156414. if(granulepos<target){
  156415. best=result; /* raw offset of packet with granulepos */
  156416. begin=vf->offset; /* raw offset of next page */
  156417. begintime=granulepos;
  156418. if(target-begintime>44100)break;
  156419. bisect=begin; /* *not* begin + 1 */
  156420. }else{
  156421. if(bisect<=begin+1)
  156422. end=begin; /* found it */
  156423. else{
  156424. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156425. end=result;
  156426. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156427. if(bisect<=begin)bisect=begin+1;
  156428. _seek_helper(vf,bisect);
  156429. }else{
  156430. end=result;
  156431. endtime=granulepos;
  156432. break;
  156433. }
  156434. }
  156435. }
  156436. }
  156437. }
  156438. }
  156439. /* found our page. seek to it, update pcm offset. Easier case than
  156440. raw_seek, don't keep packets preceeding granulepos. */
  156441. {
  156442. ogg_page og;
  156443. ogg_packet op;
  156444. /* seek */
  156445. _seek_helper(vf,best);
  156446. vf->pcm_offset=-1;
  156447. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156448. if(link!=vf->current_link){
  156449. /* Different link; dump entire decode machine */
  156450. _decode_clear(vf);
  156451. vf->current_link=link;
  156452. vf->current_serialno=ogg_page_serialno(&og);
  156453. vf->ready_state=STREAMSET;
  156454. }else{
  156455. vorbis_synthesis_restart(&vf->vd);
  156456. }
  156457. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156458. ogg_stream_pagein(&vf->os,&og);
  156459. /* pull out all but last packet; the one with granulepos */
  156460. while(1){
  156461. result=ogg_stream_packetpeek(&vf->os,&op);
  156462. if(result==0){
  156463. /* !!! the packet finishing this page originated on a
  156464. preceeding page. Keep fetching previous pages until we
  156465. get one with a granulepos or without the 'continued' flag
  156466. set. Then just use raw_seek for simplicity. */
  156467. _seek_helper(vf,best);
  156468. while(1){
  156469. result=_get_prev_page(vf,&og);
  156470. if(result<0) goto seek_error;
  156471. if(ogg_page_granulepos(&og)>-1 ||
  156472. !ogg_page_continued(&og)){
  156473. return ov_raw_seek(vf,result);
  156474. }
  156475. vf->offset=result;
  156476. }
  156477. }
  156478. if(result<0){
  156479. result = OV_EBADPACKET;
  156480. goto seek_error;
  156481. }
  156482. if(op.granulepos!=-1){
  156483. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156484. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156485. vf->pcm_offset+=total;
  156486. break;
  156487. }else
  156488. result=ogg_stream_packetout(&vf->os,NULL);
  156489. }
  156490. }
  156491. }
  156492. /* verify result */
  156493. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156494. result=OV_EFAULT;
  156495. goto seek_error;
  156496. }
  156497. vf->bittrack=0.f;
  156498. vf->samptrack=0.f;
  156499. return(0);
  156500. seek_error:
  156501. /* dump machine so we're in a known state */
  156502. vf->pcm_offset=-1;
  156503. _decode_clear(vf);
  156504. return (int)result;
  156505. }
  156506. /* seek to a sample offset relative to the decompressed pcm stream
  156507. returns zero on success, nonzero on failure */
  156508. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156509. int thisblock,lastblock=0;
  156510. int ret=ov_pcm_seek_page(vf,pos);
  156511. if(ret<0)return(ret);
  156512. if((ret=_make_decode_ready(vf)))return ret;
  156513. /* discard leading packets we don't need for the lapping of the
  156514. position we want; don't decode them */
  156515. while(1){
  156516. ogg_packet op;
  156517. ogg_page og;
  156518. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156519. if(ret>0){
  156520. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156521. if(thisblock<0){
  156522. ogg_stream_packetout(&vf->os,NULL);
  156523. continue; /* non audio packet */
  156524. }
  156525. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156526. if(vf->pcm_offset+((thisblock+
  156527. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156528. /* remove the packet from packet queue and track its granulepos */
  156529. ogg_stream_packetout(&vf->os,NULL);
  156530. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156531. only tracking, no
  156532. pcm_decode */
  156533. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156534. /* end of logical stream case is hard, especially with exact
  156535. length positioning. */
  156536. if(op.granulepos>-1){
  156537. int i;
  156538. /* always believe the stream markers */
  156539. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156540. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156541. for(i=0;i<vf->current_link;i++)
  156542. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156543. }
  156544. lastblock=thisblock;
  156545. }else{
  156546. if(ret<0 && ret!=OV_HOLE)break;
  156547. /* suck in a new page */
  156548. if(_get_next_page(vf,&og,-1)<0)break;
  156549. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156550. if(vf->ready_state<STREAMSET){
  156551. int link;
  156552. vf->current_serialno=ogg_page_serialno(&og);
  156553. for(link=0;link<vf->links;link++)
  156554. if(vf->serialnos[link]==vf->current_serialno)break;
  156555. if(link==vf->links)return(OV_EBADLINK);
  156556. vf->current_link=link;
  156557. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156558. vf->ready_state=STREAMSET;
  156559. ret=_make_decode_ready(vf);
  156560. if(ret)return ret;
  156561. lastblock=0;
  156562. }
  156563. ogg_stream_pagein(&vf->os,&og);
  156564. }
  156565. }
  156566. vf->bittrack=0.f;
  156567. vf->samptrack=0.f;
  156568. /* discard samples until we reach the desired position. Crossing a
  156569. logical bitstream boundary with abandon is OK. */
  156570. while(vf->pcm_offset<pos){
  156571. ogg_int64_t target=pos-vf->pcm_offset;
  156572. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156573. if(samples>target)samples=target;
  156574. vorbis_synthesis_read(&vf->vd,samples);
  156575. vf->pcm_offset+=samples;
  156576. if(samples<target)
  156577. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156578. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156579. }
  156580. return 0;
  156581. }
  156582. /* seek to a playback time relative to the decompressed pcm stream
  156583. returns zero on success, nonzero on failure */
  156584. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156585. /* translate time to PCM position and call ov_pcm_seek */
  156586. int link=-1;
  156587. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156588. double time_total=ov_time_total(vf,-1);
  156589. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156590. if(!vf->seekable)return(OV_ENOSEEK);
  156591. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156592. /* which bitstream section does this time offset occur in? */
  156593. for(link=vf->links-1;link>=0;link--){
  156594. pcm_total-=vf->pcmlengths[link*2+1];
  156595. time_total-=ov_time_total(vf,link);
  156596. if(seconds>=time_total)break;
  156597. }
  156598. /* enough information to convert time offset to pcm offset */
  156599. {
  156600. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156601. return(ov_pcm_seek(vf,target));
  156602. }
  156603. }
  156604. /* page-granularity version of ov_time_seek
  156605. returns zero on success, nonzero on failure */
  156606. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156607. /* translate time to PCM position and call ov_pcm_seek */
  156608. int link=-1;
  156609. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156610. double time_total=ov_time_total(vf,-1);
  156611. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156612. if(!vf->seekable)return(OV_ENOSEEK);
  156613. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156614. /* which bitstream section does this time offset occur in? */
  156615. for(link=vf->links-1;link>=0;link--){
  156616. pcm_total-=vf->pcmlengths[link*2+1];
  156617. time_total-=ov_time_total(vf,link);
  156618. if(seconds>=time_total)break;
  156619. }
  156620. /* enough information to convert time offset to pcm offset */
  156621. {
  156622. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156623. return(ov_pcm_seek_page(vf,target));
  156624. }
  156625. }
  156626. /* tell the current stream offset cursor. Note that seek followed by
  156627. tell will likely not give the set offset due to caching */
  156628. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156629. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156630. return(vf->offset);
  156631. }
  156632. /* return PCM offset (sample) of next PCM sample to be read */
  156633. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156634. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156635. return(vf->pcm_offset);
  156636. }
  156637. /* return time offset (seconds) of next PCM sample to be read */
  156638. double ov_time_tell(OggVorbis_File *vf){
  156639. int link=0;
  156640. ogg_int64_t pcm_total=0;
  156641. double time_total=0.f;
  156642. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156643. if(vf->seekable){
  156644. pcm_total=ov_pcm_total(vf,-1);
  156645. time_total=ov_time_total(vf,-1);
  156646. /* which bitstream section does this time offset occur in? */
  156647. for(link=vf->links-1;link>=0;link--){
  156648. pcm_total-=vf->pcmlengths[link*2+1];
  156649. time_total-=ov_time_total(vf,link);
  156650. if(vf->pcm_offset>=pcm_total)break;
  156651. }
  156652. }
  156653. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156654. }
  156655. /* link: -1) return the vorbis_info struct for the bitstream section
  156656. currently being decoded
  156657. 0-n) to request information for a specific bitstream section
  156658. In the case of a non-seekable bitstream, any call returns the
  156659. current bitstream. NULL in the case that the machine is not
  156660. initialized */
  156661. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156662. if(vf->seekable){
  156663. if(link<0)
  156664. if(vf->ready_state>=STREAMSET)
  156665. return vf->vi+vf->current_link;
  156666. else
  156667. return vf->vi;
  156668. else
  156669. if(link>=vf->links)
  156670. return NULL;
  156671. else
  156672. return vf->vi+link;
  156673. }else{
  156674. return vf->vi;
  156675. }
  156676. }
  156677. /* grr, strong typing, grr, no templates/inheritence, grr */
  156678. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156679. if(vf->seekable){
  156680. if(link<0)
  156681. if(vf->ready_state>=STREAMSET)
  156682. return vf->vc+vf->current_link;
  156683. else
  156684. return vf->vc;
  156685. else
  156686. if(link>=vf->links)
  156687. return NULL;
  156688. else
  156689. return vf->vc+link;
  156690. }else{
  156691. return vf->vc;
  156692. }
  156693. }
  156694. static int host_is_big_endian() {
  156695. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156696. unsigned char *bytewise = (unsigned char *)&pattern;
  156697. if (bytewise[0] == 0xfe) return 1;
  156698. return 0;
  156699. }
  156700. /* up to this point, everything could more or less hide the multiple
  156701. logical bitstream nature of chaining from the toplevel application
  156702. if the toplevel application didn't particularly care. However, at
  156703. the point that we actually read audio back, the multiple-section
  156704. nature must surface: Multiple bitstream sections do not necessarily
  156705. have to have the same number of channels or sampling rate.
  156706. ov_read returns the sequential logical bitstream number currently
  156707. being decoded along with the PCM data in order that the toplevel
  156708. application can take action on channel/sample rate changes. This
  156709. number will be incremented even for streamed (non-seekable) streams
  156710. (for seekable streams, it represents the actual logical bitstream
  156711. index within the physical bitstream. Note that the accessor
  156712. functions above are aware of this dichotomy).
  156713. input values: buffer) a buffer to hold packed PCM data for return
  156714. length) the byte length requested to be placed into buffer
  156715. bigendianp) should the data be packed LSB first (0) or
  156716. MSB first (1)
  156717. word) word size for output. currently 1 (byte) or
  156718. 2 (16 bit short)
  156719. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156720. 0) EOF
  156721. n) number of bytes of PCM actually returned. The
  156722. below works on a packet-by-packet basis, so the
  156723. return length is not related to the 'length' passed
  156724. in, just guaranteed to fit.
  156725. *section) set to the logical bitstream number */
  156726. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156727. int bigendianp,int word,int sgned,int *bitstream){
  156728. int i,j;
  156729. int host_endian = host_is_big_endian();
  156730. float **pcm;
  156731. long samples;
  156732. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156733. while(1){
  156734. if(vf->ready_state==INITSET){
  156735. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156736. if(samples)break;
  156737. }
  156738. /* suck in another packet */
  156739. {
  156740. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156741. if(ret==OV_EOF)
  156742. return(0);
  156743. if(ret<=0)
  156744. return(ret);
  156745. }
  156746. }
  156747. if(samples>0){
  156748. /* yay! proceed to pack data into the byte buffer */
  156749. long channels=ov_info(vf,-1)->channels;
  156750. long bytespersample=word * channels;
  156751. vorbis_fpu_control fpu;
  156752. (void) fpu; // (to avoid a warning about it being unused)
  156753. if(samples>length/bytespersample)samples=length/bytespersample;
  156754. if(samples <= 0)
  156755. return OV_EINVAL;
  156756. /* a tight loop to pack each size */
  156757. {
  156758. int val;
  156759. if(word==1){
  156760. int off=(sgned?0:128);
  156761. vorbis_fpu_setround(&fpu);
  156762. for(j=0;j<samples;j++)
  156763. for(i=0;i<channels;i++){
  156764. val=vorbis_ftoi(pcm[i][j]*128.f);
  156765. if(val>127)val=127;
  156766. else if(val<-128)val=-128;
  156767. *buffer++=val+off;
  156768. }
  156769. vorbis_fpu_restore(fpu);
  156770. }else{
  156771. int off=(sgned?0:32768);
  156772. if(host_endian==bigendianp){
  156773. if(sgned){
  156774. vorbis_fpu_setround(&fpu);
  156775. for(i=0;i<channels;i++) { /* It's faster in this order */
  156776. float *src=pcm[i];
  156777. short *dest=((short *)buffer)+i;
  156778. for(j=0;j<samples;j++) {
  156779. val=vorbis_ftoi(src[j]*32768.f);
  156780. if(val>32767)val=32767;
  156781. else if(val<-32768)val=-32768;
  156782. *dest=val;
  156783. dest+=channels;
  156784. }
  156785. }
  156786. vorbis_fpu_restore(fpu);
  156787. }else{
  156788. vorbis_fpu_setround(&fpu);
  156789. for(i=0;i<channels;i++) {
  156790. float *src=pcm[i];
  156791. short *dest=((short *)buffer)+i;
  156792. for(j=0;j<samples;j++) {
  156793. val=vorbis_ftoi(src[j]*32768.f);
  156794. if(val>32767)val=32767;
  156795. else if(val<-32768)val=-32768;
  156796. *dest=val+off;
  156797. dest+=channels;
  156798. }
  156799. }
  156800. vorbis_fpu_restore(fpu);
  156801. }
  156802. }else if(bigendianp){
  156803. vorbis_fpu_setround(&fpu);
  156804. for(j=0;j<samples;j++)
  156805. for(i=0;i<channels;i++){
  156806. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156807. if(val>32767)val=32767;
  156808. else if(val<-32768)val=-32768;
  156809. val+=off;
  156810. *buffer++=(val>>8);
  156811. *buffer++=(val&0xff);
  156812. }
  156813. vorbis_fpu_restore(fpu);
  156814. }else{
  156815. int val;
  156816. vorbis_fpu_setround(&fpu);
  156817. for(j=0;j<samples;j++)
  156818. for(i=0;i<channels;i++){
  156819. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156820. if(val>32767)val=32767;
  156821. else if(val<-32768)val=-32768;
  156822. val+=off;
  156823. *buffer++=(val&0xff);
  156824. *buffer++=(val>>8);
  156825. }
  156826. vorbis_fpu_restore(fpu);
  156827. }
  156828. }
  156829. }
  156830. vorbis_synthesis_read(&vf->vd,samples);
  156831. vf->pcm_offset+=samples;
  156832. if(bitstream)*bitstream=vf->current_link;
  156833. return(samples*bytespersample);
  156834. }else{
  156835. return(samples);
  156836. }
  156837. }
  156838. /* input values: pcm_channels) a float vector per channel of output
  156839. length) the sample length being read by the app
  156840. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156841. 0) EOF
  156842. n) number of samples of PCM actually returned. The
  156843. below works on a packet-by-packet basis, so the
  156844. return length is not related to the 'length' passed
  156845. in, just guaranteed to fit.
  156846. *section) set to the logical bitstream number */
  156847. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156848. int *bitstream){
  156849. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156850. while(1){
  156851. if(vf->ready_state==INITSET){
  156852. float **pcm;
  156853. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156854. if(samples){
  156855. if(pcm_channels)*pcm_channels=pcm;
  156856. if(samples>length)samples=length;
  156857. vorbis_synthesis_read(&vf->vd,samples);
  156858. vf->pcm_offset+=samples;
  156859. if(bitstream)*bitstream=vf->current_link;
  156860. return samples;
  156861. }
  156862. }
  156863. /* suck in another packet */
  156864. {
  156865. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156866. if(ret==OV_EOF)return(0);
  156867. if(ret<=0)return(ret);
  156868. }
  156869. }
  156870. }
  156871. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156872. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156873. ogg_int64_t off);
  156874. static void _ov_splice(float **pcm,float **lappcm,
  156875. int n1, int n2,
  156876. int ch1, int ch2,
  156877. float *w1, float *w2){
  156878. int i,j;
  156879. float *w=w1;
  156880. int n=n1;
  156881. if(n1>n2){
  156882. n=n2;
  156883. w=w2;
  156884. }
  156885. /* splice */
  156886. for(j=0;j<ch1 && j<ch2;j++){
  156887. float *s=lappcm[j];
  156888. float *d=pcm[j];
  156889. for(i=0;i<n;i++){
  156890. float wd=w[i]*w[i];
  156891. float ws=1.-wd;
  156892. d[i]=d[i]*wd + s[i]*ws;
  156893. }
  156894. }
  156895. /* window from zero */
  156896. for(;j<ch2;j++){
  156897. float *d=pcm[j];
  156898. for(i=0;i<n;i++){
  156899. float wd=w[i]*w[i];
  156900. d[i]=d[i]*wd;
  156901. }
  156902. }
  156903. }
  156904. /* make sure vf is INITSET */
  156905. static int _ov_initset(OggVorbis_File *vf){
  156906. while(1){
  156907. if(vf->ready_state==INITSET)break;
  156908. /* suck in another packet */
  156909. {
  156910. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156911. if(ret<0 && ret!=OV_HOLE)return(ret);
  156912. }
  156913. }
  156914. return 0;
  156915. }
  156916. /* make sure vf is INITSET and that we have a primed buffer; if
  156917. we're crosslapping at a stream section boundary, this also makes
  156918. sure we're sanity checking against the right stream information */
  156919. static int _ov_initprime(OggVorbis_File *vf){
  156920. vorbis_dsp_state *vd=&vf->vd;
  156921. while(1){
  156922. if(vf->ready_state==INITSET)
  156923. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156924. /* suck in another packet */
  156925. {
  156926. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156927. if(ret<0 && ret!=OV_HOLE)return(ret);
  156928. }
  156929. }
  156930. return 0;
  156931. }
  156932. /* grab enough data for lapping from vf; this may be in the form of
  156933. unreturned, already-decoded pcm, remaining PCM we will need to
  156934. decode, or synthetic postextrapolation from last packets. */
  156935. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156936. float **lappcm,int lapsize){
  156937. int lapcount=0,i;
  156938. float **pcm;
  156939. /* try first to decode the lapping data */
  156940. while(lapcount<lapsize){
  156941. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156942. if(samples){
  156943. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156944. for(i=0;i<vi->channels;i++)
  156945. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156946. lapcount+=samples;
  156947. vorbis_synthesis_read(vd,samples);
  156948. }else{
  156949. /* suck in another packet */
  156950. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156951. if(ret==OV_EOF)break;
  156952. }
  156953. }
  156954. if(lapcount<lapsize){
  156955. /* failed to get lapping data from normal decode; pry it from the
  156956. postextrapolation buffering, or the second half of the MDCT
  156957. from the last packet */
  156958. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156959. if(samples==0){
  156960. for(i=0;i<vi->channels;i++)
  156961. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156962. lapcount=lapsize;
  156963. }else{
  156964. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156965. for(i=0;i<vi->channels;i++)
  156966. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156967. lapcount+=samples;
  156968. }
  156969. }
  156970. }
  156971. /* this sets up crosslapping of a sample by using trailing data from
  156972. sample 1 and lapping it into the windowing buffer of sample 2 */
  156973. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156974. vorbis_info *vi1,*vi2;
  156975. float **lappcm;
  156976. float **pcm;
  156977. float *w1,*w2;
  156978. int n1,n2,i,ret,hs1,hs2;
  156979. if(vf1==vf2)return(0); /* degenerate case */
  156980. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156981. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156982. /* the relevant overlap buffers must be pre-checked and pre-primed
  156983. before looking at settings in the event that priming would cross
  156984. a bitstream boundary. So, do it now */
  156985. ret=_ov_initset(vf1);
  156986. if(ret)return(ret);
  156987. ret=_ov_initprime(vf2);
  156988. if(ret)return(ret);
  156989. vi1=ov_info(vf1,-1);
  156990. vi2=ov_info(vf2,-1);
  156991. hs1=ov_halfrate_p(vf1);
  156992. hs2=ov_halfrate_p(vf2);
  156993. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156994. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156995. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156996. w1=vorbis_window(&vf1->vd,0);
  156997. w2=vorbis_window(&vf2->vd,0);
  156998. for(i=0;i<vi1->channels;i++)
  156999. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157000. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  157001. /* have a lapping buffer from vf1; now to splice it into the lapping
  157002. buffer of vf2 */
  157003. /* consolidate and expose the buffer. */
  157004. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  157005. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  157006. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  157007. /* splice */
  157008. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  157009. /* done */
  157010. return(0);
  157011. }
  157012. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  157013. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  157014. vorbis_info *vi;
  157015. float **lappcm;
  157016. float **pcm;
  157017. float *w1,*w2;
  157018. int n1,n2,ch1,ch2,hs;
  157019. int i,ret;
  157020. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157021. ret=_ov_initset(vf);
  157022. if(ret)return(ret);
  157023. vi=ov_info(vf,-1);
  157024. hs=ov_halfrate_p(vf);
  157025. ch1=vi->channels;
  157026. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157027. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157028. persistent; even if the decode state
  157029. from this link gets dumped, this
  157030. window array continues to exist */
  157031. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157032. for(i=0;i<ch1;i++)
  157033. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157034. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157035. /* have lapping data; seek and prime the buffer */
  157036. ret=localseek(vf,pos);
  157037. if(ret)return ret;
  157038. ret=_ov_initprime(vf);
  157039. if(ret)return(ret);
  157040. /* Guard against cross-link changes; they're perfectly legal */
  157041. vi=ov_info(vf,-1);
  157042. ch2=vi->channels;
  157043. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157044. w2=vorbis_window(&vf->vd,0);
  157045. /* consolidate and expose the buffer. */
  157046. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157047. /* splice */
  157048. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157049. /* done */
  157050. return(0);
  157051. }
  157052. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157053. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157054. }
  157055. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157056. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157057. }
  157058. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157059. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157060. }
  157061. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157062. int (*localseek)(OggVorbis_File *,double)){
  157063. vorbis_info *vi;
  157064. float **lappcm;
  157065. float **pcm;
  157066. float *w1,*w2;
  157067. int n1,n2,ch1,ch2,hs;
  157068. int i,ret;
  157069. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157070. ret=_ov_initset(vf);
  157071. if(ret)return(ret);
  157072. vi=ov_info(vf,-1);
  157073. hs=ov_halfrate_p(vf);
  157074. ch1=vi->channels;
  157075. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157076. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157077. persistent; even if the decode state
  157078. from this link gets dumped, this
  157079. window array continues to exist */
  157080. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157081. for(i=0;i<ch1;i++)
  157082. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157083. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157084. /* have lapping data; seek and prime the buffer */
  157085. ret=localseek(vf,pos);
  157086. if(ret)return ret;
  157087. ret=_ov_initprime(vf);
  157088. if(ret)return(ret);
  157089. /* Guard against cross-link changes; they're perfectly legal */
  157090. vi=ov_info(vf,-1);
  157091. ch2=vi->channels;
  157092. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157093. w2=vorbis_window(&vf->vd,0);
  157094. /* consolidate and expose the buffer. */
  157095. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157096. /* splice */
  157097. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157098. /* done */
  157099. return(0);
  157100. }
  157101. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157102. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157103. }
  157104. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157105. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157106. }
  157107. #endif
  157108. /*** End of inlined file: vorbisfile.c ***/
  157109. /*** Start of inlined file: window.c ***/
  157110. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157111. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157112. // tasks..
  157113. #if JUCE_MSVC
  157114. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157115. #endif
  157116. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157117. #if JUCE_USE_OGGVORBIS
  157118. #include <stdlib.h>
  157119. #include <math.h>
  157120. static float vwin64[32] = {
  157121. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157122. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157123. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157124. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157125. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157126. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157127. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157128. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157129. };
  157130. static float vwin128[64] = {
  157131. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157132. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157133. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157134. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157135. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157136. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157137. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157138. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157139. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157140. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157141. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157142. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157143. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157144. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157145. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157146. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157147. };
  157148. static float vwin256[128] = {
  157149. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157150. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157151. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157152. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157153. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157154. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157155. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157156. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157157. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157158. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157159. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157160. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157161. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157162. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157163. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157164. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157165. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157166. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157167. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157168. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157169. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157170. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157171. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157172. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157173. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157174. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157175. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157176. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157177. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157178. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157179. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157180. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157181. };
  157182. static float vwin512[256] = {
  157183. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157184. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157185. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157186. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157187. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157188. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157189. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157190. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157191. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157192. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157193. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157194. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157195. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157196. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157197. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157198. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157199. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157200. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157201. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157202. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157203. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157204. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157205. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157206. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157207. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157208. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157209. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157210. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157211. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157212. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157213. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157214. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157215. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157216. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157217. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157218. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157219. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157220. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157221. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157222. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157223. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157224. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157225. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157226. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157227. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157228. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157229. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157230. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157231. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157232. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157233. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157234. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157235. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157236. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157237. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157238. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157239. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157240. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157241. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157242. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157243. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157244. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157245. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157246. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157247. };
  157248. static float vwin1024[512] = {
  157249. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157250. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157251. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157252. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157253. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157254. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157255. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157256. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157257. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157258. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157259. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157260. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157261. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157262. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157263. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157264. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157265. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157266. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157267. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157268. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157269. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157270. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157271. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157272. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157273. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157274. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157275. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157276. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157277. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157278. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157279. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157280. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157281. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157282. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157283. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157284. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157285. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157286. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157287. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157288. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157289. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157290. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157291. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157292. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157293. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157294. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157295. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157296. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157297. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157298. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157299. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157300. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157301. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157302. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157303. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157304. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157305. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157306. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157307. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157308. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157309. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157310. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157311. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157312. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157313. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157314. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157315. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157316. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157317. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157318. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157319. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157320. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157321. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157322. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157323. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157324. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157325. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157326. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157327. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157328. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157329. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157330. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157331. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157332. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157333. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157334. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157335. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157336. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157337. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157338. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157339. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157340. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157341. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157342. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157343. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157344. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157345. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157346. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157347. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157348. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157349. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157350. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157351. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157352. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157353. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157354. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157355. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157356. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157357. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157358. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157359. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157360. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157361. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157362. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157363. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157364. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157365. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157366. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157367. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157368. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157369. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157370. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157371. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157372. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157373. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157374. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157375. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157376. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157377. };
  157378. static float vwin2048[1024] = {
  157379. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157380. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157381. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157382. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157383. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157384. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157385. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157386. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157387. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157388. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157389. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157390. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157391. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157392. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157393. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157394. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157395. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157396. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157397. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157398. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157399. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157400. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157401. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157402. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157403. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157404. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157405. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157406. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157407. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157408. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157409. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157410. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157411. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157412. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157413. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157414. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157415. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157416. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157417. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157418. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157419. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157420. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157421. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157422. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157423. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157424. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157425. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157426. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157427. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157428. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157429. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157430. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157431. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157432. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157433. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157434. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157435. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157436. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157437. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157438. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157439. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157440. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157441. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157442. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157443. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157444. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157445. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157446. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157447. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157448. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157449. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157450. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157451. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157452. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157453. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157454. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157455. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157456. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157457. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157458. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157459. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157460. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157461. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157462. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157463. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157464. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157465. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157466. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157467. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157468. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157469. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157470. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157471. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157472. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157473. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157474. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157475. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157476. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157477. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157478. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157479. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157480. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157481. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157482. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157483. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157484. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157485. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157486. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157487. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157488. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157489. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157490. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157491. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157492. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157493. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157494. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157495. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157496. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157497. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157498. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157499. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157500. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157501. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157502. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157503. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157504. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157505. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157506. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157507. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157508. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157509. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157510. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157511. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157512. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157513. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157514. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157515. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157516. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157517. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157518. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157519. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157520. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157521. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157522. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157523. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157524. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157525. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157526. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157527. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157528. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157529. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157530. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157531. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157532. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157533. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157534. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157535. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157536. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157537. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157538. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157539. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157540. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157541. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157542. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157543. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157544. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157545. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157546. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157547. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157548. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157549. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157550. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157551. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157552. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157553. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157554. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157555. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157556. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157557. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157558. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157559. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157560. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157561. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157562. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157563. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157564. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157565. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157566. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157567. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157568. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157569. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157570. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157571. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157572. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157573. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157574. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157575. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157576. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157577. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157578. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157579. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157580. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157581. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157582. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157583. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157584. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157585. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157586. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157587. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157588. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157589. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157590. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157591. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157592. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157593. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157594. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157595. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157596. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157597. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157598. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157599. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157600. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157601. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157602. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157603. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157604. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157605. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157606. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157607. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157608. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157609. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157610. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157611. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157612. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157613. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157614. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157615. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157616. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157617. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157618. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157619. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157620. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157621. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157622. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157623. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157624. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157625. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157626. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157627. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157628. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157629. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157630. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157631. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157632. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157633. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157634. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157635. };
  157636. static float vwin4096[2048] = {
  157637. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157638. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157639. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157640. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157641. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157642. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157643. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157644. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157645. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157646. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157647. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157648. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157649. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157650. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157651. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157652. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157653. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157654. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157655. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157656. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157657. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157658. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157659. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157660. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157661. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157662. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157663. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157664. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157665. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157666. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157667. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157668. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157669. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157670. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157671. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157672. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157673. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157674. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157675. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157676. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157677. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157678. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157679. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157680. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157681. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157682. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157683. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157684. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157685. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157686. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157687. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157688. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157689. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157690. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157691. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157692. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157693. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157694. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157695. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157696. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157697. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157698. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157699. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157700. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157701. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157702. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157703. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157704. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157705. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157706. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157707. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157708. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157709. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157710. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157711. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157712. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157713. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157714. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157715. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157716. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157717. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157718. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157719. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157720. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157721. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157722. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157723. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157724. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157725. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157726. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157727. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157728. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157729. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157730. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157731. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157732. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157733. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157734. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157735. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157736. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157737. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157738. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157739. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157740. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157741. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157742. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157743. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157744. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157745. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157746. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157747. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157748. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157749. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157750. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157751. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157752. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157753. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157754. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157755. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157756. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157757. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157758. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157759. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157760. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157761. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157762. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157763. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157764. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157765. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157766. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157767. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157768. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157769. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157770. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157771. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157772. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157773. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157774. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157775. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157776. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157777. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157778. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157779. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157780. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157781. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157782. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157783. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157784. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157785. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157786. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157787. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157788. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157789. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157790. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157791. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157792. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157793. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157794. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157795. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157796. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157797. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157798. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157799. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157800. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157801. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157802. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157803. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157804. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157805. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157806. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157807. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157808. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157809. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157810. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157811. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157812. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157813. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157814. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157815. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157816. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157817. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157818. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157819. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157820. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157821. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157822. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157823. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157824. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157825. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157826. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157827. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157828. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157829. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157830. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157831. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157832. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157833. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157834. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157835. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157836. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157837. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157838. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157839. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157840. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157841. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157842. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157843. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157844. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157845. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157846. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157847. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157848. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157849. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157850. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157851. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157852. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157853. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157854. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157855. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157856. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157857. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157858. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157859. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157860. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157861. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157862. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157863. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157864. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157865. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157866. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157867. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157868. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157869. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157870. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157871. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157872. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157873. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157874. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157875. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157876. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157877. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157878. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157879. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157880. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157881. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157882. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157883. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157884. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157885. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157886. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157887. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157888. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157889. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157890. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157891. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157892. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157893. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157894. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157895. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157896. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157897. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157898. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157899. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157900. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157901. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157902. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157903. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157904. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157905. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157906. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157907. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157908. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157909. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157910. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157911. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157912. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157913. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157914. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157915. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157916. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157917. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157918. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157919. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157920. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157921. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157922. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157923. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157924. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157925. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157926. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157927. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157928. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157929. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157930. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157931. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157932. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157933. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157934. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157935. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157936. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157937. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157938. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157939. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157940. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157941. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157942. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157943. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157944. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157945. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157946. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157947. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157948. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157949. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157950. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157951. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157952. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157953. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157954. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157955. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157956. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157957. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157958. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157959. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157960. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157961. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157962. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157963. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157964. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157965. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157966. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157967. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157968. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157969. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157970. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157971. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157972. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157973. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157974. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157975. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157976. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157977. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157978. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157979. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157980. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157981. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157982. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157983. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157984. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157985. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157986. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157987. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157988. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157989. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157990. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157991. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157992. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157993. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157994. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157995. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157996. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157997. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157998. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157999. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  158000. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  158001. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  158002. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  158003. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  158004. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  158005. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  158006. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  158007. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  158008. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  158009. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  158010. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  158011. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  158012. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  158013. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  158014. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  158015. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  158016. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  158017. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  158018. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  158019. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  158020. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  158021. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  158022. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  158023. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  158024. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  158025. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  158026. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  158027. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  158028. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  158029. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  158030. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  158031. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  158032. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  158033. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  158034. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  158035. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  158036. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  158037. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  158038. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  158039. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  158040. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  158041. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  158042. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  158043. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  158044. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  158045. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  158046. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  158047. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  158048. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  158049. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  158050. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  158051. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  158052. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  158053. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  158054. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  158055. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  158056. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  158057. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  158058. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  158059. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  158060. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  158061. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  158062. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  158063. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  158064. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  158065. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  158066. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  158067. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  158068. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  158069. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  158070. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  158071. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  158072. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158073. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158074. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158075. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158076. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158077. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158078. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158079. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158080. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158081. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158082. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158083. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158084. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158085. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158086. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158087. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158088. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158089. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158090. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158091. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158092. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158093. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158094. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158095. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158096. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158097. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158098. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158099. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158100. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158101. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158102. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158103. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158104. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158105. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158106. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158107. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158108. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158109. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158110. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158111. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158112. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158113. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158114. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158115. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158116. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158117. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158118. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158119. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158120. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158121. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158122. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158123. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158124. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158125. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158126. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158127. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158128. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158129. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158130. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158131. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158132. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158133. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158134. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158135. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158136. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158137. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158138. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158139. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158140. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158141. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158142. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158143. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158144. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158145. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158146. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158147. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158148. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158149. };
  158150. static float vwin8192[4096] = {
  158151. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158152. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158153. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158154. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158155. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158156. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158157. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158158. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158159. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158160. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158161. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158162. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158163. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158164. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158165. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158166. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158167. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158168. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158169. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158170. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158171. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158172. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158173. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158174. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158175. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158176. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158177. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158178. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158179. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158180. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158181. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158182. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158183. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158184. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158185. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158186. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158187. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158188. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158189. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158190. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158191. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158192. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158193. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158194. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158195. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158196. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158197. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158198. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158199. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158200. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158201. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158202. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158203. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158204. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158205. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158206. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158207. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158208. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158209. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158210. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158211. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158212. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158213. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158214. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158215. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158216. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158217. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158218. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158219. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158220. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158221. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158222. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158223. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158224. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158225. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158226. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158227. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158228. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158229. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158230. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158231. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158232. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158233. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158234. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158235. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158236. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158237. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158238. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158239. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158240. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158241. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158242. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158243. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158244. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158245. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158246. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158247. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158248. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158249. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158250. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158251. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158252. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158253. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158254. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158255. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158256. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158257. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158258. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158259. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158260. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158261. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158262. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158263. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158264. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158265. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158266. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158267. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158268. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158269. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158270. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158271. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158272. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158273. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158274. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158275. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158276. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158277. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158278. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158279. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158280. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158281. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158282. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158283. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158284. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158285. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158286. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158287. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158288. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158289. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158290. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158291. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158292. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158293. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158294. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158295. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158296. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158297. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158298. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158299. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158300. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158301. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158302. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158303. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158304. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158305. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158306. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158307. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158308. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158309. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158310. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158311. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158312. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158313. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158314. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158315. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158316. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158317. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158318. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158319. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158320. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158321. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158322. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158323. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158324. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158325. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158326. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158327. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158328. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158329. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158330. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158331. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158332. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158333. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158334. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158335. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158336. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158337. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158338. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158339. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158340. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158341. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158342. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158343. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158344. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158345. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158346. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158347. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158348. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158349. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158350. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158351. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158352. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158353. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158354. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158355. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158356. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158357. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158358. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158359. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158360. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158361. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158362. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158363. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158364. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158365. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158366. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158367. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158368. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158369. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158370. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158371. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158372. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158373. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158374. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158375. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158376. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158377. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158378. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158379. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158380. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158381. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158382. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158383. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158384. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158385. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158386. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158387. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158388. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158389. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158390. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158391. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158392. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158393. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158394. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158395. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158396. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158397. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158398. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158399. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158400. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158401. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158402. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158403. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158404. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158405. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158406. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158407. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158408. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158409. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158410. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158411. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158412. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158413. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158414. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158415. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158416. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158417. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158418. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158419. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158420. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158421. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158422. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158423. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158424. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158425. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158426. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158427. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158428. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158429. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158430. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158431. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158432. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158433. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158434. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158435. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158436. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158437. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158438. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158439. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158440. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158441. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158442. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158443. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158444. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158445. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158446. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158447. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158448. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158449. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158450. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158451. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158452. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158453. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158454. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158455. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158456. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158457. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158458. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158459. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158460. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158461. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158462. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158463. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158464. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158465. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158466. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158467. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158468. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158469. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158470. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158471. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158472. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158473. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158474. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158475. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158476. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158477. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158478. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158479. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158480. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158481. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158482. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158483. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158484. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158485. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158486. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158487. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158488. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158489. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158490. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158491. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158492. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158493. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158494. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158495. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158496. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158497. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158498. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158499. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158500. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158501. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158502. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158503. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158504. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158505. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158506. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158507. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158508. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158509. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158510. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158511. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158512. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158513. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158514. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158515. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158516. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158517. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158518. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158519. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158520. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158521. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158522. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158523. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158524. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158525. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158526. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158527. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158528. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158529. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158530. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158531. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158532. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158533. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158534. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158535. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158536. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158537. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158538. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158539. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158540. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158541. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158542. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158543. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158544. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158545. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158546. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158547. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158548. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158549. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158550. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158551. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158552. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158553. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158554. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158555. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158556. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158557. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158558. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158559. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158560. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158561. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158562. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158563. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158564. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158565. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158566. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158567. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158568. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158569. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158570. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158571. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158572. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158573. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158574. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158575. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158576. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158577. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158578. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158579. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158580. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158581. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158582. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158583. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158584. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158585. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158586. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158587. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158588. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158589. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158590. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158591. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158592. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158593. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158594. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158595. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158596. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158597. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158598. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158599. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158600. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158601. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158602. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158603. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158604. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158605. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158606. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158607. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158608. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158609. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158610. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158611. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158612. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158613. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158614. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158615. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158616. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158617. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158618. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158619. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158620. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158621. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158622. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158623. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158624. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158625. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158626. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158627. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158628. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158629. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158630. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158631. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158632. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158633. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158634. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158635. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158636. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158637. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158638. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158639. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158640. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158641. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158642. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158643. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158644. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158645. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158646. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158647. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158648. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158649. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158650. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158651. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158652. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158653. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158654. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158655. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158656. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158657. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158658. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158659. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158660. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158661. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158662. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158663. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158664. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158665. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158666. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158667. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158668. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158669. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158670. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158671. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158672. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158673. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158674. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158675. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158676. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158677. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158678. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158679. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158680. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158681. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158682. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158683. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158684. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158685. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158686. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158687. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158688. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158689. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158690. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158691. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158692. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158693. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158694. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158695. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158696. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158697. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158698. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158699. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158700. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158701. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158702. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158703. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158704. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158705. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158706. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158707. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158708. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158709. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158710. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158711. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158712. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158713. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158714. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158715. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158716. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158717. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158718. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158719. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158720. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158721. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158722. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158723. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158724. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158725. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158726. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158727. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158728. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158729. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158730. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158731. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158732. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158733. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158734. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158735. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158736. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158737. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158738. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158739. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158740. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158741. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158742. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158743. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158744. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158745. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158746. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158747. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158748. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158749. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158750. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158751. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158752. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158753. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158754. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158755. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158756. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158757. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158758. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158759. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158760. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158761. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158762. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158763. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158764. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158765. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158766. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158767. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158768. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158769. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158770. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158771. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158772. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158773. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158774. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158775. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158776. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158777. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158778. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158779. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158780. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158781. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158782. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158783. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158784. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158785. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158786. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158787. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158788. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158789. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158790. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158791. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158792. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158793. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158794. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158795. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158796. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158797. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158798. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158799. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158800. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158801. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158802. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158803. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158804. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158805. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158806. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158807. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158808. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158809. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158810. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158811. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158812. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158813. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158814. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158815. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158816. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158817. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158818. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158819. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158820. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158821. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158822. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158823. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158824. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158825. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158826. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158827. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158828. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158829. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158830. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158831. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158832. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158833. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158834. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158835. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158836. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158837. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158838. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158839. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158840. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158841. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158842. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158843. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158844. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158845. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158846. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158847. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158848. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158849. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158850. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158851. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158852. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158853. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158854. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158855. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158856. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158857. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158858. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158859. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158860. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158861. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158862. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158863. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158864. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158865. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158866. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158867. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158868. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158869. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158870. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158871. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158872. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158873. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158874. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158875. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158876. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158877. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158878. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158879. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158880. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158881. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158882. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158883. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158884. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158885. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158886. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158887. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158888. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158889. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158890. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158891. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158892. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158893. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158894. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158895. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158896. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158897. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158898. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158899. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158900. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158901. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158902. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158903. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158904. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158905. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158906. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158907. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158908. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158909. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158910. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158911. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158912. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158913. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158914. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158915. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158916. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158917. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158918. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158919. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158920. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158921. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158922. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158923. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158924. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158925. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158926. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158927. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158928. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158929. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158930. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158931. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158932. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158933. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158934. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158935. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158936. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158937. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158938. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158939. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158940. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158941. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158942. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158943. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158944. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158945. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158946. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158947. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158948. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158949. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158950. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158951. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158952. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158953. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158954. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158955. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158956. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158957. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158958. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158959. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158960. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158961. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158962. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158963. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158964. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158965. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158966. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158967. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158968. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158969. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158970. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158971. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158972. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158973. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158974. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158975. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158976. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158977. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158978. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158979. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158980. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158981. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158982. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158983. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158984. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158985. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158986. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158987. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158988. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158989. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158990. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158991. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158992. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158993. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158994. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158995. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158996. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158997. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158998. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158999. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  159000. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  159001. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  159002. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  159003. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  159004. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  159005. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  159006. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  159007. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  159008. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  159009. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  159010. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  159011. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  159012. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  159013. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  159014. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  159015. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  159016. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  159017. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  159018. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  159019. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  159020. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  159021. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  159022. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  159023. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  159024. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  159025. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  159026. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  159027. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  159028. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  159029. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  159030. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  159031. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  159032. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  159033. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  159034. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  159035. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  159036. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  159037. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  159038. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  159039. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  159040. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  159041. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  159042. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  159043. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  159044. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  159045. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  159046. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  159047. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  159048. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  159049. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  159050. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  159051. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  159052. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  159053. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  159054. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  159055. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  159056. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  159057. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  159058. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  159059. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  159060. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  159061. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  159062. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  159063. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  159064. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  159065. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  159066. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  159067. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  159068. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  159069. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  159070. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  159071. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  159072. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159073. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159074. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159075. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159076. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159077. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159078. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159079. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159080. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159081. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159082. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159083. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159084. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159085. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159086. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159087. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159088. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159089. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159090. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159091. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159092. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159093. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159094. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159095. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159096. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159097. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159098. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159099. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159100. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159101. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159102. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159103. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159104. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159105. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159106. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159107. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159108. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159109. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159110. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159111. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159112. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159113. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159114. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159115. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159116. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159117. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159118. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159119. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159120. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159121. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159122. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159123. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159124. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159125. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159126. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159127. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159128. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159129. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159130. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159131. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159132. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159133. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159134. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159135. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159136. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159137. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159138. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159139. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159140. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159141. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159142. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159143. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159144. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159145. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159146. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159147. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159148. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159149. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159150. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159151. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159152. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159153. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159154. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159155. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159156. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159157. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159158. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159159. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159160. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159161. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159162. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159163. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159164. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159165. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159166. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159167. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159168. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159169. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159170. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159171. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159172. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159173. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159174. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159175. };
  159176. static float *vwin[8] = {
  159177. vwin64,
  159178. vwin128,
  159179. vwin256,
  159180. vwin512,
  159181. vwin1024,
  159182. vwin2048,
  159183. vwin4096,
  159184. vwin8192,
  159185. };
  159186. float *_vorbis_window_get(int n){
  159187. return vwin[n];
  159188. }
  159189. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159190. int lW,int W,int nW){
  159191. lW=(W?lW:0);
  159192. nW=(W?nW:0);
  159193. {
  159194. float *windowLW=vwin[winno[lW]];
  159195. float *windowNW=vwin[winno[nW]];
  159196. long n=blocksizes[W];
  159197. long ln=blocksizes[lW];
  159198. long rn=blocksizes[nW];
  159199. long leftbegin=n/4-ln/4;
  159200. long leftend=leftbegin+ln/2;
  159201. long rightbegin=n/2+n/4-rn/4;
  159202. long rightend=rightbegin+rn/2;
  159203. int i,p;
  159204. for(i=0;i<leftbegin;i++)
  159205. d[i]=0.f;
  159206. for(p=0;i<leftend;i++,p++)
  159207. d[i]*=windowLW[p];
  159208. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159209. d[i]*=windowNW[p];
  159210. for(;i<n;i++)
  159211. d[i]=0.f;
  159212. }
  159213. }
  159214. #endif
  159215. /*** End of inlined file: window.c ***/
  159216. #else
  159217. #include <vorbis/vorbisenc.h>
  159218. #include <vorbis/codec.h>
  159219. #include <vorbis/vorbisfile.h>
  159220. #endif
  159221. }
  159222. #undef max
  159223. #undef min
  159224. BEGIN_JUCE_NAMESPACE
  159225. static const char* const oggFormatName = "Ogg-Vorbis file";
  159226. static const char* const oggExtensions[] = { ".ogg", 0 };
  159227. class OggReader : public AudioFormatReader
  159228. {
  159229. OggVorbisNamespace::OggVorbis_File ovFile;
  159230. OggVorbisNamespace::ov_callbacks callbacks;
  159231. AudioSampleBuffer reservoir;
  159232. int reservoirStart, samplesInReservoir;
  159233. public:
  159234. OggReader (InputStream* const inp)
  159235. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159236. reservoir (2, 4096),
  159237. reservoirStart (0),
  159238. samplesInReservoir (0)
  159239. {
  159240. using namespace OggVorbisNamespace;
  159241. sampleRate = 0;
  159242. usesFloatingPointData = true;
  159243. callbacks.read_func = &oggReadCallback;
  159244. callbacks.seek_func = &oggSeekCallback;
  159245. callbacks.close_func = &oggCloseCallback;
  159246. callbacks.tell_func = &oggTellCallback;
  159247. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159248. if (err == 0)
  159249. {
  159250. vorbis_info* info = ov_info (&ovFile, -1);
  159251. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159252. numChannels = info->channels;
  159253. bitsPerSample = 16;
  159254. sampleRate = info->rate;
  159255. reservoir.setSize (numChannels,
  159256. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159257. }
  159258. }
  159259. ~OggReader()
  159260. {
  159261. OggVorbisNamespace::ov_clear (&ovFile);
  159262. }
  159263. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159264. int64 startSampleInFile, int numSamples)
  159265. {
  159266. while (numSamples > 0)
  159267. {
  159268. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159269. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159270. {
  159271. // got a few samples overlapping, so use them before seeking..
  159272. const int numToUse = jmin (numSamples, numAvailable);
  159273. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159274. if (destSamples[i] != 0)
  159275. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159276. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159277. sizeof (float) * numToUse);
  159278. startSampleInFile += numToUse;
  159279. numSamples -= numToUse;
  159280. startOffsetInDestBuffer += numToUse;
  159281. if (numSamples == 0)
  159282. break;
  159283. }
  159284. if (startSampleInFile < reservoirStart
  159285. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159286. {
  159287. // buffer miss, so refill the reservoir
  159288. int bitStream = 0;
  159289. reservoirStart = jmax (0, (int) startSampleInFile);
  159290. samplesInReservoir = reservoir.getNumSamples();
  159291. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159292. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159293. int offset = 0;
  159294. int numToRead = samplesInReservoir;
  159295. while (numToRead > 0)
  159296. {
  159297. float** dataIn = 0;
  159298. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159299. if (samps <= 0)
  159300. break;
  159301. jassert (samps <= numToRead);
  159302. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159303. {
  159304. memcpy (reservoir.getSampleData (i, offset),
  159305. dataIn[i],
  159306. sizeof (float) * samps);
  159307. }
  159308. numToRead -= samps;
  159309. offset += samps;
  159310. }
  159311. if (numToRead > 0)
  159312. reservoir.clear (offset, numToRead);
  159313. }
  159314. }
  159315. if (numSamples > 0)
  159316. {
  159317. for (int i = numDestChannels; --i >= 0;)
  159318. if (destSamples[i] != 0)
  159319. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159320. sizeof (int) * numSamples);
  159321. }
  159322. return true;
  159323. }
  159324. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159325. {
  159326. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159327. }
  159328. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159329. {
  159330. InputStream* const in = static_cast <InputStream*> (datasource);
  159331. if (whence == SEEK_CUR)
  159332. offset += in->getPosition();
  159333. else if (whence == SEEK_END)
  159334. offset += in->getTotalLength();
  159335. in->setPosition (offset);
  159336. return 0;
  159337. }
  159338. static int oggCloseCallback (void*)
  159339. {
  159340. return 0;
  159341. }
  159342. static long oggTellCallback (void* datasource)
  159343. {
  159344. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159345. }
  159346. juce_UseDebuggingNewOperator
  159347. };
  159348. class OggWriter : public AudioFormatWriter
  159349. {
  159350. OggVorbisNamespace::ogg_stream_state os;
  159351. OggVorbisNamespace::ogg_page og;
  159352. OggVorbisNamespace::ogg_packet op;
  159353. OggVorbisNamespace::vorbis_info vi;
  159354. OggVorbisNamespace::vorbis_comment vc;
  159355. OggVorbisNamespace::vorbis_dsp_state vd;
  159356. OggVorbisNamespace::vorbis_block vb;
  159357. public:
  159358. bool ok;
  159359. OggWriter (OutputStream* const out,
  159360. const double sampleRate,
  159361. const int numChannels,
  159362. const int bitsPerSample,
  159363. const int qualityIndex)
  159364. : AudioFormatWriter (out, TRANS (oggFormatName),
  159365. sampleRate,
  159366. numChannels,
  159367. bitsPerSample)
  159368. {
  159369. using namespace OggVorbisNamespace;
  159370. ok = false;
  159371. vorbis_info_init (&vi);
  159372. if (vorbis_encode_init_vbr (&vi,
  159373. numChannels,
  159374. (int) sampleRate,
  159375. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159376. {
  159377. vorbis_comment_init (&vc);
  159378. if (JUCEApplication::getInstance() != 0)
  159379. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159380. vorbis_analysis_init (&vd, &vi);
  159381. vorbis_block_init (&vd, &vb);
  159382. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159383. ogg_packet header;
  159384. ogg_packet header_comm;
  159385. ogg_packet header_code;
  159386. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159387. ogg_stream_packetin (&os, &header);
  159388. ogg_stream_packetin (&os, &header_comm);
  159389. ogg_stream_packetin (&os, &header_code);
  159390. for (;;)
  159391. {
  159392. if (ogg_stream_flush (&os, &og) == 0)
  159393. break;
  159394. output->write (og.header, og.header_len);
  159395. output->write (og.body, og.body_len);
  159396. }
  159397. ok = true;
  159398. }
  159399. }
  159400. ~OggWriter()
  159401. {
  159402. using namespace OggVorbisNamespace;
  159403. if (ok)
  159404. {
  159405. // write a zero-length packet to show ogg that we're finished..
  159406. write (0, 0);
  159407. ogg_stream_clear (&os);
  159408. vorbis_block_clear (&vb);
  159409. vorbis_dsp_clear (&vd);
  159410. vorbis_comment_clear (&vc);
  159411. vorbis_info_clear (&vi);
  159412. output->flush();
  159413. }
  159414. else
  159415. {
  159416. vorbis_info_clear (&vi);
  159417. output = 0; // to stop the base class deleting this, as it needs to be returned
  159418. // to the caller of createWriter()
  159419. }
  159420. }
  159421. bool write (const int** samplesToWrite, int numSamples)
  159422. {
  159423. using namespace OggVorbisNamespace;
  159424. if (! ok)
  159425. return false;
  159426. if (numSamples > 0)
  159427. {
  159428. const double gain = 1.0 / 0x80000000u;
  159429. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159430. for (int i = numChannels; --i >= 0;)
  159431. {
  159432. float* const dst = vorbisBuffer[i];
  159433. const int* const src = samplesToWrite [i];
  159434. if (src != 0 && dst != 0)
  159435. {
  159436. for (int j = 0; j < numSamples; ++j)
  159437. dst[j] = (float) (src[j] * gain);
  159438. }
  159439. }
  159440. }
  159441. vorbis_analysis_wrote (&vd, numSamples);
  159442. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159443. {
  159444. vorbis_analysis (&vb, 0);
  159445. vorbis_bitrate_addblock (&vb);
  159446. while (vorbis_bitrate_flushpacket (&vd, &op))
  159447. {
  159448. ogg_stream_packetin (&os, &op);
  159449. for (;;)
  159450. {
  159451. if (ogg_stream_pageout (&os, &og) == 0)
  159452. break;
  159453. output->write (og.header, og.header_len);
  159454. output->write (og.body, og.body_len);
  159455. if (ogg_page_eos (&og))
  159456. break;
  159457. }
  159458. }
  159459. }
  159460. return true;
  159461. }
  159462. juce_UseDebuggingNewOperator
  159463. };
  159464. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159465. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159466. {
  159467. }
  159468. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159469. {
  159470. }
  159471. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159472. {
  159473. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159474. return Array <int> (rates);
  159475. }
  159476. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159477. {
  159478. const int depths[] = { 32, 0 };
  159479. return Array <int> (depths);
  159480. }
  159481. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159482. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159483. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159484. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159485. const bool deleteStreamIfOpeningFails)
  159486. {
  159487. ScopedPointer <OggReader> r (new OggReader (in));
  159488. if (r->sampleRate != 0)
  159489. return r.release();
  159490. if (! deleteStreamIfOpeningFails)
  159491. r->input = 0;
  159492. return 0;
  159493. }
  159494. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159495. double sampleRate,
  159496. unsigned int numChannels,
  159497. int bitsPerSample,
  159498. const StringPairArray& /*metadataValues*/,
  159499. int qualityOptionIndex)
  159500. {
  159501. ScopedPointer <OggWriter> w (new OggWriter (out,
  159502. sampleRate,
  159503. numChannels,
  159504. bitsPerSample,
  159505. qualityOptionIndex));
  159506. return w->ok ? w.release() : 0;
  159507. }
  159508. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159509. {
  159510. StringArray s;
  159511. s.add ("Low Quality");
  159512. s.add ("Medium Quality");
  159513. s.add ("High Quality");
  159514. return s;
  159515. }
  159516. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159517. {
  159518. FileInputStream* const in = source.createInputStream();
  159519. if (in != 0)
  159520. {
  159521. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159522. if (r != 0)
  159523. {
  159524. const int64 numSamps = r->lengthInSamples;
  159525. r = 0;
  159526. const int64 fileNumSamps = source.getSize() / 4;
  159527. const double ratio = numSamps / (double) fileNumSamps;
  159528. if (ratio > 12.0)
  159529. return 0;
  159530. else if (ratio > 6.0)
  159531. return 1;
  159532. else
  159533. return 2;
  159534. }
  159535. }
  159536. return 1;
  159537. }
  159538. END_JUCE_NAMESPACE
  159539. #endif
  159540. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159541. #endif
  159542. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159543. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159544. #if JUCE_MSVC
  159545. #pragma warning (push)
  159546. #endif
  159547. namespace jpeglibNamespace
  159548. {
  159549. #if JUCE_INCLUDE_JPEGLIB_CODE
  159550. #if JUCE_MINGW
  159551. typedef unsigned char boolean;
  159552. #endif
  159553. #define JPEG_INTERNALS
  159554. #undef FAR
  159555. /*** Start of inlined file: jpeglib.h ***/
  159556. #ifndef JPEGLIB_H
  159557. #define JPEGLIB_H
  159558. /*
  159559. * First we include the configuration files that record how this
  159560. * installation of the JPEG library is set up. jconfig.h can be
  159561. * generated automatically for many systems. jmorecfg.h contains
  159562. * manual configuration options that most people need not worry about.
  159563. */
  159564. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159565. /*** Start of inlined file: jconfig.h ***/
  159566. /* see jconfig.doc for explanations */
  159567. // disable all the warnings under MSVC
  159568. #ifdef _MSC_VER
  159569. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159570. #endif
  159571. #ifdef __BORLANDC__
  159572. #pragma warn -8057
  159573. #pragma warn -8019
  159574. #pragma warn -8004
  159575. #pragma warn -8008
  159576. #endif
  159577. #define HAVE_PROTOTYPES
  159578. #define HAVE_UNSIGNED_CHAR
  159579. #define HAVE_UNSIGNED_SHORT
  159580. /* #define void char */
  159581. /* #define const */
  159582. #undef CHAR_IS_UNSIGNED
  159583. #define HAVE_STDDEF_H
  159584. #define HAVE_STDLIB_H
  159585. #undef NEED_BSD_STRINGS
  159586. #undef NEED_SYS_TYPES_H
  159587. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159588. #undef NEED_SHORT_EXTERNAL_NAMES
  159589. #undef INCOMPLETE_TYPES_BROKEN
  159590. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159591. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159592. typedef unsigned char boolean;
  159593. #endif
  159594. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159595. #ifdef JPEG_INTERNALS
  159596. #undef RIGHT_SHIFT_IS_UNSIGNED
  159597. #endif /* JPEG_INTERNALS */
  159598. #ifdef JPEG_CJPEG_DJPEG
  159599. #define BMP_SUPPORTED /* BMP image file format */
  159600. #define GIF_SUPPORTED /* GIF image file format */
  159601. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159602. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159603. #define TARGA_SUPPORTED /* Targa image file format */
  159604. #define TWO_FILE_COMMANDLINE /* optional */
  159605. #define USE_SETMODE /* Microsoft has setmode() */
  159606. #undef NEED_SIGNAL_CATCHER
  159607. #undef DONT_USE_B_MODE
  159608. #undef PROGRESS_REPORT /* optional */
  159609. #endif /* JPEG_CJPEG_DJPEG */
  159610. /*** End of inlined file: jconfig.h ***/
  159611. /* widely used configuration options */
  159612. #endif
  159613. /*** Start of inlined file: jmorecfg.h ***/
  159614. /*
  159615. * Define BITS_IN_JSAMPLE as either
  159616. * 8 for 8-bit sample values (the usual setting)
  159617. * 12 for 12-bit sample values
  159618. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159619. * JPEG standard, and the IJG code does not support anything else!
  159620. * We do not support run-time selection of data precision, sorry.
  159621. */
  159622. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159623. /*
  159624. * Maximum number of components (color channels) allowed in JPEG image.
  159625. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159626. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159627. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159628. * really short on memory. (Each allowed component costs a hundred or so
  159629. * bytes of storage, whether actually used in an image or not.)
  159630. */
  159631. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159632. /*
  159633. * Basic data types.
  159634. * You may need to change these if you have a machine with unusual data
  159635. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159636. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159637. * but it had better be at least 16.
  159638. */
  159639. /* Representation of a single sample (pixel element value).
  159640. * We frequently allocate large arrays of these, so it's important to keep
  159641. * them small. But if you have memory to burn and access to char or short
  159642. * arrays is very slow on your hardware, you might want to change these.
  159643. */
  159644. #if BITS_IN_JSAMPLE == 8
  159645. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159646. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159647. */
  159648. #ifdef HAVE_UNSIGNED_CHAR
  159649. typedef unsigned char JSAMPLE;
  159650. #define GETJSAMPLE(value) ((int) (value))
  159651. #else /* not HAVE_UNSIGNED_CHAR */
  159652. typedef char JSAMPLE;
  159653. #ifdef CHAR_IS_UNSIGNED
  159654. #define GETJSAMPLE(value) ((int) (value))
  159655. #else
  159656. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159657. #endif /* CHAR_IS_UNSIGNED */
  159658. #endif /* HAVE_UNSIGNED_CHAR */
  159659. #define MAXJSAMPLE 255
  159660. #define CENTERJSAMPLE 128
  159661. #endif /* BITS_IN_JSAMPLE == 8 */
  159662. #if BITS_IN_JSAMPLE == 12
  159663. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159664. * On nearly all machines "short" will do nicely.
  159665. */
  159666. typedef short JSAMPLE;
  159667. #define GETJSAMPLE(value) ((int) (value))
  159668. #define MAXJSAMPLE 4095
  159669. #define CENTERJSAMPLE 2048
  159670. #endif /* BITS_IN_JSAMPLE == 12 */
  159671. /* Representation of a DCT frequency coefficient.
  159672. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159673. * Again, we allocate large arrays of these, but you can change to int
  159674. * if you have memory to burn and "short" is really slow.
  159675. */
  159676. typedef short JCOEF;
  159677. /* Compressed datastreams are represented as arrays of JOCTET.
  159678. * These must be EXACTLY 8 bits wide, at least once they are written to
  159679. * external storage. Note that when using the stdio data source/destination
  159680. * managers, this is also the data type passed to fread/fwrite.
  159681. */
  159682. #ifdef HAVE_UNSIGNED_CHAR
  159683. typedef unsigned char JOCTET;
  159684. #define GETJOCTET(value) (value)
  159685. #else /* not HAVE_UNSIGNED_CHAR */
  159686. typedef char JOCTET;
  159687. #ifdef CHAR_IS_UNSIGNED
  159688. #define GETJOCTET(value) (value)
  159689. #else
  159690. #define GETJOCTET(value) ((value) & 0xFF)
  159691. #endif /* CHAR_IS_UNSIGNED */
  159692. #endif /* HAVE_UNSIGNED_CHAR */
  159693. /* These typedefs are used for various table entries and so forth.
  159694. * They must be at least as wide as specified; but making them too big
  159695. * won't cost a huge amount of memory, so we don't provide special
  159696. * extraction code like we did for JSAMPLE. (In other words, these
  159697. * typedefs live at a different point on the speed/space tradeoff curve.)
  159698. */
  159699. /* UINT8 must hold at least the values 0..255. */
  159700. #ifdef HAVE_UNSIGNED_CHAR
  159701. typedef unsigned char UINT8;
  159702. #else /* not HAVE_UNSIGNED_CHAR */
  159703. #ifdef CHAR_IS_UNSIGNED
  159704. typedef char UINT8;
  159705. #else /* not CHAR_IS_UNSIGNED */
  159706. typedef short UINT8;
  159707. #endif /* CHAR_IS_UNSIGNED */
  159708. #endif /* HAVE_UNSIGNED_CHAR */
  159709. /* UINT16 must hold at least the values 0..65535. */
  159710. #ifdef HAVE_UNSIGNED_SHORT
  159711. typedef unsigned short UINT16;
  159712. #else /* not HAVE_UNSIGNED_SHORT */
  159713. typedef unsigned int UINT16;
  159714. #endif /* HAVE_UNSIGNED_SHORT */
  159715. /* INT16 must hold at least the values -32768..32767. */
  159716. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159717. typedef short INT16;
  159718. #endif
  159719. /* INT32 must hold at least signed 32-bit values. */
  159720. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159721. typedef long INT32;
  159722. #endif
  159723. /* Datatype used for image dimensions. The JPEG standard only supports
  159724. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159725. * "unsigned int" is sufficient on all machines. However, if you need to
  159726. * handle larger images and you don't mind deviating from the spec, you
  159727. * can change this datatype.
  159728. */
  159729. typedef unsigned int JDIMENSION;
  159730. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159731. /* These macros are used in all function definitions and extern declarations.
  159732. * You could modify them if you need to change function linkage conventions;
  159733. * in particular, you'll need to do that to make the library a Windows DLL.
  159734. * Another application is to make all functions global for use with debuggers
  159735. * or code profilers that require it.
  159736. */
  159737. /* a function called through method pointers: */
  159738. #define METHODDEF(type) static type
  159739. /* a function used only in its module: */
  159740. #define LOCAL(type) static type
  159741. /* a function referenced thru EXTERNs: */
  159742. #define GLOBAL(type) type
  159743. /* a reference to a GLOBAL function: */
  159744. #define EXTERN(type) extern type
  159745. /* This macro is used to declare a "method", that is, a function pointer.
  159746. * We want to supply prototype parameters if the compiler can cope.
  159747. * Note that the arglist parameter must be parenthesized!
  159748. * Again, you can customize this if you need special linkage keywords.
  159749. */
  159750. #ifdef HAVE_PROTOTYPES
  159751. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159752. #else
  159753. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159754. #endif
  159755. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159756. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159757. * by just saying "FAR *" where such a pointer is needed. In a few places
  159758. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159759. */
  159760. #ifdef NEED_FAR_POINTERS
  159761. #define FAR far
  159762. #else
  159763. #define FAR
  159764. #endif
  159765. /*
  159766. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159767. * in standard header files. Or you may have conflicts with application-
  159768. * specific header files that you want to include together with these files.
  159769. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159770. */
  159771. #ifndef HAVE_BOOLEAN
  159772. typedef int boolean;
  159773. #endif
  159774. #ifndef FALSE /* in case these macros already exist */
  159775. #define FALSE 0 /* values of boolean */
  159776. #endif
  159777. #ifndef TRUE
  159778. #define TRUE 1
  159779. #endif
  159780. /*
  159781. * The remaining options affect code selection within the JPEG library,
  159782. * but they don't need to be visible to most applications using the library.
  159783. * To minimize application namespace pollution, the symbols won't be
  159784. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159785. */
  159786. #ifdef JPEG_INTERNALS
  159787. #define JPEG_INTERNAL_OPTIONS
  159788. #endif
  159789. #ifdef JPEG_INTERNAL_OPTIONS
  159790. /*
  159791. * These defines indicate whether to include various optional functions.
  159792. * Undefining some of these symbols will produce a smaller but less capable
  159793. * library. Note that you can leave certain source files out of the
  159794. * compilation/linking process if you've #undef'd the corresponding symbols.
  159795. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159796. */
  159797. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159798. /* Capability options common to encoder and decoder: */
  159799. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159800. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159801. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159802. /* Encoder capability options: */
  159803. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159804. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159805. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159806. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159807. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159808. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159809. * precision, so jchuff.c normally uses entropy optimization to compute
  159810. * usable tables for higher precision. If you don't want to do optimization,
  159811. * you'll have to supply different default Huffman tables.
  159812. * The exact same statements apply for progressive JPEG: the default tables
  159813. * don't work for progressive mode. (This may get fixed, however.)
  159814. */
  159815. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159816. /* Decoder capability options: */
  159817. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159818. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159819. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159820. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159821. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159822. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159823. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159824. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159825. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159826. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159827. /* more capability options later, no doubt */
  159828. /*
  159829. * Ordering of RGB data in scanlines passed to or from the application.
  159830. * If your application wants to deal with data in the order B,G,R, just
  159831. * change these macros. You can also deal with formats such as R,G,B,X
  159832. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159833. * the offsets will also change the order in which colormap data is organized.
  159834. * RESTRICTIONS:
  159835. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159836. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159837. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159838. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159839. * is not 3 (they don't understand about dummy color components!). So you
  159840. * can't use color quantization if you change that value.
  159841. */
  159842. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159843. #define RGB_GREEN 1 /* Offset of Green */
  159844. #define RGB_BLUE 2 /* Offset of Blue */
  159845. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159846. /* Definitions for speed-related optimizations. */
  159847. /* If your compiler supports inline functions, define INLINE
  159848. * as the inline keyword; otherwise define it as empty.
  159849. */
  159850. #ifndef INLINE
  159851. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159852. #define INLINE __inline__
  159853. #endif
  159854. #ifndef INLINE
  159855. #define INLINE /* default is to define it as empty */
  159856. #endif
  159857. #endif
  159858. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159859. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159860. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159861. */
  159862. #ifndef MULTIPLIER
  159863. #define MULTIPLIER int /* type for fastest integer multiply */
  159864. #endif
  159865. /* FAST_FLOAT should be either float or double, whichever is done faster
  159866. * by your compiler. (Note that this type is only used in the floating point
  159867. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159868. * Typically, float is faster in ANSI C compilers, while double is faster in
  159869. * pre-ANSI compilers (because they insist on converting to double anyway).
  159870. * The code below therefore chooses float if we have ANSI-style prototypes.
  159871. */
  159872. #ifndef FAST_FLOAT
  159873. #ifdef HAVE_PROTOTYPES
  159874. #define FAST_FLOAT float
  159875. #else
  159876. #define FAST_FLOAT double
  159877. #endif
  159878. #endif
  159879. #endif /* JPEG_INTERNAL_OPTIONS */
  159880. /*** End of inlined file: jmorecfg.h ***/
  159881. /* seldom changed options */
  159882. /* Version ID for the JPEG library.
  159883. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159884. */
  159885. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159886. /* Various constants determining the sizes of things.
  159887. * All of these are specified by the JPEG standard, so don't change them
  159888. * if you want to be compatible.
  159889. */
  159890. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159891. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159892. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159893. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159894. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159895. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159896. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159897. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159898. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159899. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159900. * to handle it. We even let you do this from the jconfig.h file. However,
  159901. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159902. * sometimes emits noncompliant files doesn't mean you should too.
  159903. */
  159904. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159905. #ifndef D_MAX_BLOCKS_IN_MCU
  159906. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159907. #endif
  159908. /* Data structures for images (arrays of samples and of DCT coefficients).
  159909. * On 80x86 machines, the image arrays are too big for near pointers,
  159910. * but the pointer arrays can fit in near memory.
  159911. */
  159912. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159913. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159914. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159915. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159916. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159917. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159918. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159919. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159920. /* Types for JPEG compression parameters and working tables. */
  159921. /* DCT coefficient quantization tables. */
  159922. typedef struct {
  159923. /* This array gives the coefficient quantizers in natural array order
  159924. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159925. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159926. */
  159927. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159928. /* This field is used only during compression. It's initialized FALSE when
  159929. * the table is created, and set TRUE when it's been output to the file.
  159930. * You could suppress output of a table by setting this to TRUE.
  159931. * (See jpeg_suppress_tables for an example.)
  159932. */
  159933. boolean sent_table; /* TRUE when table has been output */
  159934. } JQUANT_TBL;
  159935. /* Huffman coding tables. */
  159936. typedef struct {
  159937. /* These two fields directly represent the contents of a JPEG DHT marker */
  159938. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159939. /* length k bits; bits[0] is unused */
  159940. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159941. /* This field is used only during compression. It's initialized FALSE when
  159942. * the table is created, and set TRUE when it's been output to the file.
  159943. * You could suppress output of a table by setting this to TRUE.
  159944. * (See jpeg_suppress_tables for an example.)
  159945. */
  159946. boolean sent_table; /* TRUE when table has been output */
  159947. } JHUFF_TBL;
  159948. /* Basic info about one component (color channel). */
  159949. typedef struct {
  159950. /* These values are fixed over the whole image. */
  159951. /* For compression, they must be supplied by parameter setup; */
  159952. /* for decompression, they are read from the SOF marker. */
  159953. int component_id; /* identifier for this component (0..255) */
  159954. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159955. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159956. int v_samp_factor; /* vertical sampling factor (1..4) */
  159957. int quant_tbl_no; /* quantization table selector (0..3) */
  159958. /* These values may vary between scans. */
  159959. /* For compression, they must be supplied by parameter setup; */
  159960. /* for decompression, they are read from the SOS marker. */
  159961. /* The decompressor output side may not use these variables. */
  159962. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159963. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159964. /* Remaining fields should be treated as private by applications. */
  159965. /* These values are computed during compression or decompression startup: */
  159966. /* Component's size in DCT blocks.
  159967. * Any dummy blocks added to complete an MCU are not counted; therefore
  159968. * these values do not depend on whether a scan is interleaved or not.
  159969. */
  159970. JDIMENSION width_in_blocks;
  159971. JDIMENSION height_in_blocks;
  159972. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159973. * For decompression this is the size of the output from one DCT block,
  159974. * reflecting any scaling we choose to apply during the IDCT step.
  159975. * Values of 1,2,4,8 are likely to be supported. Note that different
  159976. * components may receive different IDCT scalings.
  159977. */
  159978. int DCT_scaled_size;
  159979. /* The downsampled dimensions are the component's actual, unpadded number
  159980. * of samples at the main buffer (preprocessing/compression interface), thus
  159981. * downsampled_width = ceil(image_width * Hi/Hmax)
  159982. * and similarly for height. For decompression, IDCT scaling is included, so
  159983. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159984. */
  159985. JDIMENSION downsampled_width; /* actual width in samples */
  159986. JDIMENSION downsampled_height; /* actual height in samples */
  159987. /* This flag is used only for decompression. In cases where some of the
  159988. * components will be ignored (eg grayscale output from YCbCr image),
  159989. * we can skip most computations for the unused components.
  159990. */
  159991. boolean component_needed; /* do we need the value of this component? */
  159992. /* These values are computed before starting a scan of the component. */
  159993. /* The decompressor output side may not use these variables. */
  159994. int MCU_width; /* number of blocks per MCU, horizontally */
  159995. int MCU_height; /* number of blocks per MCU, vertically */
  159996. int MCU_blocks; /* MCU_width * MCU_height */
  159997. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159998. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159999. int last_row_height; /* # of non-dummy blocks down in last MCU */
  160000. /* Saved quantization table for component; NULL if none yet saved.
  160001. * See jdinput.c comments about the need for this information.
  160002. * This field is currently used only for decompression.
  160003. */
  160004. JQUANT_TBL * quant_table;
  160005. /* Private per-component storage for DCT or IDCT subsystem. */
  160006. void * dct_table;
  160007. } jpeg_component_info;
  160008. /* The script for encoding a multiple-scan file is an array of these: */
  160009. typedef struct {
  160010. int comps_in_scan; /* number of components encoded in this scan */
  160011. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  160012. int Ss, Se; /* progressive JPEG spectral selection parms */
  160013. int Ah, Al; /* progressive JPEG successive approx. parms */
  160014. } jpeg_scan_info;
  160015. /* The decompressor can save APPn and COM markers in a list of these: */
  160016. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  160017. struct jpeg_marker_struct {
  160018. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  160019. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  160020. unsigned int original_length; /* # bytes of data in the file */
  160021. unsigned int data_length; /* # bytes of data saved at data[] */
  160022. JOCTET FAR * data; /* the data contained in the marker */
  160023. /* the marker length word is not counted in data_length or original_length */
  160024. };
  160025. /* Known color spaces. */
  160026. typedef enum {
  160027. JCS_UNKNOWN, /* error/unspecified */
  160028. JCS_GRAYSCALE, /* monochrome */
  160029. JCS_RGB, /* red/green/blue */
  160030. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  160031. JCS_CMYK, /* C/M/Y/K */
  160032. JCS_YCCK /* Y/Cb/Cr/K */
  160033. } J_COLOR_SPACE;
  160034. /* DCT/IDCT algorithm options. */
  160035. typedef enum {
  160036. JDCT_ISLOW, /* slow but accurate integer algorithm */
  160037. JDCT_IFAST, /* faster, less accurate integer method */
  160038. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  160039. } J_DCT_METHOD;
  160040. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  160041. #define JDCT_DEFAULT JDCT_ISLOW
  160042. #endif
  160043. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  160044. #define JDCT_FASTEST JDCT_IFAST
  160045. #endif
  160046. /* Dithering options for decompression. */
  160047. typedef enum {
  160048. JDITHER_NONE, /* no dithering */
  160049. JDITHER_ORDERED, /* simple ordered dither */
  160050. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  160051. } J_DITHER_MODE;
  160052. /* Common fields between JPEG compression and decompression master structs. */
  160053. #define jpeg_common_fields \
  160054. struct jpeg_error_mgr * err; /* Error handler module */\
  160055. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  160056. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  160057. void * client_data; /* Available for use by application */\
  160058. boolean is_decompressor; /* So common code can tell which is which */\
  160059. int global_state /* For checking call sequence validity */
  160060. /* Routines that are to be used by both halves of the library are declared
  160061. * to receive a pointer to this structure. There are no actual instances of
  160062. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160063. */
  160064. struct jpeg_common_struct {
  160065. jpeg_common_fields; /* Fields common to both master struct types */
  160066. /* Additional fields follow in an actual jpeg_compress_struct or
  160067. * jpeg_decompress_struct. All three structs must agree on these
  160068. * initial fields! (This would be a lot cleaner in C++.)
  160069. */
  160070. };
  160071. typedef struct jpeg_common_struct * j_common_ptr;
  160072. typedef struct jpeg_compress_struct * j_compress_ptr;
  160073. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160074. /* Master record for a compression instance */
  160075. struct jpeg_compress_struct {
  160076. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160077. /* Destination for compressed data */
  160078. struct jpeg_destination_mgr * dest;
  160079. /* Description of source image --- these fields must be filled in by
  160080. * outer application before starting compression. in_color_space must
  160081. * be correct before you can even call jpeg_set_defaults().
  160082. */
  160083. JDIMENSION image_width; /* input image width */
  160084. JDIMENSION image_height; /* input image height */
  160085. int input_components; /* # of color components in input image */
  160086. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160087. double input_gamma; /* image gamma of input image */
  160088. /* Compression parameters --- these fields must be set before calling
  160089. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160090. * initialize everything to reasonable defaults, then changing anything
  160091. * the application specifically wants to change. That way you won't get
  160092. * burnt when new parameters are added. Also note that there are several
  160093. * helper routines to simplify changing parameters.
  160094. */
  160095. int data_precision; /* bits of precision in image data */
  160096. int num_components; /* # of color components in JPEG image */
  160097. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160098. jpeg_component_info * comp_info;
  160099. /* comp_info[i] describes component that appears i'th in SOF */
  160100. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160101. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160102. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160103. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160104. /* ptrs to Huffman coding tables, or NULL if not defined */
  160105. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160106. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160107. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160108. int num_scans; /* # of entries in scan_info array */
  160109. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160110. /* The default value of scan_info is NULL, which causes a single-scan
  160111. * sequential JPEG file to be emitted. To create a multi-scan file,
  160112. * set num_scans and scan_info to point to an array of scan definitions.
  160113. */
  160114. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160115. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160116. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160117. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160118. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160119. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160120. /* The restart interval can be specified in absolute MCUs by setting
  160121. * restart_interval, or in MCU rows by setting restart_in_rows
  160122. * (in which case the correct restart_interval will be figured
  160123. * for each scan).
  160124. */
  160125. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160126. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160127. /* Parameters controlling emission of special markers. */
  160128. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160129. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160130. UINT8 JFIF_minor_version;
  160131. /* These three values are not used by the JPEG code, merely copied */
  160132. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160133. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160134. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160135. UINT8 density_unit; /* JFIF code for pixel size units */
  160136. UINT16 X_density; /* Horizontal pixel density */
  160137. UINT16 Y_density; /* Vertical pixel density */
  160138. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160139. /* State variable: index of next scanline to be written to
  160140. * jpeg_write_scanlines(). Application may use this to control its
  160141. * processing loop, e.g., "while (next_scanline < image_height)".
  160142. */
  160143. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160144. /* Remaining fields are known throughout compressor, but generally
  160145. * should not be touched by a surrounding application.
  160146. */
  160147. /*
  160148. * These fields are computed during compression startup
  160149. */
  160150. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160151. int max_h_samp_factor; /* largest h_samp_factor */
  160152. int max_v_samp_factor; /* largest v_samp_factor */
  160153. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160154. /* The coefficient controller receives data in units of MCU rows as defined
  160155. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160156. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160157. * "iMCU" (interleaved MCU) row.
  160158. */
  160159. /*
  160160. * These fields are valid during any one scan.
  160161. * They describe the components and MCUs actually appearing in the scan.
  160162. */
  160163. int comps_in_scan; /* # of JPEG components in this scan */
  160164. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160165. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160166. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160167. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160168. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160169. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160170. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160171. /* i'th block in an MCU */
  160172. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160173. /*
  160174. * Links to compression subobjects (methods and private variables of modules)
  160175. */
  160176. struct jpeg_comp_master * master;
  160177. struct jpeg_c_main_controller * main;
  160178. struct jpeg_c_prep_controller * prep;
  160179. struct jpeg_c_coef_controller * coef;
  160180. struct jpeg_marker_writer * marker;
  160181. struct jpeg_color_converter * cconvert;
  160182. struct jpeg_downsampler * downsample;
  160183. struct jpeg_forward_dct * fdct;
  160184. struct jpeg_entropy_encoder * entropy;
  160185. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160186. int script_space_size;
  160187. };
  160188. /* Master record for a decompression instance */
  160189. struct jpeg_decompress_struct {
  160190. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160191. /* Source of compressed data */
  160192. struct jpeg_source_mgr * src;
  160193. /* Basic description of image --- filled in by jpeg_read_header(). */
  160194. /* Application may inspect these values to decide how to process image. */
  160195. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160196. JDIMENSION image_height; /* nominal image height */
  160197. int num_components; /* # of color components in JPEG image */
  160198. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160199. /* Decompression processing parameters --- these fields must be set before
  160200. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160201. * them to default values.
  160202. */
  160203. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160204. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160205. double output_gamma; /* image gamma wanted in output */
  160206. boolean buffered_image; /* TRUE=multiple output passes */
  160207. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160208. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160209. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160210. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160211. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160212. /* the following are ignored if not quantize_colors: */
  160213. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160214. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160215. int desired_number_of_colors; /* max # colors to use in created colormap */
  160216. /* these are significant only in buffered-image mode: */
  160217. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160218. boolean enable_external_quant;/* enable future use of external colormap */
  160219. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160220. /* Description of actual output image that will be returned to application.
  160221. * These fields are computed by jpeg_start_decompress().
  160222. * You can also use jpeg_calc_output_dimensions() to determine these values
  160223. * in advance of calling jpeg_start_decompress().
  160224. */
  160225. JDIMENSION output_width; /* scaled image width */
  160226. JDIMENSION output_height; /* scaled image height */
  160227. int out_color_components; /* # of color components in out_color_space */
  160228. int output_components; /* # of color components returned */
  160229. /* output_components is 1 (a colormap index) when quantizing colors;
  160230. * otherwise it equals out_color_components.
  160231. */
  160232. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160233. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160234. * high, space and time will be wasted due to unnecessary data copying.
  160235. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160236. */
  160237. /* When quantizing colors, the output colormap is described by these fields.
  160238. * The application can supply a colormap by setting colormap non-NULL before
  160239. * calling jpeg_start_decompress; otherwise a colormap is created during
  160240. * jpeg_start_decompress or jpeg_start_output.
  160241. * The map has out_color_components rows and actual_number_of_colors columns.
  160242. */
  160243. int actual_number_of_colors; /* number of entries in use */
  160244. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160245. /* State variables: these variables indicate the progress of decompression.
  160246. * The application may examine these but must not modify them.
  160247. */
  160248. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160249. * Application may use this to control its processing loop, e.g.,
  160250. * "while (output_scanline < output_height)".
  160251. */
  160252. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160253. /* Current input scan number and number of iMCU rows completed in scan.
  160254. * These indicate the progress of the decompressor input side.
  160255. */
  160256. int input_scan_number; /* Number of SOS markers seen so far */
  160257. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160258. /* The "output scan number" is the notional scan being displayed by the
  160259. * output side. The decompressor will not allow output scan/row number
  160260. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160261. */
  160262. int output_scan_number; /* Nominal scan number being displayed */
  160263. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160264. /* Current progression status. coef_bits[c][i] indicates the precision
  160265. * with which component c's DCT coefficient i (in zigzag order) is known.
  160266. * It is -1 when no data has yet been received, otherwise it is the point
  160267. * transform (shift) value for the most recent scan of the coefficient
  160268. * (thus, 0 at completion of the progression).
  160269. * This pointer is NULL when reading a non-progressive file.
  160270. */
  160271. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160272. /* Internal JPEG parameters --- the application usually need not look at
  160273. * these fields. Note that the decompressor output side may not use
  160274. * any parameters that can change between scans.
  160275. */
  160276. /* Quantization and Huffman tables are carried forward across input
  160277. * datastreams when processing abbreviated JPEG datastreams.
  160278. */
  160279. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160280. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160281. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160282. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160283. /* ptrs to Huffman coding tables, or NULL if not defined */
  160284. /* These parameters are never carried across datastreams, since they
  160285. * are given in SOF/SOS markers or defined to be reset by SOI.
  160286. */
  160287. int data_precision; /* bits of precision in image data */
  160288. jpeg_component_info * comp_info;
  160289. /* comp_info[i] describes component that appears i'th in SOF */
  160290. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160291. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160292. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160293. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160294. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160295. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160296. /* These fields record data obtained from optional markers recognized by
  160297. * the JPEG library.
  160298. */
  160299. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160300. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160301. UINT8 JFIF_major_version; /* JFIF version number */
  160302. UINT8 JFIF_minor_version;
  160303. UINT8 density_unit; /* JFIF code for pixel size units */
  160304. UINT16 X_density; /* Horizontal pixel density */
  160305. UINT16 Y_density; /* Vertical pixel density */
  160306. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160307. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160308. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160309. /* Aside from the specific data retained from APPn markers known to the
  160310. * library, the uninterpreted contents of any or all APPn and COM markers
  160311. * can be saved in a list for examination by the application.
  160312. */
  160313. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160314. /* Remaining fields are known throughout decompressor, but generally
  160315. * should not be touched by a surrounding application.
  160316. */
  160317. /*
  160318. * These fields are computed during decompression startup
  160319. */
  160320. int max_h_samp_factor; /* largest h_samp_factor */
  160321. int max_v_samp_factor; /* largest v_samp_factor */
  160322. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160323. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160324. /* The coefficient controller's input and output progress is measured in
  160325. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160326. * in fully interleaved JPEG scans, but are used whether the scan is
  160327. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160328. * rows of each component. Therefore, the IDCT output contains
  160329. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160330. */
  160331. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160332. /*
  160333. * These fields are valid during any one scan.
  160334. * They describe the components and MCUs actually appearing in the scan.
  160335. * Note that the decompressor output side must not use these fields.
  160336. */
  160337. int comps_in_scan; /* # of JPEG components in this scan */
  160338. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160339. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160340. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160341. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160342. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160343. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160344. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160345. /* i'th block in an MCU */
  160346. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160347. /* This field is shared between entropy decoder and marker parser.
  160348. * It is either zero or the code of a JPEG marker that has been
  160349. * read from the data source, but has not yet been processed.
  160350. */
  160351. int unread_marker;
  160352. /*
  160353. * Links to decompression subobjects (methods, private variables of modules)
  160354. */
  160355. struct jpeg_decomp_master * master;
  160356. struct jpeg_d_main_controller * main;
  160357. struct jpeg_d_coef_controller * coef;
  160358. struct jpeg_d_post_controller * post;
  160359. struct jpeg_input_controller * inputctl;
  160360. struct jpeg_marker_reader * marker;
  160361. struct jpeg_entropy_decoder * entropy;
  160362. struct jpeg_inverse_dct * idct;
  160363. struct jpeg_upsampler * upsample;
  160364. struct jpeg_color_deconverter * cconvert;
  160365. struct jpeg_color_quantizer * cquantize;
  160366. };
  160367. /* "Object" declarations for JPEG modules that may be supplied or called
  160368. * directly by the surrounding application.
  160369. * As with all objects in the JPEG library, these structs only define the
  160370. * publicly visible methods and state variables of a module. Additional
  160371. * private fields may exist after the public ones.
  160372. */
  160373. /* Error handler object */
  160374. struct jpeg_error_mgr {
  160375. /* Error exit handler: does not return to caller */
  160376. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160377. /* Conditionally emit a trace or warning message */
  160378. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160379. /* Routine that actually outputs a trace or error message */
  160380. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160381. /* Format a message string for the most recent JPEG error or message */
  160382. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160383. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160384. /* Reset error state variables at start of a new image */
  160385. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160386. /* The message ID code and any parameters are saved here.
  160387. * A message can have one string parameter or up to 8 int parameters.
  160388. */
  160389. int msg_code;
  160390. #define JMSG_STR_PARM_MAX 80
  160391. union {
  160392. int i[8];
  160393. char s[JMSG_STR_PARM_MAX];
  160394. } msg_parm;
  160395. /* Standard state variables for error facility */
  160396. int trace_level; /* max msg_level that will be displayed */
  160397. /* For recoverable corrupt-data errors, we emit a warning message,
  160398. * but keep going unless emit_message chooses to abort. emit_message
  160399. * should count warnings in num_warnings. The surrounding application
  160400. * can check for bad data by seeing if num_warnings is nonzero at the
  160401. * end of processing.
  160402. */
  160403. long num_warnings; /* number of corrupt-data warnings */
  160404. /* These fields point to the table(s) of error message strings.
  160405. * An application can change the table pointer to switch to a different
  160406. * message list (typically, to change the language in which errors are
  160407. * reported). Some applications may wish to add additional error codes
  160408. * that will be handled by the JPEG library error mechanism; the second
  160409. * table pointer is used for this purpose.
  160410. *
  160411. * First table includes all errors generated by JPEG library itself.
  160412. * Error code 0 is reserved for a "no such error string" message.
  160413. */
  160414. const char * const * jpeg_message_table; /* Library errors */
  160415. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160416. /* Second table can be added by application (see cjpeg/djpeg for example).
  160417. * It contains strings numbered first_addon_message..last_addon_message.
  160418. */
  160419. const char * const * addon_message_table; /* Non-library errors */
  160420. int first_addon_message; /* code for first string in addon table */
  160421. int last_addon_message; /* code for last string in addon table */
  160422. };
  160423. /* Progress monitor object */
  160424. struct jpeg_progress_mgr {
  160425. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160426. long pass_counter; /* work units completed in this pass */
  160427. long pass_limit; /* total number of work units in this pass */
  160428. int completed_passes; /* passes completed so far */
  160429. int total_passes; /* total number of passes expected */
  160430. };
  160431. /* Data destination object for compression */
  160432. struct jpeg_destination_mgr {
  160433. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160434. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160435. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160436. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160437. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160438. };
  160439. /* Data source object for decompression */
  160440. struct jpeg_source_mgr {
  160441. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160442. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160443. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160444. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160445. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160446. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160447. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160448. };
  160449. /* Memory manager object.
  160450. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160451. * and "really big" objects (virtual arrays with backing store if needed).
  160452. * The memory manager does not allow individual objects to be freed; rather,
  160453. * each created object is assigned to a pool, and whole pools can be freed
  160454. * at once. This is faster and more convenient than remembering exactly what
  160455. * to free, especially where malloc()/free() are not too speedy.
  160456. * NB: alloc routines never return NULL. They exit to error_exit if not
  160457. * successful.
  160458. */
  160459. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160460. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160461. #define JPOOL_NUMPOOLS 2
  160462. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160463. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160464. struct jpeg_memory_mgr {
  160465. /* Method pointers */
  160466. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160467. size_t sizeofobject));
  160468. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160469. size_t sizeofobject));
  160470. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160471. JDIMENSION samplesperrow,
  160472. JDIMENSION numrows));
  160473. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160474. JDIMENSION blocksperrow,
  160475. JDIMENSION numrows));
  160476. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160477. int pool_id,
  160478. boolean pre_zero,
  160479. JDIMENSION samplesperrow,
  160480. JDIMENSION numrows,
  160481. JDIMENSION maxaccess));
  160482. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160483. int pool_id,
  160484. boolean pre_zero,
  160485. JDIMENSION blocksperrow,
  160486. JDIMENSION numrows,
  160487. JDIMENSION maxaccess));
  160488. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160489. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160490. jvirt_sarray_ptr ptr,
  160491. JDIMENSION start_row,
  160492. JDIMENSION num_rows,
  160493. boolean writable));
  160494. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160495. jvirt_barray_ptr ptr,
  160496. JDIMENSION start_row,
  160497. JDIMENSION num_rows,
  160498. boolean writable));
  160499. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160500. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160501. /* Limit on memory allocation for this JPEG object. (Note that this is
  160502. * merely advisory, not a guaranteed maximum; it only affects the space
  160503. * used for virtual-array buffers.) May be changed by outer application
  160504. * after creating the JPEG object.
  160505. */
  160506. long max_memory_to_use;
  160507. /* Maximum allocation request accepted by alloc_large. */
  160508. long max_alloc_chunk;
  160509. };
  160510. /* Routine signature for application-supplied marker processing methods.
  160511. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160512. */
  160513. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160514. /* Declarations for routines called by application.
  160515. * The JPP macro hides prototype parameters from compilers that can't cope.
  160516. * Note JPP requires double parentheses.
  160517. */
  160518. #ifdef HAVE_PROTOTYPES
  160519. #define JPP(arglist) arglist
  160520. #else
  160521. #define JPP(arglist) ()
  160522. #endif
  160523. /* Short forms of external names for systems with brain-damaged linkers.
  160524. * We shorten external names to be unique in the first six letters, which
  160525. * is good enough for all known systems.
  160526. * (If your compiler itself needs names to be unique in less than 15
  160527. * characters, you are out of luck. Get a better compiler.)
  160528. */
  160529. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160530. #define jpeg_std_error jStdError
  160531. #define jpeg_CreateCompress jCreaCompress
  160532. #define jpeg_CreateDecompress jCreaDecompress
  160533. #define jpeg_destroy_compress jDestCompress
  160534. #define jpeg_destroy_decompress jDestDecompress
  160535. #define jpeg_stdio_dest jStdDest
  160536. #define jpeg_stdio_src jStdSrc
  160537. #define jpeg_set_defaults jSetDefaults
  160538. #define jpeg_set_colorspace jSetColorspace
  160539. #define jpeg_default_colorspace jDefColorspace
  160540. #define jpeg_set_quality jSetQuality
  160541. #define jpeg_set_linear_quality jSetLQuality
  160542. #define jpeg_add_quant_table jAddQuantTable
  160543. #define jpeg_quality_scaling jQualityScaling
  160544. #define jpeg_simple_progression jSimProgress
  160545. #define jpeg_suppress_tables jSuppressTables
  160546. #define jpeg_alloc_quant_table jAlcQTable
  160547. #define jpeg_alloc_huff_table jAlcHTable
  160548. #define jpeg_start_compress jStrtCompress
  160549. #define jpeg_write_scanlines jWrtScanlines
  160550. #define jpeg_finish_compress jFinCompress
  160551. #define jpeg_write_raw_data jWrtRawData
  160552. #define jpeg_write_marker jWrtMarker
  160553. #define jpeg_write_m_header jWrtMHeader
  160554. #define jpeg_write_m_byte jWrtMByte
  160555. #define jpeg_write_tables jWrtTables
  160556. #define jpeg_read_header jReadHeader
  160557. #define jpeg_start_decompress jStrtDecompress
  160558. #define jpeg_read_scanlines jReadScanlines
  160559. #define jpeg_finish_decompress jFinDecompress
  160560. #define jpeg_read_raw_data jReadRawData
  160561. #define jpeg_has_multiple_scans jHasMultScn
  160562. #define jpeg_start_output jStrtOutput
  160563. #define jpeg_finish_output jFinOutput
  160564. #define jpeg_input_complete jInComplete
  160565. #define jpeg_new_colormap jNewCMap
  160566. #define jpeg_consume_input jConsumeInput
  160567. #define jpeg_calc_output_dimensions jCalcDimensions
  160568. #define jpeg_save_markers jSaveMarkers
  160569. #define jpeg_set_marker_processor jSetMarker
  160570. #define jpeg_read_coefficients jReadCoefs
  160571. #define jpeg_write_coefficients jWrtCoefs
  160572. #define jpeg_copy_critical_parameters jCopyCrit
  160573. #define jpeg_abort_compress jAbrtCompress
  160574. #define jpeg_abort_decompress jAbrtDecompress
  160575. #define jpeg_abort jAbort
  160576. #define jpeg_destroy jDestroy
  160577. #define jpeg_resync_to_restart jResyncRestart
  160578. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160579. /* Default error-management setup */
  160580. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160581. JPP((struct jpeg_error_mgr * err));
  160582. /* Initialization of JPEG compression objects.
  160583. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160584. * names that applications should call. These expand to calls on
  160585. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160586. * passed for version mismatch checking.
  160587. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160588. */
  160589. #define jpeg_create_compress(cinfo) \
  160590. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160591. (size_t) sizeof(struct jpeg_compress_struct))
  160592. #define jpeg_create_decompress(cinfo) \
  160593. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160594. (size_t) sizeof(struct jpeg_decompress_struct))
  160595. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160596. int version, size_t structsize));
  160597. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160598. int version, size_t structsize));
  160599. /* Destruction of JPEG compression objects */
  160600. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160601. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160602. /* Standard data source and destination managers: stdio streams. */
  160603. /* Caller is responsible for opening the file before and closing after. */
  160604. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160605. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160606. /* Default parameter setup for compression */
  160607. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160608. /* Compression parameter setup aids */
  160609. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160610. J_COLOR_SPACE colorspace));
  160611. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160612. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160613. boolean force_baseline));
  160614. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160615. int scale_factor,
  160616. boolean force_baseline));
  160617. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160618. const unsigned int *basic_table,
  160619. int scale_factor,
  160620. boolean force_baseline));
  160621. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160622. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160623. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160624. boolean suppress));
  160625. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160626. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160627. /* Main entry points for compression */
  160628. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160629. boolean write_all_tables));
  160630. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160631. JSAMPARRAY scanlines,
  160632. JDIMENSION num_lines));
  160633. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160634. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160635. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160636. JSAMPIMAGE data,
  160637. JDIMENSION num_lines));
  160638. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160639. EXTERN(void) jpeg_write_marker
  160640. JPP((j_compress_ptr cinfo, int marker,
  160641. const JOCTET * dataptr, unsigned int datalen));
  160642. /* Same, but piecemeal. */
  160643. EXTERN(void) jpeg_write_m_header
  160644. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160645. EXTERN(void) jpeg_write_m_byte
  160646. JPP((j_compress_ptr cinfo, int val));
  160647. /* Alternate compression function: just write an abbreviated table file */
  160648. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160649. /* Decompression startup: read start of JPEG datastream to see what's there */
  160650. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160651. boolean require_image));
  160652. /* Return value is one of: */
  160653. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160654. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160655. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160656. /* If you pass require_image = TRUE (normal case), you need not check for
  160657. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160658. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160659. * give a suspension return (the stdio source module doesn't).
  160660. */
  160661. /* Main entry points for decompression */
  160662. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160663. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160664. JSAMPARRAY scanlines,
  160665. JDIMENSION max_lines));
  160666. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160667. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160668. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160669. JSAMPIMAGE data,
  160670. JDIMENSION max_lines));
  160671. /* Additional entry points for buffered-image mode. */
  160672. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160673. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160674. int scan_number));
  160675. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160676. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160677. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160678. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160679. /* Return value is one of: */
  160680. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160681. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160682. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160683. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160684. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160685. /* Precalculate output dimensions for current decompression parameters. */
  160686. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160687. /* Control saving of COM and APPn markers into marker_list. */
  160688. EXTERN(void) jpeg_save_markers
  160689. JPP((j_decompress_ptr cinfo, int marker_code,
  160690. unsigned int length_limit));
  160691. /* Install a special processing method for COM or APPn markers. */
  160692. EXTERN(void) jpeg_set_marker_processor
  160693. JPP((j_decompress_ptr cinfo, int marker_code,
  160694. jpeg_marker_parser_method routine));
  160695. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160696. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160697. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160698. jvirt_barray_ptr * coef_arrays));
  160699. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160700. j_compress_ptr dstinfo));
  160701. /* If you choose to abort compression or decompression before completing
  160702. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160703. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160704. * if you're done with the JPEG object, but if you want to clean it up and
  160705. * reuse it, call this:
  160706. */
  160707. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160708. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160709. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160710. * flavor of JPEG object. These may be more convenient in some places.
  160711. */
  160712. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160713. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160714. /* Default restart-marker-resync procedure for use by data source modules */
  160715. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160716. int desired));
  160717. /* These marker codes are exported since applications and data source modules
  160718. * are likely to want to use them.
  160719. */
  160720. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160721. #define JPEG_EOI 0xD9 /* EOI marker code */
  160722. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160723. #define JPEG_COM 0xFE /* COM marker code */
  160724. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160725. * for structure definitions that are never filled in, keep it quiet by
  160726. * supplying dummy definitions for the various substructures.
  160727. */
  160728. #ifdef INCOMPLETE_TYPES_BROKEN
  160729. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160730. struct jvirt_sarray_control { long dummy; };
  160731. struct jvirt_barray_control { long dummy; };
  160732. struct jpeg_comp_master { long dummy; };
  160733. struct jpeg_c_main_controller { long dummy; };
  160734. struct jpeg_c_prep_controller { long dummy; };
  160735. struct jpeg_c_coef_controller { long dummy; };
  160736. struct jpeg_marker_writer { long dummy; };
  160737. struct jpeg_color_converter { long dummy; };
  160738. struct jpeg_downsampler { long dummy; };
  160739. struct jpeg_forward_dct { long dummy; };
  160740. struct jpeg_entropy_encoder { long dummy; };
  160741. struct jpeg_decomp_master { long dummy; };
  160742. struct jpeg_d_main_controller { long dummy; };
  160743. struct jpeg_d_coef_controller { long dummy; };
  160744. struct jpeg_d_post_controller { long dummy; };
  160745. struct jpeg_input_controller { long dummy; };
  160746. struct jpeg_marker_reader { long dummy; };
  160747. struct jpeg_entropy_decoder { long dummy; };
  160748. struct jpeg_inverse_dct { long dummy; };
  160749. struct jpeg_upsampler { long dummy; };
  160750. struct jpeg_color_deconverter { long dummy; };
  160751. struct jpeg_color_quantizer { long dummy; };
  160752. #endif /* JPEG_INTERNALS */
  160753. #endif /* INCOMPLETE_TYPES_BROKEN */
  160754. /*
  160755. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160756. * The internal structure declarations are read only when that is true.
  160757. * Applications using the library should not include jpegint.h, but may wish
  160758. * to include jerror.h.
  160759. */
  160760. #ifdef JPEG_INTERNALS
  160761. /*** Start of inlined file: jpegint.h ***/
  160762. /* Declarations for both compression & decompression */
  160763. typedef enum { /* Operating modes for buffer controllers */
  160764. JBUF_PASS_THRU, /* Plain stripwise operation */
  160765. /* Remaining modes require a full-image buffer to have been created */
  160766. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160767. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160768. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160769. } J_BUF_MODE;
  160770. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160771. #define CSTATE_START 100 /* after create_compress */
  160772. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160773. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160774. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160775. #define DSTATE_START 200 /* after create_decompress */
  160776. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160777. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160778. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160779. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160780. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160781. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160782. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160783. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160784. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160785. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160786. /* Declarations for compression modules */
  160787. /* Master control module */
  160788. struct jpeg_comp_master {
  160789. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160790. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160791. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160792. /* State variables made visible to other modules */
  160793. boolean call_pass_startup; /* True if pass_startup must be called */
  160794. boolean is_last_pass; /* True during last pass */
  160795. };
  160796. /* Main buffer control (downsampled-data buffer) */
  160797. struct jpeg_c_main_controller {
  160798. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160799. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160800. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160801. JDIMENSION in_rows_avail));
  160802. };
  160803. /* Compression preprocessing (downsampling input buffer control) */
  160804. struct jpeg_c_prep_controller {
  160805. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160806. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160807. JSAMPARRAY input_buf,
  160808. JDIMENSION *in_row_ctr,
  160809. JDIMENSION in_rows_avail,
  160810. JSAMPIMAGE output_buf,
  160811. JDIMENSION *out_row_group_ctr,
  160812. JDIMENSION out_row_groups_avail));
  160813. };
  160814. /* Coefficient buffer control */
  160815. struct jpeg_c_coef_controller {
  160816. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160817. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160818. JSAMPIMAGE input_buf));
  160819. };
  160820. /* Colorspace conversion */
  160821. struct jpeg_color_converter {
  160822. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160823. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160824. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160825. JDIMENSION output_row, int num_rows));
  160826. };
  160827. /* Downsampling */
  160828. struct jpeg_downsampler {
  160829. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160830. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160831. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160832. JSAMPIMAGE output_buf,
  160833. JDIMENSION out_row_group_index));
  160834. boolean need_context_rows; /* TRUE if need rows above & below */
  160835. };
  160836. /* Forward DCT (also controls coefficient quantization) */
  160837. struct jpeg_forward_dct {
  160838. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160839. /* perhaps this should be an array??? */
  160840. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160841. jpeg_component_info * compptr,
  160842. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160843. JDIMENSION start_row, JDIMENSION start_col,
  160844. JDIMENSION num_blocks));
  160845. };
  160846. /* Entropy encoding */
  160847. struct jpeg_entropy_encoder {
  160848. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160849. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160850. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160851. };
  160852. /* Marker writing */
  160853. struct jpeg_marker_writer {
  160854. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160855. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160856. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160857. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160858. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160859. /* These routines are exported to allow insertion of extra markers */
  160860. /* Probably only COM and APPn markers should be written this way */
  160861. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160862. unsigned int datalen));
  160863. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160864. };
  160865. /* Declarations for decompression modules */
  160866. /* Master control module */
  160867. struct jpeg_decomp_master {
  160868. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160869. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160870. /* State variables made visible to other modules */
  160871. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160872. };
  160873. /* Input control module */
  160874. struct jpeg_input_controller {
  160875. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160876. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160877. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160878. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160879. /* State variables made visible to other modules */
  160880. boolean has_multiple_scans; /* True if file has multiple scans */
  160881. boolean eoi_reached; /* True when EOI has been consumed */
  160882. };
  160883. /* Main buffer control (downsampled-data buffer) */
  160884. struct jpeg_d_main_controller {
  160885. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160886. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160887. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160888. JDIMENSION out_rows_avail));
  160889. };
  160890. /* Coefficient buffer control */
  160891. struct jpeg_d_coef_controller {
  160892. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160893. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160894. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160895. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160896. JSAMPIMAGE output_buf));
  160897. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160898. jvirt_barray_ptr *coef_arrays;
  160899. };
  160900. /* Decompression postprocessing (color quantization buffer control) */
  160901. struct jpeg_d_post_controller {
  160902. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160903. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160904. JSAMPIMAGE input_buf,
  160905. JDIMENSION *in_row_group_ctr,
  160906. JDIMENSION in_row_groups_avail,
  160907. JSAMPARRAY output_buf,
  160908. JDIMENSION *out_row_ctr,
  160909. JDIMENSION out_rows_avail));
  160910. };
  160911. /* Marker reading & parsing */
  160912. struct jpeg_marker_reader {
  160913. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160914. /* Read markers until SOS or EOI.
  160915. * Returns same codes as are defined for jpeg_consume_input:
  160916. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160917. */
  160918. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160919. /* Read a restart marker --- exported for use by entropy decoder only */
  160920. jpeg_marker_parser_method read_restart_marker;
  160921. /* State of marker reader --- nominally internal, but applications
  160922. * supplying COM or APPn handlers might like to know the state.
  160923. */
  160924. boolean saw_SOI; /* found SOI? */
  160925. boolean saw_SOF; /* found SOF? */
  160926. int next_restart_num; /* next restart number expected (0-7) */
  160927. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160928. };
  160929. /* Entropy decoding */
  160930. struct jpeg_entropy_decoder {
  160931. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160932. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160933. JBLOCKROW *MCU_data));
  160934. /* This is here to share code between baseline and progressive decoders; */
  160935. /* other modules probably should not use it */
  160936. boolean insufficient_data; /* set TRUE after emitting warning */
  160937. };
  160938. /* Inverse DCT (also performs dequantization) */
  160939. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160940. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160941. JCOEFPTR coef_block,
  160942. JSAMPARRAY output_buf, JDIMENSION output_col));
  160943. struct jpeg_inverse_dct {
  160944. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160945. /* It is useful to allow each component to have a separate IDCT method. */
  160946. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160947. };
  160948. /* Upsampling (note that upsampler must also call color converter) */
  160949. struct jpeg_upsampler {
  160950. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160951. JMETHOD(void, upsample, (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. boolean need_context_rows; /* TRUE if need rows above & below */
  160959. };
  160960. /* Colorspace conversion */
  160961. struct jpeg_color_deconverter {
  160962. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160963. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160964. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160965. JSAMPARRAY output_buf, int num_rows));
  160966. };
  160967. /* Color quantization or color precision reduction */
  160968. struct jpeg_color_quantizer {
  160969. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160970. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160971. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160972. int num_rows));
  160973. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160974. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160975. };
  160976. /* Miscellaneous useful macros */
  160977. #undef MAX
  160978. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160979. #undef MIN
  160980. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160981. /* We assume that right shift corresponds to signed division by 2 with
  160982. * rounding towards minus infinity. This is correct for typical "arithmetic
  160983. * shift" instructions that shift in copies of the sign bit. But some
  160984. * C compilers implement >> with an unsigned shift. For these machines you
  160985. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160986. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160987. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160988. * included in the variables of any routine using RIGHT_SHIFT.
  160989. */
  160990. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160991. #define SHIFT_TEMPS INT32 shift_temp;
  160992. #define RIGHT_SHIFT(x,shft) \
  160993. ((shift_temp = (x)) < 0 ? \
  160994. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160995. (shift_temp >> (shft)))
  160996. #else
  160997. #define SHIFT_TEMPS
  160998. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160999. #endif
  161000. /* Short forms of external names for systems with brain-damaged linkers. */
  161001. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161002. #define jinit_compress_master jICompress
  161003. #define jinit_c_master_control jICMaster
  161004. #define jinit_c_main_controller jICMainC
  161005. #define jinit_c_prep_controller jICPrepC
  161006. #define jinit_c_coef_controller jICCoefC
  161007. #define jinit_color_converter jICColor
  161008. #define jinit_downsampler jIDownsampler
  161009. #define jinit_forward_dct jIFDCT
  161010. #define jinit_huff_encoder jIHEncoder
  161011. #define jinit_phuff_encoder jIPHEncoder
  161012. #define jinit_marker_writer jIMWriter
  161013. #define jinit_master_decompress jIDMaster
  161014. #define jinit_d_main_controller jIDMainC
  161015. #define jinit_d_coef_controller jIDCoefC
  161016. #define jinit_d_post_controller jIDPostC
  161017. #define jinit_input_controller jIInCtlr
  161018. #define jinit_marker_reader jIMReader
  161019. #define jinit_huff_decoder jIHDecoder
  161020. #define jinit_phuff_decoder jIPHDecoder
  161021. #define jinit_inverse_dct jIIDCT
  161022. #define jinit_upsampler jIUpsampler
  161023. #define jinit_color_deconverter jIDColor
  161024. #define jinit_1pass_quantizer jI1Quant
  161025. #define jinit_2pass_quantizer jI2Quant
  161026. #define jinit_merged_upsampler jIMUpsampler
  161027. #define jinit_memory_mgr jIMemMgr
  161028. #define jdiv_round_up jDivRound
  161029. #define jround_up jRound
  161030. #define jcopy_sample_rows jCopySamples
  161031. #define jcopy_block_row jCopyBlocks
  161032. #define jzero_far jZeroFar
  161033. #define jpeg_zigzag_order jZIGTable
  161034. #define jpeg_natural_order jZAGTable
  161035. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161036. /* Compression module initialization routines */
  161037. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  161038. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  161039. boolean transcode_only));
  161040. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  161041. boolean need_full_buffer));
  161042. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  161043. boolean need_full_buffer));
  161044. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  161045. boolean need_full_buffer));
  161046. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  161047. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  161048. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  161049. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  161050. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  161051. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  161052. /* Decompression module initialization routines */
  161053. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  161054. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  161055. boolean need_full_buffer));
  161056. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  161057. boolean need_full_buffer));
  161058. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  161059. boolean need_full_buffer));
  161060. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161061. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161062. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161063. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161064. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161065. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161066. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161067. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161068. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161069. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161070. /* Memory manager initialization */
  161071. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161072. /* Utility routines in jutils.c */
  161073. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161074. EXTERN(long) jround_up JPP((long a, long b));
  161075. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161076. JSAMPARRAY output_array, int dest_row,
  161077. int num_rows, JDIMENSION num_cols));
  161078. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161079. JDIMENSION num_blocks));
  161080. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161081. /* Constant tables in jutils.c */
  161082. #if 0 /* This table is not actually needed in v6a */
  161083. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161084. #endif
  161085. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161086. /* Suppress undefined-structure complaints if necessary. */
  161087. #ifdef INCOMPLETE_TYPES_BROKEN
  161088. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161089. struct jvirt_sarray_control { long dummy; };
  161090. struct jvirt_barray_control { long dummy; };
  161091. #endif
  161092. #endif /* INCOMPLETE_TYPES_BROKEN */
  161093. /*** End of inlined file: jpegint.h ***/
  161094. /* fetch private declarations */
  161095. /*** Start of inlined file: jerror.h ***/
  161096. /*
  161097. * To define the enum list of message codes, include this file without
  161098. * defining macro JMESSAGE. To create a message string table, include it
  161099. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161100. */
  161101. #ifndef JMESSAGE
  161102. #ifndef JERROR_H
  161103. /* First time through, define the enum list */
  161104. #define JMAKE_ENUM_LIST
  161105. #else
  161106. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161107. #define JMESSAGE(code,string)
  161108. #endif /* JERROR_H */
  161109. #endif /* JMESSAGE */
  161110. #ifdef JMAKE_ENUM_LIST
  161111. typedef enum {
  161112. #define JMESSAGE(code,string) code ,
  161113. #endif /* JMAKE_ENUM_LIST */
  161114. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161115. /* For maintenance convenience, list is alphabetical by message code name */
  161116. JMESSAGE(JERR_ARITH_NOTIMPL,
  161117. "Sorry, there are legal restrictions on arithmetic coding")
  161118. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161119. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161120. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161121. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161122. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161123. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161124. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161125. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161126. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161127. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161128. JMESSAGE(JERR_BAD_LIB_VERSION,
  161129. "Wrong JPEG library version: library is %d, caller expects %d")
  161130. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161131. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161132. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161133. JMESSAGE(JERR_BAD_PROGRESSION,
  161134. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161135. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161136. "Invalid progressive parameters at scan script entry %d")
  161137. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161138. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161139. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161140. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161141. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161142. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161143. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161144. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161145. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161146. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161147. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161148. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161149. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161150. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161151. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161152. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161153. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161154. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161155. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161156. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161157. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161158. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161159. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161160. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161161. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161162. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161163. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161164. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161165. "Cannot transcode due to multiple use of quantization table %d")
  161166. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161167. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161168. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161169. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161170. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161171. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161172. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161173. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161174. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161175. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161176. JMESSAGE(JERR_QUANT_COMPONENTS,
  161177. "Cannot quantize more than %d color components")
  161178. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161179. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161180. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161181. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161182. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161183. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161184. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161185. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161186. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161187. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161188. JMESSAGE(JERR_TFILE_WRITE,
  161189. "Write failed on temporary file --- out of disk space?")
  161190. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161191. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161192. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161193. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161194. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161195. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161196. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161197. JMESSAGE(JMSG_VERSION, JVERSION)
  161198. JMESSAGE(JTRC_16BIT_TABLES,
  161199. "Caution: quantization tables are too coarse for baseline JPEG")
  161200. JMESSAGE(JTRC_ADOBE,
  161201. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161202. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161203. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161204. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161205. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161206. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161207. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161208. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161209. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161210. JMESSAGE(JTRC_EOI, "End Of Image")
  161211. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161212. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161213. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161214. "Warning: thumbnail image size does not match data length %u")
  161215. JMESSAGE(JTRC_JFIF_EXTENSION,
  161216. "JFIF extension marker: type 0x%02x, length %u")
  161217. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161218. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161219. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161220. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161221. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161222. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161223. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161224. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161225. JMESSAGE(JTRC_RST, "RST%d")
  161226. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161227. "Smoothing not supported with nonstandard sampling ratios")
  161228. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161229. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161230. JMESSAGE(JTRC_SOI, "Start of Image")
  161231. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161232. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161233. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161234. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161235. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161236. JMESSAGE(JTRC_THUMB_JPEG,
  161237. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161238. JMESSAGE(JTRC_THUMB_PALETTE,
  161239. "JFIF extension marker: palette thumbnail image, length %u")
  161240. JMESSAGE(JTRC_THUMB_RGB,
  161241. "JFIF extension marker: RGB thumbnail image, length %u")
  161242. JMESSAGE(JTRC_UNKNOWN_IDS,
  161243. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161244. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161245. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161246. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161247. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161248. "Inconsistent progression sequence for component %d coefficient %d")
  161249. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161250. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161251. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161252. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161253. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161254. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161255. JMESSAGE(JWRN_MUST_RESYNC,
  161256. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161257. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161258. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161259. #ifdef JMAKE_ENUM_LIST
  161260. JMSG_LASTMSGCODE
  161261. } J_MESSAGE_CODE;
  161262. #undef JMAKE_ENUM_LIST
  161263. #endif /* JMAKE_ENUM_LIST */
  161264. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161265. #undef JMESSAGE
  161266. #ifndef JERROR_H
  161267. #define JERROR_H
  161268. /* Macros to simplify using the error and trace message stuff */
  161269. /* The first parameter is either type of cinfo pointer */
  161270. /* Fatal errors (print message and exit) */
  161271. #define ERREXIT(cinfo,code) \
  161272. ((cinfo)->err->msg_code = (code), \
  161273. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161274. #define ERREXIT1(cinfo,code,p1) \
  161275. ((cinfo)->err->msg_code = (code), \
  161276. (cinfo)->err->msg_parm.i[0] = (p1), \
  161277. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161278. #define ERREXIT2(cinfo,code,p1,p2) \
  161279. ((cinfo)->err->msg_code = (code), \
  161280. (cinfo)->err->msg_parm.i[0] = (p1), \
  161281. (cinfo)->err->msg_parm.i[1] = (p2), \
  161282. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161283. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161284. ((cinfo)->err->msg_code = (code), \
  161285. (cinfo)->err->msg_parm.i[0] = (p1), \
  161286. (cinfo)->err->msg_parm.i[1] = (p2), \
  161287. (cinfo)->err->msg_parm.i[2] = (p3), \
  161288. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161289. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161290. ((cinfo)->err->msg_code = (code), \
  161291. (cinfo)->err->msg_parm.i[0] = (p1), \
  161292. (cinfo)->err->msg_parm.i[1] = (p2), \
  161293. (cinfo)->err->msg_parm.i[2] = (p3), \
  161294. (cinfo)->err->msg_parm.i[3] = (p4), \
  161295. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161296. #define ERREXITS(cinfo,code,str) \
  161297. ((cinfo)->err->msg_code = (code), \
  161298. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161299. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161300. #define MAKESTMT(stuff) do { stuff } while (0)
  161301. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161302. #define WARNMS(cinfo,code) \
  161303. ((cinfo)->err->msg_code = (code), \
  161304. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161305. #define WARNMS1(cinfo,code,p1) \
  161306. ((cinfo)->err->msg_code = (code), \
  161307. (cinfo)->err->msg_parm.i[0] = (p1), \
  161308. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161309. #define WARNMS2(cinfo,code,p1,p2) \
  161310. ((cinfo)->err->msg_code = (code), \
  161311. (cinfo)->err->msg_parm.i[0] = (p1), \
  161312. (cinfo)->err->msg_parm.i[1] = (p2), \
  161313. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161314. /* Informational/debugging messages */
  161315. #define TRACEMS(cinfo,lvl,code) \
  161316. ((cinfo)->err->msg_code = (code), \
  161317. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161318. #define TRACEMS1(cinfo,lvl,code,p1) \
  161319. ((cinfo)->err->msg_code = (code), \
  161320. (cinfo)->err->msg_parm.i[0] = (p1), \
  161321. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161322. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161323. ((cinfo)->err->msg_code = (code), \
  161324. (cinfo)->err->msg_parm.i[0] = (p1), \
  161325. (cinfo)->err->msg_parm.i[1] = (p2), \
  161326. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161327. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161328. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161329. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161330. (cinfo)->err->msg_code = (code); \
  161331. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161332. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161333. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161334. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161335. (cinfo)->err->msg_code = (code); \
  161336. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161337. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161338. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161339. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161340. _mp[4] = (p5); \
  161341. (cinfo)->err->msg_code = (code); \
  161342. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161343. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161344. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161345. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161346. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161347. (cinfo)->err->msg_code = (code); \
  161348. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161349. #define TRACEMSS(cinfo,lvl,code,str) \
  161350. ((cinfo)->err->msg_code = (code), \
  161351. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161352. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161353. #endif /* JERROR_H */
  161354. /*** End of inlined file: jerror.h ***/
  161355. /* fetch error codes too */
  161356. #endif
  161357. #endif /* JPEGLIB_H */
  161358. /*** End of inlined file: jpeglib.h ***/
  161359. /*** Start of inlined file: jcapimin.c ***/
  161360. #define JPEG_INTERNALS
  161361. /*** Start of inlined file: jinclude.h ***/
  161362. /* Include auto-config file to find out which system include files we need. */
  161363. #ifndef __jinclude_h__
  161364. #define __jinclude_h__
  161365. /*** Start of inlined file: jconfig.h ***/
  161366. /* see jconfig.doc for explanations */
  161367. // disable all the warnings under MSVC
  161368. #ifdef _MSC_VER
  161369. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161370. #endif
  161371. #ifdef __BORLANDC__
  161372. #pragma warn -8057
  161373. #pragma warn -8019
  161374. #pragma warn -8004
  161375. #pragma warn -8008
  161376. #endif
  161377. #define HAVE_PROTOTYPES
  161378. #define HAVE_UNSIGNED_CHAR
  161379. #define HAVE_UNSIGNED_SHORT
  161380. /* #define void char */
  161381. /* #define const */
  161382. #undef CHAR_IS_UNSIGNED
  161383. #define HAVE_STDDEF_H
  161384. #define HAVE_STDLIB_H
  161385. #undef NEED_BSD_STRINGS
  161386. #undef NEED_SYS_TYPES_H
  161387. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161388. #undef NEED_SHORT_EXTERNAL_NAMES
  161389. #undef INCOMPLETE_TYPES_BROKEN
  161390. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161391. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161392. typedef unsigned char boolean;
  161393. #endif
  161394. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161395. #ifdef JPEG_INTERNALS
  161396. #undef RIGHT_SHIFT_IS_UNSIGNED
  161397. #endif /* JPEG_INTERNALS */
  161398. #ifdef JPEG_CJPEG_DJPEG
  161399. #define BMP_SUPPORTED /* BMP image file format */
  161400. #define GIF_SUPPORTED /* GIF image file format */
  161401. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161402. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161403. #define TARGA_SUPPORTED /* Targa image file format */
  161404. #define TWO_FILE_COMMANDLINE /* optional */
  161405. #define USE_SETMODE /* Microsoft has setmode() */
  161406. #undef NEED_SIGNAL_CATCHER
  161407. #undef DONT_USE_B_MODE
  161408. #undef PROGRESS_REPORT /* optional */
  161409. #endif /* JPEG_CJPEG_DJPEG */
  161410. /*** End of inlined file: jconfig.h ***/
  161411. /* auto configuration options */
  161412. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161413. /*
  161414. * We need the NULL macro and size_t typedef.
  161415. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161416. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161417. * pull in <sys/types.h> as well.
  161418. * Note that the core JPEG library does not require <stdio.h>;
  161419. * only the default error handler and data source/destination modules do.
  161420. * But we must pull it in because of the references to FILE in jpeglib.h.
  161421. * You can remove those references if you want to compile without <stdio.h>.
  161422. */
  161423. #ifdef HAVE_STDDEF_H
  161424. #include <stddef.h>
  161425. #endif
  161426. #ifdef HAVE_STDLIB_H
  161427. #include <stdlib.h>
  161428. #endif
  161429. #ifdef NEED_SYS_TYPES_H
  161430. #include <sys/types.h>
  161431. #endif
  161432. #include <stdio.h>
  161433. /*
  161434. * We need memory copying and zeroing functions, plus strncpy().
  161435. * ANSI and System V implementations declare these in <string.h>.
  161436. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161437. * Some systems may declare memset and memcpy in <memory.h>.
  161438. *
  161439. * NOTE: we assume the size parameters to these functions are of type size_t.
  161440. * Change the casts in these macros if not!
  161441. */
  161442. #ifdef NEED_BSD_STRINGS
  161443. #include <strings.h>
  161444. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161445. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161446. #else /* not BSD, assume ANSI/SysV string lib */
  161447. #include <string.h>
  161448. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161449. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161450. #endif
  161451. /*
  161452. * In ANSI C, and indeed any rational implementation, size_t is also the
  161453. * type returned by sizeof(). However, it seems there are some irrational
  161454. * implementations out there, in which sizeof() returns an int even though
  161455. * size_t is defined as long or unsigned long. To ensure consistent results
  161456. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161457. */
  161458. #define SIZEOF(object) ((size_t) sizeof(object))
  161459. /*
  161460. * The modules that use fread() and fwrite() always invoke them through
  161461. * these macros. On some systems you may need to twiddle the argument casts.
  161462. * CAUTION: argument order is different from underlying functions!
  161463. */
  161464. #define JFREAD(file,buf,sizeofbuf) \
  161465. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161466. #define JFWRITE(file,buf,sizeofbuf) \
  161467. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161468. typedef enum { /* JPEG marker codes */
  161469. M_SOF0 = 0xc0,
  161470. M_SOF1 = 0xc1,
  161471. M_SOF2 = 0xc2,
  161472. M_SOF3 = 0xc3,
  161473. M_SOF5 = 0xc5,
  161474. M_SOF6 = 0xc6,
  161475. M_SOF7 = 0xc7,
  161476. M_JPG = 0xc8,
  161477. M_SOF9 = 0xc9,
  161478. M_SOF10 = 0xca,
  161479. M_SOF11 = 0xcb,
  161480. M_SOF13 = 0xcd,
  161481. M_SOF14 = 0xce,
  161482. M_SOF15 = 0xcf,
  161483. M_DHT = 0xc4,
  161484. M_DAC = 0xcc,
  161485. M_RST0 = 0xd0,
  161486. M_RST1 = 0xd1,
  161487. M_RST2 = 0xd2,
  161488. M_RST3 = 0xd3,
  161489. M_RST4 = 0xd4,
  161490. M_RST5 = 0xd5,
  161491. M_RST6 = 0xd6,
  161492. M_RST7 = 0xd7,
  161493. M_SOI = 0xd8,
  161494. M_EOI = 0xd9,
  161495. M_SOS = 0xda,
  161496. M_DQT = 0xdb,
  161497. M_DNL = 0xdc,
  161498. M_DRI = 0xdd,
  161499. M_DHP = 0xde,
  161500. M_EXP = 0xdf,
  161501. M_APP0 = 0xe0,
  161502. M_APP1 = 0xe1,
  161503. M_APP2 = 0xe2,
  161504. M_APP3 = 0xe3,
  161505. M_APP4 = 0xe4,
  161506. M_APP5 = 0xe5,
  161507. M_APP6 = 0xe6,
  161508. M_APP7 = 0xe7,
  161509. M_APP8 = 0xe8,
  161510. M_APP9 = 0xe9,
  161511. M_APP10 = 0xea,
  161512. M_APP11 = 0xeb,
  161513. M_APP12 = 0xec,
  161514. M_APP13 = 0xed,
  161515. M_APP14 = 0xee,
  161516. M_APP15 = 0xef,
  161517. M_JPG0 = 0xf0,
  161518. M_JPG13 = 0xfd,
  161519. M_COM = 0xfe,
  161520. M_TEM = 0x01,
  161521. M_ERROR = 0x100
  161522. } JPEG_MARKER;
  161523. /*
  161524. * Figure F.12: extend sign bit.
  161525. * On some machines, a shift and add will be faster than a table lookup.
  161526. */
  161527. #ifdef AVOID_TABLES
  161528. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161529. #else
  161530. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161531. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161532. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161533. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161534. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161535. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161536. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161537. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161538. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161539. #endif /* AVOID_TABLES */
  161540. #endif
  161541. /*** End of inlined file: jinclude.h ***/
  161542. /*
  161543. * Initialization of a JPEG compression object.
  161544. * The error manager must already be set up (in case memory manager fails).
  161545. */
  161546. GLOBAL(void)
  161547. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161548. {
  161549. int i;
  161550. /* Guard against version mismatches between library and caller. */
  161551. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161552. if (version != JPEG_LIB_VERSION)
  161553. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161554. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161555. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161556. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161557. /* For debugging purposes, we zero the whole master structure.
  161558. * But the application has already set the err pointer, and may have set
  161559. * client_data, so we have to save and restore those fields.
  161560. * Note: if application hasn't set client_data, tools like Purify may
  161561. * complain here.
  161562. */
  161563. {
  161564. struct jpeg_error_mgr * err = cinfo->err;
  161565. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161566. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161567. cinfo->err = err;
  161568. cinfo->client_data = client_data;
  161569. }
  161570. cinfo->is_decompressor = FALSE;
  161571. /* Initialize a memory manager instance for this object */
  161572. jinit_memory_mgr((j_common_ptr) cinfo);
  161573. /* Zero out pointers to permanent structures. */
  161574. cinfo->progress = NULL;
  161575. cinfo->dest = NULL;
  161576. cinfo->comp_info = NULL;
  161577. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161578. cinfo->quant_tbl_ptrs[i] = NULL;
  161579. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161580. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161581. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161582. }
  161583. cinfo->script_space = NULL;
  161584. cinfo->input_gamma = 1.0; /* in case application forgets */
  161585. /* OK, I'm ready */
  161586. cinfo->global_state = CSTATE_START;
  161587. }
  161588. /*
  161589. * Destruction of a JPEG compression object
  161590. */
  161591. GLOBAL(void)
  161592. jpeg_destroy_compress (j_compress_ptr cinfo)
  161593. {
  161594. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161595. }
  161596. /*
  161597. * Abort processing of a JPEG compression operation,
  161598. * but don't destroy the object itself.
  161599. */
  161600. GLOBAL(void)
  161601. jpeg_abort_compress (j_compress_ptr cinfo)
  161602. {
  161603. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161604. }
  161605. /*
  161606. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161607. * Marks all currently defined tables as already written (if suppress)
  161608. * or not written (if !suppress). This will control whether they get emitted
  161609. * by a subsequent jpeg_start_compress call.
  161610. *
  161611. * This routine is exported for use by applications that want to produce
  161612. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161613. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161614. * jcparam.o would be linked whether the application used it or not.
  161615. */
  161616. GLOBAL(void)
  161617. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161618. {
  161619. int i;
  161620. JQUANT_TBL * qtbl;
  161621. JHUFF_TBL * htbl;
  161622. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161623. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161624. qtbl->sent_table = suppress;
  161625. }
  161626. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161627. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161628. htbl->sent_table = suppress;
  161629. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161630. htbl->sent_table = suppress;
  161631. }
  161632. }
  161633. /*
  161634. * Finish JPEG compression.
  161635. *
  161636. * If a multipass operating mode was selected, this may do a great deal of
  161637. * work including most of the actual output.
  161638. */
  161639. GLOBAL(void)
  161640. jpeg_finish_compress (j_compress_ptr cinfo)
  161641. {
  161642. JDIMENSION iMCU_row;
  161643. if (cinfo->global_state == CSTATE_SCANNING ||
  161644. cinfo->global_state == CSTATE_RAW_OK) {
  161645. /* Terminate first pass */
  161646. if (cinfo->next_scanline < cinfo->image_height)
  161647. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161648. (*cinfo->master->finish_pass) (cinfo);
  161649. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161650. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161651. /* Perform any remaining passes */
  161652. while (! cinfo->master->is_last_pass) {
  161653. (*cinfo->master->prepare_for_pass) (cinfo);
  161654. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161655. if (cinfo->progress != NULL) {
  161656. cinfo->progress->pass_counter = (long) iMCU_row;
  161657. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161658. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161659. }
  161660. /* We bypass the main controller and invoke coef controller directly;
  161661. * all work is being done from the coefficient buffer.
  161662. */
  161663. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161664. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161665. }
  161666. (*cinfo->master->finish_pass) (cinfo);
  161667. }
  161668. /* Write EOI, do final cleanup */
  161669. (*cinfo->marker->write_file_trailer) (cinfo);
  161670. (*cinfo->dest->term_destination) (cinfo);
  161671. /* We can use jpeg_abort to release memory and reset global_state */
  161672. jpeg_abort((j_common_ptr) cinfo);
  161673. }
  161674. /*
  161675. * Write a special marker.
  161676. * This is only recommended for writing COM or APPn markers.
  161677. * Must be called after jpeg_start_compress() and before
  161678. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161679. */
  161680. GLOBAL(void)
  161681. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161682. const JOCTET *dataptr, unsigned int datalen)
  161683. {
  161684. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161685. if (cinfo->next_scanline != 0 ||
  161686. (cinfo->global_state != CSTATE_SCANNING &&
  161687. cinfo->global_state != CSTATE_RAW_OK &&
  161688. cinfo->global_state != CSTATE_WRCOEFS))
  161689. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161690. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161691. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161692. while (datalen--) {
  161693. (*write_marker_byte) (cinfo, *dataptr);
  161694. dataptr++;
  161695. }
  161696. }
  161697. /* Same, but piecemeal. */
  161698. GLOBAL(void)
  161699. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161700. {
  161701. if (cinfo->next_scanline != 0 ||
  161702. (cinfo->global_state != CSTATE_SCANNING &&
  161703. cinfo->global_state != CSTATE_RAW_OK &&
  161704. cinfo->global_state != CSTATE_WRCOEFS))
  161705. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161706. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161707. }
  161708. GLOBAL(void)
  161709. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161710. {
  161711. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161712. }
  161713. /*
  161714. * Alternate compression function: just write an abbreviated table file.
  161715. * Before calling this, all parameters and a data destination must be set up.
  161716. *
  161717. * To produce a pair of files containing abbreviated tables and abbreviated
  161718. * image data, one would proceed as follows:
  161719. *
  161720. * initialize JPEG object
  161721. * set JPEG parameters
  161722. * set destination to table file
  161723. * jpeg_write_tables(cinfo);
  161724. * set destination to image file
  161725. * jpeg_start_compress(cinfo, FALSE);
  161726. * write data...
  161727. * jpeg_finish_compress(cinfo);
  161728. *
  161729. * jpeg_write_tables has the side effect of marking all tables written
  161730. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161731. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161732. */
  161733. GLOBAL(void)
  161734. jpeg_write_tables (j_compress_ptr cinfo)
  161735. {
  161736. if (cinfo->global_state != CSTATE_START)
  161737. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161738. /* (Re)initialize error mgr and destination modules */
  161739. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161740. (*cinfo->dest->init_destination) (cinfo);
  161741. /* Initialize the marker writer ... bit of a crock to do it here. */
  161742. jinit_marker_writer(cinfo);
  161743. /* Write them tables! */
  161744. (*cinfo->marker->write_tables_only) (cinfo);
  161745. /* And clean up. */
  161746. (*cinfo->dest->term_destination) (cinfo);
  161747. /*
  161748. * In library releases up through v6a, we called jpeg_abort() here to free
  161749. * any working memory allocated by the destination manager and marker
  161750. * writer. Some applications had a problem with that: they allocated space
  161751. * of their own from the library memory manager, and didn't want it to go
  161752. * away during write_tables. So now we do nothing. This will cause a
  161753. * memory leak if an app calls write_tables repeatedly without doing a full
  161754. * compression cycle or otherwise resetting the JPEG object. However, that
  161755. * seems less bad than unexpectedly freeing memory in the normal case.
  161756. * An app that prefers the old behavior can call jpeg_abort for itself after
  161757. * each call to jpeg_write_tables().
  161758. */
  161759. }
  161760. /*** End of inlined file: jcapimin.c ***/
  161761. /*** Start of inlined file: jcapistd.c ***/
  161762. #define JPEG_INTERNALS
  161763. /*
  161764. * Compression initialization.
  161765. * Before calling this, all parameters and a data destination must be set up.
  161766. *
  161767. * We require a write_all_tables parameter as a failsafe check when writing
  161768. * multiple datastreams from the same compression object. Since prior runs
  161769. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161770. * would emit an abbreviated stream (no tables) by default. This may be what
  161771. * is wanted, but for safety's sake it should not be the default behavior:
  161772. * programmers should have to make a deliberate choice to emit abbreviated
  161773. * images. Therefore the documentation and examples should encourage people
  161774. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161775. * wrong thing.
  161776. */
  161777. GLOBAL(void)
  161778. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161779. {
  161780. if (cinfo->global_state != CSTATE_START)
  161781. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161782. if (write_all_tables)
  161783. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161784. /* (Re)initialize error mgr and destination modules */
  161785. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161786. (*cinfo->dest->init_destination) (cinfo);
  161787. /* Perform master selection of active modules */
  161788. jinit_compress_master(cinfo);
  161789. /* Set up for the first pass */
  161790. (*cinfo->master->prepare_for_pass) (cinfo);
  161791. /* Ready for application to drive first pass through jpeg_write_scanlines
  161792. * or jpeg_write_raw_data.
  161793. */
  161794. cinfo->next_scanline = 0;
  161795. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161796. }
  161797. /*
  161798. * Write some scanlines of data to the JPEG compressor.
  161799. *
  161800. * The return value will be the number of lines actually written.
  161801. * This should be less than the supplied num_lines only in case that
  161802. * the data destination module has requested suspension of the compressor,
  161803. * or if more than image_height scanlines are passed in.
  161804. *
  161805. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161806. * this likely signals an application programmer error. However,
  161807. * excess scanlines passed in the last valid call are *silently* ignored,
  161808. * so that the application need not adjust num_lines for end-of-image
  161809. * when using a multiple-scanline buffer.
  161810. */
  161811. GLOBAL(JDIMENSION)
  161812. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161813. JDIMENSION num_lines)
  161814. {
  161815. JDIMENSION row_ctr, rows_left;
  161816. if (cinfo->global_state != CSTATE_SCANNING)
  161817. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161818. if (cinfo->next_scanline >= cinfo->image_height)
  161819. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161820. /* Call progress monitor hook if present */
  161821. if (cinfo->progress != NULL) {
  161822. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161823. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161824. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161825. }
  161826. /* Give master control module another chance if this is first call to
  161827. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161828. * delayed so that application can write COM, etc, markers between
  161829. * jpeg_start_compress and jpeg_write_scanlines.
  161830. */
  161831. if (cinfo->master->call_pass_startup)
  161832. (*cinfo->master->pass_startup) (cinfo);
  161833. /* Ignore any extra scanlines at bottom of image. */
  161834. rows_left = cinfo->image_height - cinfo->next_scanline;
  161835. if (num_lines > rows_left)
  161836. num_lines = rows_left;
  161837. row_ctr = 0;
  161838. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161839. cinfo->next_scanline += row_ctr;
  161840. return row_ctr;
  161841. }
  161842. /*
  161843. * Alternate entry point to write raw data.
  161844. * Processes exactly one iMCU row per call, unless suspended.
  161845. */
  161846. GLOBAL(JDIMENSION)
  161847. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161848. JDIMENSION num_lines)
  161849. {
  161850. JDIMENSION lines_per_iMCU_row;
  161851. if (cinfo->global_state != CSTATE_RAW_OK)
  161852. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161853. if (cinfo->next_scanline >= cinfo->image_height) {
  161854. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161855. return 0;
  161856. }
  161857. /* Call progress monitor hook if present */
  161858. if (cinfo->progress != NULL) {
  161859. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161860. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161861. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161862. }
  161863. /* Give master control module another chance if this is first call to
  161864. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161865. * delayed so that application can write COM, etc, markers between
  161866. * jpeg_start_compress and jpeg_write_raw_data.
  161867. */
  161868. if (cinfo->master->call_pass_startup)
  161869. (*cinfo->master->pass_startup) (cinfo);
  161870. /* Verify that at least one iMCU row has been passed. */
  161871. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161872. if (num_lines < lines_per_iMCU_row)
  161873. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161874. /* Directly compress the row. */
  161875. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161876. /* If compressor did not consume the whole row, suspend processing. */
  161877. return 0;
  161878. }
  161879. /* OK, we processed one iMCU row. */
  161880. cinfo->next_scanline += lines_per_iMCU_row;
  161881. return lines_per_iMCU_row;
  161882. }
  161883. /*** End of inlined file: jcapistd.c ***/
  161884. /*** Start of inlined file: jccoefct.c ***/
  161885. #define JPEG_INTERNALS
  161886. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161887. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161888. * step is run during the first pass, and subsequent passes need only read
  161889. * the buffered coefficients.
  161890. */
  161891. #ifdef ENTROPY_OPT_SUPPORTED
  161892. #define FULL_COEF_BUFFER_SUPPORTED
  161893. #else
  161894. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161895. #define FULL_COEF_BUFFER_SUPPORTED
  161896. #endif
  161897. #endif
  161898. /* Private buffer controller object */
  161899. typedef struct {
  161900. struct jpeg_c_coef_controller pub; /* public fields */
  161901. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161902. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161903. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161904. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161905. /* For single-pass compression, it's sufficient to buffer just one MCU
  161906. * (although this may prove a bit slow in practice). We allocate a
  161907. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161908. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161909. * it's not really very big; this is to keep the module interfaces unchanged
  161910. * when a large coefficient buffer is necessary.)
  161911. * In multi-pass modes, this array points to the current MCU's blocks
  161912. * within the virtual arrays.
  161913. */
  161914. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161915. /* In multi-pass modes, we need a virtual block array for each component. */
  161916. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161917. } my_coef_controller;
  161918. typedef my_coef_controller * my_coef_ptr;
  161919. /* Forward declarations */
  161920. METHODDEF(boolean) compress_data
  161921. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161922. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161923. METHODDEF(boolean) compress_first_pass
  161924. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161925. METHODDEF(boolean) compress_output
  161926. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161927. #endif
  161928. LOCAL(void)
  161929. start_iMCU_row (j_compress_ptr cinfo)
  161930. /* Reset within-iMCU-row counters for a new row */
  161931. {
  161932. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161933. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161934. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161935. * But at the bottom of the image, process only what's left.
  161936. */
  161937. if (cinfo->comps_in_scan > 1) {
  161938. coef->MCU_rows_per_iMCU_row = 1;
  161939. } else {
  161940. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161941. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161942. else
  161943. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161944. }
  161945. coef->mcu_ctr = 0;
  161946. coef->MCU_vert_offset = 0;
  161947. }
  161948. /*
  161949. * Initialize for a processing pass.
  161950. */
  161951. METHODDEF(void)
  161952. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161953. {
  161954. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161955. coef->iMCU_row_num = 0;
  161956. start_iMCU_row(cinfo);
  161957. switch (pass_mode) {
  161958. case JBUF_PASS_THRU:
  161959. if (coef->whole_image[0] != NULL)
  161960. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161961. coef->pub.compress_data = compress_data;
  161962. break;
  161963. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161964. case JBUF_SAVE_AND_PASS:
  161965. if (coef->whole_image[0] == NULL)
  161966. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161967. coef->pub.compress_data = compress_first_pass;
  161968. break;
  161969. case JBUF_CRANK_DEST:
  161970. if (coef->whole_image[0] == NULL)
  161971. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161972. coef->pub.compress_data = compress_output;
  161973. break;
  161974. #endif
  161975. default:
  161976. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161977. break;
  161978. }
  161979. }
  161980. /*
  161981. * Process some data in the single-pass case.
  161982. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161983. * per call, ie, v_samp_factor block rows for each component in the image.
  161984. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161985. *
  161986. * NB: input_buf contains a plane for each component in image,
  161987. * which we index according to the component's SOF position.
  161988. */
  161989. METHODDEF(boolean)
  161990. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161991. {
  161992. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161993. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161994. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161995. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161996. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161997. JDIMENSION ypos, xpos;
  161998. jpeg_component_info *compptr;
  161999. /* Loop to write as much as one whole iMCU row */
  162000. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162001. yoffset++) {
  162002. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  162003. MCU_col_num++) {
  162004. /* Determine where data comes from in input_buf and do the DCT thing.
  162005. * Each call on forward_DCT processes a horizontal row of DCT blocks
  162006. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  162007. * sequentially. Dummy blocks at the right or bottom edge are filled in
  162008. * specially. The data in them does not matter for image reconstruction,
  162009. * so we fill them with values that will encode to the smallest amount of
  162010. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  162011. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  162012. */
  162013. blkn = 0;
  162014. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162015. compptr = cinfo->cur_comp_info[ci];
  162016. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162017. : compptr->last_col_width;
  162018. xpos = MCU_col_num * compptr->MCU_sample_width;
  162019. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  162020. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162021. if (coef->iMCU_row_num < last_iMCU_row ||
  162022. yoffset+yindex < compptr->last_row_height) {
  162023. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162024. input_buf[compptr->component_index],
  162025. coef->MCU_buffer[blkn],
  162026. ypos, xpos, (JDIMENSION) blockcnt);
  162027. if (blockcnt < compptr->MCU_width) {
  162028. /* Create some dummy blocks at the right edge of the image. */
  162029. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  162030. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  162031. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  162032. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  162033. }
  162034. }
  162035. } else {
  162036. /* Create a row of dummy blocks at the bottom of the image. */
  162037. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  162038. compptr->MCU_width * SIZEOF(JBLOCK));
  162039. for (bi = 0; bi < compptr->MCU_width; bi++) {
  162040. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  162041. }
  162042. }
  162043. blkn += compptr->MCU_width;
  162044. ypos += DCTSIZE;
  162045. }
  162046. }
  162047. /* Try to write the MCU. In event of a suspension failure, we will
  162048. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  162049. */
  162050. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162051. /* Suspension forced; update state counters and exit */
  162052. coef->MCU_vert_offset = yoffset;
  162053. coef->mcu_ctr = MCU_col_num;
  162054. return FALSE;
  162055. }
  162056. }
  162057. /* Completed an MCU row, but perhaps not an iMCU row */
  162058. coef->mcu_ctr = 0;
  162059. }
  162060. /* Completed the iMCU row, advance counters for next one */
  162061. coef->iMCU_row_num++;
  162062. start_iMCU_row(cinfo);
  162063. return TRUE;
  162064. }
  162065. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162066. /*
  162067. * Process some data in the first pass of a multi-pass case.
  162068. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162069. * per call, ie, v_samp_factor block rows for each component in the image.
  162070. * This amount of data is read from the source buffer, DCT'd and quantized,
  162071. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162072. * as needed at the right and lower edges. (The dummy blocks are constructed
  162073. * in the virtual arrays, which have been padded appropriately.) This makes
  162074. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162075. *
  162076. * We must also emit the data to the entropy encoder. This is conveniently
  162077. * done by calling compress_output() after we've loaded the current strip
  162078. * of the virtual arrays.
  162079. *
  162080. * NB: input_buf contains a plane for each component in image. All
  162081. * components are DCT'd and loaded into the virtual arrays in this pass.
  162082. * However, it may be that only a subset of the components are emitted to
  162083. * the entropy encoder during this first pass; be careful about looking
  162084. * at the scan-dependent variables (MCU dimensions, etc).
  162085. */
  162086. METHODDEF(boolean)
  162087. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162088. {
  162089. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162090. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162091. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162092. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162093. JCOEF lastDC;
  162094. jpeg_component_info *compptr;
  162095. JBLOCKARRAY buffer;
  162096. JBLOCKROW thisblockrow, lastblockrow;
  162097. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162098. ci++, compptr++) {
  162099. /* Align the virtual buffer for this component. */
  162100. buffer = (*cinfo->mem->access_virt_barray)
  162101. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162102. coef->iMCU_row_num * compptr->v_samp_factor,
  162103. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162104. /* Count non-dummy DCT block rows in this iMCU row. */
  162105. if (coef->iMCU_row_num < last_iMCU_row)
  162106. block_rows = compptr->v_samp_factor;
  162107. else {
  162108. /* NB: can't use last_row_height here, since may not be set! */
  162109. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162110. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162111. }
  162112. blocks_across = compptr->width_in_blocks;
  162113. h_samp_factor = compptr->h_samp_factor;
  162114. /* Count number of dummy blocks to be added at the right margin. */
  162115. ndummy = (int) (blocks_across % h_samp_factor);
  162116. if (ndummy > 0)
  162117. ndummy = h_samp_factor - ndummy;
  162118. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162119. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162120. */
  162121. for (block_row = 0; block_row < block_rows; block_row++) {
  162122. thisblockrow = buffer[block_row];
  162123. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162124. input_buf[ci], thisblockrow,
  162125. (JDIMENSION) (block_row * DCTSIZE),
  162126. (JDIMENSION) 0, blocks_across);
  162127. if (ndummy > 0) {
  162128. /* Create dummy blocks at the right edge of the image. */
  162129. thisblockrow += blocks_across; /* => first dummy block */
  162130. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162131. lastDC = thisblockrow[-1][0];
  162132. for (bi = 0; bi < ndummy; bi++) {
  162133. thisblockrow[bi][0] = lastDC;
  162134. }
  162135. }
  162136. }
  162137. /* If at end of image, create dummy block rows as needed.
  162138. * The tricky part here is that within each MCU, we want the DC values
  162139. * of the dummy blocks to match the last real block's DC value.
  162140. * This squeezes a few more bytes out of the resulting file...
  162141. */
  162142. if (coef->iMCU_row_num == last_iMCU_row) {
  162143. blocks_across += ndummy; /* include lower right corner */
  162144. MCUs_across = blocks_across / h_samp_factor;
  162145. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162146. block_row++) {
  162147. thisblockrow = buffer[block_row];
  162148. lastblockrow = buffer[block_row-1];
  162149. jzero_far((void FAR *) thisblockrow,
  162150. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162151. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162152. lastDC = lastblockrow[h_samp_factor-1][0];
  162153. for (bi = 0; bi < h_samp_factor; bi++) {
  162154. thisblockrow[bi][0] = lastDC;
  162155. }
  162156. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162157. lastblockrow += h_samp_factor;
  162158. }
  162159. }
  162160. }
  162161. }
  162162. /* NB: compress_output will increment iMCU_row_num if successful.
  162163. * A suspension return will result in redoing all the work above next time.
  162164. */
  162165. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162166. return compress_output(cinfo, input_buf);
  162167. }
  162168. /*
  162169. * Process some data in subsequent passes of a multi-pass case.
  162170. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162171. * per call, ie, v_samp_factor block rows for each component in the scan.
  162172. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162173. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162174. *
  162175. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162176. */
  162177. METHODDEF(boolean)
  162178. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162179. {
  162180. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162181. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162182. int blkn, ci, xindex, yindex, yoffset;
  162183. JDIMENSION start_col;
  162184. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162185. JBLOCKROW buffer_ptr;
  162186. jpeg_component_info *compptr;
  162187. /* Align the virtual buffers for the components used in this scan.
  162188. * NB: during first pass, this is safe only because the buffers will
  162189. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162190. */
  162191. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162192. compptr = cinfo->cur_comp_info[ci];
  162193. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162194. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162195. coef->iMCU_row_num * compptr->v_samp_factor,
  162196. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162197. }
  162198. /* Loop to process one whole iMCU row */
  162199. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162200. yoffset++) {
  162201. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162202. MCU_col_num++) {
  162203. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162204. blkn = 0; /* index of current DCT block within MCU */
  162205. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162206. compptr = cinfo->cur_comp_info[ci];
  162207. start_col = MCU_col_num * compptr->MCU_width;
  162208. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162209. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162210. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162211. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162212. }
  162213. }
  162214. }
  162215. /* Try to write the MCU. */
  162216. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162217. /* Suspension forced; update state counters and exit */
  162218. coef->MCU_vert_offset = yoffset;
  162219. coef->mcu_ctr = MCU_col_num;
  162220. return FALSE;
  162221. }
  162222. }
  162223. /* Completed an MCU row, but perhaps not an iMCU row */
  162224. coef->mcu_ctr = 0;
  162225. }
  162226. /* Completed the iMCU row, advance counters for next one */
  162227. coef->iMCU_row_num++;
  162228. start_iMCU_row(cinfo);
  162229. return TRUE;
  162230. }
  162231. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162232. /*
  162233. * Initialize coefficient buffer controller.
  162234. */
  162235. GLOBAL(void)
  162236. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162237. {
  162238. my_coef_ptr coef;
  162239. coef = (my_coef_ptr)
  162240. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162241. SIZEOF(my_coef_controller));
  162242. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162243. coef->pub.start_pass = start_pass_coef;
  162244. /* Create the coefficient buffer. */
  162245. if (need_full_buffer) {
  162246. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162247. /* Allocate a full-image virtual array for each component, */
  162248. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162249. int ci;
  162250. jpeg_component_info *compptr;
  162251. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162252. ci++, compptr++) {
  162253. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162254. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162255. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162256. (long) compptr->h_samp_factor),
  162257. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162258. (long) compptr->v_samp_factor),
  162259. (JDIMENSION) compptr->v_samp_factor);
  162260. }
  162261. #else
  162262. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162263. #endif
  162264. } else {
  162265. /* We only need a single-MCU buffer. */
  162266. JBLOCKROW buffer;
  162267. int i;
  162268. buffer = (JBLOCKROW)
  162269. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162270. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162271. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162272. coef->MCU_buffer[i] = buffer + i;
  162273. }
  162274. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162275. }
  162276. }
  162277. /*** End of inlined file: jccoefct.c ***/
  162278. /*** Start of inlined file: jccolor.c ***/
  162279. #define JPEG_INTERNALS
  162280. /* Private subobject */
  162281. typedef struct {
  162282. struct jpeg_color_converter pub; /* public fields */
  162283. /* Private state for RGB->YCC conversion */
  162284. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162285. } my_color_converter;
  162286. typedef my_color_converter * my_cconvert_ptr;
  162287. /**************** RGB -> YCbCr conversion: most common case **************/
  162288. /*
  162289. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162290. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162291. * The conversion equations to be implemented are therefore
  162292. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162293. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162294. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162295. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162296. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162297. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162298. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162299. * were not represented exactly. Now we sacrifice exact representation of
  162300. * maximum red and maximum blue in order to get exact grayscales.
  162301. *
  162302. * To avoid floating-point arithmetic, we represent the fractional constants
  162303. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162304. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162305. *
  162306. * For even more speed, we avoid doing any multiplications in the inner loop
  162307. * by precalculating the constants times R,G,B for all possible values.
  162308. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162309. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162310. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162311. * colorspace anyway.
  162312. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162313. * in the tables to save adding them separately in the inner loop.
  162314. */
  162315. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162316. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162317. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162318. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162319. /* We allocate one big table and divide it up into eight parts, instead of
  162320. * doing eight alloc_small requests. This lets us use a single table base
  162321. * address, which can be held in a register in the inner loops on many
  162322. * machines (more than can hold all eight addresses, anyway).
  162323. */
  162324. #define R_Y_OFF 0 /* offset to R => Y section */
  162325. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162326. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162327. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162328. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162329. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162330. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162331. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162332. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162333. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162334. /*
  162335. * Initialize for RGB->YCC colorspace conversion.
  162336. */
  162337. METHODDEF(void)
  162338. rgb_ycc_start (j_compress_ptr cinfo)
  162339. {
  162340. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162341. INT32 * rgb_ycc_tab;
  162342. INT32 i;
  162343. /* Allocate and fill in the conversion tables. */
  162344. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162345. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162346. (TABLE_SIZE * SIZEOF(INT32)));
  162347. for (i = 0; i <= MAXJSAMPLE; i++) {
  162348. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162349. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162350. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162351. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162352. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162353. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162354. * This ensures that the maximum output will round to MAXJSAMPLE
  162355. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162356. */
  162357. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162358. /* B=>Cb and R=>Cr tables are the same
  162359. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162360. */
  162361. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162362. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162363. }
  162364. }
  162365. /*
  162366. * Convert some rows of samples to the JPEG colorspace.
  162367. *
  162368. * Note that we change from the application's interleaved-pixel format
  162369. * to our internal noninterleaved, one-plane-per-component format.
  162370. * The input buffer is therefore three times as wide as the output buffer.
  162371. *
  162372. * A starting row offset is provided only for the output buffer. The caller
  162373. * can easily adjust the passed input_buf value to accommodate any row
  162374. * offset required on that side.
  162375. */
  162376. METHODDEF(void)
  162377. rgb_ycc_convert (j_compress_ptr cinfo,
  162378. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162379. JDIMENSION output_row, int num_rows)
  162380. {
  162381. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162382. register int r, g, b;
  162383. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162384. register JSAMPROW inptr;
  162385. register JSAMPROW outptr0, outptr1, outptr2;
  162386. register JDIMENSION col;
  162387. JDIMENSION num_cols = cinfo->image_width;
  162388. while (--num_rows >= 0) {
  162389. inptr = *input_buf++;
  162390. outptr0 = output_buf[0][output_row];
  162391. outptr1 = output_buf[1][output_row];
  162392. outptr2 = output_buf[2][output_row];
  162393. output_row++;
  162394. for (col = 0; col < num_cols; col++) {
  162395. r = GETJSAMPLE(inptr[RGB_RED]);
  162396. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162397. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162398. inptr += RGB_PIXELSIZE;
  162399. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162400. * must be too; we do not need an explicit range-limiting operation.
  162401. * Hence the value being shifted is never negative, and we don't
  162402. * need the general RIGHT_SHIFT macro.
  162403. */
  162404. /* Y */
  162405. outptr0[col] = (JSAMPLE)
  162406. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162407. >> SCALEBITS);
  162408. /* Cb */
  162409. outptr1[col] = (JSAMPLE)
  162410. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162411. >> SCALEBITS);
  162412. /* Cr */
  162413. outptr2[col] = (JSAMPLE)
  162414. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162415. >> SCALEBITS);
  162416. }
  162417. }
  162418. }
  162419. /**************** Cases other than RGB -> YCbCr **************/
  162420. /*
  162421. * Convert some rows of samples to the JPEG colorspace.
  162422. * This version handles RGB->grayscale conversion, which is the same
  162423. * as the RGB->Y portion of RGB->YCbCr.
  162424. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162425. */
  162426. METHODDEF(void)
  162427. rgb_gray_convert (j_compress_ptr cinfo,
  162428. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162429. JDIMENSION output_row, int num_rows)
  162430. {
  162431. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162432. register int r, g, b;
  162433. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162434. register JSAMPROW inptr;
  162435. register JSAMPROW outptr;
  162436. register JDIMENSION col;
  162437. JDIMENSION num_cols = cinfo->image_width;
  162438. while (--num_rows >= 0) {
  162439. inptr = *input_buf++;
  162440. outptr = output_buf[0][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. /* Y */
  162448. outptr[col] = (JSAMPLE)
  162449. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162450. >> SCALEBITS);
  162451. }
  162452. }
  162453. }
  162454. /*
  162455. * Convert some rows of samples to the JPEG colorspace.
  162456. * This version handles Adobe-style CMYK->YCCK conversion,
  162457. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162458. * conversion as above, while passing K (black) unchanged.
  162459. * We assume rgb_ycc_start has been called.
  162460. */
  162461. METHODDEF(void)
  162462. cmyk_ycck_convert (j_compress_ptr cinfo,
  162463. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162464. JDIMENSION output_row, int num_rows)
  162465. {
  162466. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162467. register int r, g, b;
  162468. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162469. register JSAMPROW inptr;
  162470. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162471. register JDIMENSION col;
  162472. JDIMENSION num_cols = cinfo->image_width;
  162473. while (--num_rows >= 0) {
  162474. inptr = *input_buf++;
  162475. outptr0 = output_buf[0][output_row];
  162476. outptr1 = output_buf[1][output_row];
  162477. outptr2 = output_buf[2][output_row];
  162478. outptr3 = output_buf[3][output_row];
  162479. output_row++;
  162480. for (col = 0; col < num_cols; col++) {
  162481. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162482. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162483. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162484. /* K passes through as-is */
  162485. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162486. inptr += 4;
  162487. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162488. * must be too; we do not need an explicit range-limiting operation.
  162489. * Hence the value being shifted is never negative, and we don't
  162490. * need the general RIGHT_SHIFT macro.
  162491. */
  162492. /* Y */
  162493. outptr0[col] = (JSAMPLE)
  162494. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162495. >> SCALEBITS);
  162496. /* Cb */
  162497. outptr1[col] = (JSAMPLE)
  162498. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162499. >> SCALEBITS);
  162500. /* Cr */
  162501. outptr2[col] = (JSAMPLE)
  162502. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162503. >> SCALEBITS);
  162504. }
  162505. }
  162506. }
  162507. /*
  162508. * Convert some rows of samples to the JPEG colorspace.
  162509. * This version handles grayscale output with no conversion.
  162510. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162511. */
  162512. METHODDEF(void)
  162513. grayscale_convert (j_compress_ptr cinfo,
  162514. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162515. JDIMENSION output_row, int num_rows)
  162516. {
  162517. register JSAMPROW inptr;
  162518. register JSAMPROW outptr;
  162519. register JDIMENSION col;
  162520. JDIMENSION num_cols = cinfo->image_width;
  162521. int instride = cinfo->input_components;
  162522. while (--num_rows >= 0) {
  162523. inptr = *input_buf++;
  162524. outptr = output_buf[0][output_row];
  162525. output_row++;
  162526. for (col = 0; col < num_cols; col++) {
  162527. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162528. inptr += instride;
  162529. }
  162530. }
  162531. }
  162532. /*
  162533. * Convert some rows of samples to the JPEG colorspace.
  162534. * This version handles multi-component colorspaces without conversion.
  162535. * We assume input_components == num_components.
  162536. */
  162537. METHODDEF(void)
  162538. null_convert (j_compress_ptr cinfo,
  162539. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162540. JDIMENSION output_row, int num_rows)
  162541. {
  162542. register JSAMPROW inptr;
  162543. register JSAMPROW outptr;
  162544. register JDIMENSION col;
  162545. register int ci;
  162546. int nc = cinfo->num_components;
  162547. JDIMENSION num_cols = cinfo->image_width;
  162548. while (--num_rows >= 0) {
  162549. /* It seems fastest to make a separate pass for each component. */
  162550. for (ci = 0; ci < nc; ci++) {
  162551. inptr = *input_buf;
  162552. outptr = output_buf[ci][output_row];
  162553. for (col = 0; col < num_cols; col++) {
  162554. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162555. inptr += nc;
  162556. }
  162557. }
  162558. input_buf++;
  162559. output_row++;
  162560. }
  162561. }
  162562. /*
  162563. * Empty method for start_pass.
  162564. */
  162565. METHODDEF(void)
  162566. null_method (j_compress_ptr)
  162567. {
  162568. /* no work needed */
  162569. }
  162570. /*
  162571. * Module initialization routine for input colorspace conversion.
  162572. */
  162573. GLOBAL(void)
  162574. jinit_color_converter (j_compress_ptr cinfo)
  162575. {
  162576. my_cconvert_ptr cconvert;
  162577. cconvert = (my_cconvert_ptr)
  162578. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162579. SIZEOF(my_color_converter));
  162580. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162581. /* set start_pass to null method until we find out differently */
  162582. cconvert->pub.start_pass = null_method;
  162583. /* Make sure input_components agrees with in_color_space */
  162584. switch (cinfo->in_color_space) {
  162585. case JCS_GRAYSCALE:
  162586. if (cinfo->input_components != 1)
  162587. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162588. break;
  162589. case JCS_RGB:
  162590. #if RGB_PIXELSIZE != 3
  162591. if (cinfo->input_components != RGB_PIXELSIZE)
  162592. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162593. break;
  162594. #endif /* else share code with YCbCr */
  162595. case JCS_YCbCr:
  162596. if (cinfo->input_components != 3)
  162597. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162598. break;
  162599. case JCS_CMYK:
  162600. case JCS_YCCK:
  162601. if (cinfo->input_components != 4)
  162602. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162603. break;
  162604. default: /* JCS_UNKNOWN can be anything */
  162605. if (cinfo->input_components < 1)
  162606. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162607. break;
  162608. }
  162609. /* Check num_components, set conversion method based on requested space */
  162610. switch (cinfo->jpeg_color_space) {
  162611. case JCS_GRAYSCALE:
  162612. if (cinfo->num_components != 1)
  162613. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162614. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162615. cconvert->pub.color_convert = grayscale_convert;
  162616. else if (cinfo->in_color_space == JCS_RGB) {
  162617. cconvert->pub.start_pass = rgb_ycc_start;
  162618. cconvert->pub.color_convert = rgb_gray_convert;
  162619. } else if (cinfo->in_color_space == JCS_YCbCr)
  162620. cconvert->pub.color_convert = grayscale_convert;
  162621. else
  162622. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162623. break;
  162624. case JCS_RGB:
  162625. if (cinfo->num_components != 3)
  162626. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162627. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162628. cconvert->pub.color_convert = null_convert;
  162629. else
  162630. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162631. break;
  162632. case JCS_YCbCr:
  162633. if (cinfo->num_components != 3)
  162634. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162635. if (cinfo->in_color_space == JCS_RGB) {
  162636. cconvert->pub.start_pass = rgb_ycc_start;
  162637. cconvert->pub.color_convert = rgb_ycc_convert;
  162638. } else if (cinfo->in_color_space == JCS_YCbCr)
  162639. cconvert->pub.color_convert = null_convert;
  162640. else
  162641. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162642. break;
  162643. case JCS_CMYK:
  162644. if (cinfo->num_components != 4)
  162645. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162646. if (cinfo->in_color_space == JCS_CMYK)
  162647. cconvert->pub.color_convert = null_convert;
  162648. else
  162649. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162650. break;
  162651. case JCS_YCCK:
  162652. if (cinfo->num_components != 4)
  162653. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162654. if (cinfo->in_color_space == JCS_CMYK) {
  162655. cconvert->pub.start_pass = rgb_ycc_start;
  162656. cconvert->pub.color_convert = cmyk_ycck_convert;
  162657. } else if (cinfo->in_color_space == JCS_YCCK)
  162658. cconvert->pub.color_convert = null_convert;
  162659. else
  162660. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162661. break;
  162662. default: /* allow null conversion of JCS_UNKNOWN */
  162663. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162664. cinfo->num_components != cinfo->input_components)
  162665. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162666. cconvert->pub.color_convert = null_convert;
  162667. break;
  162668. }
  162669. }
  162670. /*** End of inlined file: jccolor.c ***/
  162671. #undef FIX
  162672. /*** Start of inlined file: jcdctmgr.c ***/
  162673. #define JPEG_INTERNALS
  162674. /*** Start of inlined file: jdct.h ***/
  162675. /*
  162676. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162677. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162678. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162679. * implementations use an array of type FAST_FLOAT, instead.)
  162680. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162681. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162682. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162683. * convention improves accuracy in integer implementations and saves some
  162684. * work in floating-point ones.
  162685. * Quantization of the output coefficients is done by jcdctmgr.c.
  162686. */
  162687. #ifndef __jdct_h__
  162688. #define __jdct_h__
  162689. #if BITS_IN_JSAMPLE == 8
  162690. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162691. #else
  162692. typedef INT32 DCTELEM; /* must have 32 bits */
  162693. #endif
  162694. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162695. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162696. /*
  162697. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162698. * to an output sample array. The routine must dequantize the input data as
  162699. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162700. * pointed to by compptr->dct_table. The output data is to be placed into the
  162701. * sample array starting at a specified column. (Any row offset needed will
  162702. * be applied to the array pointer before it is passed to the IDCT code.)
  162703. * Note that the number of samples emitted by the IDCT routine is
  162704. * DCT_scaled_size * DCT_scaled_size.
  162705. */
  162706. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162707. /*
  162708. * Each IDCT routine has its own ideas about the best dct_table element type.
  162709. */
  162710. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162711. #if BITS_IN_JSAMPLE == 8
  162712. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162713. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162714. #else
  162715. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162716. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162717. #endif
  162718. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162719. /*
  162720. * Each IDCT routine is responsible for range-limiting its results and
  162721. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162722. * be quite far out of range if the input data is corrupt, so a bulletproof
  162723. * range-limiting step is required. We use a mask-and-table-lookup method
  162724. * to do the combined operations quickly. See the comments with
  162725. * prepare_range_limit_table (in jdmaster.c) for more info.
  162726. */
  162727. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162728. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162729. /* Short forms of external names for systems with brain-damaged linkers. */
  162730. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162731. #define jpeg_fdct_islow jFDislow
  162732. #define jpeg_fdct_ifast jFDifast
  162733. #define jpeg_fdct_float jFDfloat
  162734. #define jpeg_idct_islow jRDislow
  162735. #define jpeg_idct_ifast jRDifast
  162736. #define jpeg_idct_float jRDfloat
  162737. #define jpeg_idct_4x4 jRD4x4
  162738. #define jpeg_idct_2x2 jRD2x2
  162739. #define jpeg_idct_1x1 jRD1x1
  162740. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162741. /* Extern declarations for the forward and inverse DCT routines. */
  162742. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162743. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162744. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162745. EXTERN(void) jpeg_idct_islow
  162746. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162747. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162748. EXTERN(void) jpeg_idct_ifast
  162749. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162750. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162751. EXTERN(void) jpeg_idct_float
  162752. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162753. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162754. EXTERN(void) jpeg_idct_4x4
  162755. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162756. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162757. EXTERN(void) jpeg_idct_2x2
  162758. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162759. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162760. EXTERN(void) jpeg_idct_1x1
  162761. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162762. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162763. /*
  162764. * Macros for handling fixed-point arithmetic; these are used by many
  162765. * but not all of the DCT/IDCT modules.
  162766. *
  162767. * All values are expected to be of type INT32.
  162768. * Fractional constants are scaled left by CONST_BITS bits.
  162769. * CONST_BITS is defined within each module using these macros,
  162770. * and may differ from one module to the next.
  162771. */
  162772. #define ONE ((INT32) 1)
  162773. #define CONST_SCALE (ONE << CONST_BITS)
  162774. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162775. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162776. * thus causing a lot of useless floating-point operations at run time.
  162777. */
  162778. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162779. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162780. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162781. * the fudge factor is correct for either sign of X.
  162782. */
  162783. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162784. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162785. * This macro is used only when the two inputs will actually be no more than
  162786. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162787. * full 32x32 multiply. This provides a useful speedup on many machines.
  162788. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162789. * in C, but some C compilers will do the right thing if you provide the
  162790. * correct combination of casts.
  162791. */
  162792. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162793. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162794. #endif
  162795. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162796. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162797. #endif
  162798. #ifndef MULTIPLY16C16 /* default definition */
  162799. #define MULTIPLY16C16(var,const) ((var) * (const))
  162800. #endif
  162801. /* Same except both inputs are variables. */
  162802. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162803. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162804. #endif
  162805. #ifndef MULTIPLY16V16 /* default definition */
  162806. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162807. #endif
  162808. #endif
  162809. /*** End of inlined file: jdct.h ***/
  162810. /* Private declarations for DCT subsystem */
  162811. /* Private subobject for this module */
  162812. typedef struct {
  162813. struct jpeg_forward_dct pub; /* public fields */
  162814. /* Pointer to the DCT routine actually in use */
  162815. forward_DCT_method_ptr do_dct;
  162816. /* The actual post-DCT divisors --- not identical to the quant table
  162817. * entries, because of scaling (especially for an unnormalized DCT).
  162818. * Each table is given in normal array order.
  162819. */
  162820. DCTELEM * divisors[NUM_QUANT_TBLS];
  162821. #ifdef DCT_FLOAT_SUPPORTED
  162822. /* Same as above for the floating-point case. */
  162823. float_DCT_method_ptr do_float_dct;
  162824. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162825. #endif
  162826. } my_fdct_controller;
  162827. typedef my_fdct_controller * my_fdct_ptr;
  162828. /*
  162829. * Initialize for a processing pass.
  162830. * Verify that all referenced Q-tables are present, and set up
  162831. * the divisor table for each one.
  162832. * In the current implementation, DCT of all components is done during
  162833. * the first pass, even if only some components will be output in the
  162834. * first scan. Hence all components should be examined here.
  162835. */
  162836. METHODDEF(void)
  162837. start_pass_fdctmgr (j_compress_ptr cinfo)
  162838. {
  162839. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162840. int ci, qtblno, i;
  162841. jpeg_component_info *compptr;
  162842. JQUANT_TBL * qtbl;
  162843. DCTELEM * dtbl;
  162844. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162845. ci++, compptr++) {
  162846. qtblno = compptr->quant_tbl_no;
  162847. /* Make sure specified quantization table is present */
  162848. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162849. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162850. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162851. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162852. /* Compute divisors for this quant table */
  162853. /* We may do this more than once for same table, but it's not a big deal */
  162854. switch (cinfo->dct_method) {
  162855. #ifdef DCT_ISLOW_SUPPORTED
  162856. case JDCT_ISLOW:
  162857. /* For LL&M IDCT method, divisors are equal to raw quantization
  162858. * coefficients multiplied by 8 (to counteract scaling).
  162859. */
  162860. if (fdct->divisors[qtblno] == NULL) {
  162861. fdct->divisors[qtblno] = (DCTELEM *)
  162862. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162863. DCTSIZE2 * SIZEOF(DCTELEM));
  162864. }
  162865. dtbl = fdct->divisors[qtblno];
  162866. for (i = 0; i < DCTSIZE2; i++) {
  162867. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162868. }
  162869. break;
  162870. #endif
  162871. #ifdef DCT_IFAST_SUPPORTED
  162872. case JDCT_IFAST:
  162873. {
  162874. /* For AA&N IDCT method, divisors are equal to quantization
  162875. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162876. * scalefactor[0] = 1
  162877. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162878. * We apply a further scale factor of 8.
  162879. */
  162880. #define CONST_BITS 14
  162881. static const INT16 aanscales[DCTSIZE2] = {
  162882. /* precomputed values scaled up by 14 bits */
  162883. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162884. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162885. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162886. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162887. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162888. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162889. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162890. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162891. };
  162892. SHIFT_TEMPS
  162893. if (fdct->divisors[qtblno] == NULL) {
  162894. fdct->divisors[qtblno] = (DCTELEM *)
  162895. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162896. DCTSIZE2 * SIZEOF(DCTELEM));
  162897. }
  162898. dtbl = fdct->divisors[qtblno];
  162899. for (i = 0; i < DCTSIZE2; i++) {
  162900. dtbl[i] = (DCTELEM)
  162901. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162902. (INT32) aanscales[i]),
  162903. CONST_BITS-3);
  162904. }
  162905. }
  162906. break;
  162907. #endif
  162908. #ifdef DCT_FLOAT_SUPPORTED
  162909. case JDCT_FLOAT:
  162910. {
  162911. /* For float AA&N IDCT method, divisors are equal to quantization
  162912. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162913. * scalefactor[0] = 1
  162914. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162915. * We apply a further scale factor of 8.
  162916. * What's actually stored is 1/divisor so that the inner loop can
  162917. * use a multiplication rather than a division.
  162918. */
  162919. FAST_FLOAT * fdtbl;
  162920. int row, col;
  162921. static const double aanscalefactor[DCTSIZE] = {
  162922. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162923. 1.0, 0.785694958, 0.541196100, 0.275899379
  162924. };
  162925. if (fdct->float_divisors[qtblno] == NULL) {
  162926. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162927. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162928. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162929. }
  162930. fdtbl = fdct->float_divisors[qtblno];
  162931. i = 0;
  162932. for (row = 0; row < DCTSIZE; row++) {
  162933. for (col = 0; col < DCTSIZE; col++) {
  162934. fdtbl[i] = (FAST_FLOAT)
  162935. (1.0 / (((double) qtbl->quantval[i] *
  162936. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162937. i++;
  162938. }
  162939. }
  162940. }
  162941. break;
  162942. #endif
  162943. default:
  162944. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162945. break;
  162946. }
  162947. }
  162948. }
  162949. /*
  162950. * Perform forward DCT on one or more blocks of a component.
  162951. *
  162952. * The input samples are taken from the sample_data[] array starting at
  162953. * position start_row/start_col, and moving to the right for any additional
  162954. * blocks. The quantized coefficients are returned in coef_blocks[].
  162955. */
  162956. METHODDEF(void)
  162957. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162958. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162959. JDIMENSION start_row, JDIMENSION start_col,
  162960. JDIMENSION num_blocks)
  162961. /* This version is used for integer DCT implementations. */
  162962. {
  162963. /* This routine is heavily used, so it's worth coding it tightly. */
  162964. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162965. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162966. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162967. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162968. JDIMENSION bi;
  162969. sample_data += start_row; /* fold in the vertical offset once */
  162970. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162971. /* Load data into workspace, applying unsigned->signed conversion */
  162972. { register DCTELEM *workspaceptr;
  162973. register JSAMPROW elemptr;
  162974. register int elemr;
  162975. workspaceptr = workspace;
  162976. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162977. elemptr = sample_data[elemr] + start_col;
  162978. #if DCTSIZE == 8 /* unroll the inner loop */
  162979. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162980. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162981. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162982. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162983. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162984. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162985. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162986. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162987. #else
  162988. { register int elemc;
  162989. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162990. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162991. }
  162992. }
  162993. #endif
  162994. }
  162995. }
  162996. /* Perform the DCT */
  162997. (*do_dct) (workspace);
  162998. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162999. { register DCTELEM temp, qval;
  163000. register int i;
  163001. register JCOEFPTR output_ptr = coef_blocks[bi];
  163002. for (i = 0; i < DCTSIZE2; i++) {
  163003. qval = divisors[i];
  163004. temp = workspace[i];
  163005. /* Divide the coefficient value by qval, ensuring proper rounding.
  163006. * Since C does not specify the direction of rounding for negative
  163007. * quotients, we have to force the dividend positive for portability.
  163008. *
  163009. * In most files, at least half of the output values will be zero
  163010. * (at default quantization settings, more like three-quarters...)
  163011. * so we should ensure that this case is fast. On many machines,
  163012. * a comparison is enough cheaper than a divide to make a special test
  163013. * a win. Since both inputs will be nonnegative, we need only test
  163014. * for a < b to discover whether a/b is 0.
  163015. * If your machine's division is fast enough, define FAST_DIVIDE.
  163016. */
  163017. #ifdef FAST_DIVIDE
  163018. #define DIVIDE_BY(a,b) a /= b
  163019. #else
  163020. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  163021. #endif
  163022. if (temp < 0) {
  163023. temp = -temp;
  163024. temp += qval>>1; /* for rounding */
  163025. DIVIDE_BY(temp, qval);
  163026. temp = -temp;
  163027. } else {
  163028. temp += qval>>1; /* for rounding */
  163029. DIVIDE_BY(temp, qval);
  163030. }
  163031. output_ptr[i] = (JCOEF) temp;
  163032. }
  163033. }
  163034. }
  163035. }
  163036. #ifdef DCT_FLOAT_SUPPORTED
  163037. METHODDEF(void)
  163038. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163039. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163040. JDIMENSION start_row, JDIMENSION start_col,
  163041. JDIMENSION num_blocks)
  163042. /* This version is used for floating-point DCT implementations. */
  163043. {
  163044. /* This routine is heavily used, so it's worth coding it tightly. */
  163045. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163046. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  163047. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  163048. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163049. JDIMENSION bi;
  163050. sample_data += start_row; /* fold in the vertical offset once */
  163051. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163052. /* Load data into workspace, applying unsigned->signed conversion */
  163053. { register FAST_FLOAT *workspaceptr;
  163054. register JSAMPROW elemptr;
  163055. register int elemr;
  163056. workspaceptr = workspace;
  163057. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163058. elemptr = sample_data[elemr] + start_col;
  163059. #if DCTSIZE == 8 /* unroll the inner loop */
  163060. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163061. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163062. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163063. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163064. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163065. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163066. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163067. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163068. #else
  163069. { register int elemc;
  163070. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163071. *workspaceptr++ = (FAST_FLOAT)
  163072. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163073. }
  163074. }
  163075. #endif
  163076. }
  163077. }
  163078. /* Perform the DCT */
  163079. (*do_dct) (workspace);
  163080. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163081. { register FAST_FLOAT temp;
  163082. register int i;
  163083. register JCOEFPTR output_ptr = coef_blocks[bi];
  163084. for (i = 0; i < DCTSIZE2; i++) {
  163085. /* Apply the quantization and scaling factor */
  163086. temp = workspace[i] * divisors[i];
  163087. /* Round to nearest integer.
  163088. * Since C does not specify the direction of rounding for negative
  163089. * quotients, we have to force the dividend positive for portability.
  163090. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163091. * code should work for either 16-bit or 32-bit ints.
  163092. */
  163093. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163094. }
  163095. }
  163096. }
  163097. }
  163098. #endif /* DCT_FLOAT_SUPPORTED */
  163099. /*
  163100. * Initialize FDCT manager.
  163101. */
  163102. GLOBAL(void)
  163103. jinit_forward_dct (j_compress_ptr cinfo)
  163104. {
  163105. my_fdct_ptr fdct;
  163106. int i;
  163107. fdct = (my_fdct_ptr)
  163108. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163109. SIZEOF(my_fdct_controller));
  163110. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163111. fdct->pub.start_pass = start_pass_fdctmgr;
  163112. switch (cinfo->dct_method) {
  163113. #ifdef DCT_ISLOW_SUPPORTED
  163114. case JDCT_ISLOW:
  163115. fdct->pub.forward_DCT = forward_DCT;
  163116. fdct->do_dct = jpeg_fdct_islow;
  163117. break;
  163118. #endif
  163119. #ifdef DCT_IFAST_SUPPORTED
  163120. case JDCT_IFAST:
  163121. fdct->pub.forward_DCT = forward_DCT;
  163122. fdct->do_dct = jpeg_fdct_ifast;
  163123. break;
  163124. #endif
  163125. #ifdef DCT_FLOAT_SUPPORTED
  163126. case JDCT_FLOAT:
  163127. fdct->pub.forward_DCT = forward_DCT_float;
  163128. fdct->do_float_dct = jpeg_fdct_float;
  163129. break;
  163130. #endif
  163131. default:
  163132. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163133. break;
  163134. }
  163135. /* Mark divisor tables unallocated */
  163136. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163137. fdct->divisors[i] = NULL;
  163138. #ifdef DCT_FLOAT_SUPPORTED
  163139. fdct->float_divisors[i] = NULL;
  163140. #endif
  163141. }
  163142. }
  163143. /*** End of inlined file: jcdctmgr.c ***/
  163144. #undef CONST_BITS
  163145. /*** Start of inlined file: jchuff.c ***/
  163146. #define JPEG_INTERNALS
  163147. /*** Start of inlined file: jchuff.h ***/
  163148. /* The legal range of a DCT coefficient is
  163149. * -1024 .. +1023 for 8-bit data;
  163150. * -16384 .. +16383 for 12-bit data.
  163151. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163152. */
  163153. #ifndef _jchuff_h_
  163154. #define _jchuff_h_
  163155. #if BITS_IN_JSAMPLE == 8
  163156. #define MAX_COEF_BITS 10
  163157. #else
  163158. #define MAX_COEF_BITS 14
  163159. #endif
  163160. /* Derived data constructed for each Huffman table */
  163161. typedef struct {
  163162. unsigned int ehufco[256]; /* code for each symbol */
  163163. char ehufsi[256]; /* length of code for each symbol */
  163164. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163165. } c_derived_tbl;
  163166. /* Short forms of external names for systems with brain-damaged linkers. */
  163167. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163168. #define jpeg_make_c_derived_tbl jMkCDerived
  163169. #define jpeg_gen_optimal_table jGenOptTbl
  163170. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163171. /* Expand a Huffman table definition into the derived format */
  163172. EXTERN(void) jpeg_make_c_derived_tbl
  163173. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163174. c_derived_tbl ** pdtbl));
  163175. /* Generate an optimal table definition given the specified counts */
  163176. EXTERN(void) jpeg_gen_optimal_table
  163177. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163178. #endif
  163179. /*** End of inlined file: jchuff.h ***/
  163180. /* Declarations shared with jcphuff.c */
  163181. /* Expanded entropy encoder object for Huffman encoding.
  163182. *
  163183. * The savable_state subrecord contains fields that change within an MCU,
  163184. * but must not be updated permanently until we complete the MCU.
  163185. */
  163186. typedef struct {
  163187. INT32 put_buffer; /* current bit-accumulation buffer */
  163188. int put_bits; /* # of bits now in it */
  163189. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163190. } savable_state;
  163191. /* This macro is to work around compilers with missing or broken
  163192. * structure assignment. You'll need to fix this code if you have
  163193. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163194. */
  163195. #ifndef NO_STRUCT_ASSIGN
  163196. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163197. #else
  163198. #if MAX_COMPS_IN_SCAN == 4
  163199. #define ASSIGN_STATE(dest,src) \
  163200. ((dest).put_buffer = (src).put_buffer, \
  163201. (dest).put_bits = (src).put_bits, \
  163202. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163203. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163204. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163205. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163206. #endif
  163207. #endif
  163208. typedef struct {
  163209. struct jpeg_entropy_encoder pub; /* public fields */
  163210. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163211. /* These fields are NOT loaded into local working state. */
  163212. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163213. int next_restart_num; /* next restart number to write (0-7) */
  163214. /* Pointers to derived tables (these workspaces have image lifespan) */
  163215. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163216. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163217. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163218. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163219. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163220. #endif
  163221. } huff_entropy_encoder;
  163222. typedef huff_entropy_encoder * huff_entropy_ptr;
  163223. /* Working state while writing an MCU.
  163224. * This struct contains all the fields that are needed by subroutines.
  163225. */
  163226. typedef struct {
  163227. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163228. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163229. savable_state cur; /* Current bit buffer & DC state */
  163230. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163231. } working_state;
  163232. /* Forward declarations */
  163233. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163234. JBLOCKROW *MCU_data));
  163235. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163236. #ifdef ENTROPY_OPT_SUPPORTED
  163237. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163238. JBLOCKROW *MCU_data));
  163239. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163240. #endif
  163241. /*
  163242. * Initialize for a Huffman-compressed scan.
  163243. * If gather_statistics is TRUE, we do not output anything during the scan,
  163244. * just count the Huffman symbols used and generate Huffman code tables.
  163245. */
  163246. METHODDEF(void)
  163247. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163248. {
  163249. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163250. int ci, dctbl, actbl;
  163251. jpeg_component_info * compptr;
  163252. if (gather_statistics) {
  163253. #ifdef ENTROPY_OPT_SUPPORTED
  163254. entropy->pub.encode_mcu = encode_mcu_gather;
  163255. entropy->pub.finish_pass = finish_pass_gather;
  163256. #else
  163257. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163258. #endif
  163259. } else {
  163260. entropy->pub.encode_mcu = encode_mcu_huff;
  163261. entropy->pub.finish_pass = finish_pass_huff;
  163262. }
  163263. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163264. compptr = cinfo->cur_comp_info[ci];
  163265. dctbl = compptr->dc_tbl_no;
  163266. actbl = compptr->ac_tbl_no;
  163267. if (gather_statistics) {
  163268. #ifdef ENTROPY_OPT_SUPPORTED
  163269. /* Check for invalid table indexes */
  163270. /* (make_c_derived_tbl does this in the other path) */
  163271. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163272. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163273. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163274. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163275. /* Allocate and zero the statistics tables */
  163276. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163277. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163278. entropy->dc_count_ptrs[dctbl] = (long *)
  163279. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163280. 257 * SIZEOF(long));
  163281. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163282. if (entropy->ac_count_ptrs[actbl] == NULL)
  163283. entropy->ac_count_ptrs[actbl] = (long *)
  163284. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163285. 257 * SIZEOF(long));
  163286. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163287. #endif
  163288. } else {
  163289. /* Compute derived values for Huffman tables */
  163290. /* We may do this more than once for a table, but it's not expensive */
  163291. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163292. & entropy->dc_derived_tbls[dctbl]);
  163293. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163294. & entropy->ac_derived_tbls[actbl]);
  163295. }
  163296. /* Initialize DC predictions to 0 */
  163297. entropy->saved.last_dc_val[ci] = 0;
  163298. }
  163299. /* Initialize bit buffer to empty */
  163300. entropy->saved.put_buffer = 0;
  163301. entropy->saved.put_bits = 0;
  163302. /* Initialize restart stuff */
  163303. entropy->restarts_to_go = cinfo->restart_interval;
  163304. entropy->next_restart_num = 0;
  163305. }
  163306. /*
  163307. * Compute the derived values for a Huffman table.
  163308. * This routine also performs some validation checks on the table.
  163309. *
  163310. * Note this is also used by jcphuff.c.
  163311. */
  163312. GLOBAL(void)
  163313. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163314. c_derived_tbl ** pdtbl)
  163315. {
  163316. JHUFF_TBL *htbl;
  163317. c_derived_tbl *dtbl;
  163318. int p, i, l, lastp, si, maxsymbol;
  163319. char huffsize[257];
  163320. unsigned int huffcode[257];
  163321. unsigned int code;
  163322. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163323. * paralleling the order of the symbols themselves in htbl->huffval[].
  163324. */
  163325. /* Find the input Huffman table */
  163326. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163327. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163328. htbl =
  163329. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163330. if (htbl == NULL)
  163331. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163332. /* Allocate a workspace if we haven't already done so. */
  163333. if (*pdtbl == NULL)
  163334. *pdtbl = (c_derived_tbl *)
  163335. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163336. SIZEOF(c_derived_tbl));
  163337. dtbl = *pdtbl;
  163338. /* Figure C.1: make table of Huffman code length for each symbol */
  163339. p = 0;
  163340. for (l = 1; l <= 16; l++) {
  163341. i = (int) htbl->bits[l];
  163342. if (i < 0 || p + i > 256) /* protect against table overrun */
  163343. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163344. while (i--)
  163345. huffsize[p++] = (char) l;
  163346. }
  163347. huffsize[p] = 0;
  163348. lastp = p;
  163349. /* Figure C.2: generate the codes themselves */
  163350. /* We also validate that the counts represent a legal Huffman code tree. */
  163351. code = 0;
  163352. si = huffsize[0];
  163353. p = 0;
  163354. while (huffsize[p]) {
  163355. while (((int) huffsize[p]) == si) {
  163356. huffcode[p++] = code;
  163357. code++;
  163358. }
  163359. /* code is now 1 more than the last code used for codelength si; but
  163360. * it must still fit in si bits, since no code is allowed to be all ones.
  163361. */
  163362. if (((INT32) code) >= (((INT32) 1) << si))
  163363. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163364. code <<= 1;
  163365. si++;
  163366. }
  163367. /* Figure C.3: generate encoding tables */
  163368. /* These are code and size indexed by symbol value */
  163369. /* Set all codeless symbols to have code length 0;
  163370. * this lets us detect duplicate VAL entries here, and later
  163371. * allows emit_bits to detect any attempt to emit such symbols.
  163372. */
  163373. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163374. /* This is also a convenient place to check for out-of-range
  163375. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163376. * but only 0..15 for DC. (We could constrain them further
  163377. * based on data depth and mode, but this seems enough.)
  163378. */
  163379. maxsymbol = isDC ? 15 : 255;
  163380. for (p = 0; p < lastp; p++) {
  163381. i = htbl->huffval[p];
  163382. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163383. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163384. dtbl->ehufco[i] = huffcode[p];
  163385. dtbl->ehufsi[i] = huffsize[p];
  163386. }
  163387. }
  163388. /* Outputting bytes to the file */
  163389. /* Emit a byte, taking 'action' if must suspend. */
  163390. #define emit_byte(state,val,action) \
  163391. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163392. if (--(state)->free_in_buffer == 0) \
  163393. if (! dump_buffer(state)) \
  163394. { action; } }
  163395. LOCAL(boolean)
  163396. dump_buffer (working_state * state)
  163397. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163398. {
  163399. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163400. if (! (*dest->empty_output_buffer) (state->cinfo))
  163401. return FALSE;
  163402. /* After a successful buffer dump, must reset buffer pointers */
  163403. state->next_output_byte = dest->next_output_byte;
  163404. state->free_in_buffer = dest->free_in_buffer;
  163405. return TRUE;
  163406. }
  163407. /* Outputting bits to the file */
  163408. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163409. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163410. * in one call, and we never retain more than 7 bits in put_buffer
  163411. * between calls, so 24 bits are sufficient.
  163412. */
  163413. INLINE
  163414. LOCAL(boolean)
  163415. emit_bits (working_state * state, unsigned int code, int size)
  163416. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163417. {
  163418. /* This routine is heavily used, so it's worth coding tightly. */
  163419. register INT32 put_buffer = (INT32) code;
  163420. register int put_bits = state->cur.put_bits;
  163421. /* if size is 0, caller used an invalid Huffman table entry */
  163422. if (size == 0)
  163423. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163424. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163425. put_bits += size; /* new number of bits in buffer */
  163426. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163427. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163428. while (put_bits >= 8) {
  163429. int c = (int) ((put_buffer >> 16) & 0xFF);
  163430. emit_byte(state, c, return FALSE);
  163431. if (c == 0xFF) { /* need to stuff a zero byte? */
  163432. emit_byte(state, 0, return FALSE);
  163433. }
  163434. put_buffer <<= 8;
  163435. put_bits -= 8;
  163436. }
  163437. state->cur.put_buffer = put_buffer; /* update state variables */
  163438. state->cur.put_bits = put_bits;
  163439. return TRUE;
  163440. }
  163441. LOCAL(boolean)
  163442. flush_bits (working_state * state)
  163443. {
  163444. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163445. return FALSE;
  163446. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163447. state->cur.put_bits = 0;
  163448. return TRUE;
  163449. }
  163450. /* Encode a single block's worth of coefficients */
  163451. LOCAL(boolean)
  163452. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163453. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163454. {
  163455. register int temp, temp2;
  163456. register int nbits;
  163457. register int k, r, i;
  163458. /* Encode the DC coefficient difference per section F.1.2.1 */
  163459. temp = temp2 = block[0] - last_dc_val;
  163460. if (temp < 0) {
  163461. temp = -temp; /* temp is abs value of input */
  163462. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163463. /* This code assumes we are on a two's complement machine */
  163464. temp2--;
  163465. }
  163466. /* Find the number of bits needed for the magnitude of the coefficient */
  163467. nbits = 0;
  163468. while (temp) {
  163469. nbits++;
  163470. temp >>= 1;
  163471. }
  163472. /* Check for out-of-range coefficient values.
  163473. * Since we're encoding a difference, the range limit is twice as much.
  163474. */
  163475. if (nbits > MAX_COEF_BITS+1)
  163476. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163477. /* Emit the Huffman-coded symbol for the number of bits */
  163478. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163479. return FALSE;
  163480. /* Emit that number of bits of the value, if positive, */
  163481. /* or the complement of its magnitude, if negative. */
  163482. if (nbits) /* emit_bits rejects calls with size 0 */
  163483. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163484. return FALSE;
  163485. /* Encode the AC coefficients per section F.1.2.2 */
  163486. r = 0; /* r = run length of zeros */
  163487. for (k = 1; k < DCTSIZE2; k++) {
  163488. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163489. r++;
  163490. } else {
  163491. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163492. while (r > 15) {
  163493. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163494. return FALSE;
  163495. r -= 16;
  163496. }
  163497. temp2 = temp;
  163498. if (temp < 0) {
  163499. temp = -temp; /* temp is abs value of input */
  163500. /* This code assumes we are on a two's complement machine */
  163501. temp2--;
  163502. }
  163503. /* Find the number of bits needed for the magnitude of the coefficient */
  163504. nbits = 1; /* there must be at least one 1 bit */
  163505. while ((temp >>= 1))
  163506. nbits++;
  163507. /* Check for out-of-range coefficient values */
  163508. if (nbits > MAX_COEF_BITS)
  163509. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163510. /* Emit Huffman symbol for run length / number of bits */
  163511. i = (r << 4) + nbits;
  163512. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163513. return FALSE;
  163514. /* Emit that number of bits of the value, if positive, */
  163515. /* or the complement of its magnitude, if negative. */
  163516. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163517. return FALSE;
  163518. r = 0;
  163519. }
  163520. }
  163521. /* If the last coef(s) were zero, emit an end-of-block code */
  163522. if (r > 0)
  163523. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163524. return FALSE;
  163525. return TRUE;
  163526. }
  163527. /*
  163528. * Emit a restart marker & resynchronize predictions.
  163529. */
  163530. LOCAL(boolean)
  163531. emit_restart (working_state * state, int restart_num)
  163532. {
  163533. int ci;
  163534. if (! flush_bits(state))
  163535. return FALSE;
  163536. emit_byte(state, 0xFF, return FALSE);
  163537. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163538. /* Re-initialize DC predictions to 0 */
  163539. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163540. state->cur.last_dc_val[ci] = 0;
  163541. /* The restart counter is not updated until we successfully write the MCU. */
  163542. return TRUE;
  163543. }
  163544. /*
  163545. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163546. */
  163547. METHODDEF(boolean)
  163548. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163549. {
  163550. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163551. working_state state;
  163552. int blkn, ci;
  163553. jpeg_component_info * compptr;
  163554. /* Load up working state */
  163555. state.next_output_byte = cinfo->dest->next_output_byte;
  163556. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163557. ASSIGN_STATE(state.cur, entropy->saved);
  163558. state.cinfo = cinfo;
  163559. /* Emit restart marker if needed */
  163560. if (cinfo->restart_interval) {
  163561. if (entropy->restarts_to_go == 0)
  163562. if (! emit_restart(&state, entropy->next_restart_num))
  163563. return FALSE;
  163564. }
  163565. /* Encode the MCU data blocks */
  163566. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163567. ci = cinfo->MCU_membership[blkn];
  163568. compptr = cinfo->cur_comp_info[ci];
  163569. if (! encode_one_block(&state,
  163570. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163571. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163572. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163573. return FALSE;
  163574. /* Update last_dc_val */
  163575. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163576. }
  163577. /* Completed MCU, so update state */
  163578. cinfo->dest->next_output_byte = state.next_output_byte;
  163579. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163580. ASSIGN_STATE(entropy->saved, state.cur);
  163581. /* Update restart-interval state too */
  163582. if (cinfo->restart_interval) {
  163583. if (entropy->restarts_to_go == 0) {
  163584. entropy->restarts_to_go = cinfo->restart_interval;
  163585. entropy->next_restart_num++;
  163586. entropy->next_restart_num &= 7;
  163587. }
  163588. entropy->restarts_to_go--;
  163589. }
  163590. return TRUE;
  163591. }
  163592. /*
  163593. * Finish up at the end of a Huffman-compressed scan.
  163594. */
  163595. METHODDEF(void)
  163596. finish_pass_huff (j_compress_ptr cinfo)
  163597. {
  163598. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163599. working_state state;
  163600. /* Load up working state ... flush_bits needs it */
  163601. state.next_output_byte = cinfo->dest->next_output_byte;
  163602. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163603. ASSIGN_STATE(state.cur, entropy->saved);
  163604. state.cinfo = cinfo;
  163605. /* Flush out the last data */
  163606. if (! flush_bits(&state))
  163607. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163608. /* Update state */
  163609. cinfo->dest->next_output_byte = state.next_output_byte;
  163610. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163611. ASSIGN_STATE(entropy->saved, state.cur);
  163612. }
  163613. /*
  163614. * Huffman coding optimization.
  163615. *
  163616. * We first scan the supplied data and count the number of uses of each symbol
  163617. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163618. * Then we build a Huffman coding tree for the observed counts.
  163619. * Symbols which are not needed at all for the particular image are not
  163620. * assigned any code, which saves space in the DHT marker as well as in
  163621. * the compressed data.
  163622. */
  163623. #ifdef ENTROPY_OPT_SUPPORTED
  163624. /* Process a single block's worth of coefficients */
  163625. LOCAL(void)
  163626. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163627. long dc_counts[], long ac_counts[])
  163628. {
  163629. register int temp;
  163630. register int nbits;
  163631. register int k, r;
  163632. /* Encode the DC coefficient difference per section F.1.2.1 */
  163633. temp = block[0] - last_dc_val;
  163634. if (temp < 0)
  163635. temp = -temp;
  163636. /* Find the number of bits needed for the magnitude of the coefficient */
  163637. nbits = 0;
  163638. while (temp) {
  163639. nbits++;
  163640. temp >>= 1;
  163641. }
  163642. /* Check for out-of-range coefficient values.
  163643. * Since we're encoding a difference, the range limit is twice as much.
  163644. */
  163645. if (nbits > MAX_COEF_BITS+1)
  163646. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163647. /* Count the Huffman symbol for the number of bits */
  163648. dc_counts[nbits]++;
  163649. /* Encode the AC coefficients per section F.1.2.2 */
  163650. r = 0; /* r = run length of zeros */
  163651. for (k = 1; k < DCTSIZE2; k++) {
  163652. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163653. r++;
  163654. } else {
  163655. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163656. while (r > 15) {
  163657. ac_counts[0xF0]++;
  163658. r -= 16;
  163659. }
  163660. /* Find the number of bits needed for the magnitude of the coefficient */
  163661. if (temp < 0)
  163662. temp = -temp;
  163663. /* Find the number of bits needed for the magnitude of the coefficient */
  163664. nbits = 1; /* there must be at least one 1 bit */
  163665. while ((temp >>= 1))
  163666. nbits++;
  163667. /* Check for out-of-range coefficient values */
  163668. if (nbits > MAX_COEF_BITS)
  163669. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163670. /* Count Huffman symbol for run length / number of bits */
  163671. ac_counts[(r << 4) + nbits]++;
  163672. r = 0;
  163673. }
  163674. }
  163675. /* If the last coef(s) were zero, emit an end-of-block code */
  163676. if (r > 0)
  163677. ac_counts[0]++;
  163678. }
  163679. /*
  163680. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163681. * No data is actually output, so no suspension return is possible.
  163682. */
  163683. METHODDEF(boolean)
  163684. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163685. {
  163686. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163687. int blkn, ci;
  163688. jpeg_component_info * compptr;
  163689. /* Take care of restart intervals if needed */
  163690. if (cinfo->restart_interval) {
  163691. if (entropy->restarts_to_go == 0) {
  163692. /* Re-initialize DC predictions to 0 */
  163693. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163694. entropy->saved.last_dc_val[ci] = 0;
  163695. /* Update restart state */
  163696. entropy->restarts_to_go = cinfo->restart_interval;
  163697. }
  163698. entropy->restarts_to_go--;
  163699. }
  163700. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163701. ci = cinfo->MCU_membership[blkn];
  163702. compptr = cinfo->cur_comp_info[ci];
  163703. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163704. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163705. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163706. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163707. }
  163708. return TRUE;
  163709. }
  163710. /*
  163711. * Generate the best Huffman code table for the given counts, fill htbl.
  163712. * Note this is also used by jcphuff.c.
  163713. *
  163714. * The JPEG standard requires that no symbol be assigned a codeword of all
  163715. * one bits (so that padding bits added at the end of a compressed segment
  163716. * can't look like a valid code). Because of the canonical ordering of
  163717. * codewords, this just means that there must be an unused slot in the
  163718. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163719. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163720. * with count 1. In theory that's not optimal; giving it count zero but
  163721. * including it in the symbol set anyway should give a better Huffman code.
  163722. * But the theoretically better code actually seems to come out worse in
  163723. * practice, because it produces more all-ones bytes (which incur stuffed
  163724. * zero bytes in the final file). In any case the difference is tiny.
  163725. *
  163726. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163727. * If some symbols have a very small but nonzero probability, the Huffman tree
  163728. * must be adjusted to meet the code length restriction. We currently use
  163729. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163730. * optimal; it may not choose the best possible limited-length code. But
  163731. * typically only very-low-frequency symbols will be given less-than-optimal
  163732. * lengths, so the code is almost optimal. Experimental comparisons against
  163733. * an optimal limited-length-code algorithm indicate that the difference is
  163734. * microscopic --- usually less than a hundredth of a percent of total size.
  163735. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163736. */
  163737. GLOBAL(void)
  163738. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163739. {
  163740. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163741. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163742. int codesize[257]; /* codesize[k] = code length of symbol k */
  163743. int others[257]; /* next symbol in current branch of tree */
  163744. int c1, c2;
  163745. int p, i, j;
  163746. long v;
  163747. /* This algorithm is explained in section K.2 of the JPEG standard */
  163748. MEMZERO(bits, SIZEOF(bits));
  163749. MEMZERO(codesize, SIZEOF(codesize));
  163750. for (i = 0; i < 257; i++)
  163751. others[i] = -1; /* init links to empty */
  163752. freq[256] = 1; /* make sure 256 has a nonzero count */
  163753. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163754. * that no real symbol is given code-value of all ones, because 256
  163755. * will be placed last in the largest codeword category.
  163756. */
  163757. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163758. for (;;) {
  163759. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163760. /* In case of ties, take the larger symbol number */
  163761. c1 = -1;
  163762. v = 1000000000L;
  163763. for (i = 0; i <= 256; i++) {
  163764. if (freq[i] && freq[i] <= v) {
  163765. v = freq[i];
  163766. c1 = i;
  163767. }
  163768. }
  163769. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163770. /* In case of ties, take the larger symbol number */
  163771. c2 = -1;
  163772. v = 1000000000L;
  163773. for (i = 0; i <= 256; i++) {
  163774. if (freq[i] && freq[i] <= v && i != c1) {
  163775. v = freq[i];
  163776. c2 = i;
  163777. }
  163778. }
  163779. /* Done if we've merged everything into one frequency */
  163780. if (c2 < 0)
  163781. break;
  163782. /* Else merge the two counts/trees */
  163783. freq[c1] += freq[c2];
  163784. freq[c2] = 0;
  163785. /* Increment the codesize of everything in c1's tree branch */
  163786. codesize[c1]++;
  163787. while (others[c1] >= 0) {
  163788. c1 = others[c1];
  163789. codesize[c1]++;
  163790. }
  163791. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163792. /* Increment the codesize of everything in c2's tree branch */
  163793. codesize[c2]++;
  163794. while (others[c2] >= 0) {
  163795. c2 = others[c2];
  163796. codesize[c2]++;
  163797. }
  163798. }
  163799. /* Now count the number of symbols of each code length */
  163800. for (i = 0; i <= 256; i++) {
  163801. if (codesize[i]) {
  163802. /* The JPEG standard seems to think that this can't happen, */
  163803. /* but I'm paranoid... */
  163804. if (codesize[i] > MAX_CLEN)
  163805. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163806. bits[codesize[i]]++;
  163807. }
  163808. }
  163809. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163810. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163811. * Here is what the JPEG spec says about how this next bit works:
  163812. * Since symbols are paired for the longest Huffman code, the symbols are
  163813. * removed from this length category two at a time. The prefix for the pair
  163814. * (which is one bit shorter) is allocated to one of the pair; then,
  163815. * skipping the BITS entry for that prefix length, a code word from the next
  163816. * shortest nonzero BITS entry is converted into a prefix for two code words
  163817. * one bit longer.
  163818. */
  163819. for (i = MAX_CLEN; i > 16; i--) {
  163820. while (bits[i] > 0) {
  163821. j = i - 2; /* find length of new prefix to be used */
  163822. while (bits[j] == 0)
  163823. j--;
  163824. bits[i] -= 2; /* remove two symbols */
  163825. bits[i-1]++; /* one goes in this length */
  163826. bits[j+1] += 2; /* two new symbols in this length */
  163827. bits[j]--; /* symbol of this length is now a prefix */
  163828. }
  163829. }
  163830. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163831. while (bits[i] == 0) /* find largest codelength still in use */
  163832. i--;
  163833. bits[i]--;
  163834. /* Return final symbol counts (only for lengths 0..16) */
  163835. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163836. /* Return a list of the symbols sorted by code length */
  163837. /* It's not real clear to me why we don't need to consider the codelength
  163838. * changes made above, but the JPEG spec seems to think this works.
  163839. */
  163840. p = 0;
  163841. for (i = 1; i <= MAX_CLEN; i++) {
  163842. for (j = 0; j <= 255; j++) {
  163843. if (codesize[j] == i) {
  163844. htbl->huffval[p] = (UINT8) j;
  163845. p++;
  163846. }
  163847. }
  163848. }
  163849. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163850. htbl->sent_table = FALSE;
  163851. }
  163852. /*
  163853. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163854. */
  163855. METHODDEF(void)
  163856. finish_pass_gather (j_compress_ptr cinfo)
  163857. {
  163858. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163859. int ci, dctbl, actbl;
  163860. jpeg_component_info * compptr;
  163861. JHUFF_TBL **htblptr;
  163862. boolean did_dc[NUM_HUFF_TBLS];
  163863. boolean did_ac[NUM_HUFF_TBLS];
  163864. /* It's important not to apply jpeg_gen_optimal_table more than once
  163865. * per table, because it clobbers the input frequency counts!
  163866. */
  163867. MEMZERO(did_dc, SIZEOF(did_dc));
  163868. MEMZERO(did_ac, SIZEOF(did_ac));
  163869. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163870. compptr = cinfo->cur_comp_info[ci];
  163871. dctbl = compptr->dc_tbl_no;
  163872. actbl = compptr->ac_tbl_no;
  163873. if (! did_dc[dctbl]) {
  163874. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163875. if (*htblptr == NULL)
  163876. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163877. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163878. did_dc[dctbl] = TRUE;
  163879. }
  163880. if (! did_ac[actbl]) {
  163881. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163882. if (*htblptr == NULL)
  163883. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163884. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163885. did_ac[actbl] = TRUE;
  163886. }
  163887. }
  163888. }
  163889. #endif /* ENTROPY_OPT_SUPPORTED */
  163890. /*
  163891. * Module initialization routine for Huffman entropy encoding.
  163892. */
  163893. GLOBAL(void)
  163894. jinit_huff_encoder (j_compress_ptr cinfo)
  163895. {
  163896. huff_entropy_ptr entropy;
  163897. int i;
  163898. entropy = (huff_entropy_ptr)
  163899. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163900. SIZEOF(huff_entropy_encoder));
  163901. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163902. entropy->pub.start_pass = start_pass_huff;
  163903. /* Mark tables unallocated */
  163904. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163905. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163906. #ifdef ENTROPY_OPT_SUPPORTED
  163907. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163908. #endif
  163909. }
  163910. }
  163911. /*** End of inlined file: jchuff.c ***/
  163912. #undef emit_byte
  163913. /*** Start of inlined file: jcinit.c ***/
  163914. #define JPEG_INTERNALS
  163915. /*
  163916. * Master selection of compression modules.
  163917. * This is done once at the start of processing an image. We determine
  163918. * which modules will be used and give them appropriate initialization calls.
  163919. */
  163920. GLOBAL(void)
  163921. jinit_compress_master (j_compress_ptr cinfo)
  163922. {
  163923. /* Initialize master control (includes parameter checking/processing) */
  163924. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163925. /* Preprocessing */
  163926. if (! cinfo->raw_data_in) {
  163927. jinit_color_converter(cinfo);
  163928. jinit_downsampler(cinfo);
  163929. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163930. }
  163931. /* Forward DCT */
  163932. jinit_forward_dct(cinfo);
  163933. /* Entropy encoding: either Huffman or arithmetic coding. */
  163934. if (cinfo->arith_code) {
  163935. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163936. } else {
  163937. if (cinfo->progressive_mode) {
  163938. #ifdef C_PROGRESSIVE_SUPPORTED
  163939. jinit_phuff_encoder(cinfo);
  163940. #else
  163941. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163942. #endif
  163943. } else
  163944. jinit_huff_encoder(cinfo);
  163945. }
  163946. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163947. jinit_c_coef_controller(cinfo,
  163948. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163949. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163950. jinit_marker_writer(cinfo);
  163951. /* We can now tell the memory manager to allocate virtual arrays. */
  163952. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163953. /* Write the datastream header (SOI) immediately.
  163954. * Frame and scan headers are postponed till later.
  163955. * This lets application insert special markers after the SOI.
  163956. */
  163957. (*cinfo->marker->write_file_header) (cinfo);
  163958. }
  163959. /*** End of inlined file: jcinit.c ***/
  163960. /*** Start of inlined file: jcmainct.c ***/
  163961. #define JPEG_INTERNALS
  163962. /* Note: currently, there is no operating mode in which a full-image buffer
  163963. * is needed at this step. If there were, that mode could not be used with
  163964. * "raw data" input, since this module is bypassed in that case. However,
  163965. * we've left the code here for possible use in special applications.
  163966. */
  163967. #undef FULL_MAIN_BUFFER_SUPPORTED
  163968. /* Private buffer controller object */
  163969. typedef struct {
  163970. struct jpeg_c_main_controller pub; /* public fields */
  163971. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163972. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163973. boolean suspended; /* remember if we suspended output */
  163974. J_BUF_MODE pass_mode; /* current operating mode */
  163975. /* If using just a strip buffer, this points to the entire set of buffers
  163976. * (we allocate one for each component). In the full-image case, this
  163977. * points to the currently accessible strips of the virtual arrays.
  163978. */
  163979. JSAMPARRAY buffer[MAX_COMPONENTS];
  163980. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163981. /* If using full-image storage, this array holds pointers to virtual-array
  163982. * control blocks for each component. Unused if not full-image storage.
  163983. */
  163984. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163985. #endif
  163986. } my_main_controller;
  163987. typedef my_main_controller * my_main_ptr;
  163988. /* Forward declarations */
  163989. METHODDEF(void) process_data_simple_main
  163990. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163991. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163992. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163993. METHODDEF(void) process_data_buffer_main
  163994. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163995. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163996. #endif
  163997. /*
  163998. * Initialize for a processing pass.
  163999. */
  164000. METHODDEF(void)
  164001. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  164002. {
  164003. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164004. /* Do nothing in raw-data mode. */
  164005. if (cinfo->raw_data_in)
  164006. return;
  164007. main_->cur_iMCU_row = 0; /* initialize counters */
  164008. main_->rowgroup_ctr = 0;
  164009. main_->suspended = FALSE;
  164010. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  164011. switch (pass_mode) {
  164012. case JBUF_PASS_THRU:
  164013. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164014. if (main_->whole_image[0] != NULL)
  164015. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164016. #endif
  164017. main_->pub.process_data = process_data_simple_main;
  164018. break;
  164019. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164020. case JBUF_SAVE_SOURCE:
  164021. case JBUF_CRANK_DEST:
  164022. case JBUF_SAVE_AND_PASS:
  164023. if (main_->whole_image[0] == NULL)
  164024. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164025. main_->pub.process_data = process_data_buffer_main;
  164026. break;
  164027. #endif
  164028. default:
  164029. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164030. break;
  164031. }
  164032. }
  164033. /*
  164034. * Process some data.
  164035. * This routine handles the simple pass-through mode,
  164036. * where we have only a strip buffer.
  164037. */
  164038. METHODDEF(void)
  164039. process_data_simple_main (j_compress_ptr cinfo,
  164040. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164041. JDIMENSION in_rows_avail)
  164042. {
  164043. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164044. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164045. /* Read input data if we haven't filled the main buffer yet */
  164046. if (main_->rowgroup_ctr < DCTSIZE)
  164047. (*cinfo->prep->pre_process_data) (cinfo,
  164048. input_buf, in_row_ctr, in_rows_avail,
  164049. main_->buffer, &main_->rowgroup_ctr,
  164050. (JDIMENSION) DCTSIZE);
  164051. /* If we don't have a full iMCU row buffered, return to application for
  164052. * more data. Note that preprocessor will always pad to fill the iMCU row
  164053. * at the bottom of the image.
  164054. */
  164055. if (main_->rowgroup_ctr != DCTSIZE)
  164056. return;
  164057. /* Send the completed row to the compressor */
  164058. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  164059. /* If compressor did not consume the whole row, then we must need to
  164060. * suspend processing and return to the application. In this situation
  164061. * we pretend we didn't yet consume the last input row; otherwise, if
  164062. * it happened to be the last row of the image, the application would
  164063. * think we were done.
  164064. */
  164065. if (! main_->suspended) {
  164066. (*in_row_ctr)--;
  164067. main_->suspended = TRUE;
  164068. }
  164069. return;
  164070. }
  164071. /* We did finish the row. Undo our little suspension hack if a previous
  164072. * call suspended; then mark the main buffer empty.
  164073. */
  164074. if (main_->suspended) {
  164075. (*in_row_ctr)++;
  164076. main_->suspended = FALSE;
  164077. }
  164078. main_->rowgroup_ctr = 0;
  164079. main_->cur_iMCU_row++;
  164080. }
  164081. }
  164082. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164083. /*
  164084. * Process some data.
  164085. * This routine handles all of the modes that use a full-size buffer.
  164086. */
  164087. METHODDEF(void)
  164088. process_data_buffer_main (j_compress_ptr cinfo,
  164089. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164090. JDIMENSION in_rows_avail)
  164091. {
  164092. my_main_ptr main = (my_main_ptr) cinfo->main;
  164093. int ci;
  164094. jpeg_component_info *compptr;
  164095. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164096. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164097. /* Realign the virtual buffers if at the start of an iMCU row. */
  164098. if (main->rowgroup_ctr == 0) {
  164099. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164100. ci++, compptr++) {
  164101. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164102. ((j_common_ptr) cinfo, main->whole_image[ci],
  164103. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164104. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164105. }
  164106. /* In a read pass, pretend we just read some source data. */
  164107. if (! writing) {
  164108. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164109. main->rowgroup_ctr = DCTSIZE;
  164110. }
  164111. }
  164112. /* If a write pass, read input data until the current iMCU row is full. */
  164113. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164114. if (writing) {
  164115. (*cinfo->prep->pre_process_data) (cinfo,
  164116. input_buf, in_row_ctr, in_rows_avail,
  164117. main->buffer, &main->rowgroup_ctr,
  164118. (JDIMENSION) DCTSIZE);
  164119. /* Return to application if we need more data to fill the iMCU row. */
  164120. if (main->rowgroup_ctr < DCTSIZE)
  164121. return;
  164122. }
  164123. /* Emit data, unless this is a sink-only pass. */
  164124. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164125. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164126. /* If compressor did not consume the whole row, then we must need to
  164127. * suspend processing and return to the application. In this situation
  164128. * we pretend we didn't yet consume the last input row; otherwise, if
  164129. * it happened to be the last row of the image, the application would
  164130. * think we were done.
  164131. */
  164132. if (! main->suspended) {
  164133. (*in_row_ctr)--;
  164134. main->suspended = TRUE;
  164135. }
  164136. return;
  164137. }
  164138. /* We did finish the row. Undo our little suspension hack if a previous
  164139. * call suspended; then mark the main buffer empty.
  164140. */
  164141. if (main->suspended) {
  164142. (*in_row_ctr)++;
  164143. main->suspended = FALSE;
  164144. }
  164145. }
  164146. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164147. main->rowgroup_ctr = 0;
  164148. main->cur_iMCU_row++;
  164149. }
  164150. }
  164151. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164152. /*
  164153. * Initialize main buffer controller.
  164154. */
  164155. GLOBAL(void)
  164156. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164157. {
  164158. my_main_ptr main_;
  164159. int ci;
  164160. jpeg_component_info *compptr;
  164161. main_ = (my_main_ptr)
  164162. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164163. SIZEOF(my_main_controller));
  164164. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164165. main_->pub.start_pass = start_pass_main;
  164166. /* We don't need to create a buffer in raw-data mode. */
  164167. if (cinfo->raw_data_in)
  164168. return;
  164169. /* Create the buffer. It holds downsampled data, so each component
  164170. * may be of a different size.
  164171. */
  164172. if (need_full_buffer) {
  164173. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164174. /* Allocate a full-image virtual array for each component */
  164175. /* Note we pad the bottom to a multiple of the iMCU height */
  164176. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164177. ci++, compptr++) {
  164178. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164179. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164180. compptr->width_in_blocks * DCTSIZE,
  164181. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164182. (long) compptr->v_samp_factor) * DCTSIZE,
  164183. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164184. }
  164185. #else
  164186. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164187. #endif
  164188. } else {
  164189. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164190. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164191. #endif
  164192. /* Allocate a strip buffer for each component */
  164193. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164194. ci++, compptr++) {
  164195. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164196. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164197. compptr->width_in_blocks * DCTSIZE,
  164198. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164199. }
  164200. }
  164201. }
  164202. /*** End of inlined file: jcmainct.c ***/
  164203. /*** Start of inlined file: jcmarker.c ***/
  164204. #define JPEG_INTERNALS
  164205. /* Private state */
  164206. typedef struct {
  164207. struct jpeg_marker_writer pub; /* public fields */
  164208. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164209. } my_marker_writer;
  164210. typedef my_marker_writer * my_marker_ptr;
  164211. /*
  164212. * Basic output routines.
  164213. *
  164214. * Note that we do not support suspension while writing a marker.
  164215. * Therefore, an application using suspension must ensure that there is
  164216. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164217. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164218. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164219. * modes are not supported at all with suspension, so those two are the only
  164220. * points where markers will be written.
  164221. */
  164222. LOCAL(void)
  164223. emit_byte (j_compress_ptr cinfo, int val)
  164224. /* Emit a byte */
  164225. {
  164226. struct jpeg_destination_mgr * dest = cinfo->dest;
  164227. *(dest->next_output_byte)++ = (JOCTET) val;
  164228. if (--dest->free_in_buffer == 0) {
  164229. if (! (*dest->empty_output_buffer) (cinfo))
  164230. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164231. }
  164232. }
  164233. LOCAL(void)
  164234. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164235. /* Emit a marker code */
  164236. {
  164237. emit_byte(cinfo, 0xFF);
  164238. emit_byte(cinfo, (int) mark);
  164239. }
  164240. LOCAL(void)
  164241. emit_2bytes (j_compress_ptr cinfo, int value)
  164242. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164243. {
  164244. emit_byte(cinfo, (value >> 8) & 0xFF);
  164245. emit_byte(cinfo, value & 0xFF);
  164246. }
  164247. /*
  164248. * Routines to write specific marker types.
  164249. */
  164250. LOCAL(int)
  164251. emit_dqt (j_compress_ptr cinfo, int index)
  164252. /* Emit a DQT marker */
  164253. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164254. {
  164255. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164256. int prec;
  164257. int i;
  164258. if (qtbl == NULL)
  164259. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164260. prec = 0;
  164261. for (i = 0; i < DCTSIZE2; i++) {
  164262. if (qtbl->quantval[i] > 255)
  164263. prec = 1;
  164264. }
  164265. if (! qtbl->sent_table) {
  164266. emit_marker(cinfo, M_DQT);
  164267. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164268. emit_byte(cinfo, index + (prec<<4));
  164269. for (i = 0; i < DCTSIZE2; i++) {
  164270. /* The table entries must be emitted in zigzag order. */
  164271. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164272. if (prec)
  164273. emit_byte(cinfo, (int) (qval >> 8));
  164274. emit_byte(cinfo, (int) (qval & 0xFF));
  164275. }
  164276. qtbl->sent_table = TRUE;
  164277. }
  164278. return prec;
  164279. }
  164280. LOCAL(void)
  164281. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164282. /* Emit a DHT marker */
  164283. {
  164284. JHUFF_TBL * htbl;
  164285. int length, i;
  164286. if (is_ac) {
  164287. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164288. index += 0x10; /* output index has AC bit set */
  164289. } else {
  164290. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164291. }
  164292. if (htbl == NULL)
  164293. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164294. if (! htbl->sent_table) {
  164295. emit_marker(cinfo, M_DHT);
  164296. length = 0;
  164297. for (i = 1; i <= 16; i++)
  164298. length += htbl->bits[i];
  164299. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164300. emit_byte(cinfo, index);
  164301. for (i = 1; i <= 16; i++)
  164302. emit_byte(cinfo, htbl->bits[i]);
  164303. for (i = 0; i < length; i++)
  164304. emit_byte(cinfo, htbl->huffval[i]);
  164305. htbl->sent_table = TRUE;
  164306. }
  164307. }
  164308. LOCAL(void)
  164309. emit_dac (j_compress_ptr)
  164310. /* Emit a DAC marker */
  164311. /* Since the useful info is so small, we want to emit all the tables in */
  164312. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164313. {
  164314. #ifdef C_ARITH_CODING_SUPPORTED
  164315. char dc_in_use[NUM_ARITH_TBLS];
  164316. char ac_in_use[NUM_ARITH_TBLS];
  164317. int length, i;
  164318. jpeg_component_info *compptr;
  164319. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164320. dc_in_use[i] = ac_in_use[i] = 0;
  164321. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164322. compptr = cinfo->cur_comp_info[i];
  164323. dc_in_use[compptr->dc_tbl_no] = 1;
  164324. ac_in_use[compptr->ac_tbl_no] = 1;
  164325. }
  164326. length = 0;
  164327. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164328. length += dc_in_use[i] + ac_in_use[i];
  164329. emit_marker(cinfo, M_DAC);
  164330. emit_2bytes(cinfo, length*2 + 2);
  164331. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164332. if (dc_in_use[i]) {
  164333. emit_byte(cinfo, i);
  164334. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164335. }
  164336. if (ac_in_use[i]) {
  164337. emit_byte(cinfo, i + 0x10);
  164338. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164339. }
  164340. }
  164341. #endif /* C_ARITH_CODING_SUPPORTED */
  164342. }
  164343. LOCAL(void)
  164344. emit_dri (j_compress_ptr cinfo)
  164345. /* Emit a DRI marker */
  164346. {
  164347. emit_marker(cinfo, M_DRI);
  164348. emit_2bytes(cinfo, 4); /* fixed length */
  164349. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164350. }
  164351. LOCAL(void)
  164352. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164353. /* Emit a SOF marker */
  164354. {
  164355. int ci;
  164356. jpeg_component_info *compptr;
  164357. emit_marker(cinfo, code);
  164358. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164359. /* Make sure image isn't bigger than SOF field can handle */
  164360. if ((long) cinfo->image_height > 65535L ||
  164361. (long) cinfo->image_width > 65535L)
  164362. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164363. emit_byte(cinfo, cinfo->data_precision);
  164364. emit_2bytes(cinfo, (int) cinfo->image_height);
  164365. emit_2bytes(cinfo, (int) cinfo->image_width);
  164366. emit_byte(cinfo, cinfo->num_components);
  164367. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164368. ci++, compptr++) {
  164369. emit_byte(cinfo, compptr->component_id);
  164370. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164371. emit_byte(cinfo, compptr->quant_tbl_no);
  164372. }
  164373. }
  164374. LOCAL(void)
  164375. emit_sos (j_compress_ptr cinfo)
  164376. /* Emit a SOS marker */
  164377. {
  164378. int i, td, ta;
  164379. jpeg_component_info *compptr;
  164380. emit_marker(cinfo, M_SOS);
  164381. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164382. emit_byte(cinfo, cinfo->comps_in_scan);
  164383. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164384. compptr = cinfo->cur_comp_info[i];
  164385. emit_byte(cinfo, compptr->component_id);
  164386. td = compptr->dc_tbl_no;
  164387. ta = compptr->ac_tbl_no;
  164388. if (cinfo->progressive_mode) {
  164389. /* Progressive mode: only DC or only AC tables are used in one scan;
  164390. * furthermore, Huffman coding of DC refinement uses no table at all.
  164391. * We emit 0 for unused field(s); this is recommended by the P&M text
  164392. * but does not seem to be specified in the standard.
  164393. */
  164394. if (cinfo->Ss == 0) {
  164395. ta = 0; /* DC scan */
  164396. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164397. td = 0; /* no DC table either */
  164398. } else {
  164399. td = 0; /* AC scan */
  164400. }
  164401. }
  164402. emit_byte(cinfo, (td << 4) + ta);
  164403. }
  164404. emit_byte(cinfo, cinfo->Ss);
  164405. emit_byte(cinfo, cinfo->Se);
  164406. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164407. }
  164408. LOCAL(void)
  164409. emit_jfif_app0 (j_compress_ptr cinfo)
  164410. /* Emit a JFIF-compliant APP0 marker */
  164411. {
  164412. /*
  164413. * Length of APP0 block (2 bytes)
  164414. * Block ID (4 bytes - ASCII "JFIF")
  164415. * Zero byte (1 byte to terminate the ID string)
  164416. * Version Major, Minor (2 bytes - major first)
  164417. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164418. * Xdpu (2 bytes - dots per unit horizontal)
  164419. * Ydpu (2 bytes - dots per unit vertical)
  164420. * Thumbnail X size (1 byte)
  164421. * Thumbnail Y size (1 byte)
  164422. */
  164423. emit_marker(cinfo, M_APP0);
  164424. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164425. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164426. emit_byte(cinfo, 0x46);
  164427. emit_byte(cinfo, 0x49);
  164428. emit_byte(cinfo, 0x46);
  164429. emit_byte(cinfo, 0);
  164430. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164431. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164432. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164433. emit_2bytes(cinfo, (int) cinfo->X_density);
  164434. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164435. emit_byte(cinfo, 0); /* No thumbnail image */
  164436. emit_byte(cinfo, 0);
  164437. }
  164438. LOCAL(void)
  164439. emit_adobe_app14 (j_compress_ptr cinfo)
  164440. /* Emit an Adobe APP14 marker */
  164441. {
  164442. /*
  164443. * Length of APP14 block (2 bytes)
  164444. * Block ID (5 bytes - ASCII "Adobe")
  164445. * Version Number (2 bytes - currently 100)
  164446. * Flags0 (2 bytes - currently 0)
  164447. * Flags1 (2 bytes - currently 0)
  164448. * Color transform (1 byte)
  164449. *
  164450. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164451. * now in circulation seem to use Version = 100, so that's what we write.
  164452. *
  164453. * We write the color transform byte as 1 if the JPEG color space is
  164454. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164455. * whether the encoder performed a transformation, which is pretty useless.
  164456. */
  164457. emit_marker(cinfo, M_APP14);
  164458. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164459. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164460. emit_byte(cinfo, 0x64);
  164461. emit_byte(cinfo, 0x6F);
  164462. emit_byte(cinfo, 0x62);
  164463. emit_byte(cinfo, 0x65);
  164464. emit_2bytes(cinfo, 100); /* Version */
  164465. emit_2bytes(cinfo, 0); /* Flags0 */
  164466. emit_2bytes(cinfo, 0); /* Flags1 */
  164467. switch (cinfo->jpeg_color_space) {
  164468. case JCS_YCbCr:
  164469. emit_byte(cinfo, 1); /* Color transform = 1 */
  164470. break;
  164471. case JCS_YCCK:
  164472. emit_byte(cinfo, 2); /* Color transform = 2 */
  164473. break;
  164474. default:
  164475. emit_byte(cinfo, 0); /* Color transform = 0 */
  164476. break;
  164477. }
  164478. }
  164479. /*
  164480. * These routines allow writing an arbitrary marker with parameters.
  164481. * The only intended use is to emit COM or APPn markers after calling
  164482. * write_file_header and before calling write_frame_header.
  164483. * Other uses are not guaranteed to produce desirable results.
  164484. * Counting the parameter bytes properly is the caller's responsibility.
  164485. */
  164486. METHODDEF(void)
  164487. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164488. /* Emit an arbitrary marker header */
  164489. {
  164490. if (datalen > (unsigned int) 65533) /* safety check */
  164491. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164492. emit_marker(cinfo, (JPEG_MARKER) marker);
  164493. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164494. }
  164495. METHODDEF(void)
  164496. write_marker_byte (j_compress_ptr cinfo, int val)
  164497. /* Emit one byte of marker parameters following write_marker_header */
  164498. {
  164499. emit_byte(cinfo, val);
  164500. }
  164501. /*
  164502. * Write datastream header.
  164503. * This consists of an SOI and optional APPn markers.
  164504. * We recommend use of the JFIF marker, but not the Adobe marker,
  164505. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164506. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164507. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164508. * Note that an application can write additional header markers after
  164509. * jpeg_start_compress returns.
  164510. */
  164511. METHODDEF(void)
  164512. write_file_header (j_compress_ptr cinfo)
  164513. {
  164514. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164515. emit_marker(cinfo, M_SOI); /* first the SOI */
  164516. /* SOI is defined to reset restart interval to 0 */
  164517. marker->last_restart_interval = 0;
  164518. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164519. emit_jfif_app0(cinfo);
  164520. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164521. emit_adobe_app14(cinfo);
  164522. }
  164523. /*
  164524. * Write frame header.
  164525. * This consists of DQT and SOFn markers.
  164526. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164527. * This avoids compatibility problems with incorrect implementations that
  164528. * try to error-check the quant table numbers as soon as they see the SOF.
  164529. */
  164530. METHODDEF(void)
  164531. write_frame_header (j_compress_ptr cinfo)
  164532. {
  164533. int ci, prec;
  164534. boolean is_baseline;
  164535. jpeg_component_info *compptr;
  164536. /* Emit DQT for each quantization table.
  164537. * Note that emit_dqt() suppresses any duplicate tables.
  164538. */
  164539. prec = 0;
  164540. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164541. ci++, compptr++) {
  164542. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164543. }
  164544. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164545. /* Check for a non-baseline specification.
  164546. * Note we assume that Huffman table numbers won't be changed later.
  164547. */
  164548. if (cinfo->arith_code || cinfo->progressive_mode ||
  164549. cinfo->data_precision != 8) {
  164550. is_baseline = FALSE;
  164551. } else {
  164552. is_baseline = TRUE;
  164553. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164554. ci++, compptr++) {
  164555. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164556. is_baseline = FALSE;
  164557. }
  164558. if (prec && is_baseline) {
  164559. is_baseline = FALSE;
  164560. /* If it's baseline except for quantizer size, warn the user */
  164561. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164562. }
  164563. }
  164564. /* Emit the proper SOF marker */
  164565. if (cinfo->arith_code) {
  164566. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164567. } else {
  164568. if (cinfo->progressive_mode)
  164569. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164570. else if (is_baseline)
  164571. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164572. else
  164573. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164574. }
  164575. }
  164576. /*
  164577. * Write scan header.
  164578. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164579. * Compressed data will be written following the SOS.
  164580. */
  164581. METHODDEF(void)
  164582. write_scan_header (j_compress_ptr cinfo)
  164583. {
  164584. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164585. int i;
  164586. jpeg_component_info *compptr;
  164587. if (cinfo->arith_code) {
  164588. /* Emit arith conditioning info. We may have some duplication
  164589. * if the file has multiple scans, but it's so small it's hardly
  164590. * worth worrying about.
  164591. */
  164592. emit_dac(cinfo);
  164593. } else {
  164594. /* Emit Huffman tables.
  164595. * Note that emit_dht() suppresses any duplicate tables.
  164596. */
  164597. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164598. compptr = cinfo->cur_comp_info[i];
  164599. if (cinfo->progressive_mode) {
  164600. /* Progressive mode: only DC or only AC tables are used in one scan */
  164601. if (cinfo->Ss == 0) {
  164602. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164603. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164604. } else {
  164605. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164606. }
  164607. } else {
  164608. /* Sequential mode: need both DC and AC tables */
  164609. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164610. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164611. }
  164612. }
  164613. }
  164614. /* Emit DRI if required --- note that DRI value could change for each scan.
  164615. * We avoid wasting space with unnecessary DRIs, however.
  164616. */
  164617. if (cinfo->restart_interval != marker->last_restart_interval) {
  164618. emit_dri(cinfo);
  164619. marker->last_restart_interval = cinfo->restart_interval;
  164620. }
  164621. emit_sos(cinfo);
  164622. }
  164623. /*
  164624. * Write datastream trailer.
  164625. */
  164626. METHODDEF(void)
  164627. write_file_trailer (j_compress_ptr cinfo)
  164628. {
  164629. emit_marker(cinfo, M_EOI);
  164630. }
  164631. /*
  164632. * Write an abbreviated table-specification datastream.
  164633. * This consists of SOI, DQT and DHT tables, and EOI.
  164634. * Any table that is defined and not marked sent_table = TRUE will be
  164635. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164636. */
  164637. METHODDEF(void)
  164638. write_tables_only (j_compress_ptr cinfo)
  164639. {
  164640. int i;
  164641. emit_marker(cinfo, M_SOI);
  164642. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164643. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164644. (void) emit_dqt(cinfo, i);
  164645. }
  164646. if (! cinfo->arith_code) {
  164647. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164648. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164649. emit_dht(cinfo, i, FALSE);
  164650. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164651. emit_dht(cinfo, i, TRUE);
  164652. }
  164653. }
  164654. emit_marker(cinfo, M_EOI);
  164655. }
  164656. /*
  164657. * Initialize the marker writer module.
  164658. */
  164659. GLOBAL(void)
  164660. jinit_marker_writer (j_compress_ptr cinfo)
  164661. {
  164662. my_marker_ptr marker;
  164663. /* Create the subobject */
  164664. marker = (my_marker_ptr)
  164665. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164666. SIZEOF(my_marker_writer));
  164667. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164668. /* Initialize method pointers */
  164669. marker->pub.write_file_header = write_file_header;
  164670. marker->pub.write_frame_header = write_frame_header;
  164671. marker->pub.write_scan_header = write_scan_header;
  164672. marker->pub.write_file_trailer = write_file_trailer;
  164673. marker->pub.write_tables_only = write_tables_only;
  164674. marker->pub.write_marker_header = write_marker_header;
  164675. marker->pub.write_marker_byte = write_marker_byte;
  164676. /* Initialize private state */
  164677. marker->last_restart_interval = 0;
  164678. }
  164679. /*** End of inlined file: jcmarker.c ***/
  164680. /*** Start of inlined file: jcmaster.c ***/
  164681. #define JPEG_INTERNALS
  164682. /* Private state */
  164683. typedef enum {
  164684. main_pass, /* input data, also do first output step */
  164685. huff_opt_pass, /* Huffman code optimization pass */
  164686. output_pass /* data output pass */
  164687. } c_pass_type;
  164688. typedef struct {
  164689. struct jpeg_comp_master pub; /* public fields */
  164690. c_pass_type pass_type; /* the type of the current pass */
  164691. int pass_number; /* # of passes completed */
  164692. int total_passes; /* total # of passes needed */
  164693. int scan_number; /* current index in scan_info[] */
  164694. } my_comp_master;
  164695. typedef my_comp_master * my_master_ptr;
  164696. /*
  164697. * Support routines that do various essential calculations.
  164698. */
  164699. LOCAL(void)
  164700. initial_setup (j_compress_ptr cinfo)
  164701. /* Do computations that are needed before master selection phase */
  164702. {
  164703. int ci;
  164704. jpeg_component_info *compptr;
  164705. long samplesperrow;
  164706. JDIMENSION jd_samplesperrow;
  164707. /* Sanity check on image dimensions */
  164708. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164709. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164710. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164711. /* Make sure image isn't bigger than I can handle */
  164712. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164713. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164714. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164715. /* Width of an input scanline must be representable as JDIMENSION. */
  164716. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164717. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164718. if ((long) jd_samplesperrow != samplesperrow)
  164719. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164720. /* For now, precision must match compiled-in value... */
  164721. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164722. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164723. /* Check that number of components won't exceed internal array sizes */
  164724. if (cinfo->num_components > MAX_COMPONENTS)
  164725. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164726. MAX_COMPONENTS);
  164727. /* Compute maximum sampling factors; check factor validity */
  164728. cinfo->max_h_samp_factor = 1;
  164729. cinfo->max_v_samp_factor = 1;
  164730. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164731. ci++, compptr++) {
  164732. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164733. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164734. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164735. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164736. compptr->h_samp_factor);
  164737. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164738. compptr->v_samp_factor);
  164739. }
  164740. /* Compute dimensions of components */
  164741. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164742. ci++, compptr++) {
  164743. /* Fill in the correct component_index value; don't rely on application */
  164744. compptr->component_index = ci;
  164745. /* For compression, we never do DCT scaling. */
  164746. compptr->DCT_scaled_size = DCTSIZE;
  164747. /* Size in DCT blocks */
  164748. compptr->width_in_blocks = (JDIMENSION)
  164749. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164750. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164751. compptr->height_in_blocks = (JDIMENSION)
  164752. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164753. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164754. /* Size in samples */
  164755. compptr->downsampled_width = (JDIMENSION)
  164756. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164757. (long) cinfo->max_h_samp_factor);
  164758. compptr->downsampled_height = (JDIMENSION)
  164759. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164760. (long) cinfo->max_v_samp_factor);
  164761. /* Mark component needed (this flag isn't actually used for compression) */
  164762. compptr->component_needed = TRUE;
  164763. }
  164764. /* Compute number of fully interleaved MCU rows (number of times that
  164765. * main controller will call coefficient controller).
  164766. */
  164767. cinfo->total_iMCU_rows = (JDIMENSION)
  164768. jdiv_round_up((long) cinfo->image_height,
  164769. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164770. }
  164771. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164772. LOCAL(void)
  164773. validate_script (j_compress_ptr cinfo)
  164774. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164775. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164776. */
  164777. {
  164778. const jpeg_scan_info * scanptr;
  164779. int scanno, ncomps, ci, coefi, thisi;
  164780. int Ss, Se, Ah, Al;
  164781. boolean component_sent[MAX_COMPONENTS];
  164782. #ifdef C_PROGRESSIVE_SUPPORTED
  164783. int * last_bitpos_ptr;
  164784. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164785. /* -1 until that coefficient has been seen; then last Al for it */
  164786. #endif
  164787. if (cinfo->num_scans <= 0)
  164788. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164789. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164790. * for progressive JPEG, no scan can have this.
  164791. */
  164792. scanptr = cinfo->scan_info;
  164793. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164794. #ifdef C_PROGRESSIVE_SUPPORTED
  164795. cinfo->progressive_mode = TRUE;
  164796. last_bitpos_ptr = & last_bitpos[0][0];
  164797. for (ci = 0; ci < cinfo->num_components; ci++)
  164798. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164799. *last_bitpos_ptr++ = -1;
  164800. #else
  164801. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164802. #endif
  164803. } else {
  164804. cinfo->progressive_mode = FALSE;
  164805. for (ci = 0; ci < cinfo->num_components; ci++)
  164806. component_sent[ci] = FALSE;
  164807. }
  164808. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164809. /* Validate component indexes */
  164810. ncomps = scanptr->comps_in_scan;
  164811. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164812. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164813. for (ci = 0; ci < ncomps; ci++) {
  164814. thisi = scanptr->component_index[ci];
  164815. if (thisi < 0 || thisi >= cinfo->num_components)
  164816. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164817. /* Components must appear in SOF order within each scan */
  164818. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164819. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164820. }
  164821. /* Validate progression parameters */
  164822. Ss = scanptr->Ss;
  164823. Se = scanptr->Se;
  164824. Ah = scanptr->Ah;
  164825. Al = scanptr->Al;
  164826. if (cinfo->progressive_mode) {
  164827. #ifdef C_PROGRESSIVE_SUPPORTED
  164828. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164829. * seems wrong: the upper bound ought to depend on data precision.
  164830. * Perhaps they really meant 0..N+1 for N-bit precision.
  164831. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164832. * out-of-range reconstructed DC values during the first DC scan,
  164833. * which might cause problems for some decoders.
  164834. */
  164835. #if BITS_IN_JSAMPLE == 8
  164836. #define MAX_AH_AL 10
  164837. #else
  164838. #define MAX_AH_AL 13
  164839. #endif
  164840. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164841. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164842. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164843. if (Ss == 0) {
  164844. if (Se != 0) /* DC and AC together not OK */
  164845. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164846. } else {
  164847. if (ncomps != 1) /* AC scans must be for only one component */
  164848. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164849. }
  164850. for (ci = 0; ci < ncomps; ci++) {
  164851. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164852. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164853. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164854. for (coefi = Ss; coefi <= Se; coefi++) {
  164855. if (last_bitpos_ptr[coefi] < 0) {
  164856. /* first scan of this coefficient */
  164857. if (Ah != 0)
  164858. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164859. } else {
  164860. /* not first scan */
  164861. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164862. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164863. }
  164864. last_bitpos_ptr[coefi] = Al;
  164865. }
  164866. }
  164867. #endif
  164868. } else {
  164869. /* For sequential JPEG, all progression parameters must be these: */
  164870. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164871. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164872. /* Make sure components are not sent twice */
  164873. for (ci = 0; ci < ncomps; ci++) {
  164874. thisi = scanptr->component_index[ci];
  164875. if (component_sent[thisi])
  164876. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164877. component_sent[thisi] = TRUE;
  164878. }
  164879. }
  164880. }
  164881. /* Now verify that everything got sent. */
  164882. if (cinfo->progressive_mode) {
  164883. #ifdef C_PROGRESSIVE_SUPPORTED
  164884. /* For progressive mode, we only check that at least some DC data
  164885. * got sent for each component; the spec does not require that all bits
  164886. * of all coefficients be transmitted. Would it be wiser to enforce
  164887. * transmission of all coefficient bits??
  164888. */
  164889. for (ci = 0; ci < cinfo->num_components; ci++) {
  164890. if (last_bitpos[ci][0] < 0)
  164891. ERREXIT(cinfo, JERR_MISSING_DATA);
  164892. }
  164893. #endif
  164894. } else {
  164895. for (ci = 0; ci < cinfo->num_components; ci++) {
  164896. if (! component_sent[ci])
  164897. ERREXIT(cinfo, JERR_MISSING_DATA);
  164898. }
  164899. }
  164900. }
  164901. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164902. LOCAL(void)
  164903. select_scan_parameters (j_compress_ptr cinfo)
  164904. /* Set up the scan parameters for the current scan */
  164905. {
  164906. int ci;
  164907. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164908. if (cinfo->scan_info != NULL) {
  164909. /* Prepare for current scan --- the script is already validated */
  164910. my_master_ptr master = (my_master_ptr) cinfo->master;
  164911. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164912. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164913. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164914. cinfo->cur_comp_info[ci] =
  164915. &cinfo->comp_info[scanptr->component_index[ci]];
  164916. }
  164917. cinfo->Ss = scanptr->Ss;
  164918. cinfo->Se = scanptr->Se;
  164919. cinfo->Ah = scanptr->Ah;
  164920. cinfo->Al = scanptr->Al;
  164921. }
  164922. else
  164923. #endif
  164924. {
  164925. /* Prepare for single sequential-JPEG scan containing all components */
  164926. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164927. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164928. MAX_COMPS_IN_SCAN);
  164929. cinfo->comps_in_scan = cinfo->num_components;
  164930. for (ci = 0; ci < cinfo->num_components; ci++) {
  164931. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164932. }
  164933. cinfo->Ss = 0;
  164934. cinfo->Se = DCTSIZE2-1;
  164935. cinfo->Ah = 0;
  164936. cinfo->Al = 0;
  164937. }
  164938. }
  164939. LOCAL(void)
  164940. per_scan_setup (j_compress_ptr cinfo)
  164941. /* Do computations that are needed before processing a JPEG scan */
  164942. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164943. {
  164944. int ci, mcublks, tmp;
  164945. jpeg_component_info *compptr;
  164946. if (cinfo->comps_in_scan == 1) {
  164947. /* Noninterleaved (single-component) scan */
  164948. compptr = cinfo->cur_comp_info[0];
  164949. /* Overall image size in MCUs */
  164950. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164951. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164952. /* For noninterleaved scan, always one block per MCU */
  164953. compptr->MCU_width = 1;
  164954. compptr->MCU_height = 1;
  164955. compptr->MCU_blocks = 1;
  164956. compptr->MCU_sample_width = DCTSIZE;
  164957. compptr->last_col_width = 1;
  164958. /* For noninterleaved scans, it is convenient to define last_row_height
  164959. * as the number of block rows present in the last iMCU row.
  164960. */
  164961. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164962. if (tmp == 0) tmp = compptr->v_samp_factor;
  164963. compptr->last_row_height = tmp;
  164964. /* Prepare array describing MCU composition */
  164965. cinfo->blocks_in_MCU = 1;
  164966. cinfo->MCU_membership[0] = 0;
  164967. } else {
  164968. /* Interleaved (multi-component) scan */
  164969. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164970. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164971. MAX_COMPS_IN_SCAN);
  164972. /* Overall image size in MCUs */
  164973. cinfo->MCUs_per_row = (JDIMENSION)
  164974. jdiv_round_up((long) cinfo->image_width,
  164975. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164976. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164977. jdiv_round_up((long) cinfo->image_height,
  164978. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164979. cinfo->blocks_in_MCU = 0;
  164980. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164981. compptr = cinfo->cur_comp_info[ci];
  164982. /* Sampling factors give # of blocks of component in each MCU */
  164983. compptr->MCU_width = compptr->h_samp_factor;
  164984. compptr->MCU_height = compptr->v_samp_factor;
  164985. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164986. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164987. /* Figure number of non-dummy blocks in last MCU column & row */
  164988. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164989. if (tmp == 0) tmp = compptr->MCU_width;
  164990. compptr->last_col_width = tmp;
  164991. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164992. if (tmp == 0) tmp = compptr->MCU_height;
  164993. compptr->last_row_height = tmp;
  164994. /* Prepare array describing MCU composition */
  164995. mcublks = compptr->MCU_blocks;
  164996. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164997. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164998. while (mcublks-- > 0) {
  164999. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  165000. }
  165001. }
  165002. }
  165003. /* Convert restart specified in rows to actual MCU count. */
  165004. /* Note that count must fit in 16 bits, so we provide limiting. */
  165005. if (cinfo->restart_in_rows > 0) {
  165006. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  165007. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  165008. }
  165009. }
  165010. /*
  165011. * Per-pass setup.
  165012. * This is called at the beginning of each pass. We determine which modules
  165013. * will be active during this pass and give them appropriate start_pass calls.
  165014. * We also set is_last_pass to indicate whether any more passes will be
  165015. * required.
  165016. */
  165017. METHODDEF(void)
  165018. prepare_for_pass (j_compress_ptr cinfo)
  165019. {
  165020. my_master_ptr master = (my_master_ptr) cinfo->master;
  165021. switch (master->pass_type) {
  165022. case main_pass:
  165023. /* Initial pass: will collect input data, and do either Huffman
  165024. * optimization or data output for the first scan.
  165025. */
  165026. select_scan_parameters(cinfo);
  165027. per_scan_setup(cinfo);
  165028. if (! cinfo->raw_data_in) {
  165029. (*cinfo->cconvert->start_pass) (cinfo);
  165030. (*cinfo->downsample->start_pass) (cinfo);
  165031. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  165032. }
  165033. (*cinfo->fdct->start_pass) (cinfo);
  165034. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  165035. (*cinfo->coef->start_pass) (cinfo,
  165036. (master->total_passes > 1 ?
  165037. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165038. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165039. if (cinfo->optimize_coding) {
  165040. /* No immediate data output; postpone writing frame/scan headers */
  165041. master->pub.call_pass_startup = FALSE;
  165042. } else {
  165043. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  165044. master->pub.call_pass_startup = TRUE;
  165045. }
  165046. break;
  165047. #ifdef ENTROPY_OPT_SUPPORTED
  165048. case huff_opt_pass:
  165049. /* Do Huffman optimization for a scan after the first one. */
  165050. select_scan_parameters(cinfo);
  165051. per_scan_setup(cinfo);
  165052. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  165053. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  165054. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165055. master->pub.call_pass_startup = FALSE;
  165056. break;
  165057. }
  165058. /* Special case: Huffman DC refinement scans need no Huffman table
  165059. * and therefore we can skip the optimization pass for them.
  165060. */
  165061. master->pass_type = output_pass;
  165062. master->pass_number++;
  165063. /*FALLTHROUGH*/
  165064. #endif
  165065. case output_pass:
  165066. /* Do a data-output pass. */
  165067. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165068. if (! cinfo->optimize_coding) {
  165069. select_scan_parameters(cinfo);
  165070. per_scan_setup(cinfo);
  165071. }
  165072. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165073. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165074. /* We emit frame/scan headers now */
  165075. if (master->scan_number == 0)
  165076. (*cinfo->marker->write_frame_header) (cinfo);
  165077. (*cinfo->marker->write_scan_header) (cinfo);
  165078. master->pub.call_pass_startup = FALSE;
  165079. break;
  165080. default:
  165081. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165082. }
  165083. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165084. /* Set up progress monitor's pass info if present */
  165085. if (cinfo->progress != NULL) {
  165086. cinfo->progress->completed_passes = master->pass_number;
  165087. cinfo->progress->total_passes = master->total_passes;
  165088. }
  165089. }
  165090. /*
  165091. * Special start-of-pass hook.
  165092. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165093. * In single-pass processing, we need this hook because we don't want to
  165094. * write frame/scan headers during jpeg_start_compress; we want to let the
  165095. * application write COM markers etc. between jpeg_start_compress and the
  165096. * jpeg_write_scanlines loop.
  165097. * In multi-pass processing, this routine is not used.
  165098. */
  165099. METHODDEF(void)
  165100. pass_startup (j_compress_ptr cinfo)
  165101. {
  165102. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165103. (*cinfo->marker->write_frame_header) (cinfo);
  165104. (*cinfo->marker->write_scan_header) (cinfo);
  165105. }
  165106. /*
  165107. * Finish up at end of pass.
  165108. */
  165109. METHODDEF(void)
  165110. finish_pass_master (j_compress_ptr cinfo)
  165111. {
  165112. my_master_ptr master = (my_master_ptr) cinfo->master;
  165113. /* The entropy coder always needs an end-of-pass call,
  165114. * either to analyze statistics or to flush its output buffer.
  165115. */
  165116. (*cinfo->entropy->finish_pass) (cinfo);
  165117. /* Update state for next pass */
  165118. switch (master->pass_type) {
  165119. case main_pass:
  165120. /* next pass is either output of scan 0 (after optimization)
  165121. * or output of scan 1 (if no optimization).
  165122. */
  165123. master->pass_type = output_pass;
  165124. if (! cinfo->optimize_coding)
  165125. master->scan_number++;
  165126. break;
  165127. case huff_opt_pass:
  165128. /* next pass is always output of current scan */
  165129. master->pass_type = output_pass;
  165130. break;
  165131. case output_pass:
  165132. /* next pass is either optimization or output of next scan */
  165133. if (cinfo->optimize_coding)
  165134. master->pass_type = huff_opt_pass;
  165135. master->scan_number++;
  165136. break;
  165137. }
  165138. master->pass_number++;
  165139. }
  165140. /*
  165141. * Initialize master compression control.
  165142. */
  165143. GLOBAL(void)
  165144. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165145. {
  165146. my_master_ptr master;
  165147. master = (my_master_ptr)
  165148. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165149. SIZEOF(my_comp_master));
  165150. cinfo->master = (struct jpeg_comp_master *) master;
  165151. master->pub.prepare_for_pass = prepare_for_pass;
  165152. master->pub.pass_startup = pass_startup;
  165153. master->pub.finish_pass = finish_pass_master;
  165154. master->pub.is_last_pass = FALSE;
  165155. /* Validate parameters, determine derived values */
  165156. initial_setup(cinfo);
  165157. if (cinfo->scan_info != NULL) {
  165158. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165159. validate_script(cinfo);
  165160. #else
  165161. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165162. #endif
  165163. } else {
  165164. cinfo->progressive_mode = FALSE;
  165165. cinfo->num_scans = 1;
  165166. }
  165167. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165168. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165169. /* Initialize my private state */
  165170. if (transcode_only) {
  165171. /* no main pass in transcoding */
  165172. if (cinfo->optimize_coding)
  165173. master->pass_type = huff_opt_pass;
  165174. else
  165175. master->pass_type = output_pass;
  165176. } else {
  165177. /* for normal compression, first pass is always this type: */
  165178. master->pass_type = main_pass;
  165179. }
  165180. master->scan_number = 0;
  165181. master->pass_number = 0;
  165182. if (cinfo->optimize_coding)
  165183. master->total_passes = cinfo->num_scans * 2;
  165184. else
  165185. master->total_passes = cinfo->num_scans;
  165186. }
  165187. /*** End of inlined file: jcmaster.c ***/
  165188. /*** Start of inlined file: jcomapi.c ***/
  165189. #define JPEG_INTERNALS
  165190. /*
  165191. * Abort processing of a JPEG compression or decompression operation,
  165192. * but don't destroy the object itself.
  165193. *
  165194. * For this, we merely clean up all the nonpermanent memory pools.
  165195. * Note that temp files (virtual arrays) are not allowed to belong to
  165196. * the permanent pool, so we will be able to close all temp files here.
  165197. * Closing a data source or destination, if necessary, is the application's
  165198. * responsibility.
  165199. */
  165200. GLOBAL(void)
  165201. jpeg_abort (j_common_ptr cinfo)
  165202. {
  165203. int pool;
  165204. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165205. if (cinfo->mem == NULL)
  165206. return;
  165207. /* Releasing pools in reverse order might help avoid fragmentation
  165208. * with some (brain-damaged) malloc libraries.
  165209. */
  165210. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165211. (*cinfo->mem->free_pool) (cinfo, pool);
  165212. }
  165213. /* Reset overall state for possible reuse of object */
  165214. if (cinfo->is_decompressor) {
  165215. cinfo->global_state = DSTATE_START;
  165216. /* Try to keep application from accessing now-deleted marker list.
  165217. * A bit kludgy to do it here, but this is the most central place.
  165218. */
  165219. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165220. } else {
  165221. cinfo->global_state = CSTATE_START;
  165222. }
  165223. }
  165224. /*
  165225. * Destruction of a JPEG object.
  165226. *
  165227. * Everything gets deallocated except the master jpeg_compress_struct itself
  165228. * and the error manager struct. Both of these are supplied by the application
  165229. * and must be freed, if necessary, by the application. (Often they are on
  165230. * the stack and so don't need to be freed anyway.)
  165231. * Closing a data source or destination, if necessary, is the application's
  165232. * responsibility.
  165233. */
  165234. GLOBAL(void)
  165235. jpeg_destroy (j_common_ptr cinfo)
  165236. {
  165237. /* We need only tell the memory manager to release everything. */
  165238. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165239. if (cinfo->mem != NULL)
  165240. (*cinfo->mem->self_destruct) (cinfo);
  165241. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165242. cinfo->global_state = 0; /* mark it destroyed */
  165243. }
  165244. /*
  165245. * Convenience routines for allocating quantization and Huffman tables.
  165246. * (Would jutils.c be a more reasonable place to put these?)
  165247. */
  165248. GLOBAL(JQUANT_TBL *)
  165249. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165250. {
  165251. JQUANT_TBL *tbl;
  165252. tbl = (JQUANT_TBL *)
  165253. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165254. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165255. return tbl;
  165256. }
  165257. GLOBAL(JHUFF_TBL *)
  165258. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165259. {
  165260. JHUFF_TBL *tbl;
  165261. tbl = (JHUFF_TBL *)
  165262. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165263. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165264. return tbl;
  165265. }
  165266. /*** End of inlined file: jcomapi.c ***/
  165267. /*** Start of inlined file: jcparam.c ***/
  165268. #define JPEG_INTERNALS
  165269. /*
  165270. * Quantization table setup routines
  165271. */
  165272. GLOBAL(void)
  165273. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165274. const unsigned int *basic_table,
  165275. int scale_factor, boolean force_baseline)
  165276. /* Define a quantization table equal to the basic_table times
  165277. * a scale factor (given as a percentage).
  165278. * If force_baseline is TRUE, the computed quantization table entries
  165279. * are limited to 1..255 for JPEG baseline compatibility.
  165280. */
  165281. {
  165282. JQUANT_TBL ** qtblptr;
  165283. int i;
  165284. long temp;
  165285. /* Safety check to ensure start_compress not called yet. */
  165286. if (cinfo->global_state != CSTATE_START)
  165287. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165288. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165289. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165290. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165291. if (*qtblptr == NULL)
  165292. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165293. for (i = 0; i < DCTSIZE2; i++) {
  165294. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165295. /* limit the values to the valid range */
  165296. if (temp <= 0L) temp = 1L;
  165297. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165298. if (force_baseline && temp > 255L)
  165299. temp = 255L; /* limit to baseline range if requested */
  165300. (*qtblptr)->quantval[i] = (UINT16) temp;
  165301. }
  165302. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165303. (*qtblptr)->sent_table = FALSE;
  165304. }
  165305. GLOBAL(void)
  165306. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165307. boolean force_baseline)
  165308. /* Set or change the 'quality' (quantization) setting, using default tables
  165309. * and a straight percentage-scaling quality scale. In most cases it's better
  165310. * to use jpeg_set_quality (below); this entry point is provided for
  165311. * applications that insist on a linear percentage scaling.
  165312. */
  165313. {
  165314. /* These are the sample quantization tables given in JPEG spec section K.1.
  165315. * The spec says that the values given produce "good" quality, and
  165316. * when divided by 2, "very good" quality.
  165317. */
  165318. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165319. 16, 11, 10, 16, 24, 40, 51, 61,
  165320. 12, 12, 14, 19, 26, 58, 60, 55,
  165321. 14, 13, 16, 24, 40, 57, 69, 56,
  165322. 14, 17, 22, 29, 51, 87, 80, 62,
  165323. 18, 22, 37, 56, 68, 109, 103, 77,
  165324. 24, 35, 55, 64, 81, 104, 113, 92,
  165325. 49, 64, 78, 87, 103, 121, 120, 101,
  165326. 72, 92, 95, 98, 112, 100, 103, 99
  165327. };
  165328. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165329. 17, 18, 24, 47, 99, 99, 99, 99,
  165330. 18, 21, 26, 66, 99, 99, 99, 99,
  165331. 24, 26, 56, 99, 99, 99, 99, 99,
  165332. 47, 66, 99, 99, 99, 99, 99, 99,
  165333. 99, 99, 99, 99, 99, 99, 99, 99,
  165334. 99, 99, 99, 99, 99, 99, 99, 99,
  165335. 99, 99, 99, 99, 99, 99, 99, 99,
  165336. 99, 99, 99, 99, 99, 99, 99, 99
  165337. };
  165338. /* Set up two quantization tables using the specified scaling */
  165339. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165340. scale_factor, force_baseline);
  165341. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165342. scale_factor, force_baseline);
  165343. }
  165344. GLOBAL(int)
  165345. jpeg_quality_scaling (int quality)
  165346. /* Convert a user-specified quality rating to a percentage scaling factor
  165347. * for an underlying quantization table, using our recommended scaling curve.
  165348. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165349. */
  165350. {
  165351. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165352. if (quality <= 0) quality = 1;
  165353. if (quality > 100) quality = 100;
  165354. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165355. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165356. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165357. * to make all the table entries 1 (hence, minimum quantization loss).
  165358. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165359. */
  165360. if (quality < 50)
  165361. quality = 5000 / quality;
  165362. else
  165363. quality = 200 - quality*2;
  165364. return quality;
  165365. }
  165366. GLOBAL(void)
  165367. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165368. /* Set or change the 'quality' (quantization) setting, using default tables.
  165369. * This is the standard quality-adjusting entry point for typical user
  165370. * interfaces; only those who want detailed control over quantization tables
  165371. * would use the preceding three routines directly.
  165372. */
  165373. {
  165374. /* Convert user 0-100 rating to percentage scaling */
  165375. quality = jpeg_quality_scaling(quality);
  165376. /* Set up standard quality tables */
  165377. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165378. }
  165379. /*
  165380. * Huffman table setup routines
  165381. */
  165382. LOCAL(void)
  165383. add_huff_table (j_compress_ptr cinfo,
  165384. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165385. /* Define a Huffman table */
  165386. {
  165387. int nsymbols, len;
  165388. if (*htblptr == NULL)
  165389. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165390. /* Copy the number-of-symbols-of-each-code-length counts */
  165391. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165392. /* Validate the counts. We do this here mainly so we can copy the right
  165393. * number of symbols from the val[] array, without risking marching off
  165394. * the end of memory. jchuff.c will do a more thorough test later.
  165395. */
  165396. nsymbols = 0;
  165397. for (len = 1; len <= 16; len++)
  165398. nsymbols += bits[len];
  165399. if (nsymbols < 1 || nsymbols > 256)
  165400. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165401. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165402. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165403. (*htblptr)->sent_table = FALSE;
  165404. }
  165405. LOCAL(void)
  165406. std_huff_tables (j_compress_ptr cinfo)
  165407. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165408. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165409. {
  165410. static const UINT8 bits_dc_luminance[17] =
  165411. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165412. static const UINT8 val_dc_luminance[] =
  165413. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165414. static const UINT8 bits_dc_chrominance[17] =
  165415. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165416. static const UINT8 val_dc_chrominance[] =
  165417. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165418. static const UINT8 bits_ac_luminance[17] =
  165419. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165420. static const UINT8 val_ac_luminance[] =
  165421. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165422. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165423. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165424. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165425. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165426. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165427. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165428. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165429. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165430. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165431. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165432. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165433. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165434. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165435. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165436. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165437. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165438. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165439. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165440. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165441. 0xf9, 0xfa };
  165442. static const UINT8 bits_ac_chrominance[17] =
  165443. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165444. static const UINT8 val_ac_chrominance[] =
  165445. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165446. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165447. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165448. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165449. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165450. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165451. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165452. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165453. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165454. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165455. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165456. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165457. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165458. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165459. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165460. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165461. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165462. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165463. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165464. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165465. 0xf9, 0xfa };
  165466. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165467. bits_dc_luminance, val_dc_luminance);
  165468. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165469. bits_ac_luminance, val_ac_luminance);
  165470. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165471. bits_dc_chrominance, val_dc_chrominance);
  165472. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165473. bits_ac_chrominance, val_ac_chrominance);
  165474. }
  165475. /*
  165476. * Default parameter setup for compression.
  165477. *
  165478. * Applications that don't choose to use this routine must do their
  165479. * own setup of all these parameters. Alternately, you can call this
  165480. * to establish defaults and then alter parameters selectively. This
  165481. * is the recommended approach since, if we add any new parameters,
  165482. * your code will still work (they'll be set to reasonable defaults).
  165483. */
  165484. GLOBAL(void)
  165485. jpeg_set_defaults (j_compress_ptr cinfo)
  165486. {
  165487. int i;
  165488. /* Safety check to ensure start_compress not called yet. */
  165489. if (cinfo->global_state != CSTATE_START)
  165490. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165491. /* Allocate comp_info array large enough for maximum component count.
  165492. * Array is made permanent in case application wants to compress
  165493. * multiple images at same param settings.
  165494. */
  165495. if (cinfo->comp_info == NULL)
  165496. cinfo->comp_info = (jpeg_component_info *)
  165497. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165498. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165499. /* Initialize everything not dependent on the color space */
  165500. cinfo->data_precision = BITS_IN_JSAMPLE;
  165501. /* Set up two quantization tables using default quality of 75 */
  165502. jpeg_set_quality(cinfo, 75, TRUE);
  165503. /* Set up two Huffman tables */
  165504. std_huff_tables(cinfo);
  165505. /* Initialize default arithmetic coding conditioning */
  165506. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165507. cinfo->arith_dc_L[i] = 0;
  165508. cinfo->arith_dc_U[i] = 1;
  165509. cinfo->arith_ac_K[i] = 5;
  165510. }
  165511. /* Default is no multiple-scan output */
  165512. cinfo->scan_info = NULL;
  165513. cinfo->num_scans = 0;
  165514. /* Expect normal source image, not raw downsampled data */
  165515. cinfo->raw_data_in = FALSE;
  165516. /* Use Huffman coding, not arithmetic coding, by default */
  165517. cinfo->arith_code = FALSE;
  165518. /* By default, don't do extra passes to optimize entropy coding */
  165519. cinfo->optimize_coding = FALSE;
  165520. /* The standard Huffman tables are only valid for 8-bit data precision.
  165521. * If the precision is higher, force optimization on so that usable
  165522. * tables will be computed. This test can be removed if default tables
  165523. * are supplied that are valid for the desired precision.
  165524. */
  165525. if (cinfo->data_precision > 8)
  165526. cinfo->optimize_coding = TRUE;
  165527. /* By default, use the simpler non-cosited sampling alignment */
  165528. cinfo->CCIR601_sampling = FALSE;
  165529. /* No input smoothing */
  165530. cinfo->smoothing_factor = 0;
  165531. /* DCT algorithm preference */
  165532. cinfo->dct_method = JDCT_DEFAULT;
  165533. /* No restart markers */
  165534. cinfo->restart_interval = 0;
  165535. cinfo->restart_in_rows = 0;
  165536. /* Fill in default JFIF marker parameters. Note that whether the marker
  165537. * will actually be written is determined by jpeg_set_colorspace.
  165538. *
  165539. * By default, the library emits JFIF version code 1.01.
  165540. * An application that wants to emit JFIF 1.02 extension markers should set
  165541. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165542. * to 1.02, but there may still be some decoders in use that will complain
  165543. * about that; saying 1.01 should minimize compatibility problems.
  165544. */
  165545. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165546. cinfo->JFIF_minor_version = 1;
  165547. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165548. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165549. cinfo->Y_density = 1;
  165550. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165551. jpeg_default_colorspace(cinfo);
  165552. }
  165553. /*
  165554. * Select an appropriate JPEG colorspace for in_color_space.
  165555. */
  165556. GLOBAL(void)
  165557. jpeg_default_colorspace (j_compress_ptr cinfo)
  165558. {
  165559. switch (cinfo->in_color_space) {
  165560. case JCS_GRAYSCALE:
  165561. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165562. break;
  165563. case JCS_RGB:
  165564. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165565. break;
  165566. case JCS_YCbCr:
  165567. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165568. break;
  165569. case JCS_CMYK:
  165570. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165571. break;
  165572. case JCS_YCCK:
  165573. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165574. break;
  165575. case JCS_UNKNOWN:
  165576. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165577. break;
  165578. default:
  165579. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165580. }
  165581. }
  165582. /*
  165583. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165584. */
  165585. GLOBAL(void)
  165586. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165587. {
  165588. jpeg_component_info * compptr;
  165589. int ci;
  165590. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165591. (compptr = &cinfo->comp_info[index], \
  165592. compptr->component_id = (id), \
  165593. compptr->h_samp_factor = (hsamp), \
  165594. compptr->v_samp_factor = (vsamp), \
  165595. compptr->quant_tbl_no = (quant), \
  165596. compptr->dc_tbl_no = (dctbl), \
  165597. compptr->ac_tbl_no = (actbl) )
  165598. /* Safety check to ensure start_compress not called yet. */
  165599. if (cinfo->global_state != CSTATE_START)
  165600. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165601. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165602. * tables 1 for chrominance components.
  165603. */
  165604. cinfo->jpeg_color_space = colorspace;
  165605. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165606. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165607. switch (colorspace) {
  165608. case JCS_GRAYSCALE:
  165609. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165610. cinfo->num_components = 1;
  165611. /* JFIF specifies component ID 1 */
  165612. SET_COMP(0, 1, 1,1, 0, 0,0);
  165613. break;
  165614. case JCS_RGB:
  165615. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165616. cinfo->num_components = 3;
  165617. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165618. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165619. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165620. break;
  165621. case JCS_YCbCr:
  165622. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165623. cinfo->num_components = 3;
  165624. /* JFIF specifies component IDs 1,2,3 */
  165625. /* We default to 2x2 subsamples of chrominance */
  165626. SET_COMP(0, 1, 2,2, 0, 0,0);
  165627. SET_COMP(1, 2, 1,1, 1, 1,1);
  165628. SET_COMP(2, 3, 1,1, 1, 1,1);
  165629. break;
  165630. case JCS_CMYK:
  165631. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165632. cinfo->num_components = 4;
  165633. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165634. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165635. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165636. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165637. break;
  165638. case JCS_YCCK:
  165639. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165640. cinfo->num_components = 4;
  165641. SET_COMP(0, 1, 2,2, 0, 0,0);
  165642. SET_COMP(1, 2, 1,1, 1, 1,1);
  165643. SET_COMP(2, 3, 1,1, 1, 1,1);
  165644. SET_COMP(3, 4, 2,2, 0, 0,0);
  165645. break;
  165646. case JCS_UNKNOWN:
  165647. cinfo->num_components = cinfo->input_components;
  165648. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165649. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165650. MAX_COMPONENTS);
  165651. for (ci = 0; ci < cinfo->num_components; ci++) {
  165652. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165653. }
  165654. break;
  165655. default:
  165656. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165657. }
  165658. }
  165659. #ifdef C_PROGRESSIVE_SUPPORTED
  165660. LOCAL(jpeg_scan_info *)
  165661. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165662. int Ss, int Se, int Ah, int Al)
  165663. /* Support routine: generate one scan for specified component */
  165664. {
  165665. scanptr->comps_in_scan = 1;
  165666. scanptr->component_index[0] = ci;
  165667. scanptr->Ss = Ss;
  165668. scanptr->Se = Se;
  165669. scanptr->Ah = Ah;
  165670. scanptr->Al = Al;
  165671. scanptr++;
  165672. return scanptr;
  165673. }
  165674. LOCAL(jpeg_scan_info *)
  165675. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165676. int Ss, int Se, int Ah, int Al)
  165677. /* Support routine: generate one scan for each component */
  165678. {
  165679. int ci;
  165680. for (ci = 0; ci < ncomps; ci++) {
  165681. scanptr->comps_in_scan = 1;
  165682. scanptr->component_index[0] = ci;
  165683. scanptr->Ss = Ss;
  165684. scanptr->Se = Se;
  165685. scanptr->Ah = Ah;
  165686. scanptr->Al = Al;
  165687. scanptr++;
  165688. }
  165689. return scanptr;
  165690. }
  165691. LOCAL(jpeg_scan_info *)
  165692. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165693. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165694. {
  165695. int ci;
  165696. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165697. /* Single interleaved DC scan */
  165698. scanptr->comps_in_scan = ncomps;
  165699. for (ci = 0; ci < ncomps; ci++)
  165700. scanptr->component_index[ci] = ci;
  165701. scanptr->Ss = scanptr->Se = 0;
  165702. scanptr->Ah = Ah;
  165703. scanptr->Al = Al;
  165704. scanptr++;
  165705. } else {
  165706. /* Noninterleaved DC scan for each component */
  165707. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165708. }
  165709. return scanptr;
  165710. }
  165711. /*
  165712. * Create a recommended progressive-JPEG script.
  165713. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165714. */
  165715. GLOBAL(void)
  165716. jpeg_simple_progression (j_compress_ptr cinfo)
  165717. {
  165718. int ncomps = cinfo->num_components;
  165719. int nscans;
  165720. jpeg_scan_info * scanptr;
  165721. /* Safety check to ensure start_compress not called yet. */
  165722. if (cinfo->global_state != CSTATE_START)
  165723. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165724. /* Figure space needed for script. Calculation must match code below! */
  165725. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165726. /* Custom script for YCbCr color images. */
  165727. nscans = 10;
  165728. } else {
  165729. /* All-purpose script for other color spaces. */
  165730. if (ncomps > MAX_COMPS_IN_SCAN)
  165731. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165732. else
  165733. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165734. }
  165735. /* Allocate space for script.
  165736. * We need to put it in the permanent pool in case the application performs
  165737. * multiple compressions without changing the settings. To avoid a memory
  165738. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165739. * object, we try to re-use previously allocated space, and we allocate
  165740. * enough space to handle YCbCr even if initially asked for grayscale.
  165741. */
  165742. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165743. cinfo->script_space_size = MAX(nscans, 10);
  165744. cinfo->script_space = (jpeg_scan_info *)
  165745. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165746. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165747. }
  165748. scanptr = cinfo->script_space;
  165749. cinfo->scan_info = scanptr;
  165750. cinfo->num_scans = nscans;
  165751. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165752. /* Custom script for YCbCr color images. */
  165753. /* Initial DC scan */
  165754. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165755. /* Initial AC scan: get some luma data out in a hurry */
  165756. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165757. /* Chroma data is too small to be worth expending many scans on */
  165758. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165759. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165760. /* Complete spectral selection for luma AC */
  165761. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165762. /* Refine next bit of luma AC */
  165763. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165764. /* Finish DC successive approximation */
  165765. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165766. /* Finish AC successive approximation */
  165767. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165768. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165769. /* Luma bottom bit comes last since it's usually largest scan */
  165770. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165771. } else {
  165772. /* All-purpose script for other color spaces. */
  165773. /* Successive approximation first pass */
  165774. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165775. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165776. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165777. /* Successive approximation second pass */
  165778. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165779. /* Successive approximation final pass */
  165780. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165781. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165782. }
  165783. }
  165784. #endif /* C_PROGRESSIVE_SUPPORTED */
  165785. /*** End of inlined file: jcparam.c ***/
  165786. /*** Start of inlined file: jcphuff.c ***/
  165787. #define JPEG_INTERNALS
  165788. #ifdef C_PROGRESSIVE_SUPPORTED
  165789. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165790. typedef struct {
  165791. struct jpeg_entropy_encoder pub; /* public fields */
  165792. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165793. boolean gather_statistics;
  165794. /* Bit-level coding status.
  165795. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165796. */
  165797. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165798. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165799. INT32 put_buffer; /* current bit-accumulation buffer */
  165800. int put_bits; /* # of bits now in it */
  165801. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165802. /* Coding status for DC components */
  165803. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165804. /* Coding status for AC components */
  165805. int ac_tbl_no; /* the table number of the single component */
  165806. unsigned int EOBRUN; /* run length of EOBs */
  165807. unsigned int BE; /* # of buffered correction bits before MCU */
  165808. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165809. /* packing correction bits tightly would save some space but cost time... */
  165810. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165811. int next_restart_num; /* next restart number to write (0-7) */
  165812. /* Pointers to derived tables (these workspaces have image lifespan).
  165813. * Since any one scan codes only DC or only AC, we only need one set
  165814. * of tables, not one for DC and one for AC.
  165815. */
  165816. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165817. /* Statistics tables for optimization; again, one set is enough */
  165818. long * count_ptrs[NUM_HUFF_TBLS];
  165819. } phuff_entropy_encoder;
  165820. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165821. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165822. * buffer can hold. Larger sizes may slightly improve compression, but
  165823. * 1000 is already well into the realm of overkill.
  165824. * The minimum safe size is 64 bits.
  165825. */
  165826. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165827. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165828. * We assume that int right shift is unsigned if INT32 right shift is,
  165829. * which should be safe.
  165830. */
  165831. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165832. #define ISHIFT_TEMPS int ishift_temp;
  165833. #define IRIGHT_SHIFT(x,shft) \
  165834. ((ishift_temp = (x)) < 0 ? \
  165835. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165836. (ishift_temp >> (shft)))
  165837. #else
  165838. #define ISHIFT_TEMPS
  165839. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165840. #endif
  165841. /* Forward declarations */
  165842. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165843. JBLOCKROW *MCU_data));
  165844. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165845. JBLOCKROW *MCU_data));
  165846. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165847. JBLOCKROW *MCU_data));
  165848. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165849. JBLOCKROW *MCU_data));
  165850. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165851. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165852. /*
  165853. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165854. */
  165855. METHODDEF(void)
  165856. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165857. {
  165858. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165859. boolean is_DC_band;
  165860. int ci, tbl;
  165861. jpeg_component_info * compptr;
  165862. entropy->cinfo = cinfo;
  165863. entropy->gather_statistics = gather_statistics;
  165864. is_DC_band = (cinfo->Ss == 0);
  165865. /* We assume jcmaster.c already validated the scan parameters. */
  165866. /* Select execution routines */
  165867. if (cinfo->Ah == 0) {
  165868. if (is_DC_band)
  165869. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165870. else
  165871. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165872. } else {
  165873. if (is_DC_band)
  165874. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165875. else {
  165876. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165877. /* AC refinement needs a correction bit buffer */
  165878. if (entropy->bit_buffer == NULL)
  165879. entropy->bit_buffer = (char *)
  165880. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165881. MAX_CORR_BITS * SIZEOF(char));
  165882. }
  165883. }
  165884. if (gather_statistics)
  165885. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165886. else
  165887. entropy->pub.finish_pass = finish_pass_phuff;
  165888. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165889. * for AC coefficients.
  165890. */
  165891. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165892. compptr = cinfo->cur_comp_info[ci];
  165893. /* Initialize DC predictions to 0 */
  165894. entropy->last_dc_val[ci] = 0;
  165895. /* Get table index */
  165896. if (is_DC_band) {
  165897. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165898. continue;
  165899. tbl = compptr->dc_tbl_no;
  165900. } else {
  165901. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165902. }
  165903. if (gather_statistics) {
  165904. /* Check for invalid table index */
  165905. /* (make_c_derived_tbl does this in the other path) */
  165906. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165907. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165908. /* Allocate and zero the statistics tables */
  165909. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165910. if (entropy->count_ptrs[tbl] == NULL)
  165911. entropy->count_ptrs[tbl] = (long *)
  165912. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165913. 257 * SIZEOF(long));
  165914. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165915. } else {
  165916. /* Compute derived values for Huffman table */
  165917. /* We may do this more than once for a table, but it's not expensive */
  165918. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165919. & entropy->derived_tbls[tbl]);
  165920. }
  165921. }
  165922. /* Initialize AC stuff */
  165923. entropy->EOBRUN = 0;
  165924. entropy->BE = 0;
  165925. /* Initialize bit buffer to empty */
  165926. entropy->put_buffer = 0;
  165927. entropy->put_bits = 0;
  165928. /* Initialize restart stuff */
  165929. entropy->restarts_to_go = cinfo->restart_interval;
  165930. entropy->next_restart_num = 0;
  165931. }
  165932. /* Outputting bytes to the file.
  165933. * NB: these must be called only when actually outputting,
  165934. * that is, entropy->gather_statistics == FALSE.
  165935. */
  165936. /* Emit a byte */
  165937. #define emit_byte(entropy,val) \
  165938. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165939. if (--(entropy)->free_in_buffer == 0) \
  165940. dump_buffer_p(entropy); }
  165941. LOCAL(void)
  165942. dump_buffer_p (phuff_entropy_ptr entropy)
  165943. /* Empty the output buffer; we do not support suspension in this module. */
  165944. {
  165945. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165946. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165947. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165948. /* After a successful buffer dump, must reset buffer pointers */
  165949. entropy->next_output_byte = dest->next_output_byte;
  165950. entropy->free_in_buffer = dest->free_in_buffer;
  165951. }
  165952. /* Outputting bits to the file */
  165953. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165954. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165955. * in one call, and we never retain more than 7 bits in put_buffer
  165956. * between calls, so 24 bits are sufficient.
  165957. */
  165958. INLINE
  165959. LOCAL(void)
  165960. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165961. /* Emit some bits, unless we are in gather mode */
  165962. {
  165963. /* This routine is heavily used, so it's worth coding tightly. */
  165964. register INT32 put_buffer = (INT32) code;
  165965. register int put_bits = entropy->put_bits;
  165966. /* if size is 0, caller used an invalid Huffman table entry */
  165967. if (size == 0)
  165968. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165969. if (entropy->gather_statistics)
  165970. return; /* do nothing if we're only getting stats */
  165971. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165972. put_bits += size; /* new number of bits in buffer */
  165973. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165974. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165975. while (put_bits >= 8) {
  165976. int c = (int) ((put_buffer >> 16) & 0xFF);
  165977. emit_byte(entropy, c);
  165978. if (c == 0xFF) { /* need to stuff a zero byte? */
  165979. emit_byte(entropy, 0);
  165980. }
  165981. put_buffer <<= 8;
  165982. put_bits -= 8;
  165983. }
  165984. entropy->put_buffer = put_buffer; /* update variables */
  165985. entropy->put_bits = put_bits;
  165986. }
  165987. LOCAL(void)
  165988. flush_bits_p (phuff_entropy_ptr entropy)
  165989. {
  165990. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165991. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165992. entropy->put_bits = 0;
  165993. }
  165994. /*
  165995. * Emit (or just count) a Huffman symbol.
  165996. */
  165997. INLINE
  165998. LOCAL(void)
  165999. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  166000. {
  166001. if (entropy->gather_statistics)
  166002. entropy->count_ptrs[tbl_no][symbol]++;
  166003. else {
  166004. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  166005. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  166006. }
  166007. }
  166008. /*
  166009. * Emit bits from a correction bit buffer.
  166010. */
  166011. LOCAL(void)
  166012. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  166013. unsigned int nbits)
  166014. {
  166015. if (entropy->gather_statistics)
  166016. return; /* no real work */
  166017. while (nbits > 0) {
  166018. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  166019. bufstart++;
  166020. nbits--;
  166021. }
  166022. }
  166023. /*
  166024. * Emit any pending EOBRUN symbol.
  166025. */
  166026. LOCAL(void)
  166027. emit_eobrun (phuff_entropy_ptr entropy)
  166028. {
  166029. register int temp, nbits;
  166030. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  166031. temp = entropy->EOBRUN;
  166032. nbits = 0;
  166033. while ((temp >>= 1))
  166034. nbits++;
  166035. /* safety check: shouldn't happen given limited correction-bit buffer */
  166036. if (nbits > 14)
  166037. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166038. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  166039. if (nbits)
  166040. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  166041. entropy->EOBRUN = 0;
  166042. /* Emit any buffered correction bits */
  166043. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  166044. entropy->BE = 0;
  166045. }
  166046. }
  166047. /*
  166048. * Emit a restart marker & resynchronize predictions.
  166049. */
  166050. LOCAL(void)
  166051. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  166052. {
  166053. int ci;
  166054. emit_eobrun(entropy);
  166055. if (! entropy->gather_statistics) {
  166056. flush_bits_p(entropy);
  166057. emit_byte(entropy, 0xFF);
  166058. emit_byte(entropy, JPEG_RST0 + restart_num);
  166059. }
  166060. if (entropy->cinfo->Ss == 0) {
  166061. /* Re-initialize DC predictions to 0 */
  166062. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166063. entropy->last_dc_val[ci] = 0;
  166064. } else {
  166065. /* Re-initialize all AC-related fields to 0 */
  166066. entropy->EOBRUN = 0;
  166067. entropy->BE = 0;
  166068. }
  166069. }
  166070. /*
  166071. * MCU encoding for DC initial scan (either spectral selection,
  166072. * or first pass of successive approximation).
  166073. */
  166074. METHODDEF(boolean)
  166075. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166076. {
  166077. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166078. register int temp, temp2;
  166079. register int nbits;
  166080. int blkn, ci;
  166081. int Al = cinfo->Al;
  166082. JBLOCKROW block;
  166083. jpeg_component_info * compptr;
  166084. ISHIFT_TEMPS
  166085. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166086. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166087. /* Emit restart marker if needed */
  166088. if (cinfo->restart_interval)
  166089. if (entropy->restarts_to_go == 0)
  166090. emit_restart_p(entropy, entropy->next_restart_num);
  166091. /* Encode the MCU data blocks */
  166092. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166093. block = MCU_data[blkn];
  166094. ci = cinfo->MCU_membership[blkn];
  166095. compptr = cinfo->cur_comp_info[ci];
  166096. /* Compute the DC value after the required point transform by Al.
  166097. * This is simply an arithmetic right shift.
  166098. */
  166099. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166100. /* DC differences are figured on the point-transformed values. */
  166101. temp = temp2 - entropy->last_dc_val[ci];
  166102. entropy->last_dc_val[ci] = temp2;
  166103. /* Encode the DC coefficient difference per section G.1.2.1 */
  166104. temp2 = temp;
  166105. if (temp < 0) {
  166106. temp = -temp; /* temp is abs value of input */
  166107. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166108. /* This code assumes we are on a two's complement machine */
  166109. temp2--;
  166110. }
  166111. /* Find the number of bits needed for the magnitude of the coefficient */
  166112. nbits = 0;
  166113. while (temp) {
  166114. nbits++;
  166115. temp >>= 1;
  166116. }
  166117. /* Check for out-of-range coefficient values.
  166118. * Since we're encoding a difference, the range limit is twice as much.
  166119. */
  166120. if (nbits > MAX_COEF_BITS+1)
  166121. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166122. /* Count/emit the Huffman-coded symbol for the number of bits */
  166123. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166124. /* Emit that number of bits of the value, if positive, */
  166125. /* or the complement of its magnitude, if negative. */
  166126. if (nbits) /* emit_bits rejects calls with size 0 */
  166127. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166128. }
  166129. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166130. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166131. /* Update restart-interval state too */
  166132. if (cinfo->restart_interval) {
  166133. if (entropy->restarts_to_go == 0) {
  166134. entropy->restarts_to_go = cinfo->restart_interval;
  166135. entropy->next_restart_num++;
  166136. entropy->next_restart_num &= 7;
  166137. }
  166138. entropy->restarts_to_go--;
  166139. }
  166140. return TRUE;
  166141. }
  166142. /*
  166143. * MCU encoding for AC initial scan (either spectral selection,
  166144. * or first pass of successive approximation).
  166145. */
  166146. METHODDEF(boolean)
  166147. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166148. {
  166149. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166150. register int temp, temp2;
  166151. register int nbits;
  166152. register int r, k;
  166153. int Se = cinfo->Se;
  166154. int Al = cinfo->Al;
  166155. JBLOCKROW block;
  166156. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166157. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166158. /* Emit restart marker if needed */
  166159. if (cinfo->restart_interval)
  166160. if (entropy->restarts_to_go == 0)
  166161. emit_restart_p(entropy, entropy->next_restart_num);
  166162. /* Encode the MCU data block */
  166163. block = MCU_data[0];
  166164. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166165. r = 0; /* r = run length of zeros */
  166166. for (k = cinfo->Ss; k <= Se; k++) {
  166167. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166168. r++;
  166169. continue;
  166170. }
  166171. /* We must apply the point transform by Al. For AC coefficients this
  166172. * is an integer division with rounding towards 0. To do this portably
  166173. * in C, we shift after obtaining the absolute value; so the code is
  166174. * interwoven with finding the abs value (temp) and output bits (temp2).
  166175. */
  166176. if (temp < 0) {
  166177. temp = -temp; /* temp is abs value of input */
  166178. temp >>= Al; /* apply the point transform */
  166179. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166180. temp2 = ~temp;
  166181. } else {
  166182. temp >>= Al; /* apply the point transform */
  166183. temp2 = temp;
  166184. }
  166185. /* Watch out for case that nonzero coef is zero after point transform */
  166186. if (temp == 0) {
  166187. r++;
  166188. continue;
  166189. }
  166190. /* Emit any pending EOBRUN */
  166191. if (entropy->EOBRUN > 0)
  166192. emit_eobrun(entropy);
  166193. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166194. while (r > 15) {
  166195. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166196. r -= 16;
  166197. }
  166198. /* Find the number of bits needed for the magnitude of the coefficient */
  166199. nbits = 1; /* there must be at least one 1 bit */
  166200. while ((temp >>= 1))
  166201. nbits++;
  166202. /* Check for out-of-range coefficient values */
  166203. if (nbits > MAX_COEF_BITS)
  166204. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166205. /* Count/emit Huffman symbol for run length / number of bits */
  166206. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166207. /* Emit that number of bits of the value, if positive, */
  166208. /* or the complement of its magnitude, if negative. */
  166209. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166210. r = 0; /* reset zero run length */
  166211. }
  166212. if (r > 0) { /* If there are trailing zeroes, */
  166213. entropy->EOBRUN++; /* count an EOB */
  166214. if (entropy->EOBRUN == 0x7FFF)
  166215. emit_eobrun(entropy); /* force it out to avoid overflow */
  166216. }
  166217. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166218. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166219. /* Update restart-interval state too */
  166220. if (cinfo->restart_interval) {
  166221. if (entropy->restarts_to_go == 0) {
  166222. entropy->restarts_to_go = cinfo->restart_interval;
  166223. entropy->next_restart_num++;
  166224. entropy->next_restart_num &= 7;
  166225. }
  166226. entropy->restarts_to_go--;
  166227. }
  166228. return TRUE;
  166229. }
  166230. /*
  166231. * MCU encoding for DC successive approximation refinement scan.
  166232. * Note: we assume such scans can be multi-component, although the spec
  166233. * is not very clear on the point.
  166234. */
  166235. METHODDEF(boolean)
  166236. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166237. {
  166238. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166239. register int temp;
  166240. int blkn;
  166241. int Al = cinfo->Al;
  166242. JBLOCKROW block;
  166243. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166244. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166245. /* Emit restart marker if needed */
  166246. if (cinfo->restart_interval)
  166247. if (entropy->restarts_to_go == 0)
  166248. emit_restart_p(entropy, entropy->next_restart_num);
  166249. /* Encode the MCU data blocks */
  166250. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166251. block = MCU_data[blkn];
  166252. /* We simply emit the Al'th bit of the DC coefficient value. */
  166253. temp = (*block)[0];
  166254. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166255. }
  166256. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166257. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166258. /* Update restart-interval state too */
  166259. if (cinfo->restart_interval) {
  166260. if (entropy->restarts_to_go == 0) {
  166261. entropy->restarts_to_go = cinfo->restart_interval;
  166262. entropy->next_restart_num++;
  166263. entropy->next_restart_num &= 7;
  166264. }
  166265. entropy->restarts_to_go--;
  166266. }
  166267. return TRUE;
  166268. }
  166269. /*
  166270. * MCU encoding for AC successive approximation refinement scan.
  166271. */
  166272. METHODDEF(boolean)
  166273. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166274. {
  166275. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166276. register int temp;
  166277. register int r, k;
  166278. int EOB;
  166279. char *BR_buffer;
  166280. unsigned int BR;
  166281. int Se = cinfo->Se;
  166282. int Al = cinfo->Al;
  166283. JBLOCKROW block;
  166284. int absvalues[DCTSIZE2];
  166285. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166286. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166287. /* Emit restart marker if needed */
  166288. if (cinfo->restart_interval)
  166289. if (entropy->restarts_to_go == 0)
  166290. emit_restart_p(entropy, entropy->next_restart_num);
  166291. /* Encode the MCU data block */
  166292. block = MCU_data[0];
  166293. /* It is convenient to make a pre-pass to determine the transformed
  166294. * coefficients' absolute values and the EOB position.
  166295. */
  166296. EOB = 0;
  166297. for (k = cinfo->Ss; k <= Se; k++) {
  166298. temp = (*block)[jpeg_natural_order[k]];
  166299. /* We must apply the point transform by Al. For AC coefficients this
  166300. * is an integer division with rounding towards 0. To do this portably
  166301. * in C, we shift after obtaining the absolute value.
  166302. */
  166303. if (temp < 0)
  166304. temp = -temp; /* temp is abs value of input */
  166305. temp >>= Al; /* apply the point transform */
  166306. absvalues[k] = temp; /* save abs value for main pass */
  166307. if (temp == 1)
  166308. EOB = k; /* EOB = index of last newly-nonzero coef */
  166309. }
  166310. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166311. r = 0; /* r = run length of zeros */
  166312. BR = 0; /* BR = count of buffered bits added now */
  166313. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166314. for (k = cinfo->Ss; k <= Se; k++) {
  166315. if ((temp = absvalues[k]) == 0) {
  166316. r++;
  166317. continue;
  166318. }
  166319. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166320. while (r > 15 && k <= EOB) {
  166321. /* emit any pending EOBRUN and the BE correction bits */
  166322. emit_eobrun(entropy);
  166323. /* Emit ZRL */
  166324. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166325. r -= 16;
  166326. /* Emit buffered correction bits that must be associated with ZRL */
  166327. emit_buffered_bits(entropy, BR_buffer, BR);
  166328. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166329. BR = 0;
  166330. }
  166331. /* If the coef was previously nonzero, it only needs a correction bit.
  166332. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166333. * that we also need to test r > 15. But if r > 15, we can only get here
  166334. * if k > EOB, which implies that this coefficient is not 1.
  166335. */
  166336. if (temp > 1) {
  166337. /* The correction bit is the next bit of the absolute value. */
  166338. BR_buffer[BR++] = (char) (temp & 1);
  166339. continue;
  166340. }
  166341. /* Emit any pending EOBRUN and the BE correction bits */
  166342. emit_eobrun(entropy);
  166343. /* Count/emit Huffman symbol for run length / number of bits */
  166344. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166345. /* Emit output bit for newly-nonzero coef */
  166346. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166347. emit_bits_p(entropy, (unsigned int) temp, 1);
  166348. /* Emit buffered correction bits that must be associated with this code */
  166349. emit_buffered_bits(entropy, BR_buffer, BR);
  166350. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166351. BR = 0;
  166352. r = 0; /* reset zero run length */
  166353. }
  166354. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166355. entropy->EOBRUN++; /* count an EOB */
  166356. entropy->BE += BR; /* concat my correction bits to older ones */
  166357. /* We force out the EOB if we risk either:
  166358. * 1. overflow of the EOB counter;
  166359. * 2. overflow of the correction bit buffer during the next MCU.
  166360. */
  166361. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166362. emit_eobrun(entropy);
  166363. }
  166364. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166365. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166366. /* Update restart-interval state too */
  166367. if (cinfo->restart_interval) {
  166368. if (entropy->restarts_to_go == 0) {
  166369. entropy->restarts_to_go = cinfo->restart_interval;
  166370. entropy->next_restart_num++;
  166371. entropy->next_restart_num &= 7;
  166372. }
  166373. entropy->restarts_to_go--;
  166374. }
  166375. return TRUE;
  166376. }
  166377. /*
  166378. * Finish up at the end of a Huffman-compressed progressive scan.
  166379. */
  166380. METHODDEF(void)
  166381. finish_pass_phuff (j_compress_ptr cinfo)
  166382. {
  166383. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166384. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166385. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166386. /* Flush out any buffered data */
  166387. emit_eobrun(entropy);
  166388. flush_bits_p(entropy);
  166389. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166390. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166391. }
  166392. /*
  166393. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166394. */
  166395. METHODDEF(void)
  166396. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166397. {
  166398. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166399. boolean is_DC_band;
  166400. int ci, tbl;
  166401. jpeg_component_info * compptr;
  166402. JHUFF_TBL **htblptr;
  166403. boolean did[NUM_HUFF_TBLS];
  166404. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166405. emit_eobrun(entropy);
  166406. is_DC_band = (cinfo->Ss == 0);
  166407. /* It's important not to apply jpeg_gen_optimal_table more than once
  166408. * per table, because it clobbers the input frequency counts!
  166409. */
  166410. MEMZERO(did, SIZEOF(did));
  166411. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166412. compptr = cinfo->cur_comp_info[ci];
  166413. if (is_DC_band) {
  166414. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166415. continue;
  166416. tbl = compptr->dc_tbl_no;
  166417. } else {
  166418. tbl = compptr->ac_tbl_no;
  166419. }
  166420. if (! did[tbl]) {
  166421. if (is_DC_band)
  166422. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166423. else
  166424. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166425. if (*htblptr == NULL)
  166426. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166427. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166428. did[tbl] = TRUE;
  166429. }
  166430. }
  166431. }
  166432. /*
  166433. * Module initialization routine for progressive Huffman entropy encoding.
  166434. */
  166435. GLOBAL(void)
  166436. jinit_phuff_encoder (j_compress_ptr cinfo)
  166437. {
  166438. phuff_entropy_ptr entropy;
  166439. int i;
  166440. entropy = (phuff_entropy_ptr)
  166441. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166442. SIZEOF(phuff_entropy_encoder));
  166443. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166444. entropy->pub.start_pass = start_pass_phuff;
  166445. /* Mark tables unallocated */
  166446. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166447. entropy->derived_tbls[i] = NULL;
  166448. entropy->count_ptrs[i] = NULL;
  166449. }
  166450. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166451. }
  166452. #endif /* C_PROGRESSIVE_SUPPORTED */
  166453. /*** End of inlined file: jcphuff.c ***/
  166454. /*** Start of inlined file: jcprepct.c ***/
  166455. #define JPEG_INTERNALS
  166456. /* At present, jcsample.c can request context rows only for smoothing.
  166457. * In the future, we might also need context rows for CCIR601 sampling
  166458. * or other more-complex downsampling procedures. The code to support
  166459. * context rows should be compiled only if needed.
  166460. */
  166461. #ifdef INPUT_SMOOTHING_SUPPORTED
  166462. #define CONTEXT_ROWS_SUPPORTED
  166463. #endif
  166464. /*
  166465. * For the simple (no-context-row) case, we just need to buffer one
  166466. * row group's worth of pixels for the downsampling step. At the bottom of
  166467. * the image, we pad to a full row group by replicating the last pixel row.
  166468. * The downsampler's last output row is then replicated if needed to pad
  166469. * out to a full iMCU row.
  166470. *
  166471. * When providing context rows, we must buffer three row groups' worth of
  166472. * pixels. Three row groups are physically allocated, but the row pointer
  166473. * arrays are made five row groups high, with the extra pointers above and
  166474. * below "wrapping around" to point to the last and first real row groups.
  166475. * This allows the downsampler to access the proper context rows.
  166476. * At the top and bottom of the image, we create dummy context rows by
  166477. * copying the first or last real pixel row. This copying could be avoided
  166478. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166479. * trouble on the compression side.
  166480. */
  166481. /* Private buffer controller object */
  166482. typedef struct {
  166483. struct jpeg_c_prep_controller pub; /* public fields */
  166484. /* Downsampling input buffer. This buffer holds color-converted data
  166485. * until we have enough to do a downsample step.
  166486. */
  166487. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166488. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166489. int next_buf_row; /* index of next row to store in color_buf */
  166490. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166491. int this_row_group; /* starting row index of group to process */
  166492. int next_buf_stop; /* downsample when we reach this index */
  166493. #endif
  166494. } my_prep_controller;
  166495. typedef my_prep_controller * my_prep_ptr;
  166496. /*
  166497. * Initialize for a processing pass.
  166498. */
  166499. METHODDEF(void)
  166500. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166501. {
  166502. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166503. if (pass_mode != JBUF_PASS_THRU)
  166504. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166505. /* Initialize total-height counter for detecting bottom of image */
  166506. prep->rows_to_go = cinfo->image_height;
  166507. /* Mark the conversion buffer empty */
  166508. prep->next_buf_row = 0;
  166509. #ifdef CONTEXT_ROWS_SUPPORTED
  166510. /* Preset additional state variables for context mode.
  166511. * These aren't used in non-context mode, so we needn't test which mode.
  166512. */
  166513. prep->this_row_group = 0;
  166514. /* Set next_buf_stop to stop after two row groups have been read in. */
  166515. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166516. #endif
  166517. }
  166518. /*
  166519. * Expand an image vertically from height input_rows to height output_rows,
  166520. * by duplicating the bottom row.
  166521. */
  166522. LOCAL(void)
  166523. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166524. int input_rows, int output_rows)
  166525. {
  166526. register int row;
  166527. for (row = input_rows; row < output_rows; row++) {
  166528. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166529. 1, num_cols);
  166530. }
  166531. }
  166532. /*
  166533. * Process some data in the simple no-context case.
  166534. *
  166535. * Preprocessor output data is counted in "row groups". A row group
  166536. * is defined to be v_samp_factor sample rows of each component.
  166537. * Downsampling will produce this much data from each max_v_samp_factor
  166538. * input rows.
  166539. */
  166540. METHODDEF(void)
  166541. pre_process_data (j_compress_ptr cinfo,
  166542. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166543. JDIMENSION in_rows_avail,
  166544. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166545. JDIMENSION out_row_groups_avail)
  166546. {
  166547. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166548. int numrows, ci;
  166549. JDIMENSION inrows;
  166550. jpeg_component_info * compptr;
  166551. while (*in_row_ctr < in_rows_avail &&
  166552. *out_row_group_ctr < out_row_groups_avail) {
  166553. /* Do color conversion to fill the conversion buffer. */
  166554. inrows = in_rows_avail - *in_row_ctr;
  166555. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166556. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166557. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166558. prep->color_buf,
  166559. (JDIMENSION) prep->next_buf_row,
  166560. numrows);
  166561. *in_row_ctr += numrows;
  166562. prep->next_buf_row += numrows;
  166563. prep->rows_to_go -= numrows;
  166564. /* If at bottom of image, pad to fill the conversion buffer. */
  166565. if (prep->rows_to_go == 0 &&
  166566. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166567. for (ci = 0; ci < cinfo->num_components; ci++) {
  166568. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166569. prep->next_buf_row, cinfo->max_v_samp_factor);
  166570. }
  166571. prep->next_buf_row = cinfo->max_v_samp_factor;
  166572. }
  166573. /* If we've filled the conversion buffer, empty it. */
  166574. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166575. (*cinfo->downsample->downsample) (cinfo,
  166576. prep->color_buf, (JDIMENSION) 0,
  166577. output_buf, *out_row_group_ctr);
  166578. prep->next_buf_row = 0;
  166579. (*out_row_group_ctr)++;
  166580. }
  166581. /* If at bottom of image, pad the output to a full iMCU height.
  166582. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166583. */
  166584. if (prep->rows_to_go == 0 &&
  166585. *out_row_group_ctr < out_row_groups_avail) {
  166586. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166587. ci++, compptr++) {
  166588. expand_bottom_edge(output_buf[ci],
  166589. compptr->width_in_blocks * DCTSIZE,
  166590. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166591. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166592. }
  166593. *out_row_group_ctr = out_row_groups_avail;
  166594. break; /* can exit outer loop without test */
  166595. }
  166596. }
  166597. }
  166598. #ifdef CONTEXT_ROWS_SUPPORTED
  166599. /*
  166600. * Process some data in the context case.
  166601. */
  166602. METHODDEF(void)
  166603. pre_process_context (j_compress_ptr cinfo,
  166604. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166605. JDIMENSION in_rows_avail,
  166606. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166607. JDIMENSION out_row_groups_avail)
  166608. {
  166609. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166610. int numrows, ci;
  166611. int buf_height = cinfo->max_v_samp_factor * 3;
  166612. JDIMENSION inrows;
  166613. while (*out_row_group_ctr < out_row_groups_avail) {
  166614. if (*in_row_ctr < in_rows_avail) {
  166615. /* Do color conversion to fill the conversion buffer. */
  166616. inrows = in_rows_avail - *in_row_ctr;
  166617. numrows = prep->next_buf_stop - prep->next_buf_row;
  166618. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166619. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166620. prep->color_buf,
  166621. (JDIMENSION) prep->next_buf_row,
  166622. numrows);
  166623. /* Pad at top of image, if first time through */
  166624. if (prep->rows_to_go == cinfo->image_height) {
  166625. for (ci = 0; ci < cinfo->num_components; ci++) {
  166626. int row;
  166627. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166628. jcopy_sample_rows(prep->color_buf[ci], 0,
  166629. prep->color_buf[ci], -row,
  166630. 1, cinfo->image_width);
  166631. }
  166632. }
  166633. }
  166634. *in_row_ctr += numrows;
  166635. prep->next_buf_row += numrows;
  166636. prep->rows_to_go -= numrows;
  166637. } else {
  166638. /* Return for more data, unless we are at the bottom of the image. */
  166639. if (prep->rows_to_go != 0)
  166640. break;
  166641. /* When at bottom of image, pad to fill the conversion buffer. */
  166642. if (prep->next_buf_row < prep->next_buf_stop) {
  166643. for (ci = 0; ci < cinfo->num_components; ci++) {
  166644. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166645. prep->next_buf_row, prep->next_buf_stop);
  166646. }
  166647. prep->next_buf_row = prep->next_buf_stop;
  166648. }
  166649. }
  166650. /* If we've gotten enough data, downsample a row group. */
  166651. if (prep->next_buf_row == prep->next_buf_stop) {
  166652. (*cinfo->downsample->downsample) (cinfo,
  166653. prep->color_buf,
  166654. (JDIMENSION) prep->this_row_group,
  166655. output_buf, *out_row_group_ctr);
  166656. (*out_row_group_ctr)++;
  166657. /* Advance pointers with wraparound as necessary. */
  166658. prep->this_row_group += cinfo->max_v_samp_factor;
  166659. if (prep->this_row_group >= buf_height)
  166660. prep->this_row_group = 0;
  166661. if (prep->next_buf_row >= buf_height)
  166662. prep->next_buf_row = 0;
  166663. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166664. }
  166665. }
  166666. }
  166667. /*
  166668. * Create the wrapped-around downsampling input buffer needed for context mode.
  166669. */
  166670. LOCAL(void)
  166671. create_context_buffer (j_compress_ptr cinfo)
  166672. {
  166673. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166674. int rgroup_height = cinfo->max_v_samp_factor;
  166675. int ci, i;
  166676. jpeg_component_info * compptr;
  166677. JSAMPARRAY true_buffer, fake_buffer;
  166678. /* Grab enough space for fake row pointers for all the components;
  166679. * we need five row groups' worth of pointers for each component.
  166680. */
  166681. fake_buffer = (JSAMPARRAY)
  166682. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166683. (cinfo->num_components * 5 * rgroup_height) *
  166684. SIZEOF(JSAMPROW));
  166685. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166686. ci++, compptr++) {
  166687. /* Allocate the actual buffer space (3 row groups) for this component.
  166688. * We make the buffer wide enough to allow the downsampler to edge-expand
  166689. * horizontally within the buffer, if it so chooses.
  166690. */
  166691. true_buffer = (*cinfo->mem->alloc_sarray)
  166692. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166693. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166694. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166695. (JDIMENSION) (3 * rgroup_height));
  166696. /* Copy true buffer row pointers into the middle of the fake row array */
  166697. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166698. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166699. /* Fill in the above and below wraparound pointers */
  166700. for (i = 0; i < rgroup_height; i++) {
  166701. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166702. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166703. }
  166704. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166705. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166706. }
  166707. }
  166708. #endif /* CONTEXT_ROWS_SUPPORTED */
  166709. /*
  166710. * Initialize preprocessing controller.
  166711. */
  166712. GLOBAL(void)
  166713. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166714. {
  166715. my_prep_ptr prep;
  166716. int ci;
  166717. jpeg_component_info * compptr;
  166718. if (need_full_buffer) /* safety check */
  166719. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166720. prep = (my_prep_ptr)
  166721. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166722. SIZEOF(my_prep_controller));
  166723. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166724. prep->pub.start_pass = start_pass_prep;
  166725. /* Allocate the color conversion buffer.
  166726. * We make the buffer wide enough to allow the downsampler to edge-expand
  166727. * horizontally within the buffer, if it so chooses.
  166728. */
  166729. if (cinfo->downsample->need_context_rows) {
  166730. /* Set up to provide context rows */
  166731. #ifdef CONTEXT_ROWS_SUPPORTED
  166732. prep->pub.pre_process_data = pre_process_context;
  166733. create_context_buffer(cinfo);
  166734. #else
  166735. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166736. #endif
  166737. } else {
  166738. /* No context, just make it tall enough for one row group */
  166739. prep->pub.pre_process_data = pre_process_data;
  166740. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166741. ci++, compptr++) {
  166742. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166743. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166744. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166745. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166746. (JDIMENSION) cinfo->max_v_samp_factor);
  166747. }
  166748. }
  166749. }
  166750. /*** End of inlined file: jcprepct.c ***/
  166751. /*** Start of inlined file: jcsample.c ***/
  166752. #define JPEG_INTERNALS
  166753. /* Pointer to routine to downsample a single component */
  166754. typedef JMETHOD(void, downsample1_ptr,
  166755. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166756. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166757. /* Private subobject */
  166758. typedef struct {
  166759. struct jpeg_downsampler pub; /* public fields */
  166760. /* Downsampling method pointers, one per component */
  166761. downsample1_ptr methods[MAX_COMPONENTS];
  166762. } my_downsampler;
  166763. typedef my_downsampler * my_downsample_ptr;
  166764. /*
  166765. * Initialize for a downsampling pass.
  166766. */
  166767. METHODDEF(void)
  166768. start_pass_downsample (j_compress_ptr)
  166769. {
  166770. /* no work for now */
  166771. }
  166772. /*
  166773. * Expand a component horizontally from width input_cols to width output_cols,
  166774. * by duplicating the rightmost samples.
  166775. */
  166776. LOCAL(void)
  166777. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166778. JDIMENSION input_cols, JDIMENSION output_cols)
  166779. {
  166780. register JSAMPROW ptr;
  166781. register JSAMPLE pixval;
  166782. register int count;
  166783. int row;
  166784. int numcols = (int) (output_cols - input_cols);
  166785. if (numcols > 0) {
  166786. for (row = 0; row < num_rows; row++) {
  166787. ptr = image_data[row] + input_cols;
  166788. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166789. for (count = numcols; count > 0; count--)
  166790. *ptr++ = pixval;
  166791. }
  166792. }
  166793. }
  166794. /*
  166795. * Do downsampling for a whole row group (all components).
  166796. *
  166797. * In this version we simply downsample each component independently.
  166798. */
  166799. METHODDEF(void)
  166800. sep_downsample (j_compress_ptr cinfo,
  166801. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166802. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166803. {
  166804. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166805. int ci;
  166806. jpeg_component_info * compptr;
  166807. JSAMPARRAY in_ptr, out_ptr;
  166808. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166809. ci++, compptr++) {
  166810. in_ptr = input_buf[ci] + in_row_index;
  166811. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166812. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166813. }
  166814. }
  166815. /*
  166816. * Downsample pixel values of a single component.
  166817. * One row group is processed per call.
  166818. * This version handles arbitrary integral sampling ratios, without smoothing.
  166819. * Note that this version is not actually used for customary sampling ratios.
  166820. */
  166821. METHODDEF(void)
  166822. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166823. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166824. {
  166825. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166826. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166827. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166828. JSAMPROW inptr, outptr;
  166829. INT32 outvalue;
  166830. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166831. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166832. numpix = h_expand * v_expand;
  166833. numpix2 = numpix/2;
  166834. /* Expand input data enough to let all the output samples be generated
  166835. * by the standard loop. Special-casing padded output would be more
  166836. * efficient.
  166837. */
  166838. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166839. cinfo->image_width, output_cols * h_expand);
  166840. inrow = 0;
  166841. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166842. outptr = output_data[outrow];
  166843. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166844. outcol++, outcol_h += h_expand) {
  166845. outvalue = 0;
  166846. for (v = 0; v < v_expand; v++) {
  166847. inptr = input_data[inrow+v] + outcol_h;
  166848. for (h = 0; h < h_expand; h++) {
  166849. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166850. }
  166851. }
  166852. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166853. }
  166854. inrow += v_expand;
  166855. }
  166856. }
  166857. /*
  166858. * Downsample pixel values of a single component.
  166859. * This version handles the special case of a full-size component,
  166860. * without smoothing.
  166861. */
  166862. METHODDEF(void)
  166863. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166864. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166865. {
  166866. /* Copy the data */
  166867. jcopy_sample_rows(input_data, 0, output_data, 0,
  166868. cinfo->max_v_samp_factor, cinfo->image_width);
  166869. /* Edge-expand */
  166870. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166871. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166872. }
  166873. /*
  166874. * Downsample pixel values of a single component.
  166875. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166876. * without smoothing.
  166877. *
  166878. * A note about the "bias" calculations: when rounding fractional values to
  166879. * integer, we do not want to always round 0.5 up to the next integer.
  166880. * If we did that, we'd introduce a noticeable bias towards larger values.
  166881. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166882. * alternate pixel locations (a simple ordered dither pattern).
  166883. */
  166884. METHODDEF(void)
  166885. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166886. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166887. {
  166888. int outrow;
  166889. JDIMENSION outcol;
  166890. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166891. register JSAMPROW inptr, outptr;
  166892. register int bias;
  166893. /* Expand input data enough to let all the output samples be generated
  166894. * by the standard loop. Special-casing padded output would be more
  166895. * efficient.
  166896. */
  166897. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166898. cinfo->image_width, output_cols * 2);
  166899. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166900. outptr = output_data[outrow];
  166901. inptr = input_data[outrow];
  166902. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166903. for (outcol = 0; outcol < output_cols; outcol++) {
  166904. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166905. + bias) >> 1);
  166906. bias ^= 1; /* 0=>1, 1=>0 */
  166907. inptr += 2;
  166908. }
  166909. }
  166910. }
  166911. /*
  166912. * Downsample pixel values of a single component.
  166913. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166914. * without smoothing.
  166915. */
  166916. METHODDEF(void)
  166917. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166918. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166919. {
  166920. int inrow, outrow;
  166921. JDIMENSION outcol;
  166922. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166923. register JSAMPROW inptr0, inptr1, outptr;
  166924. register int bias;
  166925. /* Expand input data enough to let all the output samples be generated
  166926. * by the standard loop. Special-casing padded output would be more
  166927. * efficient.
  166928. */
  166929. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166930. cinfo->image_width, output_cols * 2);
  166931. inrow = 0;
  166932. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166933. outptr = output_data[outrow];
  166934. inptr0 = input_data[inrow];
  166935. inptr1 = input_data[inrow+1];
  166936. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166937. for (outcol = 0; outcol < output_cols; outcol++) {
  166938. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166939. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166940. + bias) >> 2);
  166941. bias ^= 3; /* 1=>2, 2=>1 */
  166942. inptr0 += 2; inptr1 += 2;
  166943. }
  166944. inrow += 2;
  166945. }
  166946. }
  166947. #ifdef INPUT_SMOOTHING_SUPPORTED
  166948. /*
  166949. * Downsample pixel values of a single component.
  166950. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166951. * with smoothing. One row of context is required.
  166952. */
  166953. METHODDEF(void)
  166954. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166955. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166956. {
  166957. int inrow, outrow;
  166958. JDIMENSION colctr;
  166959. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166960. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166961. INT32 membersum, neighsum, memberscale, neighscale;
  166962. /* Expand input data enough to let all the output samples be generated
  166963. * by the standard loop. Special-casing padded output would be more
  166964. * efficient.
  166965. */
  166966. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166967. cinfo->image_width, output_cols * 2);
  166968. /* We don't bother to form the individual "smoothed" input pixel values;
  166969. * we can directly compute the output which is the average of the four
  166970. * smoothed values. Each of the four member pixels contributes a fraction
  166971. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166972. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166973. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166974. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166975. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166976. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166977. * factors are scaled by 2^16 = 65536.
  166978. * Also recall that SF = smoothing_factor / 1024.
  166979. */
  166980. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166981. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166982. inrow = 0;
  166983. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166984. outptr = output_data[outrow];
  166985. inptr0 = input_data[inrow];
  166986. inptr1 = input_data[inrow+1];
  166987. above_ptr = input_data[inrow-1];
  166988. below_ptr = input_data[inrow+2];
  166989. /* Special case for first column: pretend column -1 is same as column 0 */
  166990. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166991. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166992. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166993. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166994. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166995. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166996. neighsum += neighsum;
  166997. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166998. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166999. membersum = membersum * memberscale + neighsum * neighscale;
  167000. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167001. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167002. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167003. /* sum of pixels directly mapped to this output element */
  167004. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167005. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167006. /* sum of edge-neighbor pixels */
  167007. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167008. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167009. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  167010. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  167011. /* The edge-neighbors count twice as much as corner-neighbors */
  167012. neighsum += neighsum;
  167013. /* Add in the corner-neighbors */
  167014. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  167015. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  167016. /* form final output scaled up by 2^16 */
  167017. membersum = membersum * memberscale + neighsum * neighscale;
  167018. /* round, descale and output it */
  167019. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167020. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167021. }
  167022. /* Special case for last column */
  167023. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167024. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167025. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167026. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167027. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  167028. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  167029. neighsum += neighsum;
  167030. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  167031. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  167032. membersum = membersum * memberscale + neighsum * neighscale;
  167033. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167034. inrow += 2;
  167035. }
  167036. }
  167037. /*
  167038. * Downsample pixel values of a single component.
  167039. * This version handles the special case of a full-size component,
  167040. * with smoothing. One row of context is required.
  167041. */
  167042. METHODDEF(void)
  167043. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  167044. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167045. {
  167046. int outrow;
  167047. JDIMENSION colctr;
  167048. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167049. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  167050. INT32 membersum, neighsum, memberscale, neighscale;
  167051. int colsum, lastcolsum, nextcolsum;
  167052. /* Expand input data enough to let all the output samples be generated
  167053. * by the standard loop. Special-casing padded output would be more
  167054. * efficient.
  167055. */
  167056. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167057. cinfo->image_width, output_cols);
  167058. /* Each of the eight neighbor pixels contributes a fraction SF to the
  167059. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  167060. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167061. * Also recall that SF = smoothing_factor / 1024.
  167062. */
  167063. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167064. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167065. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167066. outptr = output_data[outrow];
  167067. inptr = input_data[outrow];
  167068. above_ptr = input_data[outrow-1];
  167069. below_ptr = input_data[outrow+1];
  167070. /* Special case for first column */
  167071. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167072. GETJSAMPLE(*inptr);
  167073. membersum = GETJSAMPLE(*inptr++);
  167074. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167075. GETJSAMPLE(*inptr);
  167076. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167077. membersum = membersum * memberscale + neighsum * neighscale;
  167078. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167079. lastcolsum = colsum; colsum = nextcolsum;
  167080. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167081. membersum = GETJSAMPLE(*inptr++);
  167082. above_ptr++; below_ptr++;
  167083. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167084. GETJSAMPLE(*inptr);
  167085. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167086. membersum = membersum * memberscale + neighsum * neighscale;
  167087. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167088. lastcolsum = colsum; colsum = nextcolsum;
  167089. }
  167090. /* Special case for last column */
  167091. membersum = GETJSAMPLE(*inptr);
  167092. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167093. membersum = membersum * memberscale + neighsum * neighscale;
  167094. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167095. }
  167096. }
  167097. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167098. /*
  167099. * Module initialization routine for downsampling.
  167100. * Note that we must select a routine for each component.
  167101. */
  167102. GLOBAL(void)
  167103. jinit_downsampler (j_compress_ptr cinfo)
  167104. {
  167105. my_downsample_ptr downsample;
  167106. int ci;
  167107. jpeg_component_info * compptr;
  167108. boolean smoothok = TRUE;
  167109. downsample = (my_downsample_ptr)
  167110. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167111. SIZEOF(my_downsampler));
  167112. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167113. downsample->pub.start_pass = start_pass_downsample;
  167114. downsample->pub.downsample = sep_downsample;
  167115. downsample->pub.need_context_rows = FALSE;
  167116. if (cinfo->CCIR601_sampling)
  167117. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167118. /* Verify we can handle the sampling factors, and set up method pointers */
  167119. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167120. ci++, compptr++) {
  167121. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167122. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167123. #ifdef INPUT_SMOOTHING_SUPPORTED
  167124. if (cinfo->smoothing_factor) {
  167125. downsample->methods[ci] = fullsize_smooth_downsample;
  167126. downsample->pub.need_context_rows = TRUE;
  167127. } else
  167128. #endif
  167129. downsample->methods[ci] = fullsize_downsample;
  167130. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167131. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167132. smoothok = FALSE;
  167133. downsample->methods[ci] = h2v1_downsample;
  167134. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167135. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167136. #ifdef INPUT_SMOOTHING_SUPPORTED
  167137. if (cinfo->smoothing_factor) {
  167138. downsample->methods[ci] = h2v2_smooth_downsample;
  167139. downsample->pub.need_context_rows = TRUE;
  167140. } else
  167141. #endif
  167142. downsample->methods[ci] = h2v2_downsample;
  167143. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167144. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167145. smoothok = FALSE;
  167146. downsample->methods[ci] = int_downsample;
  167147. } else
  167148. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167149. }
  167150. #ifdef INPUT_SMOOTHING_SUPPORTED
  167151. if (cinfo->smoothing_factor && !smoothok)
  167152. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167153. #endif
  167154. }
  167155. /*** End of inlined file: jcsample.c ***/
  167156. /*** Start of inlined file: jctrans.c ***/
  167157. #define JPEG_INTERNALS
  167158. /* Forward declarations */
  167159. LOCAL(void) transencode_master_selection
  167160. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167161. LOCAL(void) transencode_coef_controller
  167162. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167163. /*
  167164. * Compression initialization for writing raw-coefficient data.
  167165. * Before calling this, all parameters and a data destination must be set up.
  167166. * Call jpeg_finish_compress() to actually write the data.
  167167. *
  167168. * The number of passed virtual arrays must match cinfo->num_components.
  167169. * Note that the virtual arrays need not be filled or even realized at
  167170. * the time write_coefficients is called; indeed, if the virtual arrays
  167171. * were requested from this compression object's memory manager, they
  167172. * typically will be realized during this routine and filled afterwards.
  167173. */
  167174. GLOBAL(void)
  167175. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167176. {
  167177. if (cinfo->global_state != CSTATE_START)
  167178. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167179. /* Mark all tables to be written */
  167180. jpeg_suppress_tables(cinfo, FALSE);
  167181. /* (Re)initialize error mgr and destination modules */
  167182. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167183. (*cinfo->dest->init_destination) (cinfo);
  167184. /* Perform master selection of active modules */
  167185. transencode_master_selection(cinfo, coef_arrays);
  167186. /* Wait for jpeg_finish_compress() call */
  167187. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167188. cinfo->global_state = CSTATE_WRCOEFS;
  167189. }
  167190. /*
  167191. * Initialize the compression object with default parameters,
  167192. * then copy from the source object all parameters needed for lossless
  167193. * transcoding. Parameters that can be varied without loss (such as
  167194. * scan script and Huffman optimization) are left in their default states.
  167195. */
  167196. GLOBAL(void)
  167197. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167198. j_compress_ptr dstinfo)
  167199. {
  167200. JQUANT_TBL ** qtblptr;
  167201. jpeg_component_info *incomp, *outcomp;
  167202. JQUANT_TBL *c_quant, *slot_quant;
  167203. int tblno, ci, coefi;
  167204. /* Safety check to ensure start_compress not called yet. */
  167205. if (dstinfo->global_state != CSTATE_START)
  167206. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167207. /* Copy fundamental image dimensions */
  167208. dstinfo->image_width = srcinfo->image_width;
  167209. dstinfo->image_height = srcinfo->image_height;
  167210. dstinfo->input_components = srcinfo->num_components;
  167211. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167212. /* Initialize all parameters to default values */
  167213. jpeg_set_defaults(dstinfo);
  167214. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167215. * Fix it to get the right header markers for the image colorspace.
  167216. */
  167217. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167218. dstinfo->data_precision = srcinfo->data_precision;
  167219. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167220. /* Copy the source's quantization tables. */
  167221. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167222. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167223. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167224. if (*qtblptr == NULL)
  167225. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167226. MEMCOPY((*qtblptr)->quantval,
  167227. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167228. SIZEOF((*qtblptr)->quantval));
  167229. (*qtblptr)->sent_table = FALSE;
  167230. }
  167231. }
  167232. /* Copy the source's per-component info.
  167233. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167234. */
  167235. dstinfo->num_components = srcinfo->num_components;
  167236. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167237. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167238. MAX_COMPONENTS);
  167239. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167240. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167241. outcomp->component_id = incomp->component_id;
  167242. outcomp->h_samp_factor = incomp->h_samp_factor;
  167243. outcomp->v_samp_factor = incomp->v_samp_factor;
  167244. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167245. /* Make sure saved quantization table for component matches the qtable
  167246. * slot. If not, the input file re-used this qtable slot.
  167247. * IJG encoder currently cannot duplicate this.
  167248. */
  167249. tblno = outcomp->quant_tbl_no;
  167250. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167251. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167252. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167253. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167254. c_quant = incomp->quant_table;
  167255. if (c_quant != NULL) {
  167256. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167257. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167258. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167259. }
  167260. }
  167261. /* Note: we do not copy the source's Huffman table assignments;
  167262. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167263. */
  167264. }
  167265. /* Also copy JFIF version and resolution information, if available.
  167266. * Strictly speaking this isn't "critical" info, but it's nearly
  167267. * always appropriate to copy it if available. In particular,
  167268. * if the application chooses to copy JFIF 1.02 extension markers from
  167269. * the source file, we need to copy the version to make sure we don't
  167270. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167271. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167272. */
  167273. if (srcinfo->saw_JFIF_marker) {
  167274. if (srcinfo->JFIF_major_version == 1) {
  167275. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167276. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167277. }
  167278. dstinfo->density_unit = srcinfo->density_unit;
  167279. dstinfo->X_density = srcinfo->X_density;
  167280. dstinfo->Y_density = srcinfo->Y_density;
  167281. }
  167282. }
  167283. /*
  167284. * Master selection of compression modules for transcoding.
  167285. * This substitutes for jcinit.c's initialization of the full compressor.
  167286. */
  167287. LOCAL(void)
  167288. transencode_master_selection (j_compress_ptr cinfo,
  167289. jvirt_barray_ptr * coef_arrays)
  167290. {
  167291. /* Although we don't actually use input_components for transcoding,
  167292. * jcmaster.c's initial_setup will complain if input_components is 0.
  167293. */
  167294. cinfo->input_components = 1;
  167295. /* Initialize master control (includes parameter checking/processing) */
  167296. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167297. /* Entropy encoding: either Huffman or arithmetic coding. */
  167298. if (cinfo->arith_code) {
  167299. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167300. } else {
  167301. if (cinfo->progressive_mode) {
  167302. #ifdef C_PROGRESSIVE_SUPPORTED
  167303. jinit_phuff_encoder(cinfo);
  167304. #else
  167305. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167306. #endif
  167307. } else
  167308. jinit_huff_encoder(cinfo);
  167309. }
  167310. /* We need a special coefficient buffer controller. */
  167311. transencode_coef_controller(cinfo, coef_arrays);
  167312. jinit_marker_writer(cinfo);
  167313. /* We can now tell the memory manager to allocate virtual arrays. */
  167314. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167315. /* Write the datastream header (SOI, JFIF) immediately.
  167316. * Frame and scan headers are postponed till later.
  167317. * This lets application insert special markers after the SOI.
  167318. */
  167319. (*cinfo->marker->write_file_header) (cinfo);
  167320. }
  167321. /*
  167322. * The rest of this file is a special implementation of the coefficient
  167323. * buffer controller. This is similar to jccoefct.c, but it handles only
  167324. * output from presupplied virtual arrays. Furthermore, we generate any
  167325. * dummy padding blocks on-the-fly rather than expecting them to be present
  167326. * in the arrays.
  167327. */
  167328. /* Private buffer controller object */
  167329. typedef struct {
  167330. struct jpeg_c_coef_controller pub; /* public fields */
  167331. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167332. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167333. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167334. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167335. /* Virtual block array for each component. */
  167336. jvirt_barray_ptr * whole_image;
  167337. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167338. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167339. } my_coef_controller2;
  167340. typedef my_coef_controller2 * my_coef_ptr2;
  167341. LOCAL(void)
  167342. start_iMCU_row2 (j_compress_ptr cinfo)
  167343. /* Reset within-iMCU-row counters for a new row */
  167344. {
  167345. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167346. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167347. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167348. * But at the bottom of the image, process only what's left.
  167349. */
  167350. if (cinfo->comps_in_scan > 1) {
  167351. coef->MCU_rows_per_iMCU_row = 1;
  167352. } else {
  167353. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167354. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167355. else
  167356. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167357. }
  167358. coef->mcu_ctr = 0;
  167359. coef->MCU_vert_offset = 0;
  167360. }
  167361. /*
  167362. * Initialize for a processing pass.
  167363. */
  167364. METHODDEF(void)
  167365. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167366. {
  167367. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167368. if (pass_mode != JBUF_CRANK_DEST)
  167369. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167370. coef->iMCU_row_num = 0;
  167371. start_iMCU_row2(cinfo);
  167372. }
  167373. /*
  167374. * Process some data.
  167375. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167376. * per call, ie, v_samp_factor block rows for each component in the scan.
  167377. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167378. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167379. *
  167380. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167381. */
  167382. METHODDEF(boolean)
  167383. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167384. {
  167385. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167386. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167387. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167388. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167389. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167390. JDIMENSION start_col;
  167391. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167392. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167393. JBLOCKROW buffer_ptr;
  167394. jpeg_component_info *compptr;
  167395. /* Align the virtual buffers for the components used in this scan. */
  167396. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167397. compptr = cinfo->cur_comp_info[ci];
  167398. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167399. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167400. coef->iMCU_row_num * compptr->v_samp_factor,
  167401. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167402. }
  167403. /* Loop to process one whole iMCU row */
  167404. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167405. yoffset++) {
  167406. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167407. MCU_col_num++) {
  167408. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167409. blkn = 0; /* index of current DCT block within MCU */
  167410. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167411. compptr = cinfo->cur_comp_info[ci];
  167412. start_col = MCU_col_num * compptr->MCU_width;
  167413. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167414. : compptr->last_col_width;
  167415. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167416. if (coef->iMCU_row_num < last_iMCU_row ||
  167417. yindex+yoffset < compptr->last_row_height) {
  167418. /* Fill in pointers to real blocks in this row */
  167419. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167420. for (xindex = 0; xindex < blockcnt; xindex++)
  167421. MCU_buffer[blkn++] = buffer_ptr++;
  167422. } else {
  167423. /* At bottom of image, need a whole row of dummy blocks */
  167424. xindex = 0;
  167425. }
  167426. /* Fill in any dummy blocks needed in this row.
  167427. * Dummy blocks are filled in the same way as in jccoefct.c:
  167428. * all zeroes in the AC entries, DC entries equal to previous
  167429. * block's DC value. The init routine has already zeroed the
  167430. * AC entries, so we need only set the DC entries correctly.
  167431. */
  167432. for (; xindex < compptr->MCU_width; xindex++) {
  167433. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167434. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167435. blkn++;
  167436. }
  167437. }
  167438. }
  167439. /* Try to write the MCU. */
  167440. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167441. /* Suspension forced; update state counters and exit */
  167442. coef->MCU_vert_offset = yoffset;
  167443. coef->mcu_ctr = MCU_col_num;
  167444. return FALSE;
  167445. }
  167446. }
  167447. /* Completed an MCU row, but perhaps not an iMCU row */
  167448. coef->mcu_ctr = 0;
  167449. }
  167450. /* Completed the iMCU row, advance counters for next one */
  167451. coef->iMCU_row_num++;
  167452. start_iMCU_row2(cinfo);
  167453. return TRUE;
  167454. }
  167455. /*
  167456. * Initialize coefficient buffer controller.
  167457. *
  167458. * Each passed coefficient array must be the right size for that
  167459. * coefficient: width_in_blocks wide and height_in_blocks high,
  167460. * with unitheight at least v_samp_factor.
  167461. */
  167462. LOCAL(void)
  167463. transencode_coef_controller (j_compress_ptr cinfo,
  167464. jvirt_barray_ptr * coef_arrays)
  167465. {
  167466. my_coef_ptr2 coef;
  167467. JBLOCKROW buffer;
  167468. int i;
  167469. coef = (my_coef_ptr2)
  167470. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167471. SIZEOF(my_coef_controller2));
  167472. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167473. coef->pub.start_pass = start_pass_coef2;
  167474. coef->pub.compress_data = compress_output2;
  167475. /* Save pointer to virtual arrays */
  167476. coef->whole_image = coef_arrays;
  167477. /* Allocate and pre-zero space for dummy DCT blocks. */
  167478. buffer = (JBLOCKROW)
  167479. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167480. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167481. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167482. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167483. coef->dummy_buffer[i] = buffer + i;
  167484. }
  167485. }
  167486. /*** End of inlined file: jctrans.c ***/
  167487. /*** Start of inlined file: jdapistd.c ***/
  167488. #define JPEG_INTERNALS
  167489. /* Forward declarations */
  167490. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167491. /*
  167492. * Decompression initialization.
  167493. * jpeg_read_header must be completed before calling this.
  167494. *
  167495. * If a multipass operating mode was selected, this will do all but the
  167496. * last pass, and thus may take a great deal of time.
  167497. *
  167498. * Returns FALSE if suspended. The return value need be inspected only if
  167499. * a suspending data source is used.
  167500. */
  167501. GLOBAL(boolean)
  167502. jpeg_start_decompress (j_decompress_ptr cinfo)
  167503. {
  167504. if (cinfo->global_state == DSTATE_READY) {
  167505. /* First call: initialize master control, select active modules */
  167506. jinit_master_decompress(cinfo);
  167507. if (cinfo->buffered_image) {
  167508. /* No more work here; expecting jpeg_start_output next */
  167509. cinfo->global_state = DSTATE_BUFIMAGE;
  167510. return TRUE;
  167511. }
  167512. cinfo->global_state = DSTATE_PRELOAD;
  167513. }
  167514. if (cinfo->global_state == DSTATE_PRELOAD) {
  167515. /* If file has multiple scans, absorb them all into the coef buffer */
  167516. if (cinfo->inputctl->has_multiple_scans) {
  167517. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167518. for (;;) {
  167519. int retcode;
  167520. /* Call progress monitor hook if present */
  167521. if (cinfo->progress != NULL)
  167522. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167523. /* Absorb some more input */
  167524. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167525. if (retcode == JPEG_SUSPENDED)
  167526. return FALSE;
  167527. if (retcode == JPEG_REACHED_EOI)
  167528. break;
  167529. /* Advance progress counter if appropriate */
  167530. if (cinfo->progress != NULL &&
  167531. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167532. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167533. /* jdmaster underestimated number of scans; ratchet up one scan */
  167534. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167535. }
  167536. }
  167537. }
  167538. #else
  167539. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167540. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167541. }
  167542. cinfo->output_scan_number = cinfo->input_scan_number;
  167543. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167544. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167545. /* Perform any dummy output passes, and set up for the final pass */
  167546. return output_pass_setup(cinfo);
  167547. }
  167548. /*
  167549. * Set up for an output pass, and perform any dummy pass(es) needed.
  167550. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167551. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167552. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167553. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167554. */
  167555. LOCAL(boolean)
  167556. output_pass_setup (j_decompress_ptr cinfo)
  167557. {
  167558. if (cinfo->global_state != DSTATE_PRESCAN) {
  167559. /* First call: do pass setup */
  167560. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167561. cinfo->output_scanline = 0;
  167562. cinfo->global_state = DSTATE_PRESCAN;
  167563. }
  167564. /* Loop over any required dummy passes */
  167565. while (cinfo->master->is_dummy_pass) {
  167566. #ifdef QUANT_2PASS_SUPPORTED
  167567. /* Crank through the dummy pass */
  167568. while (cinfo->output_scanline < cinfo->output_height) {
  167569. JDIMENSION last_scanline;
  167570. /* Call progress monitor hook if present */
  167571. if (cinfo->progress != NULL) {
  167572. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167573. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167574. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167575. }
  167576. /* Process some data */
  167577. last_scanline = cinfo->output_scanline;
  167578. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167579. &cinfo->output_scanline, (JDIMENSION) 0);
  167580. if (cinfo->output_scanline == last_scanline)
  167581. return FALSE; /* No progress made, must suspend */
  167582. }
  167583. /* Finish up dummy pass, and set up for another one */
  167584. (*cinfo->master->finish_output_pass) (cinfo);
  167585. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167586. cinfo->output_scanline = 0;
  167587. #else
  167588. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167589. #endif /* QUANT_2PASS_SUPPORTED */
  167590. }
  167591. /* Ready for application to drive output pass through
  167592. * jpeg_read_scanlines or jpeg_read_raw_data.
  167593. */
  167594. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167595. return TRUE;
  167596. }
  167597. /*
  167598. * Read some scanlines of data from the JPEG decompressor.
  167599. *
  167600. * The return value will be the number of lines actually read.
  167601. * This may be less than the number requested in several cases,
  167602. * including bottom of image, data source suspension, and operating
  167603. * modes that emit multiple scanlines at a time.
  167604. *
  167605. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167606. * this likely signals an application programmer error. However,
  167607. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167608. */
  167609. GLOBAL(JDIMENSION)
  167610. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167611. JDIMENSION max_lines)
  167612. {
  167613. JDIMENSION row_ctr;
  167614. if (cinfo->global_state != DSTATE_SCANNING)
  167615. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167616. if (cinfo->output_scanline >= cinfo->output_height) {
  167617. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167618. return 0;
  167619. }
  167620. /* Call progress monitor hook if present */
  167621. if (cinfo->progress != NULL) {
  167622. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167623. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167624. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167625. }
  167626. /* Process some data */
  167627. row_ctr = 0;
  167628. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167629. cinfo->output_scanline += row_ctr;
  167630. return row_ctr;
  167631. }
  167632. /*
  167633. * Alternate entry point to read raw data.
  167634. * Processes exactly one iMCU row per call, unless suspended.
  167635. */
  167636. GLOBAL(JDIMENSION)
  167637. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167638. JDIMENSION max_lines)
  167639. {
  167640. JDIMENSION lines_per_iMCU_row;
  167641. if (cinfo->global_state != DSTATE_RAW_OK)
  167642. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167643. if (cinfo->output_scanline >= cinfo->output_height) {
  167644. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167645. return 0;
  167646. }
  167647. /* Call progress monitor hook if present */
  167648. if (cinfo->progress != NULL) {
  167649. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167650. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167651. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167652. }
  167653. /* Verify that at least one iMCU row can be returned. */
  167654. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167655. if (max_lines < lines_per_iMCU_row)
  167656. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167657. /* Decompress directly into user's buffer. */
  167658. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167659. return 0; /* suspension forced, can do nothing more */
  167660. /* OK, we processed one iMCU row. */
  167661. cinfo->output_scanline += lines_per_iMCU_row;
  167662. return lines_per_iMCU_row;
  167663. }
  167664. /* Additional entry points for buffered-image mode. */
  167665. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167666. /*
  167667. * Initialize for an output pass in buffered-image mode.
  167668. */
  167669. GLOBAL(boolean)
  167670. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167671. {
  167672. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167673. cinfo->global_state != DSTATE_PRESCAN)
  167674. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167675. /* Limit scan number to valid range */
  167676. if (scan_number <= 0)
  167677. scan_number = 1;
  167678. if (cinfo->inputctl->eoi_reached &&
  167679. scan_number > cinfo->input_scan_number)
  167680. scan_number = cinfo->input_scan_number;
  167681. cinfo->output_scan_number = scan_number;
  167682. /* Perform any dummy output passes, and set up for the real pass */
  167683. return output_pass_setup(cinfo);
  167684. }
  167685. /*
  167686. * Finish up after an output pass in buffered-image mode.
  167687. *
  167688. * Returns FALSE if suspended. The return value need be inspected only if
  167689. * a suspending data source is used.
  167690. */
  167691. GLOBAL(boolean)
  167692. jpeg_finish_output (j_decompress_ptr cinfo)
  167693. {
  167694. if ((cinfo->global_state == DSTATE_SCANNING ||
  167695. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167696. /* Terminate this pass. */
  167697. /* We do not require the whole pass to have been completed. */
  167698. (*cinfo->master->finish_output_pass) (cinfo);
  167699. cinfo->global_state = DSTATE_BUFPOST;
  167700. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167701. /* BUFPOST = repeat call after a suspension, anything else is error */
  167702. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167703. }
  167704. /* Read markers looking for SOS or EOI */
  167705. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167706. ! cinfo->inputctl->eoi_reached) {
  167707. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167708. return FALSE; /* Suspend, come back later */
  167709. }
  167710. cinfo->global_state = DSTATE_BUFIMAGE;
  167711. return TRUE;
  167712. }
  167713. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167714. /*** End of inlined file: jdapistd.c ***/
  167715. /*** Start of inlined file: jdapimin.c ***/
  167716. #define JPEG_INTERNALS
  167717. /*
  167718. * Initialization of a JPEG decompression object.
  167719. * The error manager must already be set up (in case memory manager fails).
  167720. */
  167721. GLOBAL(void)
  167722. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167723. {
  167724. int i;
  167725. /* Guard against version mismatches between library and caller. */
  167726. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167727. if (version != JPEG_LIB_VERSION)
  167728. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167729. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167730. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167731. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167732. /* For debugging purposes, we zero the whole master structure.
  167733. * But the application has already set the err pointer, and may have set
  167734. * client_data, so we have to save and restore those fields.
  167735. * Note: if application hasn't set client_data, tools like Purify may
  167736. * complain here.
  167737. */
  167738. {
  167739. struct jpeg_error_mgr * err = cinfo->err;
  167740. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167741. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167742. cinfo->err = err;
  167743. cinfo->client_data = client_data;
  167744. }
  167745. cinfo->is_decompressor = TRUE;
  167746. /* Initialize a memory manager instance for this object */
  167747. jinit_memory_mgr((j_common_ptr) cinfo);
  167748. /* Zero out pointers to permanent structures. */
  167749. cinfo->progress = NULL;
  167750. cinfo->src = NULL;
  167751. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167752. cinfo->quant_tbl_ptrs[i] = NULL;
  167753. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167754. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167755. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167756. }
  167757. /* Initialize marker processor so application can override methods
  167758. * for COM, APPn markers before calling jpeg_read_header.
  167759. */
  167760. cinfo->marker_list = NULL;
  167761. jinit_marker_reader(cinfo);
  167762. /* And initialize the overall input controller. */
  167763. jinit_input_controller(cinfo);
  167764. /* OK, I'm ready */
  167765. cinfo->global_state = DSTATE_START;
  167766. }
  167767. /*
  167768. * Destruction of a JPEG decompression object
  167769. */
  167770. GLOBAL(void)
  167771. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167772. {
  167773. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167774. }
  167775. /*
  167776. * Abort processing of a JPEG decompression operation,
  167777. * but don't destroy the object itself.
  167778. */
  167779. GLOBAL(void)
  167780. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167781. {
  167782. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167783. }
  167784. /*
  167785. * Set default decompression parameters.
  167786. */
  167787. LOCAL(void)
  167788. default_decompress_parms (j_decompress_ptr cinfo)
  167789. {
  167790. /* Guess the input colorspace, and set output colorspace accordingly. */
  167791. /* (Wish JPEG committee had provided a real way to specify this...) */
  167792. /* Note application may override our guesses. */
  167793. switch (cinfo->num_components) {
  167794. case 1:
  167795. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167796. cinfo->out_color_space = JCS_GRAYSCALE;
  167797. break;
  167798. case 3:
  167799. if (cinfo->saw_JFIF_marker) {
  167800. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167801. } else if (cinfo->saw_Adobe_marker) {
  167802. switch (cinfo->Adobe_transform) {
  167803. case 0:
  167804. cinfo->jpeg_color_space = JCS_RGB;
  167805. break;
  167806. case 1:
  167807. cinfo->jpeg_color_space = JCS_YCbCr;
  167808. break;
  167809. default:
  167810. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167811. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167812. break;
  167813. }
  167814. } else {
  167815. /* Saw no special markers, try to guess from the component IDs */
  167816. int cid0 = cinfo->comp_info[0].component_id;
  167817. int cid1 = cinfo->comp_info[1].component_id;
  167818. int cid2 = cinfo->comp_info[2].component_id;
  167819. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167820. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167821. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167822. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167823. else {
  167824. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167825. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167826. }
  167827. }
  167828. /* Always guess RGB is proper output colorspace. */
  167829. cinfo->out_color_space = JCS_RGB;
  167830. break;
  167831. case 4:
  167832. if (cinfo->saw_Adobe_marker) {
  167833. switch (cinfo->Adobe_transform) {
  167834. case 0:
  167835. cinfo->jpeg_color_space = JCS_CMYK;
  167836. break;
  167837. case 2:
  167838. cinfo->jpeg_color_space = JCS_YCCK;
  167839. break;
  167840. default:
  167841. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167842. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167843. break;
  167844. }
  167845. } else {
  167846. /* No special markers, assume straight CMYK. */
  167847. cinfo->jpeg_color_space = JCS_CMYK;
  167848. }
  167849. cinfo->out_color_space = JCS_CMYK;
  167850. break;
  167851. default:
  167852. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167853. cinfo->out_color_space = JCS_UNKNOWN;
  167854. break;
  167855. }
  167856. /* Set defaults for other decompression parameters. */
  167857. cinfo->scale_num = 1; /* 1:1 scaling */
  167858. cinfo->scale_denom = 1;
  167859. cinfo->output_gamma = 1.0;
  167860. cinfo->buffered_image = FALSE;
  167861. cinfo->raw_data_out = FALSE;
  167862. cinfo->dct_method = JDCT_DEFAULT;
  167863. cinfo->do_fancy_upsampling = TRUE;
  167864. cinfo->do_block_smoothing = TRUE;
  167865. cinfo->quantize_colors = FALSE;
  167866. /* We set these in case application only sets quantize_colors. */
  167867. cinfo->dither_mode = JDITHER_FS;
  167868. #ifdef QUANT_2PASS_SUPPORTED
  167869. cinfo->two_pass_quantize = TRUE;
  167870. #else
  167871. cinfo->two_pass_quantize = FALSE;
  167872. #endif
  167873. cinfo->desired_number_of_colors = 256;
  167874. cinfo->colormap = NULL;
  167875. /* Initialize for no mode change in buffered-image mode. */
  167876. cinfo->enable_1pass_quant = FALSE;
  167877. cinfo->enable_external_quant = FALSE;
  167878. cinfo->enable_2pass_quant = FALSE;
  167879. }
  167880. /*
  167881. * Decompression startup: read start of JPEG datastream to see what's there.
  167882. * Need only initialize JPEG object and supply a data source before calling.
  167883. *
  167884. * This routine will read as far as the first SOS marker (ie, actual start of
  167885. * compressed data), and will save all tables and parameters in the JPEG
  167886. * object. It will also initialize the decompression parameters to default
  167887. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167888. * adjust the decompression parameters and then call jpeg_start_decompress.
  167889. * (Or, if the application only wanted to determine the image parameters,
  167890. * the data need not be decompressed. In that case, call jpeg_abort or
  167891. * jpeg_destroy to release any temporary space.)
  167892. * If an abbreviated (tables only) datastream is presented, the routine will
  167893. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167894. * re-use the JPEG object to read the abbreviated image datastream(s).
  167895. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167896. * The JPEG_SUSPENDED return code only occurs if the data source module
  167897. * requests suspension of the decompressor. In this case the application
  167898. * should load more source data and then re-call jpeg_read_header to resume
  167899. * processing.
  167900. * If a non-suspending data source is used and require_image is TRUE, then the
  167901. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167902. *
  167903. * This routine is now just a front end to jpeg_consume_input, with some
  167904. * extra error checking.
  167905. */
  167906. GLOBAL(int)
  167907. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167908. {
  167909. int retcode;
  167910. if (cinfo->global_state != DSTATE_START &&
  167911. cinfo->global_state != DSTATE_INHEADER)
  167912. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167913. retcode = jpeg_consume_input(cinfo);
  167914. switch (retcode) {
  167915. case JPEG_REACHED_SOS:
  167916. retcode = JPEG_HEADER_OK;
  167917. break;
  167918. case JPEG_REACHED_EOI:
  167919. if (require_image) /* Complain if application wanted an image */
  167920. ERREXIT(cinfo, JERR_NO_IMAGE);
  167921. /* Reset to start state; it would be safer to require the application to
  167922. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167923. * A side effect is to free any temporary memory (there shouldn't be any).
  167924. */
  167925. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167926. retcode = JPEG_HEADER_TABLES_ONLY;
  167927. break;
  167928. case JPEG_SUSPENDED:
  167929. /* no work */
  167930. break;
  167931. }
  167932. return retcode;
  167933. }
  167934. /*
  167935. * Consume data in advance of what the decompressor requires.
  167936. * This can be called at any time once the decompressor object has
  167937. * been created and a data source has been set up.
  167938. *
  167939. * This routine is essentially a state machine that handles a couple
  167940. * of critical state-transition actions, namely initial setup and
  167941. * transition from header scanning to ready-for-start_decompress.
  167942. * All the actual input is done via the input controller's consume_input
  167943. * method.
  167944. */
  167945. GLOBAL(int)
  167946. jpeg_consume_input (j_decompress_ptr cinfo)
  167947. {
  167948. int retcode = JPEG_SUSPENDED;
  167949. /* NB: every possible DSTATE value should be listed in this switch */
  167950. switch (cinfo->global_state) {
  167951. case DSTATE_START:
  167952. /* Start-of-datastream actions: reset appropriate modules */
  167953. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167954. /* Initialize application's data source module */
  167955. (*cinfo->src->init_source) (cinfo);
  167956. cinfo->global_state = DSTATE_INHEADER;
  167957. /*FALLTHROUGH*/
  167958. case DSTATE_INHEADER:
  167959. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167960. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167961. /* Set up default parameters based on header data */
  167962. default_decompress_parms(cinfo);
  167963. /* Set global state: ready for start_decompress */
  167964. cinfo->global_state = DSTATE_READY;
  167965. }
  167966. break;
  167967. case DSTATE_READY:
  167968. /* Can't advance past first SOS until start_decompress is called */
  167969. retcode = JPEG_REACHED_SOS;
  167970. break;
  167971. case DSTATE_PRELOAD:
  167972. case DSTATE_PRESCAN:
  167973. case DSTATE_SCANNING:
  167974. case DSTATE_RAW_OK:
  167975. case DSTATE_BUFIMAGE:
  167976. case DSTATE_BUFPOST:
  167977. case DSTATE_STOPPING:
  167978. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167979. break;
  167980. default:
  167981. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167982. }
  167983. return retcode;
  167984. }
  167985. /*
  167986. * Have we finished reading the input file?
  167987. */
  167988. GLOBAL(boolean)
  167989. jpeg_input_complete (j_decompress_ptr cinfo)
  167990. {
  167991. /* Check for valid jpeg object */
  167992. if (cinfo->global_state < DSTATE_START ||
  167993. cinfo->global_state > DSTATE_STOPPING)
  167994. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167995. return cinfo->inputctl->eoi_reached;
  167996. }
  167997. /*
  167998. * Is there more than one scan?
  167999. */
  168000. GLOBAL(boolean)
  168001. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  168002. {
  168003. /* Only valid after jpeg_read_header completes */
  168004. if (cinfo->global_state < DSTATE_READY ||
  168005. cinfo->global_state > DSTATE_STOPPING)
  168006. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168007. return cinfo->inputctl->has_multiple_scans;
  168008. }
  168009. /*
  168010. * Finish JPEG decompression.
  168011. *
  168012. * This will normally just verify the file trailer and release temp storage.
  168013. *
  168014. * Returns FALSE if suspended. The return value need be inspected only if
  168015. * a suspending data source is used.
  168016. */
  168017. GLOBAL(boolean)
  168018. jpeg_finish_decompress (j_decompress_ptr cinfo)
  168019. {
  168020. if ((cinfo->global_state == DSTATE_SCANNING ||
  168021. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  168022. /* Terminate final pass of non-buffered mode */
  168023. if (cinfo->output_scanline < cinfo->output_height)
  168024. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  168025. (*cinfo->master->finish_output_pass) (cinfo);
  168026. cinfo->global_state = DSTATE_STOPPING;
  168027. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  168028. /* Finishing after a buffered-image operation */
  168029. cinfo->global_state = DSTATE_STOPPING;
  168030. } else if (cinfo->global_state != DSTATE_STOPPING) {
  168031. /* STOPPING = repeat call after a suspension, anything else is error */
  168032. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168033. }
  168034. /* Read until EOI */
  168035. while (! cinfo->inputctl->eoi_reached) {
  168036. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  168037. return FALSE; /* Suspend, come back later */
  168038. }
  168039. /* Do final cleanup */
  168040. (*cinfo->src->term_source) (cinfo);
  168041. /* We can use jpeg_abort to release memory and reset global_state */
  168042. jpeg_abort((j_common_ptr) cinfo);
  168043. return TRUE;
  168044. }
  168045. /*** End of inlined file: jdapimin.c ***/
  168046. /*** Start of inlined file: jdatasrc.c ***/
  168047. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  168048. /*** Start of inlined file: jerror.h ***/
  168049. /*
  168050. * To define the enum list of message codes, include this file without
  168051. * defining macro JMESSAGE. To create a message string table, include it
  168052. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  168053. */
  168054. #ifndef JMESSAGE
  168055. #ifndef JERROR_H
  168056. /* First time through, define the enum list */
  168057. #define JMAKE_ENUM_LIST
  168058. #else
  168059. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  168060. #define JMESSAGE(code,string)
  168061. #endif /* JERROR_H */
  168062. #endif /* JMESSAGE */
  168063. #ifdef JMAKE_ENUM_LIST
  168064. typedef enum {
  168065. #define JMESSAGE(code,string) code ,
  168066. #endif /* JMAKE_ENUM_LIST */
  168067. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168068. /* For maintenance convenience, list is alphabetical by message code name */
  168069. JMESSAGE(JERR_ARITH_NOTIMPL,
  168070. "Sorry, there are legal restrictions on arithmetic coding")
  168071. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168072. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168073. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168074. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168075. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168076. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168077. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168078. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168079. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168080. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168081. JMESSAGE(JERR_BAD_LIB_VERSION,
  168082. "Wrong JPEG library version: library is %d, caller expects %d")
  168083. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168084. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168085. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168086. JMESSAGE(JERR_BAD_PROGRESSION,
  168087. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168088. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168089. "Invalid progressive parameters at scan script entry %d")
  168090. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168091. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168092. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168093. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168094. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168095. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168096. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168097. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168098. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168099. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168100. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168101. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168102. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168103. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168104. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168105. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168106. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168107. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168108. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168109. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168110. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168111. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168112. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168113. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168114. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168115. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168116. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168117. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168118. "Cannot transcode due to multiple use of quantization table %d")
  168119. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168120. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168121. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168122. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168123. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168124. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168125. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168126. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168127. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168128. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168129. JMESSAGE(JERR_QUANT_COMPONENTS,
  168130. "Cannot quantize more than %d color components")
  168131. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168132. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168133. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168134. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168135. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168136. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168137. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168138. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168139. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168140. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168141. JMESSAGE(JERR_TFILE_WRITE,
  168142. "Write failed on temporary file --- out of disk space?")
  168143. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168144. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168145. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168146. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168147. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168148. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168149. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168150. JMESSAGE(JMSG_VERSION, JVERSION)
  168151. JMESSAGE(JTRC_16BIT_TABLES,
  168152. "Caution: quantization tables are too coarse for baseline JPEG")
  168153. JMESSAGE(JTRC_ADOBE,
  168154. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168155. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168156. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168157. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168158. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168159. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168160. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168161. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168162. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168163. JMESSAGE(JTRC_EOI, "End Of Image")
  168164. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168165. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168166. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168167. "Warning: thumbnail image size does not match data length %u")
  168168. JMESSAGE(JTRC_JFIF_EXTENSION,
  168169. "JFIF extension marker: type 0x%02x, length %u")
  168170. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168171. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168172. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168173. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168174. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168175. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168176. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168177. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168178. JMESSAGE(JTRC_RST, "RST%d")
  168179. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168180. "Smoothing not supported with nonstandard sampling ratios")
  168181. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168182. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168183. JMESSAGE(JTRC_SOI, "Start of Image")
  168184. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168185. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168186. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168187. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168188. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168189. JMESSAGE(JTRC_THUMB_JPEG,
  168190. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168191. JMESSAGE(JTRC_THUMB_PALETTE,
  168192. "JFIF extension marker: palette thumbnail image, length %u")
  168193. JMESSAGE(JTRC_THUMB_RGB,
  168194. "JFIF extension marker: RGB thumbnail image, length %u")
  168195. JMESSAGE(JTRC_UNKNOWN_IDS,
  168196. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168197. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168198. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168199. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168200. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168201. "Inconsistent progression sequence for component %d coefficient %d")
  168202. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168203. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168204. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168205. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168206. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168207. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168208. JMESSAGE(JWRN_MUST_RESYNC,
  168209. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168210. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168211. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168212. #ifdef JMAKE_ENUM_LIST
  168213. JMSG_LASTMSGCODE
  168214. } J_MESSAGE_CODE;
  168215. #undef JMAKE_ENUM_LIST
  168216. #endif /* JMAKE_ENUM_LIST */
  168217. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168218. #undef JMESSAGE
  168219. #ifndef JERROR_H
  168220. #define JERROR_H
  168221. /* Macros to simplify using the error and trace message stuff */
  168222. /* The first parameter is either type of cinfo pointer */
  168223. /* Fatal errors (print message and exit) */
  168224. #define ERREXIT(cinfo,code) \
  168225. ((cinfo)->err->msg_code = (code), \
  168226. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168227. #define ERREXIT1(cinfo,code,p1) \
  168228. ((cinfo)->err->msg_code = (code), \
  168229. (cinfo)->err->msg_parm.i[0] = (p1), \
  168230. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168231. #define ERREXIT2(cinfo,code,p1,p2) \
  168232. ((cinfo)->err->msg_code = (code), \
  168233. (cinfo)->err->msg_parm.i[0] = (p1), \
  168234. (cinfo)->err->msg_parm.i[1] = (p2), \
  168235. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168236. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168237. ((cinfo)->err->msg_code = (code), \
  168238. (cinfo)->err->msg_parm.i[0] = (p1), \
  168239. (cinfo)->err->msg_parm.i[1] = (p2), \
  168240. (cinfo)->err->msg_parm.i[2] = (p3), \
  168241. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168242. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168243. ((cinfo)->err->msg_code = (code), \
  168244. (cinfo)->err->msg_parm.i[0] = (p1), \
  168245. (cinfo)->err->msg_parm.i[1] = (p2), \
  168246. (cinfo)->err->msg_parm.i[2] = (p3), \
  168247. (cinfo)->err->msg_parm.i[3] = (p4), \
  168248. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168249. #define ERREXITS(cinfo,code,str) \
  168250. ((cinfo)->err->msg_code = (code), \
  168251. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168252. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168253. #define MAKESTMT(stuff) do { stuff } while (0)
  168254. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168255. #define WARNMS(cinfo,code) \
  168256. ((cinfo)->err->msg_code = (code), \
  168257. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168258. #define WARNMS1(cinfo,code,p1) \
  168259. ((cinfo)->err->msg_code = (code), \
  168260. (cinfo)->err->msg_parm.i[0] = (p1), \
  168261. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168262. #define WARNMS2(cinfo,code,p1,p2) \
  168263. ((cinfo)->err->msg_code = (code), \
  168264. (cinfo)->err->msg_parm.i[0] = (p1), \
  168265. (cinfo)->err->msg_parm.i[1] = (p2), \
  168266. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168267. /* Informational/debugging messages */
  168268. #define TRACEMS(cinfo,lvl,code) \
  168269. ((cinfo)->err->msg_code = (code), \
  168270. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168271. #define TRACEMS1(cinfo,lvl,code,p1) \
  168272. ((cinfo)->err->msg_code = (code), \
  168273. (cinfo)->err->msg_parm.i[0] = (p1), \
  168274. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168275. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168276. ((cinfo)->err->msg_code = (code), \
  168277. (cinfo)->err->msg_parm.i[0] = (p1), \
  168278. (cinfo)->err->msg_parm.i[1] = (p2), \
  168279. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168280. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168281. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168282. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168283. (cinfo)->err->msg_code = (code); \
  168284. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168285. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168286. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168287. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168288. (cinfo)->err->msg_code = (code); \
  168289. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168290. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168291. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168292. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168293. _mp[4] = (p5); \
  168294. (cinfo)->err->msg_code = (code); \
  168295. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168296. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168297. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168298. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168299. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168300. (cinfo)->err->msg_code = (code); \
  168301. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168302. #define TRACEMSS(cinfo,lvl,code,str) \
  168303. ((cinfo)->err->msg_code = (code), \
  168304. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168305. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168306. #endif /* JERROR_H */
  168307. /*** End of inlined file: jerror.h ***/
  168308. /* Expanded data source object for stdio input */
  168309. typedef struct {
  168310. struct jpeg_source_mgr pub; /* public fields */
  168311. FILE * infile; /* source stream */
  168312. JOCTET * buffer; /* start of buffer */
  168313. boolean start_of_file; /* have we gotten any data yet? */
  168314. } my_source_mgr;
  168315. typedef my_source_mgr * my_src_ptr;
  168316. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168317. /*
  168318. * Initialize source --- called by jpeg_read_header
  168319. * before any data is actually read.
  168320. */
  168321. METHODDEF(void)
  168322. init_source (j_decompress_ptr cinfo)
  168323. {
  168324. my_src_ptr src = (my_src_ptr) cinfo->src;
  168325. /* We reset the empty-input-file flag for each image,
  168326. * but we don't clear the input buffer.
  168327. * This is correct behavior for reading a series of images from one source.
  168328. */
  168329. src->start_of_file = TRUE;
  168330. }
  168331. /*
  168332. * Fill the input buffer --- called whenever buffer is emptied.
  168333. *
  168334. * In typical applications, this should read fresh data into the buffer
  168335. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168336. * reset the pointer & count to the start of the buffer, and return TRUE
  168337. * indicating that the buffer has been reloaded. It is not necessary to
  168338. * fill the buffer entirely, only to obtain at least one more byte.
  168339. *
  168340. * There is no such thing as an EOF return. If the end of the file has been
  168341. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168342. * the buffer. In most cases, generating a warning message and inserting a
  168343. * fake EOI marker is the best course of action --- this will allow the
  168344. * decompressor to output however much of the image is there. However,
  168345. * the resulting error message is misleading if the real problem is an empty
  168346. * input file, so we handle that case specially.
  168347. *
  168348. * In applications that need to be able to suspend compression due to input
  168349. * not being available yet, a FALSE return indicates that no more data can be
  168350. * obtained right now, but more may be forthcoming later. In this situation,
  168351. * the decompressor will return to its caller (with an indication of the
  168352. * number of scanlines it has read, if any). The application should resume
  168353. * decompression after it has loaded more data into the input buffer. Note
  168354. * that there are substantial restrictions on the use of suspension --- see
  168355. * the documentation.
  168356. *
  168357. * When suspending, the decompressor will back up to a convenient restart point
  168358. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168359. * indicate where the restart point will be if the current call returns FALSE.
  168360. * Data beyond this point must be rescanned after resumption, so move it to
  168361. * the front of the buffer rather than discarding it.
  168362. */
  168363. METHODDEF(boolean)
  168364. fill_input_buffer (j_decompress_ptr cinfo)
  168365. {
  168366. my_src_ptr src = (my_src_ptr) cinfo->src;
  168367. size_t nbytes;
  168368. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168369. if (nbytes <= 0) {
  168370. if (src->start_of_file) /* Treat empty input file as fatal error */
  168371. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168372. WARNMS(cinfo, JWRN_JPEG_EOF);
  168373. /* Insert a fake EOI marker */
  168374. src->buffer[0] = (JOCTET) 0xFF;
  168375. src->buffer[1] = (JOCTET) JPEG_EOI;
  168376. nbytes = 2;
  168377. }
  168378. src->pub.next_input_byte = src->buffer;
  168379. src->pub.bytes_in_buffer = nbytes;
  168380. src->start_of_file = FALSE;
  168381. return TRUE;
  168382. }
  168383. /*
  168384. * Skip data --- used to skip over a potentially large amount of
  168385. * uninteresting data (such as an APPn marker).
  168386. *
  168387. * Writers of suspendable-input applications must note that skip_input_data
  168388. * is not granted the right to give a suspension return. If the skip extends
  168389. * beyond the data currently in the buffer, the buffer can be marked empty so
  168390. * that the next read will cause a fill_input_buffer call that can suspend.
  168391. * Arranging for additional bytes to be discarded before reloading the input
  168392. * buffer is the application writer's problem.
  168393. */
  168394. METHODDEF(void)
  168395. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168396. {
  168397. my_src_ptr src = (my_src_ptr) cinfo->src;
  168398. /* Just a dumb implementation for now. Could use fseek() except
  168399. * it doesn't work on pipes. Not clear that being smart is worth
  168400. * any trouble anyway --- large skips are infrequent.
  168401. */
  168402. if (num_bytes > 0) {
  168403. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168404. num_bytes -= (long) src->pub.bytes_in_buffer;
  168405. (void) fill_input_buffer(cinfo);
  168406. /* note we assume that fill_input_buffer will never return FALSE,
  168407. * so suspension need not be handled.
  168408. */
  168409. }
  168410. src->pub.next_input_byte += (size_t) num_bytes;
  168411. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168412. }
  168413. }
  168414. /*
  168415. * An additional method that can be provided by data source modules is the
  168416. * resync_to_restart method for error recovery in the presence of RST markers.
  168417. * For the moment, this source module just uses the default resync method
  168418. * provided by the JPEG library. That method assumes that no backtracking
  168419. * is possible.
  168420. */
  168421. /*
  168422. * Terminate source --- called by jpeg_finish_decompress
  168423. * after all data has been read. Often a no-op.
  168424. *
  168425. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168426. * application must deal with any cleanup that should happen even
  168427. * for error exit.
  168428. */
  168429. METHODDEF(void)
  168430. term_source (j_decompress_ptr)
  168431. {
  168432. /* no work necessary here */
  168433. }
  168434. /*
  168435. * Prepare for input from a stdio stream.
  168436. * The caller must have already opened the stream, and is responsible
  168437. * for closing it after finishing decompression.
  168438. */
  168439. GLOBAL(void)
  168440. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168441. {
  168442. my_src_ptr src;
  168443. /* The source object and input buffer are made permanent so that a series
  168444. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168445. * only before the first one. (If we discarded the buffer at the end of
  168446. * one image, we'd likely lose the start of the next one.)
  168447. * This makes it unsafe to use this manager and a different source
  168448. * manager serially with the same JPEG object. Caveat programmer.
  168449. */
  168450. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168451. cinfo->src = (struct jpeg_source_mgr *)
  168452. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168453. SIZEOF(my_source_mgr));
  168454. src = (my_src_ptr) cinfo->src;
  168455. src->buffer = (JOCTET *)
  168456. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168457. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168458. }
  168459. src = (my_src_ptr) cinfo->src;
  168460. src->pub.init_source = init_source;
  168461. src->pub.fill_input_buffer = fill_input_buffer;
  168462. src->pub.skip_input_data = skip_input_data;
  168463. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168464. src->pub.term_source = term_source;
  168465. src->infile = infile;
  168466. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168467. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168468. }
  168469. /*** End of inlined file: jdatasrc.c ***/
  168470. /*** Start of inlined file: jdcoefct.c ***/
  168471. #define JPEG_INTERNALS
  168472. /* Block smoothing is only applicable for progressive JPEG, so: */
  168473. #ifndef D_PROGRESSIVE_SUPPORTED
  168474. #undef BLOCK_SMOOTHING_SUPPORTED
  168475. #endif
  168476. /* Private buffer controller object */
  168477. typedef struct {
  168478. struct jpeg_d_coef_controller pub; /* public fields */
  168479. /* These variables keep track of the current location of the input side. */
  168480. /* cinfo->input_iMCU_row is also used for this. */
  168481. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168482. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168483. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168484. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168485. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168486. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168487. * and let the entropy decoder write into that workspace each time.
  168488. * (On 80x86, the workspace is FAR even though it's not really very big;
  168489. * this is to keep the module interfaces unchanged when a large coefficient
  168490. * buffer is necessary.)
  168491. * In multi-pass modes, this array points to the current MCU's blocks
  168492. * within the virtual arrays; it is used only by the input side.
  168493. */
  168494. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168495. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168496. /* In multi-pass modes, we need a virtual block array for each component. */
  168497. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168498. #endif
  168499. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168500. /* When doing block smoothing, we latch coefficient Al values here */
  168501. int * coef_bits_latch;
  168502. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168503. #endif
  168504. } my_coef_controller3;
  168505. typedef my_coef_controller3 * my_coef_ptr3;
  168506. /* Forward declarations */
  168507. METHODDEF(int) decompress_onepass
  168508. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168509. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168510. METHODDEF(int) decompress_data
  168511. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168512. #endif
  168513. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168514. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168515. METHODDEF(int) decompress_smooth_data
  168516. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168517. #endif
  168518. LOCAL(void)
  168519. start_iMCU_row3 (j_decompress_ptr cinfo)
  168520. /* Reset within-iMCU-row counters for a new row (input side) */
  168521. {
  168522. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168523. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168524. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168525. * But at the bottom of the image, process only what's left.
  168526. */
  168527. if (cinfo->comps_in_scan > 1) {
  168528. coef->MCU_rows_per_iMCU_row = 1;
  168529. } else {
  168530. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168531. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168532. else
  168533. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168534. }
  168535. coef->MCU_ctr = 0;
  168536. coef->MCU_vert_offset = 0;
  168537. }
  168538. /*
  168539. * Initialize for an input processing pass.
  168540. */
  168541. METHODDEF(void)
  168542. start_input_pass (j_decompress_ptr cinfo)
  168543. {
  168544. cinfo->input_iMCU_row = 0;
  168545. start_iMCU_row3(cinfo);
  168546. }
  168547. /*
  168548. * Initialize for an output processing pass.
  168549. */
  168550. METHODDEF(void)
  168551. start_output_pass (j_decompress_ptr cinfo)
  168552. {
  168553. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168554. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168555. /* If multipass, check to see whether to use block smoothing on this pass */
  168556. if (coef->pub.coef_arrays != NULL) {
  168557. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168558. coef->pub.decompress_data = decompress_smooth_data;
  168559. else
  168560. coef->pub.decompress_data = decompress_data;
  168561. }
  168562. #endif
  168563. cinfo->output_iMCU_row = 0;
  168564. }
  168565. /*
  168566. * Decompress and return some data in the single-pass case.
  168567. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168568. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168569. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168570. *
  168571. * NB: output_buf contains a plane for each component in image,
  168572. * which we index according to the component's SOF position.
  168573. */
  168574. METHODDEF(int)
  168575. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168576. {
  168577. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168578. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168579. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168580. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168581. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168582. JSAMPARRAY output_ptr;
  168583. JDIMENSION start_col, output_col;
  168584. jpeg_component_info *compptr;
  168585. inverse_DCT_method_ptr inverse_DCT;
  168586. /* Loop to process as much as one whole iMCU row */
  168587. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168588. yoffset++) {
  168589. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168590. MCU_col_num++) {
  168591. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168592. jzero_far((void FAR *) coef->MCU_buffer[0],
  168593. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168594. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168595. /* Suspension forced; update state counters and exit */
  168596. coef->MCU_vert_offset = yoffset;
  168597. coef->MCU_ctr = MCU_col_num;
  168598. return JPEG_SUSPENDED;
  168599. }
  168600. /* Determine where data should go in output_buf and do the IDCT thing.
  168601. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168602. * incremented past them!). Note the inner loop relies on having
  168603. * allocated the MCU_buffer[] blocks sequentially.
  168604. */
  168605. blkn = 0; /* index of current DCT block within MCU */
  168606. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168607. compptr = cinfo->cur_comp_info[ci];
  168608. /* Don't bother to IDCT an uninteresting component. */
  168609. if (! compptr->component_needed) {
  168610. blkn += compptr->MCU_blocks;
  168611. continue;
  168612. }
  168613. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168614. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168615. : compptr->last_col_width;
  168616. output_ptr = output_buf[compptr->component_index] +
  168617. yoffset * compptr->DCT_scaled_size;
  168618. start_col = MCU_col_num * compptr->MCU_sample_width;
  168619. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168620. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168621. yoffset+yindex < compptr->last_row_height) {
  168622. output_col = start_col;
  168623. for (xindex = 0; xindex < useful_width; xindex++) {
  168624. (*inverse_DCT) (cinfo, compptr,
  168625. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168626. output_ptr, output_col);
  168627. output_col += compptr->DCT_scaled_size;
  168628. }
  168629. }
  168630. blkn += compptr->MCU_width;
  168631. output_ptr += compptr->DCT_scaled_size;
  168632. }
  168633. }
  168634. }
  168635. /* Completed an MCU row, but perhaps not an iMCU row */
  168636. coef->MCU_ctr = 0;
  168637. }
  168638. /* Completed the iMCU row, advance counters for next one */
  168639. cinfo->output_iMCU_row++;
  168640. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168641. start_iMCU_row3(cinfo);
  168642. return JPEG_ROW_COMPLETED;
  168643. }
  168644. /* Completed the scan */
  168645. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168646. return JPEG_SCAN_COMPLETED;
  168647. }
  168648. /*
  168649. * Dummy consume-input routine for single-pass operation.
  168650. */
  168651. METHODDEF(int)
  168652. dummy_consume_data (j_decompress_ptr)
  168653. {
  168654. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168655. }
  168656. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168657. /*
  168658. * Consume input data and store it in the full-image coefficient buffer.
  168659. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168660. * ie, v_samp_factor block rows for each component in the scan.
  168661. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168662. */
  168663. METHODDEF(int)
  168664. consume_data (j_decompress_ptr cinfo)
  168665. {
  168666. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168667. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168668. int blkn, ci, xindex, yindex, yoffset;
  168669. JDIMENSION start_col;
  168670. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168671. JBLOCKROW buffer_ptr;
  168672. jpeg_component_info *compptr;
  168673. /* Align the virtual buffers for the components used in this scan. */
  168674. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168675. compptr = cinfo->cur_comp_info[ci];
  168676. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168677. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168678. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168679. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168680. /* Note: entropy decoder expects buffer to be zeroed,
  168681. * but this is handled automatically by the memory manager
  168682. * because we requested a pre-zeroed array.
  168683. */
  168684. }
  168685. /* Loop to process one whole iMCU row */
  168686. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168687. yoffset++) {
  168688. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168689. MCU_col_num++) {
  168690. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168691. blkn = 0; /* index of current DCT block within MCU */
  168692. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168693. compptr = cinfo->cur_comp_info[ci];
  168694. start_col = MCU_col_num * compptr->MCU_width;
  168695. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168696. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168697. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168698. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168699. }
  168700. }
  168701. }
  168702. /* Try to fetch the MCU. */
  168703. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168704. /* Suspension forced; update state counters and exit */
  168705. coef->MCU_vert_offset = yoffset;
  168706. coef->MCU_ctr = MCU_col_num;
  168707. return JPEG_SUSPENDED;
  168708. }
  168709. }
  168710. /* Completed an MCU row, but perhaps not an iMCU row */
  168711. coef->MCU_ctr = 0;
  168712. }
  168713. /* Completed the iMCU row, advance counters for next one */
  168714. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168715. start_iMCU_row3(cinfo);
  168716. return JPEG_ROW_COMPLETED;
  168717. }
  168718. /* Completed the scan */
  168719. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168720. return JPEG_SCAN_COMPLETED;
  168721. }
  168722. /*
  168723. * Decompress and return some data in the multi-pass case.
  168724. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168725. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168726. *
  168727. * NB: output_buf contains a plane for each component in image.
  168728. */
  168729. METHODDEF(int)
  168730. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168731. {
  168732. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168733. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168734. JDIMENSION block_num;
  168735. int ci, block_row, block_rows;
  168736. JBLOCKARRAY buffer;
  168737. JBLOCKROW buffer_ptr;
  168738. JSAMPARRAY output_ptr;
  168739. JDIMENSION output_col;
  168740. jpeg_component_info *compptr;
  168741. inverse_DCT_method_ptr inverse_DCT;
  168742. /* Force some input to be done if we are getting ahead of the input. */
  168743. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168744. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168745. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168746. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168747. return JPEG_SUSPENDED;
  168748. }
  168749. /* OK, output from the virtual arrays. */
  168750. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168751. ci++, compptr++) {
  168752. /* Don't bother to IDCT an uninteresting component. */
  168753. if (! compptr->component_needed)
  168754. continue;
  168755. /* Align the virtual buffer for this component. */
  168756. buffer = (*cinfo->mem->access_virt_barray)
  168757. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168758. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168759. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168760. /* Count non-dummy DCT block rows in this iMCU row. */
  168761. if (cinfo->output_iMCU_row < last_iMCU_row)
  168762. block_rows = compptr->v_samp_factor;
  168763. else {
  168764. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168765. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168766. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168767. }
  168768. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168769. output_ptr = output_buf[ci];
  168770. /* Loop over all DCT blocks to be processed. */
  168771. for (block_row = 0; block_row < block_rows; block_row++) {
  168772. buffer_ptr = buffer[block_row];
  168773. output_col = 0;
  168774. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168775. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168776. output_ptr, output_col);
  168777. buffer_ptr++;
  168778. output_col += compptr->DCT_scaled_size;
  168779. }
  168780. output_ptr += compptr->DCT_scaled_size;
  168781. }
  168782. }
  168783. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168784. return JPEG_ROW_COMPLETED;
  168785. return JPEG_SCAN_COMPLETED;
  168786. }
  168787. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168788. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168789. /*
  168790. * This code applies interblock smoothing as described by section K.8
  168791. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168792. * the DC values of a DCT block and its 8 neighboring blocks.
  168793. * We apply smoothing only for progressive JPEG decoding, and only if
  168794. * the coefficients it can estimate are not yet known to full precision.
  168795. */
  168796. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168797. #define Q01_POS 1
  168798. #define Q10_POS 8
  168799. #define Q20_POS 16
  168800. #define Q11_POS 9
  168801. #define Q02_POS 2
  168802. /*
  168803. * Determine whether block smoothing is applicable and safe.
  168804. * We also latch the current states of the coef_bits[] entries for the
  168805. * AC coefficients; otherwise, if the input side of the decompressor
  168806. * advances into a new scan, we might think the coefficients are known
  168807. * more accurately than they really are.
  168808. */
  168809. LOCAL(boolean)
  168810. smoothing_ok (j_decompress_ptr cinfo)
  168811. {
  168812. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168813. boolean smoothing_useful = FALSE;
  168814. int ci, coefi;
  168815. jpeg_component_info *compptr;
  168816. JQUANT_TBL * qtable;
  168817. int * coef_bits;
  168818. int * coef_bits_latch;
  168819. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168820. return FALSE;
  168821. /* Allocate latch area if not already done */
  168822. if (coef->coef_bits_latch == NULL)
  168823. coef->coef_bits_latch = (int *)
  168824. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168825. cinfo->num_components *
  168826. (SAVED_COEFS * SIZEOF(int)));
  168827. coef_bits_latch = coef->coef_bits_latch;
  168828. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168829. ci++, compptr++) {
  168830. /* All components' quantization values must already be latched. */
  168831. if ((qtable = compptr->quant_table) == NULL)
  168832. return FALSE;
  168833. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168834. if (qtable->quantval[0] == 0 ||
  168835. qtable->quantval[Q01_POS] == 0 ||
  168836. qtable->quantval[Q10_POS] == 0 ||
  168837. qtable->quantval[Q20_POS] == 0 ||
  168838. qtable->quantval[Q11_POS] == 0 ||
  168839. qtable->quantval[Q02_POS] == 0)
  168840. return FALSE;
  168841. /* DC values must be at least partly known for all components. */
  168842. coef_bits = cinfo->coef_bits[ci];
  168843. if (coef_bits[0] < 0)
  168844. return FALSE;
  168845. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168846. for (coefi = 1; coefi <= 5; coefi++) {
  168847. coef_bits_latch[coefi] = coef_bits[coefi];
  168848. if (coef_bits[coefi] != 0)
  168849. smoothing_useful = TRUE;
  168850. }
  168851. coef_bits_latch += SAVED_COEFS;
  168852. }
  168853. return smoothing_useful;
  168854. }
  168855. /*
  168856. * Variant of decompress_data for use when doing block smoothing.
  168857. */
  168858. METHODDEF(int)
  168859. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168860. {
  168861. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168862. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168863. JDIMENSION block_num, last_block_column;
  168864. int ci, block_row, block_rows, access_rows;
  168865. JBLOCKARRAY buffer;
  168866. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168867. JSAMPARRAY output_ptr;
  168868. JDIMENSION output_col;
  168869. jpeg_component_info *compptr;
  168870. inverse_DCT_method_ptr inverse_DCT;
  168871. boolean first_row, last_row;
  168872. JBLOCK workspace;
  168873. int *coef_bits;
  168874. JQUANT_TBL *quanttbl;
  168875. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168876. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168877. int Al, pred;
  168878. /* Force some input to be done if we are getting ahead of the input. */
  168879. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168880. ! cinfo->inputctl->eoi_reached) {
  168881. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168882. /* If input is working on current scan, we ordinarily want it to
  168883. * have completed the current row. But if input scan is DC,
  168884. * we want it to keep one row ahead so that next block row's DC
  168885. * values are up to date.
  168886. */
  168887. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168888. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168889. break;
  168890. }
  168891. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168892. return JPEG_SUSPENDED;
  168893. }
  168894. /* OK, output from the virtual arrays. */
  168895. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168896. ci++, compptr++) {
  168897. /* Don't bother to IDCT an uninteresting component. */
  168898. if (! compptr->component_needed)
  168899. continue;
  168900. /* Count non-dummy DCT block rows in this iMCU row. */
  168901. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168902. block_rows = compptr->v_samp_factor;
  168903. access_rows = block_rows * 2; /* this and next iMCU row */
  168904. last_row = FALSE;
  168905. } else {
  168906. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168907. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168908. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168909. access_rows = block_rows; /* this iMCU row only */
  168910. last_row = TRUE;
  168911. }
  168912. /* Align the virtual buffer for this component. */
  168913. if (cinfo->output_iMCU_row > 0) {
  168914. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168915. buffer = (*cinfo->mem->access_virt_barray)
  168916. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168917. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168918. (JDIMENSION) access_rows, FALSE);
  168919. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168920. first_row = FALSE;
  168921. } else {
  168922. buffer = (*cinfo->mem->access_virt_barray)
  168923. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168924. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168925. first_row = TRUE;
  168926. }
  168927. /* Fetch component-dependent info */
  168928. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168929. quanttbl = compptr->quant_table;
  168930. Q00 = quanttbl->quantval[0];
  168931. Q01 = quanttbl->quantval[Q01_POS];
  168932. Q10 = quanttbl->quantval[Q10_POS];
  168933. Q20 = quanttbl->quantval[Q20_POS];
  168934. Q11 = quanttbl->quantval[Q11_POS];
  168935. Q02 = quanttbl->quantval[Q02_POS];
  168936. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168937. output_ptr = output_buf[ci];
  168938. /* Loop over all DCT blocks to be processed. */
  168939. for (block_row = 0; block_row < block_rows; block_row++) {
  168940. buffer_ptr = buffer[block_row];
  168941. if (first_row && block_row == 0)
  168942. prev_block_row = buffer_ptr;
  168943. else
  168944. prev_block_row = buffer[block_row-1];
  168945. if (last_row && block_row == block_rows-1)
  168946. next_block_row = buffer_ptr;
  168947. else
  168948. next_block_row = buffer[block_row+1];
  168949. /* We fetch the surrounding DC values using a sliding-register approach.
  168950. * Initialize all nine here so as to do the right thing on narrow pics.
  168951. */
  168952. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168953. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168954. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168955. output_col = 0;
  168956. last_block_column = compptr->width_in_blocks - 1;
  168957. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168958. /* Fetch current DCT block into workspace so we can modify it. */
  168959. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168960. /* Update DC values */
  168961. if (block_num < last_block_column) {
  168962. DC3 = (int) prev_block_row[1][0];
  168963. DC6 = (int) buffer_ptr[1][0];
  168964. DC9 = (int) next_block_row[1][0];
  168965. }
  168966. /* Compute coefficient estimates per K.8.
  168967. * An estimate is applied only if coefficient is still zero,
  168968. * and is not known to be fully accurate.
  168969. */
  168970. /* AC01 */
  168971. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168972. num = 36 * Q00 * (DC4 - DC6);
  168973. if (num >= 0) {
  168974. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168975. if (Al > 0 && pred >= (1<<Al))
  168976. pred = (1<<Al)-1;
  168977. } else {
  168978. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168979. if (Al > 0 && pred >= (1<<Al))
  168980. pred = (1<<Al)-1;
  168981. pred = -pred;
  168982. }
  168983. workspace[1] = (JCOEF) pred;
  168984. }
  168985. /* AC10 */
  168986. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168987. num = 36 * Q00 * (DC2 - DC8);
  168988. if (num >= 0) {
  168989. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168990. if (Al > 0 && pred >= (1<<Al))
  168991. pred = (1<<Al)-1;
  168992. } else {
  168993. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168994. if (Al > 0 && pred >= (1<<Al))
  168995. pred = (1<<Al)-1;
  168996. pred = -pred;
  168997. }
  168998. workspace[8] = (JCOEF) pred;
  168999. }
  169000. /* AC20 */
  169001. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  169002. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  169003. if (num >= 0) {
  169004. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  169005. if (Al > 0 && pred >= (1<<Al))
  169006. pred = (1<<Al)-1;
  169007. } else {
  169008. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  169009. if (Al > 0 && pred >= (1<<Al))
  169010. pred = (1<<Al)-1;
  169011. pred = -pred;
  169012. }
  169013. workspace[16] = (JCOEF) pred;
  169014. }
  169015. /* AC11 */
  169016. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  169017. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  169018. if (num >= 0) {
  169019. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  169020. if (Al > 0 && pred >= (1<<Al))
  169021. pred = (1<<Al)-1;
  169022. } else {
  169023. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  169024. if (Al > 0 && pred >= (1<<Al))
  169025. pred = (1<<Al)-1;
  169026. pred = -pred;
  169027. }
  169028. workspace[9] = (JCOEF) pred;
  169029. }
  169030. /* AC02 */
  169031. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  169032. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  169033. if (num >= 0) {
  169034. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  169035. if (Al > 0 && pred >= (1<<Al))
  169036. pred = (1<<Al)-1;
  169037. } else {
  169038. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  169039. if (Al > 0 && pred >= (1<<Al))
  169040. pred = (1<<Al)-1;
  169041. pred = -pred;
  169042. }
  169043. workspace[2] = (JCOEF) pred;
  169044. }
  169045. /* OK, do the IDCT */
  169046. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  169047. output_ptr, output_col);
  169048. /* Advance for next column */
  169049. DC1 = DC2; DC2 = DC3;
  169050. DC4 = DC5; DC5 = DC6;
  169051. DC7 = DC8; DC8 = DC9;
  169052. buffer_ptr++, prev_block_row++, next_block_row++;
  169053. output_col += compptr->DCT_scaled_size;
  169054. }
  169055. output_ptr += compptr->DCT_scaled_size;
  169056. }
  169057. }
  169058. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169059. return JPEG_ROW_COMPLETED;
  169060. return JPEG_SCAN_COMPLETED;
  169061. }
  169062. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169063. /*
  169064. * Initialize coefficient buffer controller.
  169065. */
  169066. GLOBAL(void)
  169067. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169068. {
  169069. my_coef_ptr3 coef;
  169070. coef = (my_coef_ptr3)
  169071. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169072. SIZEOF(my_coef_controller3));
  169073. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169074. coef->pub.start_input_pass = start_input_pass;
  169075. coef->pub.start_output_pass = start_output_pass;
  169076. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169077. coef->coef_bits_latch = NULL;
  169078. #endif
  169079. /* Create the coefficient buffer. */
  169080. if (need_full_buffer) {
  169081. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169082. /* Allocate a full-image virtual array for each component, */
  169083. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169084. /* Note we ask for a pre-zeroed array. */
  169085. int ci, access_rows;
  169086. jpeg_component_info *compptr;
  169087. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169088. ci++, compptr++) {
  169089. access_rows = compptr->v_samp_factor;
  169090. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169091. /* If block smoothing could be used, need a bigger window */
  169092. if (cinfo->progressive_mode)
  169093. access_rows *= 3;
  169094. #endif
  169095. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169096. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169097. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169098. (long) compptr->h_samp_factor),
  169099. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169100. (long) compptr->v_samp_factor),
  169101. (JDIMENSION) access_rows);
  169102. }
  169103. coef->pub.consume_data = consume_data;
  169104. coef->pub.decompress_data = decompress_data;
  169105. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169106. #else
  169107. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169108. #endif
  169109. } else {
  169110. /* We only need a single-MCU buffer. */
  169111. JBLOCKROW buffer;
  169112. int i;
  169113. buffer = (JBLOCKROW)
  169114. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169115. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169116. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169117. coef->MCU_buffer[i] = buffer + i;
  169118. }
  169119. coef->pub.consume_data = dummy_consume_data;
  169120. coef->pub.decompress_data = decompress_onepass;
  169121. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169122. }
  169123. }
  169124. /*** End of inlined file: jdcoefct.c ***/
  169125. #undef FIX
  169126. /*** Start of inlined file: jdcolor.c ***/
  169127. #define JPEG_INTERNALS
  169128. /* Private subobject */
  169129. typedef struct {
  169130. struct jpeg_color_deconverter pub; /* public fields */
  169131. /* Private state for YCC->RGB conversion */
  169132. int * Cr_r_tab; /* => table for Cr to R conversion */
  169133. int * Cb_b_tab; /* => table for Cb to B conversion */
  169134. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169135. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169136. } my_color_deconverter2;
  169137. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169138. /**************** YCbCr -> RGB conversion: most common case **************/
  169139. /*
  169140. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169141. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169142. * The conversion equations to be implemented are therefore
  169143. * R = Y + 1.40200 * Cr
  169144. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169145. * B = Y + 1.77200 * Cb
  169146. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169147. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169148. *
  169149. * To avoid floating-point arithmetic, we represent the fractional constants
  169150. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169151. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169152. * Notice that Y, being an integral input, does not contribute any fraction
  169153. * so it need not participate in the rounding.
  169154. *
  169155. * For even more speed, we avoid doing any multiplications in the inner loop
  169156. * by precalculating the constants times Cb and Cr for all possible values.
  169157. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169158. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169159. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169160. * colorspace anyway.
  169161. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169162. * values for the G calculation are left scaled up, since we must add them
  169163. * together before rounding.
  169164. */
  169165. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169166. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169167. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169168. /*
  169169. * Initialize tables for YCC->RGB colorspace conversion.
  169170. */
  169171. LOCAL(void)
  169172. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169173. {
  169174. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169175. int i;
  169176. INT32 x;
  169177. SHIFT_TEMPS
  169178. cconvert->Cr_r_tab = (int *)
  169179. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169180. (MAXJSAMPLE+1) * SIZEOF(int));
  169181. cconvert->Cb_b_tab = (int *)
  169182. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169183. (MAXJSAMPLE+1) * SIZEOF(int));
  169184. cconvert->Cr_g_tab = (INT32 *)
  169185. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169186. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169187. cconvert->Cb_g_tab = (INT32 *)
  169188. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169189. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169190. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169191. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169192. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169193. /* Cr=>R value is nearest int to 1.40200 * x */
  169194. cconvert->Cr_r_tab[i] = (int)
  169195. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169196. /* Cb=>B value is nearest int to 1.77200 * x */
  169197. cconvert->Cb_b_tab[i] = (int)
  169198. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169199. /* Cr=>G value is scaled-up -0.71414 * x */
  169200. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169201. /* Cb=>G value is scaled-up -0.34414 * x */
  169202. /* We also add in ONE_HALF so that need not do it in inner loop */
  169203. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169204. }
  169205. }
  169206. /*
  169207. * Convert some rows of samples to the output colorspace.
  169208. *
  169209. * Note that we change from noninterleaved, one-plane-per-component format
  169210. * to interleaved-pixel format. The output buffer is therefore three times
  169211. * as wide as the input buffer.
  169212. * A starting row offset is provided only for the input buffer. The caller
  169213. * can easily adjust the passed output_buf value to accommodate any row
  169214. * offset required on that side.
  169215. */
  169216. METHODDEF(void)
  169217. ycc_rgb_convert (j_decompress_ptr cinfo,
  169218. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169219. JSAMPARRAY output_buf, int num_rows)
  169220. {
  169221. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169222. register int y, cb, cr;
  169223. register JSAMPROW outptr;
  169224. register JSAMPROW inptr0, inptr1, inptr2;
  169225. register JDIMENSION col;
  169226. JDIMENSION num_cols = cinfo->output_width;
  169227. /* copy these pointers into registers if possible */
  169228. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169229. register int * Crrtab = cconvert->Cr_r_tab;
  169230. register int * Cbbtab = cconvert->Cb_b_tab;
  169231. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169232. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169233. SHIFT_TEMPS
  169234. while (--num_rows >= 0) {
  169235. inptr0 = input_buf[0][input_row];
  169236. inptr1 = input_buf[1][input_row];
  169237. inptr2 = input_buf[2][input_row];
  169238. input_row++;
  169239. outptr = *output_buf++;
  169240. for (col = 0; col < num_cols; col++) {
  169241. y = GETJSAMPLE(inptr0[col]);
  169242. cb = GETJSAMPLE(inptr1[col]);
  169243. cr = GETJSAMPLE(inptr2[col]);
  169244. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169245. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169246. outptr[RGB_GREEN] = range_limit[y +
  169247. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169248. SCALEBITS))];
  169249. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169250. outptr += RGB_PIXELSIZE;
  169251. }
  169252. }
  169253. }
  169254. /**************** Cases other than YCbCr -> RGB **************/
  169255. /*
  169256. * Color conversion for no colorspace change: just copy the data,
  169257. * converting from separate-planes to interleaved representation.
  169258. */
  169259. METHODDEF(void)
  169260. null_convert2 (j_decompress_ptr cinfo,
  169261. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169262. JSAMPARRAY output_buf, int num_rows)
  169263. {
  169264. register JSAMPROW inptr, outptr;
  169265. register JDIMENSION count;
  169266. register int num_components = cinfo->num_components;
  169267. JDIMENSION num_cols = cinfo->output_width;
  169268. int ci;
  169269. while (--num_rows >= 0) {
  169270. for (ci = 0; ci < num_components; ci++) {
  169271. inptr = input_buf[ci][input_row];
  169272. outptr = output_buf[0] + ci;
  169273. for (count = num_cols; count > 0; count--) {
  169274. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169275. outptr += num_components;
  169276. }
  169277. }
  169278. input_row++;
  169279. output_buf++;
  169280. }
  169281. }
  169282. /*
  169283. * Color conversion for grayscale: just copy the data.
  169284. * This also works for YCbCr -> grayscale conversion, in which
  169285. * we just copy the Y (luminance) component and ignore chrominance.
  169286. */
  169287. METHODDEF(void)
  169288. grayscale_convert2 (j_decompress_ptr cinfo,
  169289. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169290. JSAMPARRAY output_buf, int num_rows)
  169291. {
  169292. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169293. num_rows, cinfo->output_width);
  169294. }
  169295. /*
  169296. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169297. * This is provided to support applications that don't want to cope
  169298. * with grayscale as a separate case.
  169299. */
  169300. METHODDEF(void)
  169301. gray_rgb_convert (j_decompress_ptr cinfo,
  169302. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169303. JSAMPARRAY output_buf, int num_rows)
  169304. {
  169305. register JSAMPROW inptr, outptr;
  169306. register JDIMENSION col;
  169307. JDIMENSION num_cols = cinfo->output_width;
  169308. while (--num_rows >= 0) {
  169309. inptr = input_buf[0][input_row++];
  169310. outptr = *output_buf++;
  169311. for (col = 0; col < num_cols; col++) {
  169312. /* We can dispense with GETJSAMPLE() here */
  169313. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169314. outptr += RGB_PIXELSIZE;
  169315. }
  169316. }
  169317. }
  169318. /*
  169319. * Adobe-style YCCK->CMYK conversion.
  169320. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169321. * conversion as above, while passing K (black) unchanged.
  169322. * We assume build_ycc_rgb_table has been called.
  169323. */
  169324. METHODDEF(void)
  169325. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169326. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169327. JSAMPARRAY output_buf, int num_rows)
  169328. {
  169329. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169330. register int y, cb, cr;
  169331. register JSAMPROW outptr;
  169332. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169333. register JDIMENSION col;
  169334. JDIMENSION num_cols = cinfo->output_width;
  169335. /* copy these pointers into registers if possible */
  169336. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169337. register int * Crrtab = cconvert->Cr_r_tab;
  169338. register int * Cbbtab = cconvert->Cb_b_tab;
  169339. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169340. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169341. SHIFT_TEMPS
  169342. while (--num_rows >= 0) {
  169343. inptr0 = input_buf[0][input_row];
  169344. inptr1 = input_buf[1][input_row];
  169345. inptr2 = input_buf[2][input_row];
  169346. inptr3 = input_buf[3][input_row];
  169347. input_row++;
  169348. outptr = *output_buf++;
  169349. for (col = 0; col < num_cols; col++) {
  169350. y = GETJSAMPLE(inptr0[col]);
  169351. cb = GETJSAMPLE(inptr1[col]);
  169352. cr = GETJSAMPLE(inptr2[col]);
  169353. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169354. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169355. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169356. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169357. SCALEBITS)))];
  169358. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169359. /* K passes through unchanged */
  169360. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169361. outptr += 4;
  169362. }
  169363. }
  169364. }
  169365. /*
  169366. * Empty method for start_pass.
  169367. */
  169368. METHODDEF(void)
  169369. start_pass_dcolor (j_decompress_ptr)
  169370. {
  169371. /* no work needed */
  169372. }
  169373. /*
  169374. * Module initialization routine for output colorspace conversion.
  169375. */
  169376. GLOBAL(void)
  169377. jinit_color_deconverter (j_decompress_ptr cinfo)
  169378. {
  169379. my_cconvert_ptr2 cconvert;
  169380. int ci;
  169381. cconvert = (my_cconvert_ptr2)
  169382. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169383. SIZEOF(my_color_deconverter2));
  169384. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169385. cconvert->pub.start_pass = start_pass_dcolor;
  169386. /* Make sure num_components agrees with jpeg_color_space */
  169387. switch (cinfo->jpeg_color_space) {
  169388. case JCS_GRAYSCALE:
  169389. if (cinfo->num_components != 1)
  169390. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169391. break;
  169392. case JCS_RGB:
  169393. case JCS_YCbCr:
  169394. if (cinfo->num_components != 3)
  169395. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169396. break;
  169397. case JCS_CMYK:
  169398. case JCS_YCCK:
  169399. if (cinfo->num_components != 4)
  169400. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169401. break;
  169402. default: /* JCS_UNKNOWN can be anything */
  169403. if (cinfo->num_components < 1)
  169404. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169405. break;
  169406. }
  169407. /* Set out_color_components and conversion method based on requested space.
  169408. * Also clear the component_needed flags for any unused components,
  169409. * so that earlier pipeline stages can avoid useless computation.
  169410. */
  169411. switch (cinfo->out_color_space) {
  169412. case JCS_GRAYSCALE:
  169413. cinfo->out_color_components = 1;
  169414. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169415. cinfo->jpeg_color_space == JCS_YCbCr) {
  169416. cconvert->pub.color_convert = grayscale_convert2;
  169417. /* For color->grayscale conversion, only the Y (0) component is needed */
  169418. for (ci = 1; ci < cinfo->num_components; ci++)
  169419. cinfo->comp_info[ci].component_needed = FALSE;
  169420. } else
  169421. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169422. break;
  169423. case JCS_RGB:
  169424. cinfo->out_color_components = RGB_PIXELSIZE;
  169425. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169426. cconvert->pub.color_convert = ycc_rgb_convert;
  169427. build_ycc_rgb_table(cinfo);
  169428. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169429. cconvert->pub.color_convert = gray_rgb_convert;
  169430. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169431. cconvert->pub.color_convert = null_convert2;
  169432. } else
  169433. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169434. break;
  169435. case JCS_CMYK:
  169436. cinfo->out_color_components = 4;
  169437. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169438. cconvert->pub.color_convert = ycck_cmyk_convert;
  169439. build_ycc_rgb_table(cinfo);
  169440. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169441. cconvert->pub.color_convert = null_convert2;
  169442. } else
  169443. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169444. break;
  169445. default:
  169446. /* Permit null conversion to same output space */
  169447. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169448. cinfo->out_color_components = cinfo->num_components;
  169449. cconvert->pub.color_convert = null_convert2;
  169450. } else /* unsupported non-null conversion */
  169451. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169452. break;
  169453. }
  169454. if (cinfo->quantize_colors)
  169455. cinfo->output_components = 1; /* single colormapped output component */
  169456. else
  169457. cinfo->output_components = cinfo->out_color_components;
  169458. }
  169459. /*** End of inlined file: jdcolor.c ***/
  169460. #undef FIX
  169461. /*** Start of inlined file: jddctmgr.c ***/
  169462. #define JPEG_INTERNALS
  169463. /*
  169464. * The decompressor input side (jdinput.c) saves away the appropriate
  169465. * quantization table for each component at the start of the first scan
  169466. * involving that component. (This is necessary in order to correctly
  169467. * decode files that reuse Q-table slots.)
  169468. * When we are ready to make an output pass, the saved Q-table is converted
  169469. * to a multiplier table that will actually be used by the IDCT routine.
  169470. * The multiplier table contents are IDCT-method-dependent. To support
  169471. * application changes in IDCT method between scans, we can remake the
  169472. * multiplier tables if necessary.
  169473. * In buffered-image mode, the first output pass may occur before any data
  169474. * has been seen for some components, and thus before their Q-tables have
  169475. * been saved away. To handle this case, multiplier tables are preset
  169476. * to zeroes; the result of the IDCT will be a neutral gray level.
  169477. */
  169478. /* Private subobject for this module */
  169479. typedef struct {
  169480. struct jpeg_inverse_dct pub; /* public fields */
  169481. /* This array contains the IDCT method code that each multiplier table
  169482. * is currently set up for, or -1 if it's not yet set up.
  169483. * The actual multiplier tables are pointed to by dct_table in the
  169484. * per-component comp_info structures.
  169485. */
  169486. int cur_method[MAX_COMPONENTS];
  169487. } my_idct_controller;
  169488. typedef my_idct_controller * my_idct_ptr;
  169489. /* Allocated multiplier tables: big enough for any supported variant */
  169490. typedef union {
  169491. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169492. #ifdef DCT_IFAST_SUPPORTED
  169493. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169494. #endif
  169495. #ifdef DCT_FLOAT_SUPPORTED
  169496. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169497. #endif
  169498. } multiplier_table;
  169499. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169500. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169501. */
  169502. #ifdef DCT_ISLOW_SUPPORTED
  169503. #define PROVIDE_ISLOW_TABLES
  169504. #else
  169505. #ifdef IDCT_SCALING_SUPPORTED
  169506. #define PROVIDE_ISLOW_TABLES
  169507. #endif
  169508. #endif
  169509. /*
  169510. * Prepare for an output pass.
  169511. * Here we select the proper IDCT routine for each component and build
  169512. * a matching multiplier table.
  169513. */
  169514. METHODDEF(void)
  169515. start_pass (j_decompress_ptr cinfo)
  169516. {
  169517. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169518. int ci, i;
  169519. jpeg_component_info *compptr;
  169520. int method = 0;
  169521. inverse_DCT_method_ptr method_ptr = NULL;
  169522. JQUANT_TBL * qtbl;
  169523. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169524. ci++, compptr++) {
  169525. /* Select the proper IDCT routine for this component's scaling */
  169526. switch (compptr->DCT_scaled_size) {
  169527. #ifdef IDCT_SCALING_SUPPORTED
  169528. case 1:
  169529. method_ptr = jpeg_idct_1x1;
  169530. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169531. break;
  169532. case 2:
  169533. method_ptr = jpeg_idct_2x2;
  169534. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169535. break;
  169536. case 4:
  169537. method_ptr = jpeg_idct_4x4;
  169538. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169539. break;
  169540. #endif
  169541. case DCTSIZE:
  169542. switch (cinfo->dct_method) {
  169543. #ifdef DCT_ISLOW_SUPPORTED
  169544. case JDCT_ISLOW:
  169545. method_ptr = jpeg_idct_islow;
  169546. method = JDCT_ISLOW;
  169547. break;
  169548. #endif
  169549. #ifdef DCT_IFAST_SUPPORTED
  169550. case JDCT_IFAST:
  169551. method_ptr = jpeg_idct_ifast;
  169552. method = JDCT_IFAST;
  169553. break;
  169554. #endif
  169555. #ifdef DCT_FLOAT_SUPPORTED
  169556. case JDCT_FLOAT:
  169557. method_ptr = jpeg_idct_float;
  169558. method = JDCT_FLOAT;
  169559. break;
  169560. #endif
  169561. default:
  169562. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169563. break;
  169564. }
  169565. break;
  169566. default:
  169567. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169568. break;
  169569. }
  169570. idct->pub.inverse_DCT[ci] = method_ptr;
  169571. /* Create multiplier table from quant table.
  169572. * However, we can skip this if the component is uninteresting
  169573. * or if we already built the table. Also, if no quant table
  169574. * has yet been saved for the component, we leave the
  169575. * multiplier table all-zero; we'll be reading zeroes from the
  169576. * coefficient controller's buffer anyway.
  169577. */
  169578. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169579. continue;
  169580. qtbl = compptr->quant_table;
  169581. if (qtbl == NULL) /* happens if no data yet for component */
  169582. continue;
  169583. idct->cur_method[ci] = method;
  169584. switch (method) {
  169585. #ifdef PROVIDE_ISLOW_TABLES
  169586. case JDCT_ISLOW:
  169587. {
  169588. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169589. * coefficients, but are stored as ints to ensure access efficiency.
  169590. */
  169591. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169592. for (i = 0; i < DCTSIZE2; i++) {
  169593. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169594. }
  169595. }
  169596. break;
  169597. #endif
  169598. #ifdef DCT_IFAST_SUPPORTED
  169599. case JDCT_IFAST:
  169600. {
  169601. /* For AA&N IDCT method, multipliers are equal to quantization
  169602. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169603. * scalefactor[0] = 1
  169604. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169605. * For integer operation, the multiplier table is to be scaled by
  169606. * IFAST_SCALE_BITS.
  169607. */
  169608. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169609. #define CONST_BITS 14
  169610. static const INT16 aanscales[DCTSIZE2] = {
  169611. /* precomputed values scaled up by 14 bits */
  169612. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169613. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169614. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169615. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169616. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169617. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169618. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169619. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169620. };
  169621. SHIFT_TEMPS
  169622. for (i = 0; i < DCTSIZE2; i++) {
  169623. ifmtbl[i] = (IFAST_MULT_TYPE)
  169624. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169625. (INT32) aanscales[i]),
  169626. CONST_BITS-IFAST_SCALE_BITS);
  169627. }
  169628. }
  169629. break;
  169630. #endif
  169631. #ifdef DCT_FLOAT_SUPPORTED
  169632. case JDCT_FLOAT:
  169633. {
  169634. /* For float AA&N IDCT method, multipliers are equal to quantization
  169635. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169636. * scalefactor[0] = 1
  169637. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169638. */
  169639. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169640. int row, col;
  169641. static const double aanscalefactor[DCTSIZE] = {
  169642. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169643. 1.0, 0.785694958, 0.541196100, 0.275899379
  169644. };
  169645. i = 0;
  169646. for (row = 0; row < DCTSIZE; row++) {
  169647. for (col = 0; col < DCTSIZE; col++) {
  169648. fmtbl[i] = (FLOAT_MULT_TYPE)
  169649. ((double) qtbl->quantval[i] *
  169650. aanscalefactor[row] * aanscalefactor[col]);
  169651. i++;
  169652. }
  169653. }
  169654. }
  169655. break;
  169656. #endif
  169657. default:
  169658. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169659. break;
  169660. }
  169661. }
  169662. }
  169663. /*
  169664. * Initialize IDCT manager.
  169665. */
  169666. GLOBAL(void)
  169667. jinit_inverse_dct (j_decompress_ptr cinfo)
  169668. {
  169669. my_idct_ptr idct;
  169670. int ci;
  169671. jpeg_component_info *compptr;
  169672. idct = (my_idct_ptr)
  169673. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169674. SIZEOF(my_idct_controller));
  169675. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169676. idct->pub.start_pass = start_pass;
  169677. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169678. ci++, compptr++) {
  169679. /* Allocate and pre-zero a multiplier table for each component */
  169680. compptr->dct_table =
  169681. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169682. SIZEOF(multiplier_table));
  169683. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169684. /* Mark multiplier table not yet set up for any method */
  169685. idct->cur_method[ci] = -1;
  169686. }
  169687. }
  169688. /*** End of inlined file: jddctmgr.c ***/
  169689. #undef CONST_BITS
  169690. #undef ASSIGN_STATE
  169691. /*** Start of inlined file: jdhuff.c ***/
  169692. #define JPEG_INTERNALS
  169693. /*** Start of inlined file: jdhuff.h ***/
  169694. /* Short forms of external names for systems with brain-damaged linkers. */
  169695. #ifndef __jdhuff_h__
  169696. #define __jdhuff_h__
  169697. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169698. #define jpeg_make_d_derived_tbl jMkDDerived
  169699. #define jpeg_fill_bit_buffer jFilBitBuf
  169700. #define jpeg_huff_decode jHufDecode
  169701. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169702. /* Derived data constructed for each Huffman table */
  169703. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169704. typedef struct {
  169705. /* Basic tables: (element [0] of each array is unused) */
  169706. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169707. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169708. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169709. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169710. * the smallest code of length k; so given a code of length k, the
  169711. * corresponding symbol is huffval[code + valoffset[k]]
  169712. */
  169713. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169714. JHUFF_TBL *pub;
  169715. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169716. * the input data stream. If the next Huffman code is no more
  169717. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169718. * the corresponding symbol directly from these tables.
  169719. */
  169720. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169721. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169722. } d_derived_tbl;
  169723. /* Expand a Huffman table definition into the derived format */
  169724. EXTERN(void) jpeg_make_d_derived_tbl
  169725. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169726. d_derived_tbl ** pdtbl));
  169727. /*
  169728. * Fetching the next N bits from the input stream is a time-critical operation
  169729. * for the Huffman decoders. We implement it with a combination of inline
  169730. * macros and out-of-line subroutines. Note that N (the number of bits
  169731. * demanded at one time) never exceeds 15 for JPEG use.
  169732. *
  169733. * We read source bytes into get_buffer and dole out bits as needed.
  169734. * If get_buffer already contains enough bits, they are fetched in-line
  169735. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169736. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169737. * as full as possible (not just to the number of bits needed; this
  169738. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169739. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169740. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169741. * at least the requested number of bits --- dummy zeroes are inserted if
  169742. * necessary.
  169743. */
  169744. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169745. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169746. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169747. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169748. * appropriately should be a win. Unfortunately we can't define the size
  169749. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169750. * because not all machines measure sizeof in 8-bit bytes.
  169751. */
  169752. typedef struct { /* Bitreading state saved across MCUs */
  169753. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169754. int bits_left; /* # of unused bits in it */
  169755. } bitread_perm_state;
  169756. typedef struct { /* Bitreading working state within an MCU */
  169757. /* Current data source location */
  169758. /* We need a copy, rather than munging the original, in case of suspension */
  169759. const JOCTET * next_input_byte; /* => next byte to read from source */
  169760. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169761. /* Bit input buffer --- note these values are kept in register variables,
  169762. * not in this struct, inside the inner loops.
  169763. */
  169764. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169765. int bits_left; /* # of unused bits in it */
  169766. /* Pointer needed by jpeg_fill_bit_buffer. */
  169767. j_decompress_ptr cinfo; /* back link to decompress master record */
  169768. } bitread_working_state;
  169769. /* Macros to declare and load/save bitread local variables. */
  169770. #define BITREAD_STATE_VARS \
  169771. register bit_buf_type get_buffer; \
  169772. register int bits_left; \
  169773. bitread_working_state br_state
  169774. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169775. br_state.cinfo = cinfop; \
  169776. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169777. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169778. get_buffer = permstate.get_buffer; \
  169779. bits_left = permstate.bits_left;
  169780. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169781. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169782. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169783. permstate.get_buffer = get_buffer; \
  169784. permstate.bits_left = bits_left
  169785. /*
  169786. * These macros provide the in-line portion of bit fetching.
  169787. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169788. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169789. * The variables get_buffer and bits_left are assumed to be locals,
  169790. * but the state struct might not be (jpeg_huff_decode needs this).
  169791. * CHECK_BIT_BUFFER(state,n,action);
  169792. * Ensure there are N bits in get_buffer; if suspend, take action.
  169793. * val = GET_BITS(n);
  169794. * Fetch next N bits.
  169795. * val = PEEK_BITS(n);
  169796. * Fetch next N bits without removing them from the buffer.
  169797. * DROP_BITS(n);
  169798. * Discard next N bits.
  169799. * The value N should be a simple variable, not an expression, because it
  169800. * is evaluated multiple times.
  169801. */
  169802. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169803. { if (bits_left < (nbits)) { \
  169804. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169805. { action; } \
  169806. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169807. #define GET_BITS(nbits) \
  169808. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169809. #define PEEK_BITS(nbits) \
  169810. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169811. #define DROP_BITS(nbits) \
  169812. (bits_left -= (nbits))
  169813. /* Load up the bit buffer to a depth of at least nbits */
  169814. EXTERN(boolean) jpeg_fill_bit_buffer
  169815. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169816. register int bits_left, int nbits));
  169817. /*
  169818. * Code for extracting next Huffman-coded symbol from input bit stream.
  169819. * Again, this is time-critical and we make the main paths be macros.
  169820. *
  169821. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169822. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169823. * or fewer bits long. The few overlength codes are handled with a loop,
  169824. * which need not be inline code.
  169825. *
  169826. * Notes about the HUFF_DECODE macro:
  169827. * 1. Near the end of the data segment, we may fail to get enough bits
  169828. * for a lookahead. In that case, we do it the hard way.
  169829. * 2. If the lookahead table contains no entry, the next code must be
  169830. * more than HUFF_LOOKAHEAD bits long.
  169831. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169832. */
  169833. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169834. { register int nb, look; \
  169835. if (bits_left < HUFF_LOOKAHEAD) { \
  169836. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169837. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169838. if (bits_left < HUFF_LOOKAHEAD) { \
  169839. nb = 1; goto slowlabel; \
  169840. } \
  169841. } \
  169842. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169843. if ((nb = htbl->look_nbits[look]) != 0) { \
  169844. DROP_BITS(nb); \
  169845. result = htbl->look_sym[look]; \
  169846. } else { \
  169847. nb = HUFF_LOOKAHEAD+1; \
  169848. slowlabel: \
  169849. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169850. { failaction; } \
  169851. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169852. } \
  169853. }
  169854. /* Out-of-line case for Huffman code fetching */
  169855. EXTERN(int) jpeg_huff_decode
  169856. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169857. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169858. #endif
  169859. /*** End of inlined file: jdhuff.h ***/
  169860. /* Declarations shared with jdphuff.c */
  169861. /*
  169862. * Expanded entropy decoder object for Huffman decoding.
  169863. *
  169864. * The savable_state subrecord contains fields that change within an MCU,
  169865. * but must not be updated permanently until we complete the MCU.
  169866. */
  169867. typedef struct {
  169868. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169869. } savable_state2;
  169870. /* This macro is to work around compilers with missing or broken
  169871. * structure assignment. You'll need to fix this code if you have
  169872. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169873. */
  169874. #ifndef NO_STRUCT_ASSIGN
  169875. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169876. #else
  169877. #if MAX_COMPS_IN_SCAN == 4
  169878. #define ASSIGN_STATE(dest,src) \
  169879. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169880. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169881. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169882. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169883. #endif
  169884. #endif
  169885. typedef struct {
  169886. struct jpeg_entropy_decoder pub; /* public fields */
  169887. /* These fields are loaded into local variables at start of each MCU.
  169888. * In case of suspension, we exit WITHOUT updating them.
  169889. */
  169890. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169891. savable_state2 saved; /* Other state at start of MCU */
  169892. /* These fields are NOT loaded into local working state. */
  169893. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169894. /* Pointers to derived tables (these workspaces have image lifespan) */
  169895. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169896. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169897. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169898. /* Pointers to derived tables to be used for each block within an MCU */
  169899. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169900. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169901. /* Whether we care about the DC and AC coefficient values for each block */
  169902. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169903. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169904. } huff_entropy_decoder2;
  169905. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169906. /*
  169907. * Initialize for a Huffman-compressed scan.
  169908. */
  169909. METHODDEF(void)
  169910. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169911. {
  169912. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169913. int ci, blkn, dctbl, actbl;
  169914. jpeg_component_info * compptr;
  169915. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169916. * This ought to be an error condition, but we make it a warning because
  169917. * there are some baseline files out there with all zeroes in these bytes.
  169918. */
  169919. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169920. cinfo->Ah != 0 || cinfo->Al != 0)
  169921. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169922. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169923. compptr = cinfo->cur_comp_info[ci];
  169924. dctbl = compptr->dc_tbl_no;
  169925. actbl = compptr->ac_tbl_no;
  169926. /* Compute derived values for Huffman tables */
  169927. /* We may do this more than once for a table, but it's not expensive */
  169928. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169929. & entropy->dc_derived_tbls[dctbl]);
  169930. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169931. & entropy->ac_derived_tbls[actbl]);
  169932. /* Initialize DC predictions to 0 */
  169933. entropy->saved.last_dc_val[ci] = 0;
  169934. }
  169935. /* Precalculate decoding info for each block in an MCU of this scan */
  169936. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169937. ci = cinfo->MCU_membership[blkn];
  169938. compptr = cinfo->cur_comp_info[ci];
  169939. /* Precalculate which table to use for each block */
  169940. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169941. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169942. /* Decide whether we really care about the coefficient values */
  169943. if (compptr->component_needed) {
  169944. entropy->dc_needed[blkn] = TRUE;
  169945. /* we don't need the ACs if producing a 1/8th-size image */
  169946. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169947. } else {
  169948. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169949. }
  169950. }
  169951. /* Initialize bitread state variables */
  169952. entropy->bitstate.bits_left = 0;
  169953. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169954. entropy->pub.insufficient_data = FALSE;
  169955. /* Initialize restart counter */
  169956. entropy->restarts_to_go = cinfo->restart_interval;
  169957. }
  169958. /*
  169959. * Compute the derived values for a Huffman table.
  169960. * This routine also performs some validation checks on the table.
  169961. *
  169962. * Note this is also used by jdphuff.c.
  169963. */
  169964. GLOBAL(void)
  169965. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169966. d_derived_tbl ** pdtbl)
  169967. {
  169968. JHUFF_TBL *htbl;
  169969. d_derived_tbl *dtbl;
  169970. int p, i, l, si, numsymbols;
  169971. int lookbits, ctr;
  169972. char huffsize[257];
  169973. unsigned int huffcode[257];
  169974. unsigned int code;
  169975. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169976. * paralleling the order of the symbols themselves in htbl->huffval[].
  169977. */
  169978. /* Find the input Huffman table */
  169979. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169980. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169981. htbl =
  169982. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169983. if (htbl == NULL)
  169984. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169985. /* Allocate a workspace if we haven't already done so. */
  169986. if (*pdtbl == NULL)
  169987. *pdtbl = (d_derived_tbl *)
  169988. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169989. SIZEOF(d_derived_tbl));
  169990. dtbl = *pdtbl;
  169991. dtbl->pub = htbl; /* fill in back link */
  169992. /* Figure C.1: make table of Huffman code length for each symbol */
  169993. p = 0;
  169994. for (l = 1; l <= 16; l++) {
  169995. i = (int) htbl->bits[l];
  169996. if (i < 0 || p + i > 256) /* protect against table overrun */
  169997. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169998. while (i--)
  169999. huffsize[p++] = (char) l;
  170000. }
  170001. huffsize[p] = 0;
  170002. numsymbols = p;
  170003. /* Figure C.2: generate the codes themselves */
  170004. /* We also validate that the counts represent a legal Huffman code tree. */
  170005. code = 0;
  170006. si = huffsize[0];
  170007. p = 0;
  170008. while (huffsize[p]) {
  170009. while (((int) huffsize[p]) == si) {
  170010. huffcode[p++] = code;
  170011. code++;
  170012. }
  170013. /* code is now 1 more than the last code used for codelength si; but
  170014. * it must still fit in si bits, since no code is allowed to be all ones.
  170015. */
  170016. if (((INT32) code) >= (((INT32) 1) << si))
  170017. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170018. code <<= 1;
  170019. si++;
  170020. }
  170021. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  170022. p = 0;
  170023. for (l = 1; l <= 16; l++) {
  170024. if (htbl->bits[l]) {
  170025. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  170026. * minus the minimum code of length l
  170027. */
  170028. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  170029. p += htbl->bits[l];
  170030. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  170031. } else {
  170032. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  170033. }
  170034. }
  170035. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  170036. /* Compute lookahead tables to speed up decoding.
  170037. * First we set all the table entries to 0, indicating "too long";
  170038. * then we iterate through the Huffman codes that are short enough and
  170039. * fill in all the entries that correspond to bit sequences starting
  170040. * with that code.
  170041. */
  170042. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  170043. p = 0;
  170044. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  170045. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  170046. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170047. /* Generate left-justified code followed by all possible bit sequences */
  170048. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  170049. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  170050. dtbl->look_nbits[lookbits] = l;
  170051. dtbl->look_sym[lookbits] = htbl->huffval[p];
  170052. lookbits++;
  170053. }
  170054. }
  170055. }
  170056. /* Validate symbols as being reasonable.
  170057. * For AC tables, we make no check, but accept all byte values 0..255.
  170058. * For DC tables, we require the symbols to be in range 0..15.
  170059. * (Tighter bounds could be applied depending on the data depth and mode,
  170060. * but this is sufficient to ensure safe decoding.)
  170061. */
  170062. if (isDC) {
  170063. for (i = 0; i < numsymbols; i++) {
  170064. int sym = htbl->huffval[i];
  170065. if (sym < 0 || sym > 15)
  170066. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170067. }
  170068. }
  170069. }
  170070. /*
  170071. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170072. * See jdhuff.h for info about usage.
  170073. * Note: current values of get_buffer and bits_left are passed as parameters,
  170074. * but are returned in the corresponding fields of the state struct.
  170075. *
  170076. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170077. * of get_buffer to be used. (On machines with wider words, an even larger
  170078. * buffer could be used.) However, on some machines 32-bit shifts are
  170079. * quite slow and take time proportional to the number of places shifted.
  170080. * (This is true with most PC compilers, for instance.) In this case it may
  170081. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170082. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170083. */
  170084. #ifdef SLOW_SHIFT_32
  170085. #define MIN_GET_BITS 15 /* minimum allowable value */
  170086. #else
  170087. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170088. #endif
  170089. GLOBAL(boolean)
  170090. jpeg_fill_bit_buffer (bitread_working_state * state,
  170091. register bit_buf_type get_buffer, register int bits_left,
  170092. int nbits)
  170093. /* Load up the bit buffer to a depth of at least nbits */
  170094. {
  170095. /* Copy heavily used state fields into locals (hopefully registers) */
  170096. register const JOCTET * next_input_byte = state->next_input_byte;
  170097. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170098. j_decompress_ptr cinfo = state->cinfo;
  170099. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170100. /* (It is assumed that no request will be for more than that many bits.) */
  170101. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170102. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170103. while (bits_left < MIN_GET_BITS) {
  170104. register int c;
  170105. /* Attempt to read a byte */
  170106. if (bytes_in_buffer == 0) {
  170107. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170108. return FALSE;
  170109. next_input_byte = cinfo->src->next_input_byte;
  170110. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170111. }
  170112. bytes_in_buffer--;
  170113. c = GETJOCTET(*next_input_byte++);
  170114. /* If it's 0xFF, check and discard stuffed zero byte */
  170115. if (c == 0xFF) {
  170116. /* Loop here to discard any padding FF's on terminating marker,
  170117. * so that we can save a valid unread_marker value. NOTE: we will
  170118. * accept multiple FF's followed by a 0 as meaning a single FF data
  170119. * byte. This data pattern is not valid according to the standard.
  170120. */
  170121. do {
  170122. if (bytes_in_buffer == 0) {
  170123. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170124. return FALSE;
  170125. next_input_byte = cinfo->src->next_input_byte;
  170126. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170127. }
  170128. bytes_in_buffer--;
  170129. c = GETJOCTET(*next_input_byte++);
  170130. } while (c == 0xFF);
  170131. if (c == 0) {
  170132. /* Found FF/00, which represents an FF data byte */
  170133. c = 0xFF;
  170134. } else {
  170135. /* Oops, it's actually a marker indicating end of compressed data.
  170136. * Save the marker code for later use.
  170137. * Fine point: it might appear that we should save the marker into
  170138. * bitread working state, not straight into permanent state. But
  170139. * once we have hit a marker, we cannot need to suspend within the
  170140. * current MCU, because we will read no more bytes from the data
  170141. * source. So it is OK to update permanent state right away.
  170142. */
  170143. cinfo->unread_marker = c;
  170144. /* See if we need to insert some fake zero bits. */
  170145. goto no_more_bytes;
  170146. }
  170147. }
  170148. /* OK, load c into get_buffer */
  170149. get_buffer = (get_buffer << 8) | c;
  170150. bits_left += 8;
  170151. } /* end while */
  170152. } else {
  170153. no_more_bytes:
  170154. /* We get here if we've read the marker that terminates the compressed
  170155. * data segment. There should be enough bits in the buffer register
  170156. * to satisfy the request; if so, no problem.
  170157. */
  170158. if (nbits > bits_left) {
  170159. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170160. * the data stream, so that we can produce some kind of image.
  170161. * We use a nonvolatile flag to ensure that only one warning message
  170162. * appears per data segment.
  170163. */
  170164. if (! cinfo->entropy->insufficient_data) {
  170165. WARNMS(cinfo, JWRN_HIT_MARKER);
  170166. cinfo->entropy->insufficient_data = TRUE;
  170167. }
  170168. /* Fill the buffer with zero bits */
  170169. get_buffer <<= MIN_GET_BITS - bits_left;
  170170. bits_left = MIN_GET_BITS;
  170171. }
  170172. }
  170173. /* Unload the local registers */
  170174. state->next_input_byte = next_input_byte;
  170175. state->bytes_in_buffer = bytes_in_buffer;
  170176. state->get_buffer = get_buffer;
  170177. state->bits_left = bits_left;
  170178. return TRUE;
  170179. }
  170180. /*
  170181. * Out-of-line code for Huffman code decoding.
  170182. * See jdhuff.h for info about usage.
  170183. */
  170184. GLOBAL(int)
  170185. jpeg_huff_decode (bitread_working_state * state,
  170186. register bit_buf_type get_buffer, register int bits_left,
  170187. d_derived_tbl * htbl, int min_bits)
  170188. {
  170189. register int l = min_bits;
  170190. register INT32 code;
  170191. /* HUFF_DECODE has determined that the code is at least min_bits */
  170192. /* bits long, so fetch that many bits in one swoop. */
  170193. CHECK_BIT_BUFFER(*state, l, return -1);
  170194. code = GET_BITS(l);
  170195. /* Collect the rest of the Huffman code one bit at a time. */
  170196. /* This is per Figure F.16 in the JPEG spec. */
  170197. while (code > htbl->maxcode[l]) {
  170198. code <<= 1;
  170199. CHECK_BIT_BUFFER(*state, 1, return -1);
  170200. code |= GET_BITS(1);
  170201. l++;
  170202. }
  170203. /* Unload the local registers */
  170204. state->get_buffer = get_buffer;
  170205. state->bits_left = bits_left;
  170206. /* With garbage input we may reach the sentinel value l = 17. */
  170207. if (l > 16) {
  170208. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170209. return 0; /* fake a zero as the safest result */
  170210. }
  170211. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170212. }
  170213. /*
  170214. * Check for a restart marker & resynchronize decoder.
  170215. * Returns FALSE if must suspend.
  170216. */
  170217. LOCAL(boolean)
  170218. process_restart (j_decompress_ptr cinfo)
  170219. {
  170220. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170221. int ci;
  170222. /* Throw away any unused bits remaining in bit buffer; */
  170223. /* include any full bytes in next_marker's count of discarded bytes */
  170224. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170225. entropy->bitstate.bits_left = 0;
  170226. /* Advance past the RSTn marker */
  170227. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170228. return FALSE;
  170229. /* Re-initialize DC predictions to 0 */
  170230. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170231. entropy->saved.last_dc_val[ci] = 0;
  170232. /* Reset restart counter */
  170233. entropy->restarts_to_go = cinfo->restart_interval;
  170234. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170235. * against a marker. In that case we will end up treating the next data
  170236. * segment as empty, and we can avoid producing bogus output pixels by
  170237. * leaving the flag set.
  170238. */
  170239. if (cinfo->unread_marker == 0)
  170240. entropy->pub.insufficient_data = FALSE;
  170241. return TRUE;
  170242. }
  170243. /*
  170244. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170245. * The coefficients are reordered from zigzag order into natural array order,
  170246. * but are not dequantized.
  170247. *
  170248. * The i'th block of the MCU is stored into the block pointed to by
  170249. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170250. * (Wholesale zeroing is usually a little faster than retail...)
  170251. *
  170252. * Returns FALSE if data source requested suspension. In that case no
  170253. * changes have been made to permanent state. (Exception: some output
  170254. * coefficients may already have been assigned. This is harmless for
  170255. * this module, since we'll just re-assign them on the next call.)
  170256. */
  170257. METHODDEF(boolean)
  170258. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170259. {
  170260. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170261. int blkn;
  170262. BITREAD_STATE_VARS;
  170263. savable_state2 state;
  170264. /* Process restart marker if needed; may have to suspend */
  170265. if (cinfo->restart_interval) {
  170266. if (entropy->restarts_to_go == 0)
  170267. if (! process_restart(cinfo))
  170268. return FALSE;
  170269. }
  170270. /* If we've run out of data, just leave the MCU set to zeroes.
  170271. * This way, we return uniform gray for the remainder of the segment.
  170272. */
  170273. if (! entropy->pub.insufficient_data) {
  170274. /* Load up working state */
  170275. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170276. ASSIGN_STATE(state, entropy->saved);
  170277. /* Outer loop handles each block in the MCU */
  170278. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170279. JBLOCKROW block = MCU_data[blkn];
  170280. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170281. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170282. register int s, k, r;
  170283. /* Decode a single block's worth of coefficients */
  170284. /* Section F.2.2.1: decode the DC coefficient difference */
  170285. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170286. if (s) {
  170287. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170288. r = GET_BITS(s);
  170289. s = HUFF_EXTEND(r, s);
  170290. }
  170291. if (entropy->dc_needed[blkn]) {
  170292. /* Convert DC difference to actual value, update last_dc_val */
  170293. int ci = cinfo->MCU_membership[blkn];
  170294. s += state.last_dc_val[ci];
  170295. state.last_dc_val[ci] = s;
  170296. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170297. (*block)[0] = (JCOEF) s;
  170298. }
  170299. if (entropy->ac_needed[blkn]) {
  170300. /* Section F.2.2.2: decode the AC coefficients */
  170301. /* Since zeroes are skipped, output area must be cleared beforehand */
  170302. for (k = 1; k < DCTSIZE2; k++) {
  170303. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170304. r = s >> 4;
  170305. s &= 15;
  170306. if (s) {
  170307. k += r;
  170308. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170309. r = GET_BITS(s);
  170310. s = HUFF_EXTEND(r, s);
  170311. /* Output coefficient in natural (dezigzagged) order.
  170312. * Note: the extra entries in jpeg_natural_order[] will save us
  170313. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170314. */
  170315. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170316. } else {
  170317. if (r != 15)
  170318. break;
  170319. k += 15;
  170320. }
  170321. }
  170322. } else {
  170323. /* Section F.2.2.2: decode the AC coefficients */
  170324. /* In this path we just discard the values */
  170325. for (k = 1; k < DCTSIZE2; k++) {
  170326. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170327. r = s >> 4;
  170328. s &= 15;
  170329. if (s) {
  170330. k += r;
  170331. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170332. DROP_BITS(s);
  170333. } else {
  170334. if (r != 15)
  170335. break;
  170336. k += 15;
  170337. }
  170338. }
  170339. }
  170340. }
  170341. /* Completed MCU, so update state */
  170342. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170343. ASSIGN_STATE(entropy->saved, state);
  170344. }
  170345. /* Account for restart interval (no-op if not using restarts) */
  170346. entropy->restarts_to_go--;
  170347. return TRUE;
  170348. }
  170349. /*
  170350. * Module initialization routine for Huffman entropy decoding.
  170351. */
  170352. GLOBAL(void)
  170353. jinit_huff_decoder (j_decompress_ptr cinfo)
  170354. {
  170355. huff_entropy_ptr2 entropy;
  170356. int i;
  170357. entropy = (huff_entropy_ptr2)
  170358. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170359. SIZEOF(huff_entropy_decoder2));
  170360. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170361. entropy->pub.start_pass = start_pass_huff_decoder;
  170362. entropy->pub.decode_mcu = decode_mcu;
  170363. /* Mark tables unallocated */
  170364. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170365. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170366. }
  170367. }
  170368. /*** End of inlined file: jdhuff.c ***/
  170369. /*** Start of inlined file: jdinput.c ***/
  170370. #define JPEG_INTERNALS
  170371. /* Private state */
  170372. typedef struct {
  170373. struct jpeg_input_controller pub; /* public fields */
  170374. boolean inheaders; /* TRUE until first SOS is reached */
  170375. } my_input_controller;
  170376. typedef my_input_controller * my_inputctl_ptr;
  170377. /* Forward declarations */
  170378. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170379. /*
  170380. * Routines to calculate various quantities related to the size of the image.
  170381. */
  170382. LOCAL(void)
  170383. initial_setup2 (j_decompress_ptr cinfo)
  170384. /* Called once, when first SOS marker is reached */
  170385. {
  170386. int ci;
  170387. jpeg_component_info *compptr;
  170388. /* Make sure image isn't bigger than I can handle */
  170389. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170390. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170391. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170392. /* For now, precision must match compiled-in value... */
  170393. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170394. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170395. /* Check that number of components won't exceed internal array sizes */
  170396. if (cinfo->num_components > MAX_COMPONENTS)
  170397. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170398. MAX_COMPONENTS);
  170399. /* Compute maximum sampling factors; check factor validity */
  170400. cinfo->max_h_samp_factor = 1;
  170401. cinfo->max_v_samp_factor = 1;
  170402. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170403. ci++, compptr++) {
  170404. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170405. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170406. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170407. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170408. compptr->h_samp_factor);
  170409. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170410. compptr->v_samp_factor);
  170411. }
  170412. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170413. * In the full decompressor, this will be overridden by jdmaster.c;
  170414. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170415. */
  170416. cinfo->min_DCT_scaled_size = DCTSIZE;
  170417. /* Compute dimensions of components */
  170418. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170419. ci++, compptr++) {
  170420. compptr->DCT_scaled_size = DCTSIZE;
  170421. /* Size in DCT blocks */
  170422. compptr->width_in_blocks = (JDIMENSION)
  170423. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170424. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170425. compptr->height_in_blocks = (JDIMENSION)
  170426. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170427. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170428. /* downsampled_width and downsampled_height will also be overridden by
  170429. * jdmaster.c if we are doing full decompression. The transcoder library
  170430. * doesn't use these values, but the calling application might.
  170431. */
  170432. /* Size in samples */
  170433. compptr->downsampled_width = (JDIMENSION)
  170434. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170435. (long) cinfo->max_h_samp_factor);
  170436. compptr->downsampled_height = (JDIMENSION)
  170437. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170438. (long) cinfo->max_v_samp_factor);
  170439. /* Mark component needed, until color conversion says otherwise */
  170440. compptr->component_needed = TRUE;
  170441. /* Mark no quantization table yet saved for component */
  170442. compptr->quant_table = NULL;
  170443. }
  170444. /* Compute number of fully interleaved MCU rows. */
  170445. cinfo->total_iMCU_rows = (JDIMENSION)
  170446. jdiv_round_up((long) cinfo->image_height,
  170447. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170448. /* Decide whether file contains multiple scans */
  170449. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170450. cinfo->inputctl->has_multiple_scans = TRUE;
  170451. else
  170452. cinfo->inputctl->has_multiple_scans = FALSE;
  170453. }
  170454. LOCAL(void)
  170455. per_scan_setup2 (j_decompress_ptr cinfo)
  170456. /* Do computations that are needed before processing a JPEG scan */
  170457. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170458. {
  170459. int ci, mcublks, tmp;
  170460. jpeg_component_info *compptr;
  170461. if (cinfo->comps_in_scan == 1) {
  170462. /* Noninterleaved (single-component) scan */
  170463. compptr = cinfo->cur_comp_info[0];
  170464. /* Overall image size in MCUs */
  170465. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170466. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170467. /* For noninterleaved scan, always one block per MCU */
  170468. compptr->MCU_width = 1;
  170469. compptr->MCU_height = 1;
  170470. compptr->MCU_blocks = 1;
  170471. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170472. compptr->last_col_width = 1;
  170473. /* For noninterleaved scans, it is convenient to define last_row_height
  170474. * as the number of block rows present in the last iMCU row.
  170475. */
  170476. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170477. if (tmp == 0) tmp = compptr->v_samp_factor;
  170478. compptr->last_row_height = tmp;
  170479. /* Prepare array describing MCU composition */
  170480. cinfo->blocks_in_MCU = 1;
  170481. cinfo->MCU_membership[0] = 0;
  170482. } else {
  170483. /* Interleaved (multi-component) scan */
  170484. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170485. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170486. MAX_COMPS_IN_SCAN);
  170487. /* Overall image size in MCUs */
  170488. cinfo->MCUs_per_row = (JDIMENSION)
  170489. jdiv_round_up((long) cinfo->image_width,
  170490. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170491. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170492. jdiv_round_up((long) cinfo->image_height,
  170493. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170494. cinfo->blocks_in_MCU = 0;
  170495. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170496. compptr = cinfo->cur_comp_info[ci];
  170497. /* Sampling factors give # of blocks of component in each MCU */
  170498. compptr->MCU_width = compptr->h_samp_factor;
  170499. compptr->MCU_height = compptr->v_samp_factor;
  170500. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170501. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170502. /* Figure number of non-dummy blocks in last MCU column & row */
  170503. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170504. if (tmp == 0) tmp = compptr->MCU_width;
  170505. compptr->last_col_width = tmp;
  170506. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170507. if (tmp == 0) tmp = compptr->MCU_height;
  170508. compptr->last_row_height = tmp;
  170509. /* Prepare array describing MCU composition */
  170510. mcublks = compptr->MCU_blocks;
  170511. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170512. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170513. while (mcublks-- > 0) {
  170514. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170515. }
  170516. }
  170517. }
  170518. }
  170519. /*
  170520. * Save away a copy of the Q-table referenced by each component present
  170521. * in the current scan, unless already saved during a prior scan.
  170522. *
  170523. * In a multiple-scan JPEG file, the encoder could assign different components
  170524. * the same Q-table slot number, but change table definitions between scans
  170525. * so that each component uses a different Q-table. (The IJG encoder is not
  170526. * currently capable of doing this, but other encoders might.) Since we want
  170527. * to be able to dequantize all the components at the end of the file, this
  170528. * means that we have to save away the table actually used for each component.
  170529. * We do this by copying the table at the start of the first scan containing
  170530. * the component.
  170531. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170532. * slot between scans of a component using that slot. If the encoder does so
  170533. * anyway, this decoder will simply use the Q-table values that were current
  170534. * at the start of the first scan for the component.
  170535. *
  170536. * The decompressor output side looks only at the saved quant tables,
  170537. * not at the current Q-table slots.
  170538. */
  170539. LOCAL(void)
  170540. latch_quant_tables (j_decompress_ptr cinfo)
  170541. {
  170542. int ci, qtblno;
  170543. jpeg_component_info *compptr;
  170544. JQUANT_TBL * qtbl;
  170545. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170546. compptr = cinfo->cur_comp_info[ci];
  170547. /* No work if we already saved Q-table for this component */
  170548. if (compptr->quant_table != NULL)
  170549. continue;
  170550. /* Make sure specified quantization table is present */
  170551. qtblno = compptr->quant_tbl_no;
  170552. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170553. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170554. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170555. /* OK, save away the quantization table */
  170556. qtbl = (JQUANT_TBL *)
  170557. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170558. SIZEOF(JQUANT_TBL));
  170559. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170560. compptr->quant_table = qtbl;
  170561. }
  170562. }
  170563. /*
  170564. * Initialize the input modules to read a scan of compressed data.
  170565. * The first call to this is done by jdmaster.c after initializing
  170566. * the entire decompressor (during jpeg_start_decompress).
  170567. * Subsequent calls come from consume_markers, below.
  170568. */
  170569. METHODDEF(void)
  170570. start_input_pass2 (j_decompress_ptr cinfo)
  170571. {
  170572. per_scan_setup2(cinfo);
  170573. latch_quant_tables(cinfo);
  170574. (*cinfo->entropy->start_pass) (cinfo);
  170575. (*cinfo->coef->start_input_pass) (cinfo);
  170576. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170577. }
  170578. /*
  170579. * Finish up after inputting a compressed-data scan.
  170580. * This is called by the coefficient controller after it's read all
  170581. * the expected data of the scan.
  170582. */
  170583. METHODDEF(void)
  170584. finish_input_pass (j_decompress_ptr cinfo)
  170585. {
  170586. cinfo->inputctl->consume_input = consume_markers;
  170587. }
  170588. /*
  170589. * Read JPEG markers before, between, or after compressed-data scans.
  170590. * Change state as necessary when a new scan is reached.
  170591. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170592. *
  170593. * The consume_input method pointer points either here or to the
  170594. * coefficient controller's consume_data routine, depending on whether
  170595. * we are reading a compressed data segment or inter-segment markers.
  170596. */
  170597. METHODDEF(int)
  170598. consume_markers (j_decompress_ptr cinfo)
  170599. {
  170600. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170601. int val;
  170602. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170603. return JPEG_REACHED_EOI;
  170604. val = (*cinfo->marker->read_markers) (cinfo);
  170605. switch (val) {
  170606. case JPEG_REACHED_SOS: /* Found SOS */
  170607. if (inputctl->inheaders) { /* 1st SOS */
  170608. initial_setup2(cinfo);
  170609. inputctl->inheaders = FALSE;
  170610. /* Note: start_input_pass must be called by jdmaster.c
  170611. * before any more input can be consumed. jdapimin.c is
  170612. * responsible for enforcing this sequencing.
  170613. */
  170614. } else { /* 2nd or later SOS marker */
  170615. if (! inputctl->pub.has_multiple_scans)
  170616. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170617. start_input_pass2(cinfo);
  170618. }
  170619. break;
  170620. case JPEG_REACHED_EOI: /* Found EOI */
  170621. inputctl->pub.eoi_reached = TRUE;
  170622. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170623. if (cinfo->marker->saw_SOF)
  170624. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170625. } else {
  170626. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170627. * if user set output_scan_number larger than number of scans.
  170628. */
  170629. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170630. cinfo->output_scan_number = cinfo->input_scan_number;
  170631. }
  170632. break;
  170633. case JPEG_SUSPENDED:
  170634. break;
  170635. }
  170636. return val;
  170637. }
  170638. /*
  170639. * Reset state to begin a fresh datastream.
  170640. */
  170641. METHODDEF(void)
  170642. reset_input_controller (j_decompress_ptr cinfo)
  170643. {
  170644. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170645. inputctl->pub.consume_input = consume_markers;
  170646. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170647. inputctl->pub.eoi_reached = FALSE;
  170648. inputctl->inheaders = TRUE;
  170649. /* Reset other modules */
  170650. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170651. (*cinfo->marker->reset_marker_reader) (cinfo);
  170652. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170653. cinfo->coef_bits = NULL;
  170654. }
  170655. /*
  170656. * Initialize the input controller module.
  170657. * This is called only once, when the decompression object is created.
  170658. */
  170659. GLOBAL(void)
  170660. jinit_input_controller (j_decompress_ptr cinfo)
  170661. {
  170662. my_inputctl_ptr inputctl;
  170663. /* Create subobject in permanent pool */
  170664. inputctl = (my_inputctl_ptr)
  170665. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170666. SIZEOF(my_input_controller));
  170667. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170668. /* Initialize method pointers */
  170669. inputctl->pub.consume_input = consume_markers;
  170670. inputctl->pub.reset_input_controller = reset_input_controller;
  170671. inputctl->pub.start_input_pass = start_input_pass2;
  170672. inputctl->pub.finish_input_pass = finish_input_pass;
  170673. /* Initialize state: can't use reset_input_controller since we don't
  170674. * want to try to reset other modules yet.
  170675. */
  170676. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170677. inputctl->pub.eoi_reached = FALSE;
  170678. inputctl->inheaders = TRUE;
  170679. }
  170680. /*** End of inlined file: jdinput.c ***/
  170681. /*** Start of inlined file: jdmainct.c ***/
  170682. #define JPEG_INTERNALS
  170683. /*
  170684. * In the current system design, the main buffer need never be a full-image
  170685. * buffer; any full-height buffers will be found inside the coefficient or
  170686. * postprocessing controllers. Nonetheless, the main controller is not
  170687. * trivial. Its responsibility is to provide context rows for upsampling/
  170688. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170689. *
  170690. * Postprocessor input data is counted in "row groups". A row group
  170691. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170692. * sample rows of each component. (We require DCT_scaled_size values to be
  170693. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170694. * values will likely be powers of two, so we actually have the stronger
  170695. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170696. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170697. * row group (times any additional scale factor that the upsampler is
  170698. * applying).
  170699. *
  170700. * The coefficient controller will deliver data to us one iMCU row at a time;
  170701. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170702. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170703. * to one row of MCUs when the image is fully interleaved.) Note that the
  170704. * number of sample rows varies across components, but the number of row
  170705. * groups does not. Some garbage sample rows may be included in the last iMCU
  170706. * row at the bottom of the image.
  170707. *
  170708. * Depending on the vertical scaling algorithm used, the upsampler may need
  170709. * access to the sample row(s) above and below its current input row group.
  170710. * The upsampler is required to set need_context_rows TRUE at global selection
  170711. * time if so. When need_context_rows is FALSE, this controller can simply
  170712. * obtain one iMCU row at a time from the coefficient controller and dole it
  170713. * out as row groups to the postprocessor.
  170714. *
  170715. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170716. * passed to postprocessing contains at least one row group's worth of samples
  170717. * above and below the row group(s) being processed. Note that the context
  170718. * rows "above" the first passed row group appear at negative row offsets in
  170719. * the passed buffer. At the top and bottom of the image, the required
  170720. * context rows are manufactured by duplicating the first or last real sample
  170721. * row; this avoids having special cases in the upsampling inner loops.
  170722. *
  170723. * The amount of context is fixed at one row group just because that's a
  170724. * convenient number for this controller to work with. The existing
  170725. * upsamplers really only need one sample row of context. An upsampler
  170726. * supporting arbitrary output rescaling might wish for more than one row
  170727. * group of context when shrinking the image; tough, we don't handle that.
  170728. * (This is justified by the assumption that downsizing will be handled mostly
  170729. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170730. * the upsample step needn't be much less than one.)
  170731. *
  170732. * To provide the desired context, we have to retain the last two row groups
  170733. * of one iMCU row while reading in the next iMCU row. (The last row group
  170734. * can't be processed until we have another row group for its below-context,
  170735. * and so we have to save the next-to-last group too for its above-context.)
  170736. * We could do this most simply by copying data around in our buffer, but
  170737. * that'd be very slow. We can avoid copying any data by creating a rather
  170738. * strange pointer structure. Here's how it works. We allocate a workspace
  170739. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170740. * of row groups per iMCU row). We create two sets of redundant pointers to
  170741. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170742. * pointer lists look like this:
  170743. * M+1 M-1
  170744. * master pointer --> 0 master pointer --> 0
  170745. * 1 1
  170746. * ... ...
  170747. * M-3 M-3
  170748. * M-2 M
  170749. * M-1 M+1
  170750. * M M-2
  170751. * M+1 M-1
  170752. * 0 0
  170753. * We read alternate iMCU rows using each master pointer; thus the last two
  170754. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170755. * The pointer lists are set up so that the required context rows appear to
  170756. * be adjacent to the proper places when we pass the pointer lists to the
  170757. * upsampler.
  170758. *
  170759. * The above pictures describe the normal state of the pointer lists.
  170760. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170761. * the first or last sample row as necessary (this is cheaper than copying
  170762. * sample rows around).
  170763. *
  170764. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170765. * situation each iMCU row provides only one row group so the buffering logic
  170766. * must be different (eg, we must read two iMCU rows before we can emit the
  170767. * first row group). For now, we simply do not support providing context
  170768. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170769. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170770. * want it quick and dirty, so a context-free upsampler is sufficient.
  170771. */
  170772. /* Private buffer controller object */
  170773. typedef struct {
  170774. struct jpeg_d_main_controller pub; /* public fields */
  170775. /* Pointer to allocated workspace (M or M+2 row groups). */
  170776. JSAMPARRAY buffer[MAX_COMPONENTS];
  170777. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170778. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170779. /* Remaining fields are only used in the context case. */
  170780. /* These are the master pointers to the funny-order pointer lists. */
  170781. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170782. int whichptr; /* indicates which pointer set is now in use */
  170783. int context_state; /* process_data state machine status */
  170784. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170785. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170786. } my_main_controller4;
  170787. typedef my_main_controller4 * my_main_ptr4;
  170788. /* context_state values: */
  170789. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170790. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170791. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170792. /* Forward declarations */
  170793. METHODDEF(void) process_data_simple_main2
  170794. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170795. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170796. METHODDEF(void) process_data_context_main
  170797. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170798. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170799. #ifdef QUANT_2PASS_SUPPORTED
  170800. METHODDEF(void) process_data_crank_post
  170801. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170802. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170803. #endif
  170804. LOCAL(void)
  170805. alloc_funny_pointers (j_decompress_ptr cinfo)
  170806. /* Allocate space for the funny pointer lists.
  170807. * This is done only once, not once per pass.
  170808. */
  170809. {
  170810. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170811. int ci, rgroup;
  170812. int M = cinfo->min_DCT_scaled_size;
  170813. jpeg_component_info *compptr;
  170814. JSAMPARRAY xbuf;
  170815. /* Get top-level space for component array pointers.
  170816. * We alloc both arrays with one call to save a few cycles.
  170817. */
  170818. main_->xbuffer[0] = (JSAMPIMAGE)
  170819. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170820. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170821. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170822. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170823. ci++, compptr++) {
  170824. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170825. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170826. /* Get space for pointer lists --- M+4 row groups in each list.
  170827. * We alloc both pointer lists with one call to save a few cycles.
  170828. */
  170829. xbuf = (JSAMPARRAY)
  170830. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170831. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170832. xbuf += rgroup; /* want one row group at negative offsets */
  170833. main_->xbuffer[0][ci] = xbuf;
  170834. xbuf += rgroup * (M + 4);
  170835. main_->xbuffer[1][ci] = xbuf;
  170836. }
  170837. }
  170838. LOCAL(void)
  170839. make_funny_pointers (j_decompress_ptr cinfo)
  170840. /* Create the funny pointer lists discussed in the comments above.
  170841. * The actual workspace is already allocated (in main->buffer),
  170842. * and the space for the pointer lists is allocated too.
  170843. * This routine just fills in the curiously ordered lists.
  170844. * This will be repeated at the beginning of each pass.
  170845. */
  170846. {
  170847. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170848. int ci, i, rgroup;
  170849. int M = cinfo->min_DCT_scaled_size;
  170850. jpeg_component_info *compptr;
  170851. JSAMPARRAY buf, xbuf0, xbuf1;
  170852. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170853. ci++, compptr++) {
  170854. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170855. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170856. xbuf0 = main_->xbuffer[0][ci];
  170857. xbuf1 = main_->xbuffer[1][ci];
  170858. /* First copy the workspace pointers as-is */
  170859. buf = main_->buffer[ci];
  170860. for (i = 0; i < rgroup * (M + 2); i++) {
  170861. xbuf0[i] = xbuf1[i] = buf[i];
  170862. }
  170863. /* In the second list, put the last four row groups in swapped order */
  170864. for (i = 0; i < rgroup * 2; i++) {
  170865. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170866. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170867. }
  170868. /* The wraparound pointers at top and bottom will be filled later
  170869. * (see set_wraparound_pointers, below). Initially we want the "above"
  170870. * pointers to duplicate the first actual data line. This only needs
  170871. * to happen in xbuffer[0].
  170872. */
  170873. for (i = 0; i < rgroup; i++) {
  170874. xbuf0[i - rgroup] = xbuf0[0];
  170875. }
  170876. }
  170877. }
  170878. LOCAL(void)
  170879. set_wraparound_pointers (j_decompress_ptr cinfo)
  170880. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170881. * This changes the pointer list state from top-of-image to the normal state.
  170882. */
  170883. {
  170884. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170885. int ci, i, rgroup;
  170886. int M = cinfo->min_DCT_scaled_size;
  170887. jpeg_component_info *compptr;
  170888. JSAMPARRAY xbuf0, xbuf1;
  170889. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170890. ci++, compptr++) {
  170891. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170892. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170893. xbuf0 = main_->xbuffer[0][ci];
  170894. xbuf1 = main_->xbuffer[1][ci];
  170895. for (i = 0; i < rgroup; i++) {
  170896. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170897. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170898. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170899. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170900. }
  170901. }
  170902. }
  170903. LOCAL(void)
  170904. set_bottom_pointers (j_decompress_ptr cinfo)
  170905. /* Change the pointer lists to duplicate the last sample row at the bottom
  170906. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170907. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170908. */
  170909. {
  170910. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170911. int ci, i, rgroup, iMCUheight, rows_left;
  170912. jpeg_component_info *compptr;
  170913. JSAMPARRAY xbuf;
  170914. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170915. ci++, compptr++) {
  170916. /* Count sample rows in one iMCU row and in one row group */
  170917. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170918. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170919. /* Count nondummy sample rows remaining for this component */
  170920. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170921. if (rows_left == 0) rows_left = iMCUheight;
  170922. /* Count nondummy row groups. Should get same answer for each component,
  170923. * so we need only do it once.
  170924. */
  170925. if (ci == 0) {
  170926. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170927. }
  170928. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170929. * last partial rowgroup and ensures at least one full rowgroup of context.
  170930. */
  170931. xbuf = main_->xbuffer[main_->whichptr][ci];
  170932. for (i = 0; i < rgroup * 2; i++) {
  170933. xbuf[rows_left + i] = xbuf[rows_left-1];
  170934. }
  170935. }
  170936. }
  170937. /*
  170938. * Initialize for a processing pass.
  170939. */
  170940. METHODDEF(void)
  170941. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170942. {
  170943. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170944. switch (pass_mode) {
  170945. case JBUF_PASS_THRU:
  170946. if (cinfo->upsample->need_context_rows) {
  170947. main_->pub.process_data = process_data_context_main;
  170948. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170949. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170950. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170951. main_->iMCU_row_ctr = 0;
  170952. } else {
  170953. /* Simple case with no context needed */
  170954. main_->pub.process_data = process_data_simple_main2;
  170955. }
  170956. main_->buffer_full = FALSE; /* Mark buffer empty */
  170957. main_->rowgroup_ctr = 0;
  170958. break;
  170959. #ifdef QUANT_2PASS_SUPPORTED
  170960. case JBUF_CRANK_DEST:
  170961. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170962. main_->pub.process_data = process_data_crank_post;
  170963. break;
  170964. #endif
  170965. default:
  170966. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170967. break;
  170968. }
  170969. }
  170970. /*
  170971. * Process some data.
  170972. * This handles the simple case where no context is required.
  170973. */
  170974. METHODDEF(void)
  170975. process_data_simple_main2 (j_decompress_ptr cinfo,
  170976. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170977. JDIMENSION out_rows_avail)
  170978. {
  170979. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170980. JDIMENSION rowgroups_avail;
  170981. /* Read input data if we haven't filled the main buffer yet */
  170982. if (! main_->buffer_full) {
  170983. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170984. return; /* suspension forced, can do nothing more */
  170985. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170986. }
  170987. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170988. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170989. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170990. * to the postprocessor. The postprocessor has to check for bottom
  170991. * of image anyway (at row resolution), so no point in us doing it too.
  170992. */
  170993. /* Feed the postprocessor */
  170994. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170995. &main_->rowgroup_ctr, rowgroups_avail,
  170996. output_buf, out_row_ctr, out_rows_avail);
  170997. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170998. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170999. main_->buffer_full = FALSE;
  171000. main_->rowgroup_ctr = 0;
  171001. }
  171002. }
  171003. /*
  171004. * Process some data.
  171005. * This handles the case where context rows must be provided.
  171006. */
  171007. METHODDEF(void)
  171008. process_data_context_main (j_decompress_ptr cinfo,
  171009. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171010. JDIMENSION out_rows_avail)
  171011. {
  171012. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171013. /* Read input data if we haven't filled the main buffer yet */
  171014. if (! main_->buffer_full) {
  171015. if (! (*cinfo->coef->decompress_data) (cinfo,
  171016. main_->xbuffer[main_->whichptr]))
  171017. return; /* suspension forced, can do nothing more */
  171018. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171019. main_->iMCU_row_ctr++; /* count rows received */
  171020. }
  171021. /* Postprocessor typically will not swallow all the input data it is handed
  171022. * in one call (due to filling the output buffer first). Must be prepared
  171023. * to exit and restart. This switch lets us keep track of how far we got.
  171024. * Note that each case falls through to the next on successful completion.
  171025. */
  171026. switch (main_->context_state) {
  171027. case CTX_POSTPONED_ROW:
  171028. /* Call postprocessor using previously set pointers for postponed row */
  171029. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171030. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171031. output_buf, out_row_ctr, out_rows_avail);
  171032. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171033. return; /* Need to suspend */
  171034. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171035. if (*out_row_ctr >= out_rows_avail)
  171036. return; /* Postprocessor exactly filled output buf */
  171037. /*FALLTHROUGH*/
  171038. case CTX_PREPARE_FOR_IMCU:
  171039. /* Prepare to process first M-1 row groups of this iMCU row */
  171040. main_->rowgroup_ctr = 0;
  171041. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  171042. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  171043. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  171044. */
  171045. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  171046. set_bottom_pointers(cinfo);
  171047. main_->context_state = CTX_PROCESS_IMCU;
  171048. /*FALLTHROUGH*/
  171049. case CTX_PROCESS_IMCU:
  171050. /* Call postprocessor using previously set pointers */
  171051. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171052. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171053. output_buf, out_row_ctr, out_rows_avail);
  171054. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171055. return; /* Need to suspend */
  171056. /* After the first iMCU, change wraparound pointers to normal state */
  171057. if (main_->iMCU_row_ctr == 1)
  171058. set_wraparound_pointers(cinfo);
  171059. /* Prepare to load new iMCU row using other xbuffer list */
  171060. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171061. main_->buffer_full = FALSE;
  171062. /* Still need to process last row group of this iMCU row, */
  171063. /* which is saved at index M+1 of the other xbuffer */
  171064. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171065. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171066. main_->context_state = CTX_POSTPONED_ROW;
  171067. }
  171068. }
  171069. /*
  171070. * Process some data.
  171071. * Final pass of two-pass quantization: just call the postprocessor.
  171072. * Source data will be the postprocessor controller's internal buffer.
  171073. */
  171074. #ifdef QUANT_2PASS_SUPPORTED
  171075. METHODDEF(void)
  171076. process_data_crank_post (j_decompress_ptr cinfo,
  171077. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171078. JDIMENSION out_rows_avail)
  171079. {
  171080. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171081. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171082. output_buf, out_row_ctr, out_rows_avail);
  171083. }
  171084. #endif /* QUANT_2PASS_SUPPORTED */
  171085. /*
  171086. * Initialize main buffer controller.
  171087. */
  171088. GLOBAL(void)
  171089. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171090. {
  171091. my_main_ptr4 main_;
  171092. int ci, rgroup, ngroups;
  171093. jpeg_component_info *compptr;
  171094. main_ = (my_main_ptr4)
  171095. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171096. SIZEOF(my_main_controller4));
  171097. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171098. main_->pub.start_pass = start_pass_main2;
  171099. if (need_full_buffer) /* shouldn't happen */
  171100. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171101. /* Allocate the workspace.
  171102. * ngroups is the number of row groups we need.
  171103. */
  171104. if (cinfo->upsample->need_context_rows) {
  171105. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171106. ERREXIT(cinfo, JERR_NOTIMPL);
  171107. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171108. ngroups = cinfo->min_DCT_scaled_size + 2;
  171109. } else {
  171110. ngroups = cinfo->min_DCT_scaled_size;
  171111. }
  171112. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171113. ci++, compptr++) {
  171114. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171115. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171116. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171117. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171118. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171119. (JDIMENSION) (rgroup * ngroups));
  171120. }
  171121. }
  171122. /*** End of inlined file: jdmainct.c ***/
  171123. /*** Start of inlined file: jdmarker.c ***/
  171124. #define JPEG_INTERNALS
  171125. /* Private state */
  171126. typedef struct {
  171127. struct jpeg_marker_reader pub; /* public fields */
  171128. /* Application-overridable marker processing methods */
  171129. jpeg_marker_parser_method process_COM;
  171130. jpeg_marker_parser_method process_APPn[16];
  171131. /* Limit on marker data length to save for each marker type */
  171132. unsigned int length_limit_COM;
  171133. unsigned int length_limit_APPn[16];
  171134. /* Status of COM/APPn marker saving */
  171135. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171136. unsigned int bytes_read; /* data bytes read so far in marker */
  171137. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171138. } my_marker_reader;
  171139. typedef my_marker_reader * my_marker_ptr2;
  171140. /*
  171141. * Macros for fetching data from the data source module.
  171142. *
  171143. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171144. * the current restart point; we update them only when we have reached a
  171145. * suitable place to restart if a suspension occurs.
  171146. */
  171147. /* Declare and initialize local copies of input pointer/count */
  171148. #define INPUT_VARS(cinfo) \
  171149. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171150. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171151. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171152. /* Unload the local copies --- do this only at a restart boundary */
  171153. #define INPUT_SYNC(cinfo) \
  171154. ( datasrc->next_input_byte = next_input_byte, \
  171155. datasrc->bytes_in_buffer = bytes_in_buffer )
  171156. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171157. #define INPUT_RELOAD(cinfo) \
  171158. ( next_input_byte = datasrc->next_input_byte, \
  171159. bytes_in_buffer = datasrc->bytes_in_buffer )
  171160. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171161. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171162. * but we must reload the local copies after a successful fill.
  171163. */
  171164. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171165. if (bytes_in_buffer == 0) { \
  171166. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171167. { action; } \
  171168. INPUT_RELOAD(cinfo); \
  171169. }
  171170. /* Read a byte into variable V.
  171171. * If must suspend, take the specified action (typically "return FALSE").
  171172. */
  171173. #define INPUT_BYTE(cinfo,V,action) \
  171174. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171175. bytes_in_buffer--; \
  171176. V = GETJOCTET(*next_input_byte++); )
  171177. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171178. * V should be declared unsigned int or perhaps INT32.
  171179. */
  171180. #define INPUT_2BYTES(cinfo,V,action) \
  171181. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171182. bytes_in_buffer--; \
  171183. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171184. MAKE_BYTE_AVAIL(cinfo,action); \
  171185. bytes_in_buffer--; \
  171186. V += GETJOCTET(*next_input_byte++); )
  171187. /*
  171188. * Routines to process JPEG markers.
  171189. *
  171190. * Entry condition: JPEG marker itself has been read and its code saved
  171191. * in cinfo->unread_marker; input restart point is just after the marker.
  171192. *
  171193. * Exit: if return TRUE, have read and processed any parameters, and have
  171194. * updated the restart point to point after the parameters.
  171195. * If return FALSE, was forced to suspend before reaching end of
  171196. * marker parameters; restart point has not been moved. Same routine
  171197. * will be called again after application supplies more input data.
  171198. *
  171199. * This approach to suspension assumes that all of a marker's parameters
  171200. * can fit into a single input bufferload. This should hold for "normal"
  171201. * markers. Some COM/APPn markers might have large parameter segments
  171202. * that might not fit. If we are simply dropping such a marker, we use
  171203. * skip_input_data to get past it, and thereby put the problem on the
  171204. * source manager's shoulders. If we are saving the marker's contents
  171205. * into memory, we use a slightly different convention: when forced to
  171206. * suspend, the marker processor updates the restart point to the end of
  171207. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171208. * On resumption, cinfo->unread_marker still contains the marker code,
  171209. * but the data source will point to the next chunk of marker data.
  171210. * The marker processor must retain internal state to deal with this.
  171211. *
  171212. * Note that we don't bother to avoid duplicate trace messages if a
  171213. * suspension occurs within marker parameters. Other side effects
  171214. * require more care.
  171215. */
  171216. LOCAL(boolean)
  171217. get_soi (j_decompress_ptr cinfo)
  171218. /* Process an SOI marker */
  171219. {
  171220. int i;
  171221. TRACEMS(cinfo, 1, JTRC_SOI);
  171222. if (cinfo->marker->saw_SOI)
  171223. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171224. /* Reset all parameters that are defined to be reset by SOI */
  171225. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171226. cinfo->arith_dc_L[i] = 0;
  171227. cinfo->arith_dc_U[i] = 1;
  171228. cinfo->arith_ac_K[i] = 5;
  171229. }
  171230. cinfo->restart_interval = 0;
  171231. /* Set initial assumptions for colorspace etc */
  171232. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171233. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171234. cinfo->saw_JFIF_marker = FALSE;
  171235. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171236. cinfo->JFIF_minor_version = 1;
  171237. cinfo->density_unit = 0;
  171238. cinfo->X_density = 1;
  171239. cinfo->Y_density = 1;
  171240. cinfo->saw_Adobe_marker = FALSE;
  171241. cinfo->Adobe_transform = 0;
  171242. cinfo->marker->saw_SOI = TRUE;
  171243. return TRUE;
  171244. }
  171245. LOCAL(boolean)
  171246. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171247. /* Process a SOFn marker */
  171248. {
  171249. INT32 length;
  171250. int c, ci;
  171251. jpeg_component_info * compptr;
  171252. INPUT_VARS(cinfo);
  171253. cinfo->progressive_mode = is_prog;
  171254. cinfo->arith_code = is_arith;
  171255. INPUT_2BYTES(cinfo, length, return FALSE);
  171256. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171257. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171258. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171259. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171260. length -= 8;
  171261. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171262. (int) cinfo->image_width, (int) cinfo->image_height,
  171263. cinfo->num_components);
  171264. if (cinfo->marker->saw_SOF)
  171265. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171266. /* We don't support files in which the image height is initially specified */
  171267. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171268. /* might as well have a general sanity check. */
  171269. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171270. || cinfo->num_components <= 0)
  171271. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171272. if (length != (cinfo->num_components * 3))
  171273. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171274. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171275. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171276. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171277. cinfo->num_components * SIZEOF(jpeg_component_info));
  171278. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171279. ci++, compptr++) {
  171280. compptr->component_index = ci;
  171281. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171282. INPUT_BYTE(cinfo, c, return FALSE);
  171283. compptr->h_samp_factor = (c >> 4) & 15;
  171284. compptr->v_samp_factor = (c ) & 15;
  171285. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171286. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171287. compptr->component_id, compptr->h_samp_factor,
  171288. compptr->v_samp_factor, compptr->quant_tbl_no);
  171289. }
  171290. cinfo->marker->saw_SOF = TRUE;
  171291. INPUT_SYNC(cinfo);
  171292. return TRUE;
  171293. }
  171294. LOCAL(boolean)
  171295. get_sos (j_decompress_ptr cinfo)
  171296. /* Process a SOS marker */
  171297. {
  171298. INT32 length;
  171299. int i, ci, n, c, cc;
  171300. jpeg_component_info * compptr;
  171301. INPUT_VARS(cinfo);
  171302. if (! cinfo->marker->saw_SOF)
  171303. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171304. INPUT_2BYTES(cinfo, length, return FALSE);
  171305. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171306. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171307. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171308. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171309. cinfo->comps_in_scan = n;
  171310. /* Collect the component-spec parameters */
  171311. for (i = 0; i < n; i++) {
  171312. INPUT_BYTE(cinfo, cc, return FALSE);
  171313. INPUT_BYTE(cinfo, c, return FALSE);
  171314. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171315. ci++, compptr++) {
  171316. if (cc == compptr->component_id)
  171317. goto id_found;
  171318. }
  171319. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171320. id_found:
  171321. cinfo->cur_comp_info[i] = compptr;
  171322. compptr->dc_tbl_no = (c >> 4) & 15;
  171323. compptr->ac_tbl_no = (c ) & 15;
  171324. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171325. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171326. }
  171327. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171328. INPUT_BYTE(cinfo, c, return FALSE);
  171329. cinfo->Ss = c;
  171330. INPUT_BYTE(cinfo, c, return FALSE);
  171331. cinfo->Se = c;
  171332. INPUT_BYTE(cinfo, c, return FALSE);
  171333. cinfo->Ah = (c >> 4) & 15;
  171334. cinfo->Al = (c ) & 15;
  171335. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171336. cinfo->Ah, cinfo->Al);
  171337. /* Prepare to scan data & restart markers */
  171338. cinfo->marker->next_restart_num = 0;
  171339. /* Count another SOS marker */
  171340. cinfo->input_scan_number++;
  171341. INPUT_SYNC(cinfo);
  171342. return TRUE;
  171343. }
  171344. #ifdef D_ARITH_CODING_SUPPORTED
  171345. LOCAL(boolean)
  171346. get_dac (j_decompress_ptr cinfo)
  171347. /* Process a DAC marker */
  171348. {
  171349. INT32 length;
  171350. int index, val;
  171351. INPUT_VARS(cinfo);
  171352. INPUT_2BYTES(cinfo, length, return FALSE);
  171353. length -= 2;
  171354. while (length > 0) {
  171355. INPUT_BYTE(cinfo, index, return FALSE);
  171356. INPUT_BYTE(cinfo, val, return FALSE);
  171357. length -= 2;
  171358. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171359. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171360. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171361. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171362. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171363. } else { /* define DC table */
  171364. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171365. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171366. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171367. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171368. }
  171369. }
  171370. if (length != 0)
  171371. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171372. INPUT_SYNC(cinfo);
  171373. return TRUE;
  171374. }
  171375. #else /* ! D_ARITH_CODING_SUPPORTED */
  171376. #define get_dac(cinfo) skip_variable(cinfo)
  171377. #endif /* D_ARITH_CODING_SUPPORTED */
  171378. LOCAL(boolean)
  171379. get_dht (j_decompress_ptr cinfo)
  171380. /* Process a DHT marker */
  171381. {
  171382. INT32 length;
  171383. UINT8 bits[17];
  171384. UINT8 huffval[256];
  171385. int i, index, count;
  171386. JHUFF_TBL **htblptr;
  171387. INPUT_VARS(cinfo);
  171388. INPUT_2BYTES(cinfo, length, return FALSE);
  171389. length -= 2;
  171390. while (length > 16) {
  171391. INPUT_BYTE(cinfo, index, return FALSE);
  171392. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171393. bits[0] = 0;
  171394. count = 0;
  171395. for (i = 1; i <= 16; i++) {
  171396. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171397. count += bits[i];
  171398. }
  171399. length -= 1 + 16;
  171400. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171401. bits[1], bits[2], bits[3], bits[4],
  171402. bits[5], bits[6], bits[7], bits[8]);
  171403. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171404. bits[9], bits[10], bits[11], bits[12],
  171405. bits[13], bits[14], bits[15], bits[16]);
  171406. /* Here we just do minimal validation of the counts to avoid walking
  171407. * off the end of our table space. jdhuff.c will check more carefully.
  171408. */
  171409. if (count > 256 || ((INT32) count) > length)
  171410. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171411. for (i = 0; i < count; i++)
  171412. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171413. length -= count;
  171414. if (index & 0x10) { /* AC table definition */
  171415. index -= 0x10;
  171416. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171417. } else { /* DC table definition */
  171418. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171419. }
  171420. if (index < 0 || index >= NUM_HUFF_TBLS)
  171421. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171422. if (*htblptr == NULL)
  171423. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171424. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171425. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171426. }
  171427. if (length != 0)
  171428. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171429. INPUT_SYNC(cinfo);
  171430. return TRUE;
  171431. }
  171432. LOCAL(boolean)
  171433. get_dqt (j_decompress_ptr cinfo)
  171434. /* Process a DQT marker */
  171435. {
  171436. INT32 length;
  171437. int n, i, prec;
  171438. unsigned int tmp;
  171439. JQUANT_TBL *quant_ptr;
  171440. INPUT_VARS(cinfo);
  171441. INPUT_2BYTES(cinfo, length, return FALSE);
  171442. length -= 2;
  171443. while (length > 0) {
  171444. INPUT_BYTE(cinfo, n, return FALSE);
  171445. prec = n >> 4;
  171446. n &= 0x0F;
  171447. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171448. if (n >= NUM_QUANT_TBLS)
  171449. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171450. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171451. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171452. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171453. for (i = 0; i < DCTSIZE2; i++) {
  171454. if (prec)
  171455. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171456. else
  171457. INPUT_BYTE(cinfo, tmp, return FALSE);
  171458. /* We convert the zigzag-order table to natural array order. */
  171459. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171460. }
  171461. if (cinfo->err->trace_level >= 2) {
  171462. for (i = 0; i < DCTSIZE2; i += 8) {
  171463. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171464. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171465. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171466. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171467. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171468. }
  171469. }
  171470. length -= DCTSIZE2+1;
  171471. if (prec) length -= DCTSIZE2;
  171472. }
  171473. if (length != 0)
  171474. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171475. INPUT_SYNC(cinfo);
  171476. return TRUE;
  171477. }
  171478. LOCAL(boolean)
  171479. get_dri (j_decompress_ptr cinfo)
  171480. /* Process a DRI marker */
  171481. {
  171482. INT32 length;
  171483. unsigned int tmp;
  171484. INPUT_VARS(cinfo);
  171485. INPUT_2BYTES(cinfo, length, return FALSE);
  171486. if (length != 4)
  171487. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171488. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171489. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171490. cinfo->restart_interval = tmp;
  171491. INPUT_SYNC(cinfo);
  171492. return TRUE;
  171493. }
  171494. /*
  171495. * Routines for processing APPn and COM markers.
  171496. * These are either saved in memory or discarded, per application request.
  171497. * APP0 and APP14 are specially checked to see if they are
  171498. * JFIF and Adobe markers, respectively.
  171499. */
  171500. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171501. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171502. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171503. LOCAL(void)
  171504. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171505. unsigned int datalen, INT32 remaining)
  171506. /* Examine first few bytes from an APP0.
  171507. * Take appropriate action if it is a JFIF marker.
  171508. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171509. */
  171510. {
  171511. INT32 totallen = (INT32) datalen + remaining;
  171512. if (datalen >= APP0_DATA_LEN &&
  171513. GETJOCTET(data[0]) == 0x4A &&
  171514. GETJOCTET(data[1]) == 0x46 &&
  171515. GETJOCTET(data[2]) == 0x49 &&
  171516. GETJOCTET(data[3]) == 0x46 &&
  171517. GETJOCTET(data[4]) == 0) {
  171518. /* Found JFIF APP0 marker: save info */
  171519. cinfo->saw_JFIF_marker = TRUE;
  171520. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171521. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171522. cinfo->density_unit = GETJOCTET(data[7]);
  171523. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171524. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171525. /* Check version.
  171526. * Major version must be 1, anything else signals an incompatible change.
  171527. * (We used to treat this as an error, but now it's a nonfatal warning,
  171528. * because some bozo at Hijaak couldn't read the spec.)
  171529. * Minor version should be 0..2, but process anyway if newer.
  171530. */
  171531. if (cinfo->JFIF_major_version != 1)
  171532. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171533. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171534. /* Generate trace messages */
  171535. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171536. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171537. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171538. /* Validate thumbnail dimensions and issue appropriate messages */
  171539. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171540. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171541. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171542. totallen -= APP0_DATA_LEN;
  171543. if (totallen !=
  171544. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171545. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171546. } else if (datalen >= 6 &&
  171547. GETJOCTET(data[0]) == 0x4A &&
  171548. GETJOCTET(data[1]) == 0x46 &&
  171549. GETJOCTET(data[2]) == 0x58 &&
  171550. GETJOCTET(data[3]) == 0x58 &&
  171551. GETJOCTET(data[4]) == 0) {
  171552. /* Found JFIF "JFXX" extension APP0 marker */
  171553. /* The library doesn't actually do anything with these,
  171554. * but we try to produce a helpful trace message.
  171555. */
  171556. switch (GETJOCTET(data[5])) {
  171557. case 0x10:
  171558. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171559. break;
  171560. case 0x11:
  171561. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171562. break;
  171563. case 0x13:
  171564. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171565. break;
  171566. default:
  171567. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171568. GETJOCTET(data[5]), (int) totallen);
  171569. break;
  171570. }
  171571. } else {
  171572. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171573. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171574. }
  171575. }
  171576. LOCAL(void)
  171577. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171578. unsigned int datalen, INT32 remaining)
  171579. /* Examine first few bytes from an APP14.
  171580. * Take appropriate action if it is an Adobe marker.
  171581. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171582. */
  171583. {
  171584. unsigned int version, flags0, flags1, transform;
  171585. if (datalen >= APP14_DATA_LEN &&
  171586. GETJOCTET(data[0]) == 0x41 &&
  171587. GETJOCTET(data[1]) == 0x64 &&
  171588. GETJOCTET(data[2]) == 0x6F &&
  171589. GETJOCTET(data[3]) == 0x62 &&
  171590. GETJOCTET(data[4]) == 0x65) {
  171591. /* Found Adobe APP14 marker */
  171592. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171593. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171594. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171595. transform = GETJOCTET(data[11]);
  171596. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171597. cinfo->saw_Adobe_marker = TRUE;
  171598. cinfo->Adobe_transform = (UINT8) transform;
  171599. } else {
  171600. /* Start of APP14 does not match "Adobe", or too short */
  171601. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171602. }
  171603. }
  171604. METHODDEF(boolean)
  171605. get_interesting_appn (j_decompress_ptr cinfo)
  171606. /* Process an APP0 or APP14 marker without saving it */
  171607. {
  171608. INT32 length;
  171609. JOCTET b[APPN_DATA_LEN];
  171610. unsigned int i, numtoread;
  171611. INPUT_VARS(cinfo);
  171612. INPUT_2BYTES(cinfo, length, return FALSE);
  171613. length -= 2;
  171614. /* get the interesting part of the marker data */
  171615. if (length >= APPN_DATA_LEN)
  171616. numtoread = APPN_DATA_LEN;
  171617. else if (length > 0)
  171618. numtoread = (unsigned int) length;
  171619. else
  171620. numtoread = 0;
  171621. for (i = 0; i < numtoread; i++)
  171622. INPUT_BYTE(cinfo, b[i], return FALSE);
  171623. length -= numtoread;
  171624. /* process it */
  171625. switch (cinfo->unread_marker) {
  171626. case M_APP0:
  171627. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171628. break;
  171629. case M_APP14:
  171630. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171631. break;
  171632. default:
  171633. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171634. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171635. break;
  171636. }
  171637. /* skip any remaining data -- could be lots */
  171638. INPUT_SYNC(cinfo);
  171639. if (length > 0)
  171640. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171641. return TRUE;
  171642. }
  171643. #ifdef SAVE_MARKERS_SUPPORTED
  171644. METHODDEF(boolean)
  171645. save_marker (j_decompress_ptr cinfo)
  171646. /* Save an APPn or COM marker into the marker list */
  171647. {
  171648. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171649. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171650. unsigned int bytes_read, data_length;
  171651. JOCTET FAR * data;
  171652. INT32 length = 0;
  171653. INPUT_VARS(cinfo);
  171654. if (cur_marker == NULL) {
  171655. /* begin reading a marker */
  171656. INPUT_2BYTES(cinfo, length, return FALSE);
  171657. length -= 2;
  171658. if (length >= 0) { /* watch out for bogus length word */
  171659. /* figure out how much we want to save */
  171660. unsigned int limit;
  171661. if (cinfo->unread_marker == (int) M_COM)
  171662. limit = marker->length_limit_COM;
  171663. else
  171664. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171665. if ((unsigned int) length < limit)
  171666. limit = (unsigned int) length;
  171667. /* allocate and initialize the marker item */
  171668. cur_marker = (jpeg_saved_marker_ptr)
  171669. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171670. SIZEOF(struct jpeg_marker_struct) + limit);
  171671. cur_marker->next = NULL;
  171672. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171673. cur_marker->original_length = (unsigned int) length;
  171674. cur_marker->data_length = limit;
  171675. /* data area is just beyond the jpeg_marker_struct */
  171676. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171677. marker->cur_marker = cur_marker;
  171678. marker->bytes_read = 0;
  171679. bytes_read = 0;
  171680. data_length = limit;
  171681. } else {
  171682. /* deal with bogus length word */
  171683. bytes_read = data_length = 0;
  171684. data = NULL;
  171685. }
  171686. } else {
  171687. /* resume reading a marker */
  171688. bytes_read = marker->bytes_read;
  171689. data_length = cur_marker->data_length;
  171690. data = cur_marker->data + bytes_read;
  171691. }
  171692. while (bytes_read < data_length) {
  171693. INPUT_SYNC(cinfo); /* move the restart point to here */
  171694. marker->bytes_read = bytes_read;
  171695. /* If there's not at least one byte in buffer, suspend */
  171696. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171697. /* Copy bytes with reasonable rapidity */
  171698. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171699. *data++ = *next_input_byte++;
  171700. bytes_in_buffer--;
  171701. bytes_read++;
  171702. }
  171703. }
  171704. /* Done reading what we want to read */
  171705. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171706. /* Add new marker to end of list */
  171707. if (cinfo->marker_list == NULL) {
  171708. cinfo->marker_list = cur_marker;
  171709. } else {
  171710. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171711. while (prev->next != NULL)
  171712. prev = prev->next;
  171713. prev->next = cur_marker;
  171714. }
  171715. /* Reset pointer & calc remaining data length */
  171716. data = cur_marker->data;
  171717. length = cur_marker->original_length - data_length;
  171718. }
  171719. /* Reset to initial state for next marker */
  171720. marker->cur_marker = NULL;
  171721. /* Process the marker if interesting; else just make a generic trace msg */
  171722. switch (cinfo->unread_marker) {
  171723. case M_APP0:
  171724. examine_app0(cinfo, data, data_length, length);
  171725. break;
  171726. case M_APP14:
  171727. examine_app14(cinfo, data, data_length, length);
  171728. break;
  171729. default:
  171730. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171731. (int) (data_length + length));
  171732. break;
  171733. }
  171734. /* skip any remaining data -- could be lots */
  171735. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171736. if (length > 0)
  171737. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171738. return TRUE;
  171739. }
  171740. #endif /* SAVE_MARKERS_SUPPORTED */
  171741. METHODDEF(boolean)
  171742. skip_variable (j_decompress_ptr cinfo)
  171743. /* Skip over an unknown or uninteresting variable-length marker */
  171744. {
  171745. INT32 length;
  171746. INPUT_VARS(cinfo);
  171747. INPUT_2BYTES(cinfo, length, return FALSE);
  171748. length -= 2;
  171749. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171750. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171751. if (length > 0)
  171752. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171753. return TRUE;
  171754. }
  171755. /*
  171756. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171757. * Returns FALSE if had to suspend before reaching a marker;
  171758. * in that case cinfo->unread_marker is unchanged.
  171759. *
  171760. * Note that the result might not be a valid marker code,
  171761. * but it will never be 0 or FF.
  171762. */
  171763. LOCAL(boolean)
  171764. next_marker (j_decompress_ptr cinfo)
  171765. {
  171766. int c;
  171767. INPUT_VARS(cinfo);
  171768. for (;;) {
  171769. INPUT_BYTE(cinfo, c, return FALSE);
  171770. /* Skip any non-FF bytes.
  171771. * This may look a bit inefficient, but it will not occur in a valid file.
  171772. * We sync after each discarded byte so that a suspending data source
  171773. * can discard the byte from its buffer.
  171774. */
  171775. while (c != 0xFF) {
  171776. cinfo->marker->discarded_bytes++;
  171777. INPUT_SYNC(cinfo);
  171778. INPUT_BYTE(cinfo, c, return FALSE);
  171779. }
  171780. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171781. * pad bytes, so don't count them in discarded_bytes. We assume there
  171782. * will not be so many consecutive FF bytes as to overflow a suspending
  171783. * data source's input buffer.
  171784. */
  171785. do {
  171786. INPUT_BYTE(cinfo, c, return FALSE);
  171787. } while (c == 0xFF);
  171788. if (c != 0)
  171789. break; /* found a valid marker, exit loop */
  171790. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171791. * Discard it and loop back to try again.
  171792. */
  171793. cinfo->marker->discarded_bytes += 2;
  171794. INPUT_SYNC(cinfo);
  171795. }
  171796. if (cinfo->marker->discarded_bytes != 0) {
  171797. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171798. cinfo->marker->discarded_bytes = 0;
  171799. }
  171800. cinfo->unread_marker = c;
  171801. INPUT_SYNC(cinfo);
  171802. return TRUE;
  171803. }
  171804. LOCAL(boolean)
  171805. first_marker (j_decompress_ptr cinfo)
  171806. /* Like next_marker, but used to obtain the initial SOI marker. */
  171807. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171808. * we might well scan an entire input file before realizing it ain't JPEG.
  171809. * If an application wants to process non-JFIF files, it must seek to the
  171810. * SOI before calling the JPEG library.
  171811. */
  171812. {
  171813. int c, c2;
  171814. INPUT_VARS(cinfo);
  171815. INPUT_BYTE(cinfo, c, return FALSE);
  171816. INPUT_BYTE(cinfo, c2, return FALSE);
  171817. if (c != 0xFF || c2 != (int) M_SOI)
  171818. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171819. cinfo->unread_marker = c2;
  171820. INPUT_SYNC(cinfo);
  171821. return TRUE;
  171822. }
  171823. /*
  171824. * Read markers until SOS or EOI.
  171825. *
  171826. * Returns same codes as are defined for jpeg_consume_input:
  171827. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171828. */
  171829. METHODDEF(int)
  171830. read_markers (j_decompress_ptr cinfo)
  171831. {
  171832. /* Outer loop repeats once for each marker. */
  171833. for (;;) {
  171834. /* Collect the marker proper, unless we already did. */
  171835. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171836. if (cinfo->unread_marker == 0) {
  171837. if (! cinfo->marker->saw_SOI) {
  171838. if (! first_marker(cinfo))
  171839. return JPEG_SUSPENDED;
  171840. } else {
  171841. if (! next_marker(cinfo))
  171842. return JPEG_SUSPENDED;
  171843. }
  171844. }
  171845. /* At this point cinfo->unread_marker contains the marker code and the
  171846. * input point is just past the marker proper, but before any parameters.
  171847. * A suspension will cause us to return with this state still true.
  171848. */
  171849. switch (cinfo->unread_marker) {
  171850. case M_SOI:
  171851. if (! get_soi(cinfo))
  171852. return JPEG_SUSPENDED;
  171853. break;
  171854. case M_SOF0: /* Baseline */
  171855. case M_SOF1: /* Extended sequential, Huffman */
  171856. if (! get_sof(cinfo, FALSE, FALSE))
  171857. return JPEG_SUSPENDED;
  171858. break;
  171859. case M_SOF2: /* Progressive, Huffman */
  171860. if (! get_sof(cinfo, TRUE, FALSE))
  171861. return JPEG_SUSPENDED;
  171862. break;
  171863. case M_SOF9: /* Extended sequential, arithmetic */
  171864. if (! get_sof(cinfo, FALSE, TRUE))
  171865. return JPEG_SUSPENDED;
  171866. break;
  171867. case M_SOF10: /* Progressive, arithmetic */
  171868. if (! get_sof(cinfo, TRUE, TRUE))
  171869. return JPEG_SUSPENDED;
  171870. break;
  171871. /* Currently unsupported SOFn types */
  171872. case M_SOF3: /* Lossless, Huffman */
  171873. case M_SOF5: /* Differential sequential, Huffman */
  171874. case M_SOF6: /* Differential progressive, Huffman */
  171875. case M_SOF7: /* Differential lossless, Huffman */
  171876. case M_JPG: /* Reserved for JPEG extensions */
  171877. case M_SOF11: /* Lossless, arithmetic */
  171878. case M_SOF13: /* Differential sequential, arithmetic */
  171879. case M_SOF14: /* Differential progressive, arithmetic */
  171880. case M_SOF15: /* Differential lossless, arithmetic */
  171881. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171882. break;
  171883. case M_SOS:
  171884. if (! get_sos(cinfo))
  171885. return JPEG_SUSPENDED;
  171886. cinfo->unread_marker = 0; /* processed the marker */
  171887. return JPEG_REACHED_SOS;
  171888. case M_EOI:
  171889. TRACEMS(cinfo, 1, JTRC_EOI);
  171890. cinfo->unread_marker = 0; /* processed the marker */
  171891. return JPEG_REACHED_EOI;
  171892. case M_DAC:
  171893. if (! get_dac(cinfo))
  171894. return JPEG_SUSPENDED;
  171895. break;
  171896. case M_DHT:
  171897. if (! get_dht(cinfo))
  171898. return JPEG_SUSPENDED;
  171899. break;
  171900. case M_DQT:
  171901. if (! get_dqt(cinfo))
  171902. return JPEG_SUSPENDED;
  171903. break;
  171904. case M_DRI:
  171905. if (! get_dri(cinfo))
  171906. return JPEG_SUSPENDED;
  171907. break;
  171908. case M_APP0:
  171909. case M_APP1:
  171910. case M_APP2:
  171911. case M_APP3:
  171912. case M_APP4:
  171913. case M_APP5:
  171914. case M_APP6:
  171915. case M_APP7:
  171916. case M_APP8:
  171917. case M_APP9:
  171918. case M_APP10:
  171919. case M_APP11:
  171920. case M_APP12:
  171921. case M_APP13:
  171922. case M_APP14:
  171923. case M_APP15:
  171924. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171925. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171926. return JPEG_SUSPENDED;
  171927. break;
  171928. case M_COM:
  171929. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171930. return JPEG_SUSPENDED;
  171931. break;
  171932. case M_RST0: /* these are all parameterless */
  171933. case M_RST1:
  171934. case M_RST2:
  171935. case M_RST3:
  171936. case M_RST4:
  171937. case M_RST5:
  171938. case M_RST6:
  171939. case M_RST7:
  171940. case M_TEM:
  171941. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171942. break;
  171943. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171944. if (! skip_variable(cinfo))
  171945. return JPEG_SUSPENDED;
  171946. break;
  171947. default: /* must be DHP, EXP, JPGn, or RESn */
  171948. /* For now, we treat the reserved markers as fatal errors since they are
  171949. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171950. * Once the JPEG 3 version-number marker is well defined, this code
  171951. * ought to change!
  171952. */
  171953. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171954. break;
  171955. }
  171956. /* Successfully processed marker, so reset state variable */
  171957. cinfo->unread_marker = 0;
  171958. } /* end loop */
  171959. }
  171960. /*
  171961. * Read a restart marker, which is expected to appear next in the datastream;
  171962. * if the marker is not there, take appropriate recovery action.
  171963. * Returns FALSE if suspension is required.
  171964. *
  171965. * This is called by the entropy decoder after it has read an appropriate
  171966. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171967. * has already read a marker from the data source. Under normal conditions
  171968. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171969. * it holds a marker which the decoder will be unable to read past.
  171970. */
  171971. METHODDEF(boolean)
  171972. read_restart_marker (j_decompress_ptr cinfo)
  171973. {
  171974. /* Obtain a marker unless we already did. */
  171975. /* Note that next_marker will complain if it skips any data. */
  171976. if (cinfo->unread_marker == 0) {
  171977. if (! next_marker(cinfo))
  171978. return FALSE;
  171979. }
  171980. if (cinfo->unread_marker ==
  171981. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171982. /* Normal case --- swallow the marker and let entropy decoder continue */
  171983. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171984. cinfo->unread_marker = 0;
  171985. } else {
  171986. /* Uh-oh, the restart markers have been messed up. */
  171987. /* Let the data source manager determine how to resync. */
  171988. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171989. cinfo->marker->next_restart_num))
  171990. return FALSE;
  171991. }
  171992. /* Update next-restart state */
  171993. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171994. return TRUE;
  171995. }
  171996. /*
  171997. * This is the default resync_to_restart method for data source managers
  171998. * to use if they don't have any better approach. Some data source managers
  171999. * may be able to back up, or may have additional knowledge about the data
  172000. * which permits a more intelligent recovery strategy; such managers would
  172001. * presumably supply their own resync method.
  172002. *
  172003. * read_restart_marker calls resync_to_restart if it finds a marker other than
  172004. * the restart marker it was expecting. (This code is *not* used unless
  172005. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  172006. * the marker code actually found (might be anything, except 0 or FF).
  172007. * The desired restart marker number (0..7) is passed as a parameter.
  172008. * This routine is supposed to apply whatever error recovery strategy seems
  172009. * appropriate in order to position the input stream to the next data segment.
  172010. * Note that cinfo->unread_marker is treated as a marker appearing before
  172011. * the current data-source input point; usually it should be reset to zero
  172012. * before returning.
  172013. * Returns FALSE if suspension is required.
  172014. *
  172015. * This implementation is substantially constrained by wanting to treat the
  172016. * input as a data stream; this means we can't back up. Therefore, we have
  172017. * only the following actions to work with:
  172018. * 1. Simply discard the marker and let the entropy decoder resume at next
  172019. * byte of file.
  172020. * 2. Read forward until we find another marker, discarding intervening
  172021. * data. (In theory we could look ahead within the current bufferload,
  172022. * without having to discard data if we don't find the desired marker.
  172023. * This idea is not implemented here, in part because it makes behavior
  172024. * dependent on buffer size and chance buffer-boundary positions.)
  172025. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  172026. * This will cause the entropy decoder to process an empty data segment,
  172027. * inserting dummy zeroes, and then we will reprocess the marker.
  172028. *
  172029. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  172030. * appropriate if the found marker is a future restart marker (indicating
  172031. * that we have missed the desired restart marker, probably because it got
  172032. * corrupted).
  172033. * We apply #2 or #3 if the found marker is a restart marker no more than
  172034. * two counts behind or ahead of the expected one. We also apply #2 if the
  172035. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  172036. * If the found marker is a restart marker more than 2 counts away, we do #1
  172037. * (too much risk that the marker is erroneous; with luck we will be able to
  172038. * resync at some future point).
  172039. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  172040. * overrunning the end of a scan. An implementation limited to single-scan
  172041. * files might find it better to apply #2 for markers other than EOI, since
  172042. * any other marker would have to be bogus data in that case.
  172043. */
  172044. GLOBAL(boolean)
  172045. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  172046. {
  172047. int marker = cinfo->unread_marker;
  172048. int action = 1;
  172049. /* Always put up a warning. */
  172050. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  172051. /* Outer loop handles repeated decision after scanning forward. */
  172052. for (;;) {
  172053. if (marker < (int) M_SOF0)
  172054. action = 2; /* invalid marker */
  172055. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  172056. action = 3; /* valid non-restart marker */
  172057. else {
  172058. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  172059. marker == ((int) M_RST0 + ((desired+2) & 7)))
  172060. action = 3; /* one of the next two expected restarts */
  172061. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172062. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172063. action = 2; /* a prior restart, so advance */
  172064. else
  172065. action = 1; /* desired restart or too far away */
  172066. }
  172067. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172068. switch (action) {
  172069. case 1:
  172070. /* Discard marker and let entropy decoder resume processing. */
  172071. cinfo->unread_marker = 0;
  172072. return TRUE;
  172073. case 2:
  172074. /* Scan to the next marker, and repeat the decision loop. */
  172075. if (! next_marker(cinfo))
  172076. return FALSE;
  172077. marker = cinfo->unread_marker;
  172078. break;
  172079. case 3:
  172080. /* Return without advancing past this marker. */
  172081. /* Entropy decoder will be forced to process an empty segment. */
  172082. return TRUE;
  172083. }
  172084. } /* end loop */
  172085. }
  172086. /*
  172087. * Reset marker processing state to begin a fresh datastream.
  172088. */
  172089. METHODDEF(void)
  172090. reset_marker_reader (j_decompress_ptr cinfo)
  172091. {
  172092. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172093. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172094. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172095. cinfo->unread_marker = 0; /* no pending marker */
  172096. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172097. marker->pub.saw_SOF = FALSE;
  172098. marker->pub.discarded_bytes = 0;
  172099. marker->cur_marker = NULL;
  172100. }
  172101. /*
  172102. * Initialize the marker reader module.
  172103. * This is called only once, when the decompression object is created.
  172104. */
  172105. GLOBAL(void)
  172106. jinit_marker_reader (j_decompress_ptr cinfo)
  172107. {
  172108. my_marker_ptr2 marker;
  172109. int i;
  172110. /* Create subobject in permanent pool */
  172111. marker = (my_marker_ptr2)
  172112. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172113. SIZEOF(my_marker_reader));
  172114. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172115. /* Initialize public method pointers */
  172116. marker->pub.reset_marker_reader = reset_marker_reader;
  172117. marker->pub.read_markers = read_markers;
  172118. marker->pub.read_restart_marker = read_restart_marker;
  172119. /* Initialize COM/APPn processing.
  172120. * By default, we examine and then discard APP0 and APP14,
  172121. * but simply discard COM and all other APPn.
  172122. */
  172123. marker->process_COM = skip_variable;
  172124. marker->length_limit_COM = 0;
  172125. for (i = 0; i < 16; i++) {
  172126. marker->process_APPn[i] = skip_variable;
  172127. marker->length_limit_APPn[i] = 0;
  172128. }
  172129. marker->process_APPn[0] = get_interesting_appn;
  172130. marker->process_APPn[14] = get_interesting_appn;
  172131. /* Reset marker processing state */
  172132. reset_marker_reader(cinfo);
  172133. }
  172134. /*
  172135. * Control saving of COM and APPn markers into marker_list.
  172136. */
  172137. #ifdef SAVE_MARKERS_SUPPORTED
  172138. GLOBAL(void)
  172139. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172140. unsigned int length_limit)
  172141. {
  172142. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172143. long maxlength;
  172144. jpeg_marker_parser_method processor;
  172145. /* Length limit mustn't be larger than what we can allocate
  172146. * (should only be a concern in a 16-bit environment).
  172147. */
  172148. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172149. if (((long) length_limit) > maxlength)
  172150. length_limit = (unsigned int) maxlength;
  172151. /* Choose processor routine to use.
  172152. * APP0/APP14 have special requirements.
  172153. */
  172154. if (length_limit) {
  172155. processor = save_marker;
  172156. /* If saving APP0/APP14, save at least enough for our internal use. */
  172157. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172158. length_limit = APP0_DATA_LEN;
  172159. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172160. length_limit = APP14_DATA_LEN;
  172161. } else {
  172162. processor = skip_variable;
  172163. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172164. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172165. processor = get_interesting_appn;
  172166. }
  172167. if (marker_code == (int) M_COM) {
  172168. marker->process_COM = processor;
  172169. marker->length_limit_COM = length_limit;
  172170. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172171. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172172. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172173. } else
  172174. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172175. }
  172176. #endif /* SAVE_MARKERS_SUPPORTED */
  172177. /*
  172178. * Install a special processing method for COM or APPn markers.
  172179. */
  172180. GLOBAL(void)
  172181. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172182. jpeg_marker_parser_method routine)
  172183. {
  172184. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172185. if (marker_code == (int) M_COM)
  172186. marker->process_COM = routine;
  172187. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172188. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172189. else
  172190. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172191. }
  172192. /*** End of inlined file: jdmarker.c ***/
  172193. /*** Start of inlined file: jdmaster.c ***/
  172194. #define JPEG_INTERNALS
  172195. /* Private state */
  172196. typedef struct {
  172197. struct jpeg_decomp_master pub; /* public fields */
  172198. int pass_number; /* # of passes completed */
  172199. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172200. /* Saved references to initialized quantizer modules,
  172201. * in case we need to switch modes.
  172202. */
  172203. struct jpeg_color_quantizer * quantizer_1pass;
  172204. struct jpeg_color_quantizer * quantizer_2pass;
  172205. } my_decomp_master;
  172206. typedef my_decomp_master * my_master_ptr6;
  172207. /*
  172208. * Determine whether merged upsample/color conversion should be used.
  172209. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172210. */
  172211. LOCAL(boolean)
  172212. use_merged_upsample (j_decompress_ptr cinfo)
  172213. {
  172214. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172215. /* Merging is the equivalent of plain box-filter upsampling */
  172216. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172217. return FALSE;
  172218. /* jdmerge.c only supports YCC=>RGB color conversion */
  172219. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172220. cinfo->out_color_space != JCS_RGB ||
  172221. cinfo->out_color_components != RGB_PIXELSIZE)
  172222. return FALSE;
  172223. /* and it only handles 2h1v or 2h2v sampling ratios */
  172224. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172225. cinfo->comp_info[1].h_samp_factor != 1 ||
  172226. cinfo->comp_info[2].h_samp_factor != 1 ||
  172227. cinfo->comp_info[0].v_samp_factor > 2 ||
  172228. cinfo->comp_info[1].v_samp_factor != 1 ||
  172229. cinfo->comp_info[2].v_samp_factor != 1)
  172230. return FALSE;
  172231. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172232. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172233. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172234. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172235. return FALSE;
  172236. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172237. return TRUE; /* by golly, it'll work... */
  172238. #else
  172239. return FALSE;
  172240. #endif
  172241. }
  172242. /*
  172243. * Compute output image dimensions and related values.
  172244. * NOTE: this is exported for possible use by application.
  172245. * Hence it mustn't do anything that can't be done twice.
  172246. * Also note that it may be called before the master module is initialized!
  172247. */
  172248. GLOBAL(void)
  172249. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172250. /* Do computations that are needed before master selection phase */
  172251. {
  172252. #ifdef IDCT_SCALING_SUPPORTED
  172253. int ci;
  172254. jpeg_component_info *compptr;
  172255. #endif
  172256. /* Prevent application from calling me at wrong times */
  172257. if (cinfo->global_state != DSTATE_READY)
  172258. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172259. #ifdef IDCT_SCALING_SUPPORTED
  172260. /* Compute actual output image dimensions and DCT scaling choices. */
  172261. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172262. /* Provide 1/8 scaling */
  172263. cinfo->output_width = (JDIMENSION)
  172264. jdiv_round_up((long) cinfo->image_width, 8L);
  172265. cinfo->output_height = (JDIMENSION)
  172266. jdiv_round_up((long) cinfo->image_height, 8L);
  172267. cinfo->min_DCT_scaled_size = 1;
  172268. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172269. /* Provide 1/4 scaling */
  172270. cinfo->output_width = (JDIMENSION)
  172271. jdiv_round_up((long) cinfo->image_width, 4L);
  172272. cinfo->output_height = (JDIMENSION)
  172273. jdiv_round_up((long) cinfo->image_height, 4L);
  172274. cinfo->min_DCT_scaled_size = 2;
  172275. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172276. /* Provide 1/2 scaling */
  172277. cinfo->output_width = (JDIMENSION)
  172278. jdiv_round_up((long) cinfo->image_width, 2L);
  172279. cinfo->output_height = (JDIMENSION)
  172280. jdiv_round_up((long) cinfo->image_height, 2L);
  172281. cinfo->min_DCT_scaled_size = 4;
  172282. } else {
  172283. /* Provide 1/1 scaling */
  172284. cinfo->output_width = cinfo->image_width;
  172285. cinfo->output_height = cinfo->image_height;
  172286. cinfo->min_DCT_scaled_size = DCTSIZE;
  172287. }
  172288. /* In selecting the actual DCT scaling for each component, we try to
  172289. * scale up the chroma components via IDCT scaling rather than upsampling.
  172290. * This saves time if the upsampler gets to use 1:1 scaling.
  172291. * Note this code assumes that the supported DCT scalings are powers of 2.
  172292. */
  172293. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172294. ci++, compptr++) {
  172295. int ssize = cinfo->min_DCT_scaled_size;
  172296. while (ssize < DCTSIZE &&
  172297. (compptr->h_samp_factor * ssize * 2 <=
  172298. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172299. (compptr->v_samp_factor * ssize * 2 <=
  172300. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172301. ssize = ssize * 2;
  172302. }
  172303. compptr->DCT_scaled_size = ssize;
  172304. }
  172305. /* Recompute downsampled dimensions of components;
  172306. * application needs to know these if using raw downsampled data.
  172307. */
  172308. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172309. ci++, compptr++) {
  172310. /* Size in samples, after IDCT scaling */
  172311. compptr->downsampled_width = (JDIMENSION)
  172312. jdiv_round_up((long) cinfo->image_width *
  172313. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172314. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172315. compptr->downsampled_height = (JDIMENSION)
  172316. jdiv_round_up((long) cinfo->image_height *
  172317. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172318. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172319. }
  172320. #else /* !IDCT_SCALING_SUPPORTED */
  172321. /* Hardwire it to "no scaling" */
  172322. cinfo->output_width = cinfo->image_width;
  172323. cinfo->output_height = cinfo->image_height;
  172324. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172325. * and has computed unscaled downsampled_width and downsampled_height.
  172326. */
  172327. #endif /* IDCT_SCALING_SUPPORTED */
  172328. /* Report number of components in selected colorspace. */
  172329. /* Probably this should be in the color conversion module... */
  172330. switch (cinfo->out_color_space) {
  172331. case JCS_GRAYSCALE:
  172332. cinfo->out_color_components = 1;
  172333. break;
  172334. case JCS_RGB:
  172335. #if RGB_PIXELSIZE != 3
  172336. cinfo->out_color_components = RGB_PIXELSIZE;
  172337. break;
  172338. #endif /* else share code with YCbCr */
  172339. case JCS_YCbCr:
  172340. cinfo->out_color_components = 3;
  172341. break;
  172342. case JCS_CMYK:
  172343. case JCS_YCCK:
  172344. cinfo->out_color_components = 4;
  172345. break;
  172346. default: /* else must be same colorspace as in file */
  172347. cinfo->out_color_components = cinfo->num_components;
  172348. break;
  172349. }
  172350. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172351. cinfo->out_color_components);
  172352. /* See if upsampler will want to emit more than one row at a time */
  172353. if (use_merged_upsample(cinfo))
  172354. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172355. else
  172356. cinfo->rec_outbuf_height = 1;
  172357. }
  172358. /*
  172359. * Several decompression processes need to range-limit values to the range
  172360. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172361. * due to noise introduced by quantization, roundoff error, etc. These
  172362. * processes are inner loops and need to be as fast as possible. On most
  172363. * machines, particularly CPUs with pipelines or instruction prefetch,
  172364. * a (subscript-check-less) C table lookup
  172365. * x = sample_range_limit[x];
  172366. * is faster than explicit tests
  172367. * if (x < 0) x = 0;
  172368. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172369. * These processes all use a common table prepared by the routine below.
  172370. *
  172371. * For most steps we can mathematically guarantee that the initial value
  172372. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172373. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172374. * limiting step (just after the IDCT), a wildly out-of-range value is
  172375. * possible if the input data is corrupt. To avoid any chance of indexing
  172376. * off the end of memory and getting a bad-pointer trap, we perform the
  172377. * post-IDCT limiting thus:
  172378. * x = range_limit[x & MASK];
  172379. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172380. * samples. Under normal circumstances this is more than enough range and
  172381. * a correct output will be generated; with bogus input data the mask will
  172382. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172383. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172384. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172385. * So the post-IDCT limiting table ends up looking like this:
  172386. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172387. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172388. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172389. * 0,1,...,CENTERJSAMPLE-1
  172390. * Negative inputs select values from the upper half of the table after
  172391. * masking.
  172392. *
  172393. * We can save some space by overlapping the start of the post-IDCT table
  172394. * with the simpler range limiting table. The post-IDCT table begins at
  172395. * sample_range_limit + CENTERJSAMPLE.
  172396. *
  172397. * Note that the table is allocated in near data space on PCs; it's small
  172398. * enough and used often enough to justify this.
  172399. */
  172400. LOCAL(void)
  172401. prepare_range_limit_table (j_decompress_ptr cinfo)
  172402. /* Allocate and fill in the sample_range_limit table */
  172403. {
  172404. JSAMPLE * table;
  172405. int i;
  172406. table = (JSAMPLE *)
  172407. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172408. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172409. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172410. cinfo->sample_range_limit = table;
  172411. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172412. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172413. /* Main part of "simple" table: limit[x] = x */
  172414. for (i = 0; i <= MAXJSAMPLE; i++)
  172415. table[i] = (JSAMPLE) i;
  172416. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172417. /* End of simple table, rest of first half of post-IDCT table */
  172418. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172419. table[i] = MAXJSAMPLE;
  172420. /* Second half of post-IDCT table */
  172421. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172422. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172423. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172424. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172425. }
  172426. /*
  172427. * Master selection of decompression modules.
  172428. * This is done once at jpeg_start_decompress time. We determine
  172429. * which modules will be used and give them appropriate initialization calls.
  172430. * We also initialize the decompressor input side to begin consuming data.
  172431. *
  172432. * Since jpeg_read_header has finished, we know what is in the SOF
  172433. * and (first) SOS markers. We also have all the application parameter
  172434. * settings.
  172435. */
  172436. LOCAL(void)
  172437. master_selection (j_decompress_ptr cinfo)
  172438. {
  172439. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172440. boolean use_c_buffer;
  172441. long samplesperrow;
  172442. JDIMENSION jd_samplesperrow;
  172443. /* Initialize dimensions and other stuff */
  172444. jpeg_calc_output_dimensions(cinfo);
  172445. prepare_range_limit_table(cinfo);
  172446. /* Width of an output scanline must be representable as JDIMENSION. */
  172447. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172448. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172449. if ((long) jd_samplesperrow != samplesperrow)
  172450. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172451. /* Initialize my private state */
  172452. master->pass_number = 0;
  172453. master->using_merged_upsample = use_merged_upsample(cinfo);
  172454. /* Color quantizer selection */
  172455. master->quantizer_1pass = NULL;
  172456. master->quantizer_2pass = NULL;
  172457. /* No mode changes if not using buffered-image mode. */
  172458. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172459. cinfo->enable_1pass_quant = FALSE;
  172460. cinfo->enable_external_quant = FALSE;
  172461. cinfo->enable_2pass_quant = FALSE;
  172462. }
  172463. if (cinfo->quantize_colors) {
  172464. if (cinfo->raw_data_out)
  172465. ERREXIT(cinfo, JERR_NOTIMPL);
  172466. /* 2-pass quantizer only works in 3-component color space. */
  172467. if (cinfo->out_color_components != 3) {
  172468. cinfo->enable_1pass_quant = TRUE;
  172469. cinfo->enable_external_quant = FALSE;
  172470. cinfo->enable_2pass_quant = FALSE;
  172471. cinfo->colormap = NULL;
  172472. } else if (cinfo->colormap != NULL) {
  172473. cinfo->enable_external_quant = TRUE;
  172474. } else if (cinfo->two_pass_quantize) {
  172475. cinfo->enable_2pass_quant = TRUE;
  172476. } else {
  172477. cinfo->enable_1pass_quant = TRUE;
  172478. }
  172479. if (cinfo->enable_1pass_quant) {
  172480. #ifdef QUANT_1PASS_SUPPORTED
  172481. jinit_1pass_quantizer(cinfo);
  172482. master->quantizer_1pass = cinfo->cquantize;
  172483. #else
  172484. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172485. #endif
  172486. }
  172487. /* We use the 2-pass code to map to external colormaps. */
  172488. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172489. #ifdef QUANT_2PASS_SUPPORTED
  172490. jinit_2pass_quantizer(cinfo);
  172491. master->quantizer_2pass = cinfo->cquantize;
  172492. #else
  172493. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172494. #endif
  172495. }
  172496. /* If both quantizers are initialized, the 2-pass one is left active;
  172497. * this is necessary for starting with quantization to an external map.
  172498. */
  172499. }
  172500. /* Post-processing: in particular, color conversion first */
  172501. if (! cinfo->raw_data_out) {
  172502. if (master->using_merged_upsample) {
  172503. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172504. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172505. #else
  172506. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172507. #endif
  172508. } else {
  172509. jinit_color_deconverter(cinfo);
  172510. jinit_upsampler(cinfo);
  172511. }
  172512. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172513. }
  172514. /* Inverse DCT */
  172515. jinit_inverse_dct(cinfo);
  172516. /* Entropy decoding: either Huffman or arithmetic coding. */
  172517. if (cinfo->arith_code) {
  172518. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172519. } else {
  172520. if (cinfo->progressive_mode) {
  172521. #ifdef D_PROGRESSIVE_SUPPORTED
  172522. jinit_phuff_decoder(cinfo);
  172523. #else
  172524. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172525. #endif
  172526. } else
  172527. jinit_huff_decoder(cinfo);
  172528. }
  172529. /* Initialize principal buffer controllers. */
  172530. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172531. jinit_d_coef_controller(cinfo, use_c_buffer);
  172532. if (! cinfo->raw_data_out)
  172533. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172534. /* We can now tell the memory manager to allocate virtual arrays. */
  172535. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172536. /* Initialize input side of decompressor to consume first scan. */
  172537. (*cinfo->inputctl->start_input_pass) (cinfo);
  172538. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172539. /* If jpeg_start_decompress will read the whole file, initialize
  172540. * progress monitoring appropriately. The input step is counted
  172541. * as one pass.
  172542. */
  172543. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172544. cinfo->inputctl->has_multiple_scans) {
  172545. int nscans;
  172546. /* Estimate number of scans to set pass_limit. */
  172547. if (cinfo->progressive_mode) {
  172548. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172549. nscans = 2 + 3 * cinfo->num_components;
  172550. } else {
  172551. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172552. nscans = cinfo->num_components;
  172553. }
  172554. cinfo->progress->pass_counter = 0L;
  172555. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172556. cinfo->progress->completed_passes = 0;
  172557. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172558. /* Count the input pass as done */
  172559. master->pass_number++;
  172560. }
  172561. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172562. }
  172563. /*
  172564. * Per-pass setup.
  172565. * This is called at the beginning of each output pass. We determine which
  172566. * modules will be active during this pass and give them appropriate
  172567. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172568. * is a "real" output pass or a dummy pass for color quantization.
  172569. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172570. */
  172571. METHODDEF(void)
  172572. prepare_for_output_pass (j_decompress_ptr cinfo)
  172573. {
  172574. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172575. if (master->pub.is_dummy_pass) {
  172576. #ifdef QUANT_2PASS_SUPPORTED
  172577. /* Final pass of 2-pass quantization */
  172578. master->pub.is_dummy_pass = FALSE;
  172579. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172580. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172581. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172582. #else
  172583. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172584. #endif /* QUANT_2PASS_SUPPORTED */
  172585. } else {
  172586. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172587. /* Select new quantization method */
  172588. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172589. cinfo->cquantize = master->quantizer_2pass;
  172590. master->pub.is_dummy_pass = TRUE;
  172591. } else if (cinfo->enable_1pass_quant) {
  172592. cinfo->cquantize = master->quantizer_1pass;
  172593. } else {
  172594. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172595. }
  172596. }
  172597. (*cinfo->idct->start_pass) (cinfo);
  172598. (*cinfo->coef->start_output_pass) (cinfo);
  172599. if (! cinfo->raw_data_out) {
  172600. if (! master->using_merged_upsample)
  172601. (*cinfo->cconvert->start_pass) (cinfo);
  172602. (*cinfo->upsample->start_pass) (cinfo);
  172603. if (cinfo->quantize_colors)
  172604. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172605. (*cinfo->post->start_pass) (cinfo,
  172606. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172607. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172608. }
  172609. }
  172610. /* Set up progress monitor's pass info if present */
  172611. if (cinfo->progress != NULL) {
  172612. cinfo->progress->completed_passes = master->pass_number;
  172613. cinfo->progress->total_passes = master->pass_number +
  172614. (master->pub.is_dummy_pass ? 2 : 1);
  172615. /* In buffered-image mode, we assume one more output pass if EOI not
  172616. * yet reached, but no more passes if EOI has been reached.
  172617. */
  172618. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172619. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172620. }
  172621. }
  172622. }
  172623. /*
  172624. * Finish up at end of an output pass.
  172625. */
  172626. METHODDEF(void)
  172627. finish_output_pass (j_decompress_ptr cinfo)
  172628. {
  172629. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172630. if (cinfo->quantize_colors)
  172631. (*cinfo->cquantize->finish_pass) (cinfo);
  172632. master->pass_number++;
  172633. }
  172634. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172635. /*
  172636. * Switch to a new external colormap between output passes.
  172637. */
  172638. GLOBAL(void)
  172639. jpeg_new_colormap (j_decompress_ptr cinfo)
  172640. {
  172641. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172642. /* Prevent application from calling me at wrong times */
  172643. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172644. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172645. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172646. cinfo->colormap != NULL) {
  172647. /* Select 2-pass quantizer for external colormap use */
  172648. cinfo->cquantize = master->quantizer_2pass;
  172649. /* Notify quantizer of colormap change */
  172650. (*cinfo->cquantize->new_color_map) (cinfo);
  172651. master->pub.is_dummy_pass = FALSE; /* just in case */
  172652. } else
  172653. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172654. }
  172655. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172656. /*
  172657. * Initialize master decompression control and select active modules.
  172658. * This is performed at the start of jpeg_start_decompress.
  172659. */
  172660. GLOBAL(void)
  172661. jinit_master_decompress (j_decompress_ptr cinfo)
  172662. {
  172663. my_master_ptr6 master;
  172664. master = (my_master_ptr6)
  172665. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172666. SIZEOF(my_decomp_master));
  172667. cinfo->master = (struct jpeg_decomp_master *) master;
  172668. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172669. master->pub.finish_output_pass = finish_output_pass;
  172670. master->pub.is_dummy_pass = FALSE;
  172671. master_selection(cinfo);
  172672. }
  172673. /*** End of inlined file: jdmaster.c ***/
  172674. #undef FIX
  172675. /*** Start of inlined file: jdmerge.c ***/
  172676. #define JPEG_INTERNALS
  172677. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172678. /* Private subobject */
  172679. typedef struct {
  172680. struct jpeg_upsampler pub; /* public fields */
  172681. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172682. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172683. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172684. JSAMPARRAY output_buf));
  172685. /* Private state for YCC->RGB conversion */
  172686. int * Cr_r_tab; /* => table for Cr to R conversion */
  172687. int * Cb_b_tab; /* => table for Cb to B conversion */
  172688. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172689. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172690. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172691. * We need a "spare" row buffer to hold the second output row if the
  172692. * application provides just a one-row buffer; we also use the spare
  172693. * to discard the dummy last row if the image height is odd.
  172694. */
  172695. JSAMPROW spare_row;
  172696. boolean spare_full; /* T if spare buffer is occupied */
  172697. JDIMENSION out_row_width; /* samples per output row */
  172698. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172699. } my_upsampler;
  172700. typedef my_upsampler * my_upsample_ptr;
  172701. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172702. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172703. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172704. /*
  172705. * Initialize tables for YCC->RGB colorspace conversion.
  172706. * This is taken directly from jdcolor.c; see that file for more info.
  172707. */
  172708. LOCAL(void)
  172709. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172710. {
  172711. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172712. int i;
  172713. INT32 x;
  172714. SHIFT_TEMPS
  172715. upsample->Cr_r_tab = (int *)
  172716. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172717. (MAXJSAMPLE+1) * SIZEOF(int));
  172718. upsample->Cb_b_tab = (int *)
  172719. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172720. (MAXJSAMPLE+1) * SIZEOF(int));
  172721. upsample->Cr_g_tab = (INT32 *)
  172722. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172723. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172724. upsample->Cb_g_tab = (INT32 *)
  172725. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172726. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172727. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172728. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172729. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172730. /* Cr=>R value is nearest int to 1.40200 * x */
  172731. upsample->Cr_r_tab[i] = (int)
  172732. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172733. /* Cb=>B value is nearest int to 1.77200 * x */
  172734. upsample->Cb_b_tab[i] = (int)
  172735. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172736. /* Cr=>G value is scaled-up -0.71414 * x */
  172737. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172738. /* Cb=>G value is scaled-up -0.34414 * x */
  172739. /* We also add in ONE_HALF so that need not do it in inner loop */
  172740. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172741. }
  172742. }
  172743. /*
  172744. * Initialize for an upsampling pass.
  172745. */
  172746. METHODDEF(void)
  172747. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172748. {
  172749. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172750. /* Mark the spare buffer empty */
  172751. upsample->spare_full = FALSE;
  172752. /* Initialize total-height counter for detecting bottom of image */
  172753. upsample->rows_to_go = cinfo->output_height;
  172754. }
  172755. /*
  172756. * Control routine to do upsampling (and color conversion).
  172757. *
  172758. * The control routine just handles the row buffering considerations.
  172759. */
  172760. METHODDEF(void)
  172761. merged_2v_upsample (j_decompress_ptr cinfo,
  172762. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172763. JDIMENSION,
  172764. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172765. JDIMENSION out_rows_avail)
  172766. /* 2:1 vertical sampling case: may need a spare row. */
  172767. {
  172768. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172769. JSAMPROW work_ptrs[2];
  172770. JDIMENSION num_rows; /* number of rows returned to caller */
  172771. if (upsample->spare_full) {
  172772. /* If we have a spare row saved from a previous cycle, just return it. */
  172773. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172774. 1, upsample->out_row_width);
  172775. num_rows = 1;
  172776. upsample->spare_full = FALSE;
  172777. } else {
  172778. /* Figure number of rows to return to caller. */
  172779. num_rows = 2;
  172780. /* Not more than the distance to the end of the image. */
  172781. if (num_rows > upsample->rows_to_go)
  172782. num_rows = upsample->rows_to_go;
  172783. /* And not more than what the client can accept: */
  172784. out_rows_avail -= *out_row_ctr;
  172785. if (num_rows > out_rows_avail)
  172786. num_rows = out_rows_avail;
  172787. /* Create output pointer array for upsampler. */
  172788. work_ptrs[0] = output_buf[*out_row_ctr];
  172789. if (num_rows > 1) {
  172790. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172791. } else {
  172792. work_ptrs[1] = upsample->spare_row;
  172793. upsample->spare_full = TRUE;
  172794. }
  172795. /* Now do the upsampling. */
  172796. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172797. }
  172798. /* Adjust counts */
  172799. *out_row_ctr += num_rows;
  172800. upsample->rows_to_go -= num_rows;
  172801. /* When the buffer is emptied, declare this input row group consumed */
  172802. if (! upsample->spare_full)
  172803. (*in_row_group_ctr)++;
  172804. }
  172805. METHODDEF(void)
  172806. merged_1v_upsample (j_decompress_ptr cinfo,
  172807. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172808. JDIMENSION,
  172809. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172810. JDIMENSION)
  172811. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172812. {
  172813. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172814. /* Just do the upsampling. */
  172815. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172816. output_buf + *out_row_ctr);
  172817. /* Adjust counts */
  172818. (*out_row_ctr)++;
  172819. (*in_row_group_ctr)++;
  172820. }
  172821. /*
  172822. * These are the routines invoked by the control routines to do
  172823. * the actual upsampling/conversion. One row group is processed per call.
  172824. *
  172825. * Note: since we may be writing directly into application-supplied buffers,
  172826. * we have to be honest about the output width; we can't assume the buffer
  172827. * has been rounded up to an even width.
  172828. */
  172829. /*
  172830. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172831. */
  172832. METHODDEF(void)
  172833. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172834. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172835. JSAMPARRAY output_buf)
  172836. {
  172837. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172838. register int y, cred, cgreen, cblue;
  172839. int cb, cr;
  172840. register JSAMPROW outptr;
  172841. JSAMPROW inptr0, inptr1, inptr2;
  172842. JDIMENSION col;
  172843. /* copy these pointers into registers if possible */
  172844. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172845. int * Crrtab = upsample->Cr_r_tab;
  172846. int * Cbbtab = upsample->Cb_b_tab;
  172847. INT32 * Crgtab = upsample->Cr_g_tab;
  172848. INT32 * Cbgtab = upsample->Cb_g_tab;
  172849. SHIFT_TEMPS
  172850. inptr0 = input_buf[0][in_row_group_ctr];
  172851. inptr1 = input_buf[1][in_row_group_ctr];
  172852. inptr2 = input_buf[2][in_row_group_ctr];
  172853. outptr = output_buf[0];
  172854. /* Loop for each pair of output pixels */
  172855. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172856. /* Do the chroma part of the calculation */
  172857. cb = GETJSAMPLE(*inptr1++);
  172858. cr = GETJSAMPLE(*inptr2++);
  172859. cred = Crrtab[cr];
  172860. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172861. cblue = Cbbtab[cb];
  172862. /* Fetch 2 Y values and emit 2 pixels */
  172863. y = GETJSAMPLE(*inptr0++);
  172864. outptr[RGB_RED] = range_limit[y + cred];
  172865. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172866. outptr[RGB_BLUE] = range_limit[y + cblue];
  172867. outptr += RGB_PIXELSIZE;
  172868. y = GETJSAMPLE(*inptr0++);
  172869. outptr[RGB_RED] = range_limit[y + cred];
  172870. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172871. outptr[RGB_BLUE] = range_limit[y + cblue];
  172872. outptr += RGB_PIXELSIZE;
  172873. }
  172874. /* If image width is odd, do the last output column separately */
  172875. if (cinfo->output_width & 1) {
  172876. cb = GETJSAMPLE(*inptr1);
  172877. cr = GETJSAMPLE(*inptr2);
  172878. cred = Crrtab[cr];
  172879. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172880. cblue = Cbbtab[cb];
  172881. y = GETJSAMPLE(*inptr0);
  172882. outptr[RGB_RED] = range_limit[y + cred];
  172883. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172884. outptr[RGB_BLUE] = range_limit[y + cblue];
  172885. }
  172886. }
  172887. /*
  172888. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172889. */
  172890. METHODDEF(void)
  172891. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172892. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172893. JSAMPARRAY output_buf)
  172894. {
  172895. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172896. register int y, cred, cgreen, cblue;
  172897. int cb, cr;
  172898. register JSAMPROW outptr0, outptr1;
  172899. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172900. JDIMENSION col;
  172901. /* copy these pointers into registers if possible */
  172902. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172903. int * Crrtab = upsample->Cr_r_tab;
  172904. int * Cbbtab = upsample->Cb_b_tab;
  172905. INT32 * Crgtab = upsample->Cr_g_tab;
  172906. INT32 * Cbgtab = upsample->Cb_g_tab;
  172907. SHIFT_TEMPS
  172908. inptr00 = input_buf[0][in_row_group_ctr*2];
  172909. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172910. inptr1 = input_buf[1][in_row_group_ctr];
  172911. inptr2 = input_buf[2][in_row_group_ctr];
  172912. outptr0 = output_buf[0];
  172913. outptr1 = output_buf[1];
  172914. /* Loop for each group of output pixels */
  172915. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172916. /* Do the chroma part of the calculation */
  172917. cb = GETJSAMPLE(*inptr1++);
  172918. cr = GETJSAMPLE(*inptr2++);
  172919. cred = Crrtab[cr];
  172920. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172921. cblue = Cbbtab[cb];
  172922. /* Fetch 4 Y values and emit 4 pixels */
  172923. y = GETJSAMPLE(*inptr00++);
  172924. outptr0[RGB_RED] = range_limit[y + cred];
  172925. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172926. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172927. outptr0 += RGB_PIXELSIZE;
  172928. y = GETJSAMPLE(*inptr00++);
  172929. outptr0[RGB_RED] = range_limit[y + cred];
  172930. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172931. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172932. outptr0 += RGB_PIXELSIZE;
  172933. y = GETJSAMPLE(*inptr01++);
  172934. outptr1[RGB_RED] = range_limit[y + cred];
  172935. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172936. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172937. outptr1 += RGB_PIXELSIZE;
  172938. y = GETJSAMPLE(*inptr01++);
  172939. outptr1[RGB_RED] = range_limit[y + cred];
  172940. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172941. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172942. outptr1 += RGB_PIXELSIZE;
  172943. }
  172944. /* If image width is odd, do the last output column separately */
  172945. if (cinfo->output_width & 1) {
  172946. cb = GETJSAMPLE(*inptr1);
  172947. cr = GETJSAMPLE(*inptr2);
  172948. cred = Crrtab[cr];
  172949. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172950. cblue = Cbbtab[cb];
  172951. y = GETJSAMPLE(*inptr00);
  172952. outptr0[RGB_RED] = range_limit[y + cred];
  172953. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172954. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172955. y = GETJSAMPLE(*inptr01);
  172956. outptr1[RGB_RED] = range_limit[y + cred];
  172957. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172958. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172959. }
  172960. }
  172961. /*
  172962. * Module initialization routine for merged upsampling/color conversion.
  172963. *
  172964. * NB: this is called under the conditions determined by use_merged_upsample()
  172965. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172966. * of this module; no safety checks are made here.
  172967. */
  172968. GLOBAL(void)
  172969. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172970. {
  172971. my_upsample_ptr upsample;
  172972. upsample = (my_upsample_ptr)
  172973. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172974. SIZEOF(my_upsampler));
  172975. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172976. upsample->pub.start_pass = start_pass_merged_upsample;
  172977. upsample->pub.need_context_rows = FALSE;
  172978. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172979. if (cinfo->max_v_samp_factor == 2) {
  172980. upsample->pub.upsample = merged_2v_upsample;
  172981. upsample->upmethod = h2v2_merged_upsample;
  172982. /* Allocate a spare row buffer */
  172983. upsample->spare_row = (JSAMPROW)
  172984. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172985. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172986. } else {
  172987. upsample->pub.upsample = merged_1v_upsample;
  172988. upsample->upmethod = h2v1_merged_upsample;
  172989. /* No spare row needed */
  172990. upsample->spare_row = NULL;
  172991. }
  172992. build_ycc_rgb_table2(cinfo);
  172993. }
  172994. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172995. /*** End of inlined file: jdmerge.c ***/
  172996. #undef ASSIGN_STATE
  172997. /*** Start of inlined file: jdphuff.c ***/
  172998. #define JPEG_INTERNALS
  172999. #ifdef D_PROGRESSIVE_SUPPORTED
  173000. /*
  173001. * Expanded entropy decoder object for progressive Huffman decoding.
  173002. *
  173003. * The savable_state subrecord contains fields that change within an MCU,
  173004. * but must not be updated permanently until we complete the MCU.
  173005. */
  173006. typedef struct {
  173007. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  173008. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  173009. } savable_state3;
  173010. /* This macro is to work around compilers with missing or broken
  173011. * structure assignment. You'll need to fix this code if you have
  173012. * such a compiler and you change MAX_COMPS_IN_SCAN.
  173013. */
  173014. #ifndef NO_STRUCT_ASSIGN
  173015. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  173016. #else
  173017. #if MAX_COMPS_IN_SCAN == 4
  173018. #define ASSIGN_STATE(dest,src) \
  173019. ((dest).EOBRUN = (src).EOBRUN, \
  173020. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  173021. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  173022. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  173023. (dest).last_dc_val[3] = (src).last_dc_val[3])
  173024. #endif
  173025. #endif
  173026. typedef struct {
  173027. struct jpeg_entropy_decoder pub; /* public fields */
  173028. /* These fields are loaded into local variables at start of each MCU.
  173029. * In case of suspension, we exit WITHOUT updating them.
  173030. */
  173031. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  173032. savable_state3 saved; /* Other state at start of MCU */
  173033. /* These fields are NOT loaded into local working state. */
  173034. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  173035. /* Pointers to derived tables (these workspaces have image lifespan) */
  173036. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  173037. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  173038. } phuff_entropy_decoder;
  173039. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  173040. /* Forward declarations */
  173041. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  173042. JBLOCKROW *MCU_data));
  173043. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  173044. JBLOCKROW *MCU_data));
  173045. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  173046. JBLOCKROW *MCU_data));
  173047. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  173048. JBLOCKROW *MCU_data));
  173049. /*
  173050. * Initialize for a Huffman-compressed scan.
  173051. */
  173052. METHODDEF(void)
  173053. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  173054. {
  173055. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173056. boolean is_DC_band, bad;
  173057. int ci, coefi, tbl;
  173058. int *coef_bit_ptr;
  173059. jpeg_component_info * compptr;
  173060. is_DC_band = (cinfo->Ss == 0);
  173061. /* Validate scan parameters */
  173062. bad = FALSE;
  173063. if (is_DC_band) {
  173064. if (cinfo->Se != 0)
  173065. bad = TRUE;
  173066. } else {
  173067. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173068. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173069. bad = TRUE;
  173070. /* AC scans may have only one component */
  173071. if (cinfo->comps_in_scan != 1)
  173072. bad = TRUE;
  173073. }
  173074. if (cinfo->Ah != 0) {
  173075. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173076. if (cinfo->Al != cinfo->Ah-1)
  173077. bad = TRUE;
  173078. }
  173079. if (cinfo->Al > 13) /* need not check for < 0 */
  173080. bad = TRUE;
  173081. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173082. * but the spec doesn't say so, and we try to be liberal about what we
  173083. * accept. Note: large Al values could result in out-of-range DC
  173084. * coefficients during early scans, leading to bizarre displays due to
  173085. * overflows in the IDCT math. But we won't crash.
  173086. */
  173087. if (bad)
  173088. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173089. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173090. /* Update progression status, and verify that scan order is legal.
  173091. * Note that inter-scan inconsistencies are treated as warnings
  173092. * not fatal errors ... not clear if this is right way to behave.
  173093. */
  173094. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173095. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173096. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173097. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173098. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173099. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173100. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173101. if (cinfo->Ah != expected)
  173102. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173103. coef_bit_ptr[coefi] = cinfo->Al;
  173104. }
  173105. }
  173106. /* Select MCU decoding routine */
  173107. if (cinfo->Ah == 0) {
  173108. if (is_DC_band)
  173109. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173110. else
  173111. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173112. } else {
  173113. if (is_DC_band)
  173114. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173115. else
  173116. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173117. }
  173118. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173119. compptr = cinfo->cur_comp_info[ci];
  173120. /* Make sure requested tables are present, and compute derived tables.
  173121. * We may build same derived table more than once, but it's not expensive.
  173122. */
  173123. if (is_DC_band) {
  173124. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173125. tbl = compptr->dc_tbl_no;
  173126. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173127. & entropy->derived_tbls[tbl]);
  173128. }
  173129. } else {
  173130. tbl = compptr->ac_tbl_no;
  173131. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173132. & entropy->derived_tbls[tbl]);
  173133. /* remember the single active table */
  173134. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173135. }
  173136. /* Initialize DC predictions to 0 */
  173137. entropy->saved.last_dc_val[ci] = 0;
  173138. }
  173139. /* Initialize bitread state variables */
  173140. entropy->bitstate.bits_left = 0;
  173141. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173142. entropy->pub.insufficient_data = FALSE;
  173143. /* Initialize private state variables */
  173144. entropy->saved.EOBRUN = 0;
  173145. /* Initialize restart counter */
  173146. entropy->restarts_to_go = cinfo->restart_interval;
  173147. }
  173148. /*
  173149. * Check for a restart marker & resynchronize decoder.
  173150. * Returns FALSE if must suspend.
  173151. */
  173152. LOCAL(boolean)
  173153. process_restartp (j_decompress_ptr cinfo)
  173154. {
  173155. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173156. int ci;
  173157. /* Throw away any unused bits remaining in bit buffer; */
  173158. /* include any full bytes in next_marker's count of discarded bytes */
  173159. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173160. entropy->bitstate.bits_left = 0;
  173161. /* Advance past the RSTn marker */
  173162. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173163. return FALSE;
  173164. /* Re-initialize DC predictions to 0 */
  173165. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173166. entropy->saved.last_dc_val[ci] = 0;
  173167. /* Re-init EOB run count, too */
  173168. entropy->saved.EOBRUN = 0;
  173169. /* Reset restart counter */
  173170. entropy->restarts_to_go = cinfo->restart_interval;
  173171. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173172. * against a marker. In that case we will end up treating the next data
  173173. * segment as empty, and we can avoid producing bogus output pixels by
  173174. * leaving the flag set.
  173175. */
  173176. if (cinfo->unread_marker == 0)
  173177. entropy->pub.insufficient_data = FALSE;
  173178. return TRUE;
  173179. }
  173180. /*
  173181. * Huffman MCU decoding.
  173182. * Each of these routines decodes and returns one MCU's worth of
  173183. * Huffman-compressed coefficients.
  173184. * The coefficients are reordered from zigzag order into natural array order,
  173185. * but are not dequantized.
  173186. *
  173187. * The i'th block of the MCU is stored into the block pointed to by
  173188. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173189. *
  173190. * We return FALSE if data source requested suspension. In that case no
  173191. * changes have been made to permanent state. (Exception: some output
  173192. * coefficients may already have been assigned. This is harmless for
  173193. * spectral selection, since we'll just re-assign them on the next call.
  173194. * Successive approximation AC refinement has to be more careful, however.)
  173195. */
  173196. /*
  173197. * MCU decoding for DC initial scan (either spectral selection,
  173198. * or first pass of successive approximation).
  173199. */
  173200. METHODDEF(boolean)
  173201. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173202. {
  173203. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173204. int Al = cinfo->Al;
  173205. register int s, r;
  173206. int blkn, ci;
  173207. JBLOCKROW block;
  173208. BITREAD_STATE_VARS;
  173209. savable_state3 state;
  173210. d_derived_tbl * tbl;
  173211. jpeg_component_info * compptr;
  173212. /* Process restart marker if needed; may have to suspend */
  173213. if (cinfo->restart_interval) {
  173214. if (entropy->restarts_to_go == 0)
  173215. if (! process_restartp(cinfo))
  173216. return FALSE;
  173217. }
  173218. /* If we've run out of data, just leave the MCU set to zeroes.
  173219. * This way, we return uniform gray for the remainder of the segment.
  173220. */
  173221. if (! entropy->pub.insufficient_data) {
  173222. /* Load up working state */
  173223. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173224. ASSIGN_STATE(state, entropy->saved);
  173225. /* Outer loop handles each block in the MCU */
  173226. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173227. block = MCU_data[blkn];
  173228. ci = cinfo->MCU_membership[blkn];
  173229. compptr = cinfo->cur_comp_info[ci];
  173230. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173231. /* Decode a single block's worth of coefficients */
  173232. /* Section F.2.2.1: decode the DC coefficient difference */
  173233. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173234. if (s) {
  173235. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173236. r = GET_BITS(s);
  173237. s = HUFF_EXTEND(r, s);
  173238. }
  173239. /* Convert DC difference to actual value, update last_dc_val */
  173240. s += state.last_dc_val[ci];
  173241. state.last_dc_val[ci] = s;
  173242. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173243. (*block)[0] = (JCOEF) (s << Al);
  173244. }
  173245. /* Completed MCU, so update state */
  173246. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173247. ASSIGN_STATE(entropy->saved, state);
  173248. }
  173249. /* Account for restart interval (no-op if not using restarts) */
  173250. entropy->restarts_to_go--;
  173251. return TRUE;
  173252. }
  173253. /*
  173254. * MCU decoding for AC initial scan (either spectral selection,
  173255. * or first pass of successive approximation).
  173256. */
  173257. METHODDEF(boolean)
  173258. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173259. {
  173260. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173261. int Se = cinfo->Se;
  173262. int Al = cinfo->Al;
  173263. register int s, k, r;
  173264. unsigned int EOBRUN;
  173265. JBLOCKROW block;
  173266. BITREAD_STATE_VARS;
  173267. d_derived_tbl * tbl;
  173268. /* Process restart marker if needed; may have to suspend */
  173269. if (cinfo->restart_interval) {
  173270. if (entropy->restarts_to_go == 0)
  173271. if (! process_restartp(cinfo))
  173272. return FALSE;
  173273. }
  173274. /* If we've run out of data, just leave the MCU set to zeroes.
  173275. * This way, we return uniform gray for the remainder of the segment.
  173276. */
  173277. if (! entropy->pub.insufficient_data) {
  173278. /* Load up working state.
  173279. * We can avoid loading/saving bitread state if in an EOB run.
  173280. */
  173281. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173282. /* There is always only one block per MCU */
  173283. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173284. EOBRUN--; /* ...process it now (we do nothing) */
  173285. else {
  173286. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173287. block = MCU_data[0];
  173288. tbl = entropy->ac_derived_tbl;
  173289. for (k = cinfo->Ss; k <= Se; k++) {
  173290. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173291. r = s >> 4;
  173292. s &= 15;
  173293. if (s) {
  173294. k += r;
  173295. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173296. r = GET_BITS(s);
  173297. s = HUFF_EXTEND(r, s);
  173298. /* Scale and output coefficient in natural (dezigzagged) order */
  173299. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173300. } else {
  173301. if (r == 15) { /* ZRL */
  173302. k += 15; /* skip 15 zeroes in band */
  173303. } else { /* EOBr, run length is 2^r + appended bits */
  173304. EOBRUN = 1 << r;
  173305. if (r) { /* EOBr, r > 0 */
  173306. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173307. r = GET_BITS(r);
  173308. EOBRUN += r;
  173309. }
  173310. EOBRUN--; /* this band is processed at this moment */
  173311. break; /* force end-of-band */
  173312. }
  173313. }
  173314. }
  173315. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173316. }
  173317. /* Completed MCU, so update state */
  173318. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173319. }
  173320. /* Account for restart interval (no-op if not using restarts) */
  173321. entropy->restarts_to_go--;
  173322. return TRUE;
  173323. }
  173324. /*
  173325. * MCU decoding for DC successive approximation refinement scan.
  173326. * Note: we assume such scans can be multi-component, although the spec
  173327. * is not very clear on the point.
  173328. */
  173329. METHODDEF(boolean)
  173330. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173331. {
  173332. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173333. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173334. int blkn;
  173335. JBLOCKROW block;
  173336. BITREAD_STATE_VARS;
  173337. /* Process restart marker if needed; may have to suspend */
  173338. if (cinfo->restart_interval) {
  173339. if (entropy->restarts_to_go == 0)
  173340. if (! process_restartp(cinfo))
  173341. return FALSE;
  173342. }
  173343. /* Not worth the cycles to check insufficient_data here,
  173344. * since we will not change the data anyway if we read zeroes.
  173345. */
  173346. /* Load up working state */
  173347. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173348. /* Outer loop handles each block in the MCU */
  173349. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173350. block = MCU_data[blkn];
  173351. /* Encoded data is simply the next bit of the two's-complement DC value */
  173352. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173353. if (GET_BITS(1))
  173354. (*block)[0] |= p1;
  173355. /* Note: since we use |=, repeating the assignment later is safe */
  173356. }
  173357. /* Completed MCU, so update state */
  173358. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173359. /* Account for restart interval (no-op if not using restarts) */
  173360. entropy->restarts_to_go--;
  173361. return TRUE;
  173362. }
  173363. /*
  173364. * MCU decoding for AC successive approximation refinement scan.
  173365. */
  173366. METHODDEF(boolean)
  173367. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173368. {
  173369. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173370. int Se = cinfo->Se;
  173371. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173372. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173373. register int s, k, r;
  173374. unsigned int EOBRUN;
  173375. JBLOCKROW block;
  173376. JCOEFPTR thiscoef;
  173377. BITREAD_STATE_VARS;
  173378. d_derived_tbl * tbl;
  173379. int num_newnz;
  173380. int newnz_pos[DCTSIZE2];
  173381. /* Process restart marker if needed; may have to suspend */
  173382. if (cinfo->restart_interval) {
  173383. if (entropy->restarts_to_go == 0)
  173384. if (! process_restartp(cinfo))
  173385. return FALSE;
  173386. }
  173387. /* If we've run out of data, don't modify the MCU.
  173388. */
  173389. if (! entropy->pub.insufficient_data) {
  173390. /* Load up working state */
  173391. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173392. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173393. /* There is always only one block per MCU */
  173394. block = MCU_data[0];
  173395. tbl = entropy->ac_derived_tbl;
  173396. /* If we are forced to suspend, we must undo the assignments to any newly
  173397. * nonzero coefficients in the block, because otherwise we'd get confused
  173398. * next time about which coefficients were already nonzero.
  173399. * But we need not undo addition of bits to already-nonzero coefficients;
  173400. * instead, we can test the current bit to see if we already did it.
  173401. */
  173402. num_newnz = 0;
  173403. /* initialize coefficient loop counter to start of band */
  173404. k = cinfo->Ss;
  173405. if (EOBRUN == 0) {
  173406. for (; k <= Se; k++) {
  173407. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173408. r = s >> 4;
  173409. s &= 15;
  173410. if (s) {
  173411. if (s != 1) /* size of new coef should always be 1 */
  173412. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173413. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173414. if (GET_BITS(1))
  173415. s = p1; /* newly nonzero coef is positive */
  173416. else
  173417. s = m1; /* newly nonzero coef is negative */
  173418. } else {
  173419. if (r != 15) {
  173420. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173421. if (r) {
  173422. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173423. r = GET_BITS(r);
  173424. EOBRUN += r;
  173425. }
  173426. break; /* rest of block is handled by EOB logic */
  173427. }
  173428. /* note s = 0 for processing ZRL */
  173429. }
  173430. /* Advance over already-nonzero coefs and r still-zero coefs,
  173431. * appending correction bits to the nonzeroes. A correction bit is 1
  173432. * if the absolute value of the coefficient must be increased.
  173433. */
  173434. do {
  173435. thiscoef = *block + jpeg_natural_order[k];
  173436. if (*thiscoef != 0) {
  173437. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173438. if (GET_BITS(1)) {
  173439. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173440. if (*thiscoef >= 0)
  173441. *thiscoef += p1;
  173442. else
  173443. *thiscoef += m1;
  173444. }
  173445. }
  173446. } else {
  173447. if (--r < 0)
  173448. break; /* reached target zero coefficient */
  173449. }
  173450. k++;
  173451. } while (k <= Se);
  173452. if (s) {
  173453. int pos = jpeg_natural_order[k];
  173454. /* Output newly nonzero coefficient */
  173455. (*block)[pos] = (JCOEF) s;
  173456. /* Remember its position in case we have to suspend */
  173457. newnz_pos[num_newnz++] = pos;
  173458. }
  173459. }
  173460. }
  173461. if (EOBRUN > 0) {
  173462. /* Scan any remaining coefficient positions after the end-of-band
  173463. * (the last newly nonzero coefficient, if any). Append a correction
  173464. * bit to each already-nonzero coefficient. A correction bit is 1
  173465. * if the absolute value of the coefficient must be increased.
  173466. */
  173467. for (; k <= Se; k++) {
  173468. thiscoef = *block + jpeg_natural_order[k];
  173469. if (*thiscoef != 0) {
  173470. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173471. if (GET_BITS(1)) {
  173472. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173473. if (*thiscoef >= 0)
  173474. *thiscoef += p1;
  173475. else
  173476. *thiscoef += m1;
  173477. }
  173478. }
  173479. }
  173480. }
  173481. /* Count one block completed in EOB run */
  173482. EOBRUN--;
  173483. }
  173484. /* Completed MCU, so update state */
  173485. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173486. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173487. }
  173488. /* Account for restart interval (no-op if not using restarts) */
  173489. entropy->restarts_to_go--;
  173490. return TRUE;
  173491. undoit:
  173492. /* Re-zero any output coefficients that we made newly nonzero */
  173493. while (num_newnz > 0)
  173494. (*block)[newnz_pos[--num_newnz]] = 0;
  173495. return FALSE;
  173496. }
  173497. /*
  173498. * Module initialization routine for progressive Huffman entropy decoding.
  173499. */
  173500. GLOBAL(void)
  173501. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173502. {
  173503. phuff_entropy_ptr2 entropy;
  173504. int *coef_bit_ptr;
  173505. int ci, i;
  173506. entropy = (phuff_entropy_ptr2)
  173507. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173508. SIZEOF(phuff_entropy_decoder));
  173509. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173510. entropy->pub.start_pass = start_pass_phuff_decoder;
  173511. /* Mark derived tables unallocated */
  173512. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173513. entropy->derived_tbls[i] = NULL;
  173514. }
  173515. /* Create progression status table */
  173516. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173517. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173518. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173519. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173520. for (ci = 0; ci < cinfo->num_components; ci++)
  173521. for (i = 0; i < DCTSIZE2; i++)
  173522. *coef_bit_ptr++ = -1;
  173523. }
  173524. #endif /* D_PROGRESSIVE_SUPPORTED */
  173525. /*** End of inlined file: jdphuff.c ***/
  173526. /*** Start of inlined file: jdpostct.c ***/
  173527. #define JPEG_INTERNALS
  173528. /* Private buffer controller object */
  173529. typedef struct {
  173530. struct jpeg_d_post_controller pub; /* public fields */
  173531. /* Color quantization source buffer: this holds output data from
  173532. * the upsample/color conversion step to be passed to the quantizer.
  173533. * For two-pass color quantization, we need a full-image buffer;
  173534. * for one-pass operation, a strip buffer is sufficient.
  173535. */
  173536. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173537. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173538. JDIMENSION strip_height; /* buffer size in rows */
  173539. /* for two-pass mode only: */
  173540. JDIMENSION starting_row; /* row # of first row in current strip */
  173541. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173542. } my_post_controller;
  173543. typedef my_post_controller * my_post_ptr;
  173544. /* Forward declarations */
  173545. METHODDEF(void) post_process_1pass
  173546. JPP((j_decompress_ptr cinfo,
  173547. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173548. JDIMENSION in_row_groups_avail,
  173549. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173550. JDIMENSION out_rows_avail));
  173551. #ifdef QUANT_2PASS_SUPPORTED
  173552. METHODDEF(void) post_process_prepass
  173553. JPP((j_decompress_ptr cinfo,
  173554. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173555. JDIMENSION in_row_groups_avail,
  173556. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173557. JDIMENSION out_rows_avail));
  173558. METHODDEF(void) post_process_2pass
  173559. JPP((j_decompress_ptr cinfo,
  173560. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173561. JDIMENSION in_row_groups_avail,
  173562. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173563. JDIMENSION out_rows_avail));
  173564. #endif
  173565. /*
  173566. * Initialize for a processing pass.
  173567. */
  173568. METHODDEF(void)
  173569. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173570. {
  173571. my_post_ptr post = (my_post_ptr) cinfo->post;
  173572. switch (pass_mode) {
  173573. case JBUF_PASS_THRU:
  173574. if (cinfo->quantize_colors) {
  173575. /* Single-pass processing with color quantization. */
  173576. post->pub.post_process_data = post_process_1pass;
  173577. /* We could be doing buffered-image output before starting a 2-pass
  173578. * color quantization; in that case, jinit_d_post_controller did not
  173579. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173580. */
  173581. if (post->buffer == NULL) {
  173582. post->buffer = (*cinfo->mem->access_virt_sarray)
  173583. ((j_common_ptr) cinfo, post->whole_image,
  173584. (JDIMENSION) 0, post->strip_height, TRUE);
  173585. }
  173586. } else {
  173587. /* For single-pass processing without color quantization,
  173588. * I have no work to do; just call the upsampler directly.
  173589. */
  173590. post->pub.post_process_data = cinfo->upsample->upsample;
  173591. }
  173592. break;
  173593. #ifdef QUANT_2PASS_SUPPORTED
  173594. case JBUF_SAVE_AND_PASS:
  173595. /* First pass of 2-pass quantization */
  173596. if (post->whole_image == NULL)
  173597. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173598. post->pub.post_process_data = post_process_prepass;
  173599. break;
  173600. case JBUF_CRANK_DEST:
  173601. /* Second pass of 2-pass quantization */
  173602. if (post->whole_image == NULL)
  173603. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173604. post->pub.post_process_data = post_process_2pass;
  173605. break;
  173606. #endif /* QUANT_2PASS_SUPPORTED */
  173607. default:
  173608. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173609. break;
  173610. }
  173611. post->starting_row = post->next_row = 0;
  173612. }
  173613. /*
  173614. * Process some data in the one-pass (strip buffer) case.
  173615. * This is used for color precision reduction as well as one-pass quantization.
  173616. */
  173617. METHODDEF(void)
  173618. post_process_1pass (j_decompress_ptr cinfo,
  173619. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173620. JDIMENSION in_row_groups_avail,
  173621. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173622. JDIMENSION out_rows_avail)
  173623. {
  173624. my_post_ptr post = (my_post_ptr) cinfo->post;
  173625. JDIMENSION num_rows, max_rows;
  173626. /* Fill the buffer, but not more than what we can dump out in one go. */
  173627. /* Note we rely on the upsampler to detect bottom of image. */
  173628. max_rows = out_rows_avail - *out_row_ctr;
  173629. if (max_rows > post->strip_height)
  173630. max_rows = post->strip_height;
  173631. num_rows = 0;
  173632. (*cinfo->upsample->upsample) (cinfo,
  173633. input_buf, in_row_group_ctr, in_row_groups_avail,
  173634. post->buffer, &num_rows, max_rows);
  173635. /* Quantize and emit data. */
  173636. (*cinfo->cquantize->color_quantize) (cinfo,
  173637. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173638. *out_row_ctr += num_rows;
  173639. }
  173640. #ifdef QUANT_2PASS_SUPPORTED
  173641. /*
  173642. * Process some data in the first pass of 2-pass quantization.
  173643. */
  173644. METHODDEF(void)
  173645. post_process_prepass (j_decompress_ptr cinfo,
  173646. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173647. JDIMENSION in_row_groups_avail,
  173648. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173649. JDIMENSION)
  173650. {
  173651. my_post_ptr post = (my_post_ptr) cinfo->post;
  173652. JDIMENSION old_next_row, num_rows;
  173653. /* Reposition virtual buffer if at start of strip. */
  173654. if (post->next_row == 0) {
  173655. post->buffer = (*cinfo->mem->access_virt_sarray)
  173656. ((j_common_ptr) cinfo, post->whole_image,
  173657. post->starting_row, post->strip_height, TRUE);
  173658. }
  173659. /* Upsample some data (up to a strip height's worth). */
  173660. old_next_row = post->next_row;
  173661. (*cinfo->upsample->upsample) (cinfo,
  173662. input_buf, in_row_group_ctr, in_row_groups_avail,
  173663. post->buffer, &post->next_row, post->strip_height);
  173664. /* Allow quantizer to scan new data. No data is emitted, */
  173665. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173666. if (post->next_row > old_next_row) {
  173667. num_rows = post->next_row - old_next_row;
  173668. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173669. (JSAMPARRAY) NULL, (int) num_rows);
  173670. *out_row_ctr += num_rows;
  173671. }
  173672. /* Advance if we filled the strip. */
  173673. if (post->next_row >= post->strip_height) {
  173674. post->starting_row += post->strip_height;
  173675. post->next_row = 0;
  173676. }
  173677. }
  173678. /*
  173679. * Process some data in the second pass of 2-pass quantization.
  173680. */
  173681. METHODDEF(void)
  173682. post_process_2pass (j_decompress_ptr cinfo,
  173683. JSAMPIMAGE, JDIMENSION *,
  173684. JDIMENSION,
  173685. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173686. JDIMENSION out_rows_avail)
  173687. {
  173688. my_post_ptr post = (my_post_ptr) cinfo->post;
  173689. JDIMENSION num_rows, max_rows;
  173690. /* Reposition virtual buffer if at start of strip. */
  173691. if (post->next_row == 0) {
  173692. post->buffer = (*cinfo->mem->access_virt_sarray)
  173693. ((j_common_ptr) cinfo, post->whole_image,
  173694. post->starting_row, post->strip_height, FALSE);
  173695. }
  173696. /* Determine number of rows to emit. */
  173697. num_rows = post->strip_height - post->next_row; /* available in strip */
  173698. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173699. if (num_rows > max_rows)
  173700. num_rows = max_rows;
  173701. /* We have to check bottom of image here, can't depend on upsampler. */
  173702. max_rows = cinfo->output_height - post->starting_row;
  173703. if (num_rows > max_rows)
  173704. num_rows = max_rows;
  173705. /* Quantize and emit data. */
  173706. (*cinfo->cquantize->color_quantize) (cinfo,
  173707. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173708. (int) num_rows);
  173709. *out_row_ctr += num_rows;
  173710. /* Advance if we filled the strip. */
  173711. post->next_row += num_rows;
  173712. if (post->next_row >= post->strip_height) {
  173713. post->starting_row += post->strip_height;
  173714. post->next_row = 0;
  173715. }
  173716. }
  173717. #endif /* QUANT_2PASS_SUPPORTED */
  173718. /*
  173719. * Initialize postprocessing controller.
  173720. */
  173721. GLOBAL(void)
  173722. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173723. {
  173724. my_post_ptr post;
  173725. post = (my_post_ptr)
  173726. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173727. SIZEOF(my_post_controller));
  173728. cinfo->post = (struct jpeg_d_post_controller *) post;
  173729. post->pub.start_pass = start_pass_dpost;
  173730. post->whole_image = NULL; /* flag for no virtual arrays */
  173731. post->buffer = NULL; /* flag for no strip buffer */
  173732. /* Create the quantization buffer, if needed */
  173733. if (cinfo->quantize_colors) {
  173734. /* The buffer strip height is max_v_samp_factor, which is typically
  173735. * an efficient number of rows for upsampling to return.
  173736. * (In the presence of output rescaling, we might want to be smarter?)
  173737. */
  173738. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173739. if (need_full_buffer) {
  173740. /* Two-pass color quantization: need full-image storage. */
  173741. /* We round up the number of rows to a multiple of the strip height. */
  173742. #ifdef QUANT_2PASS_SUPPORTED
  173743. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173744. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173745. cinfo->output_width * cinfo->out_color_components,
  173746. (JDIMENSION) jround_up((long) cinfo->output_height,
  173747. (long) post->strip_height),
  173748. post->strip_height);
  173749. #else
  173750. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173751. #endif /* QUANT_2PASS_SUPPORTED */
  173752. } else {
  173753. /* One-pass color quantization: just make a strip buffer. */
  173754. post->buffer = (*cinfo->mem->alloc_sarray)
  173755. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173756. cinfo->output_width * cinfo->out_color_components,
  173757. post->strip_height);
  173758. }
  173759. }
  173760. }
  173761. /*** End of inlined file: jdpostct.c ***/
  173762. #undef FIX
  173763. /*** Start of inlined file: jdsample.c ***/
  173764. #define JPEG_INTERNALS
  173765. /* Pointer to routine to upsample a single component */
  173766. typedef JMETHOD(void, upsample1_ptr,
  173767. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173768. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173769. /* Private subobject */
  173770. typedef struct {
  173771. struct jpeg_upsampler pub; /* public fields */
  173772. /* Color conversion buffer. When using separate upsampling and color
  173773. * conversion steps, this buffer holds one upsampled row group until it
  173774. * has been color converted and output.
  173775. * Note: we do not allocate any storage for component(s) which are full-size,
  173776. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173777. * simply set to point to the input data array, thereby avoiding copying.
  173778. */
  173779. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173780. /* Per-component upsampling method pointers */
  173781. upsample1_ptr methods[MAX_COMPONENTS];
  173782. int next_row_out; /* counts rows emitted from color_buf */
  173783. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173784. /* Height of an input row group for each component. */
  173785. int rowgroup_height[MAX_COMPONENTS];
  173786. /* These arrays save pixel expansion factors so that int_expand need not
  173787. * recompute them each time. They are unused for other upsampling methods.
  173788. */
  173789. UINT8 h_expand[MAX_COMPONENTS];
  173790. UINT8 v_expand[MAX_COMPONENTS];
  173791. } my_upsampler2;
  173792. typedef my_upsampler2 * my_upsample_ptr2;
  173793. /*
  173794. * Initialize for an upsampling pass.
  173795. */
  173796. METHODDEF(void)
  173797. start_pass_upsample (j_decompress_ptr cinfo)
  173798. {
  173799. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173800. /* Mark the conversion buffer empty */
  173801. upsample->next_row_out = cinfo->max_v_samp_factor;
  173802. /* Initialize total-height counter for detecting bottom of image */
  173803. upsample->rows_to_go = cinfo->output_height;
  173804. }
  173805. /*
  173806. * Control routine to do upsampling (and color conversion).
  173807. *
  173808. * In this version we upsample each component independently.
  173809. * We upsample one row group into the conversion buffer, then apply
  173810. * color conversion a row at a time.
  173811. */
  173812. METHODDEF(void)
  173813. sep_upsample (j_decompress_ptr cinfo,
  173814. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173815. JDIMENSION,
  173816. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173817. JDIMENSION out_rows_avail)
  173818. {
  173819. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173820. int ci;
  173821. jpeg_component_info * compptr;
  173822. JDIMENSION num_rows;
  173823. /* Fill the conversion buffer, if it's empty */
  173824. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173825. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173826. ci++, compptr++) {
  173827. /* Invoke per-component upsample method. Notice we pass a POINTER
  173828. * to color_buf[ci], so that fullsize_upsample can change it.
  173829. */
  173830. (*upsample->methods[ci]) (cinfo, compptr,
  173831. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173832. upsample->color_buf + ci);
  173833. }
  173834. upsample->next_row_out = 0;
  173835. }
  173836. /* Color-convert and emit rows */
  173837. /* How many we have in the buffer: */
  173838. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173839. /* Not more than the distance to the end of the image. Need this test
  173840. * in case the image height is not a multiple of max_v_samp_factor:
  173841. */
  173842. if (num_rows > upsample->rows_to_go)
  173843. num_rows = upsample->rows_to_go;
  173844. /* And not more than what the client can accept: */
  173845. out_rows_avail -= *out_row_ctr;
  173846. if (num_rows > out_rows_avail)
  173847. num_rows = out_rows_avail;
  173848. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173849. (JDIMENSION) upsample->next_row_out,
  173850. output_buf + *out_row_ctr,
  173851. (int) num_rows);
  173852. /* Adjust counts */
  173853. *out_row_ctr += num_rows;
  173854. upsample->rows_to_go -= num_rows;
  173855. upsample->next_row_out += num_rows;
  173856. /* When the buffer is emptied, declare this input row group consumed */
  173857. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173858. (*in_row_group_ctr)++;
  173859. }
  173860. /*
  173861. * These are the routines invoked by sep_upsample to upsample pixel values
  173862. * of a single component. One row group is processed per call.
  173863. */
  173864. /*
  173865. * For full-size components, we just make color_buf[ci] point at the
  173866. * input buffer, and thus avoid copying any data. Note that this is
  173867. * safe only because sep_upsample doesn't declare the input row group
  173868. * "consumed" until we are done color converting and emitting it.
  173869. */
  173870. METHODDEF(void)
  173871. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173872. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173873. {
  173874. *output_data_ptr = input_data;
  173875. }
  173876. /*
  173877. * This is a no-op version used for "uninteresting" components.
  173878. * These components will not be referenced by color conversion.
  173879. */
  173880. METHODDEF(void)
  173881. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173882. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173883. {
  173884. *output_data_ptr = NULL; /* safety check */
  173885. }
  173886. /*
  173887. * This version handles any integral sampling ratios.
  173888. * This is not used for typical JPEG files, so it need not be fast.
  173889. * Nor, for that matter, is it particularly accurate: the algorithm is
  173890. * simple replication of the input pixel onto the corresponding output
  173891. * pixels. The hi-falutin sampling literature refers to this as a
  173892. * "box filter". A box filter tends to introduce visible artifacts,
  173893. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173894. * you would be well advised to improve this code.
  173895. */
  173896. METHODDEF(void)
  173897. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173898. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173899. {
  173900. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173901. JSAMPARRAY output_data = *output_data_ptr;
  173902. register JSAMPROW inptr, outptr;
  173903. register JSAMPLE invalue;
  173904. register int h;
  173905. JSAMPROW outend;
  173906. int h_expand, v_expand;
  173907. int inrow, outrow;
  173908. h_expand = upsample->h_expand[compptr->component_index];
  173909. v_expand = upsample->v_expand[compptr->component_index];
  173910. inrow = outrow = 0;
  173911. while (outrow < cinfo->max_v_samp_factor) {
  173912. /* Generate one output row with proper horizontal expansion */
  173913. inptr = input_data[inrow];
  173914. outptr = output_data[outrow];
  173915. outend = outptr + cinfo->output_width;
  173916. while (outptr < outend) {
  173917. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173918. for (h = h_expand; h > 0; h--) {
  173919. *outptr++ = invalue;
  173920. }
  173921. }
  173922. /* Generate any additional output rows by duplicating the first one */
  173923. if (v_expand > 1) {
  173924. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173925. v_expand-1, cinfo->output_width);
  173926. }
  173927. inrow++;
  173928. outrow += v_expand;
  173929. }
  173930. }
  173931. /*
  173932. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173933. * It's still a box filter.
  173934. */
  173935. METHODDEF(void)
  173936. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173937. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173938. {
  173939. JSAMPARRAY output_data = *output_data_ptr;
  173940. register JSAMPROW inptr, outptr;
  173941. register JSAMPLE invalue;
  173942. JSAMPROW outend;
  173943. int inrow;
  173944. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173945. inptr = input_data[inrow];
  173946. outptr = output_data[inrow];
  173947. outend = outptr + cinfo->output_width;
  173948. while (outptr < outend) {
  173949. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173950. *outptr++ = invalue;
  173951. *outptr++ = invalue;
  173952. }
  173953. }
  173954. }
  173955. /*
  173956. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173957. * It's still a box filter.
  173958. */
  173959. METHODDEF(void)
  173960. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173961. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173962. {
  173963. JSAMPARRAY output_data = *output_data_ptr;
  173964. register JSAMPROW inptr, outptr;
  173965. register JSAMPLE invalue;
  173966. JSAMPROW outend;
  173967. int inrow, outrow;
  173968. inrow = outrow = 0;
  173969. while (outrow < cinfo->max_v_samp_factor) {
  173970. inptr = input_data[inrow];
  173971. outptr = output_data[outrow];
  173972. outend = outptr + cinfo->output_width;
  173973. while (outptr < outend) {
  173974. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173975. *outptr++ = invalue;
  173976. *outptr++ = invalue;
  173977. }
  173978. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173979. 1, cinfo->output_width);
  173980. inrow++;
  173981. outrow += 2;
  173982. }
  173983. }
  173984. /*
  173985. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173986. *
  173987. * The upsampling algorithm is linear interpolation between pixel centers,
  173988. * also known as a "triangle filter". This is a good compromise between
  173989. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173990. * of the way between input pixel centers.
  173991. *
  173992. * A note about the "bias" calculations: when rounding fractional values to
  173993. * integer, we do not want to always round 0.5 up to the next integer.
  173994. * If we did that, we'd introduce a noticeable bias towards larger values.
  173995. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173996. * alternate pixel locations (a simple ordered dither pattern).
  173997. */
  173998. METHODDEF(void)
  173999. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174000. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174001. {
  174002. JSAMPARRAY output_data = *output_data_ptr;
  174003. register JSAMPROW inptr, outptr;
  174004. register int invalue;
  174005. register JDIMENSION colctr;
  174006. int inrow;
  174007. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174008. inptr = input_data[inrow];
  174009. outptr = output_data[inrow];
  174010. /* Special case for first column */
  174011. invalue = GETJSAMPLE(*inptr++);
  174012. *outptr++ = (JSAMPLE) invalue;
  174013. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  174014. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174015. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  174016. invalue = GETJSAMPLE(*inptr++) * 3;
  174017. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  174018. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  174019. }
  174020. /* Special case for last column */
  174021. invalue = GETJSAMPLE(*inptr);
  174022. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  174023. *outptr++ = (JSAMPLE) invalue;
  174024. }
  174025. }
  174026. /*
  174027. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  174028. * Again a triangle filter; see comments for h2v1 case, above.
  174029. *
  174030. * It is OK for us to reference the adjacent input rows because we demanded
  174031. * context from the main buffer controller (see initialization code).
  174032. */
  174033. METHODDEF(void)
  174034. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174035. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174036. {
  174037. JSAMPARRAY output_data = *output_data_ptr;
  174038. register JSAMPROW inptr0, inptr1, outptr;
  174039. #if BITS_IN_JSAMPLE == 8
  174040. register int thiscolsum, lastcolsum, nextcolsum;
  174041. #else
  174042. register INT32 thiscolsum, lastcolsum, nextcolsum;
  174043. #endif
  174044. register JDIMENSION colctr;
  174045. int inrow, outrow, v;
  174046. inrow = outrow = 0;
  174047. while (outrow < cinfo->max_v_samp_factor) {
  174048. for (v = 0; v < 2; v++) {
  174049. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  174050. inptr0 = input_data[inrow];
  174051. if (v == 0) /* next nearest is row above */
  174052. inptr1 = input_data[inrow-1];
  174053. else /* next nearest is row below */
  174054. inptr1 = input_data[inrow+1];
  174055. outptr = output_data[outrow++];
  174056. /* Special case for first column */
  174057. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174058. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174059. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  174060. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174061. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174062. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174063. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174064. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174065. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174066. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174067. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174068. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174069. }
  174070. /* Special case for last column */
  174071. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174072. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174073. }
  174074. inrow++;
  174075. }
  174076. }
  174077. /*
  174078. * Module initialization routine for upsampling.
  174079. */
  174080. GLOBAL(void)
  174081. jinit_upsampler (j_decompress_ptr cinfo)
  174082. {
  174083. my_upsample_ptr2 upsample;
  174084. int ci;
  174085. jpeg_component_info * compptr;
  174086. boolean need_buffer, do_fancy;
  174087. int h_in_group, v_in_group, h_out_group, v_out_group;
  174088. upsample = (my_upsample_ptr2)
  174089. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174090. SIZEOF(my_upsampler2));
  174091. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174092. upsample->pub.start_pass = start_pass_upsample;
  174093. upsample->pub.upsample = sep_upsample;
  174094. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174095. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174096. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174097. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174098. * so don't ask for it.
  174099. */
  174100. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174101. /* Verify we can handle the sampling factors, select per-component methods,
  174102. * and create storage as needed.
  174103. */
  174104. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174105. ci++, compptr++) {
  174106. /* Compute size of an "input group" after IDCT scaling. This many samples
  174107. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174108. */
  174109. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174110. cinfo->min_DCT_scaled_size;
  174111. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174112. cinfo->min_DCT_scaled_size;
  174113. h_out_group = cinfo->max_h_samp_factor;
  174114. v_out_group = cinfo->max_v_samp_factor;
  174115. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174116. need_buffer = TRUE;
  174117. if (! compptr->component_needed) {
  174118. /* Don't bother to upsample an uninteresting component. */
  174119. upsample->methods[ci] = noop_upsample;
  174120. need_buffer = FALSE;
  174121. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174122. /* Fullsize components can be processed without any work. */
  174123. upsample->methods[ci] = fullsize_upsample;
  174124. need_buffer = FALSE;
  174125. } else if (h_in_group * 2 == h_out_group &&
  174126. v_in_group == v_out_group) {
  174127. /* Special cases for 2h1v upsampling */
  174128. if (do_fancy && compptr->downsampled_width > 2)
  174129. upsample->methods[ci] = h2v1_fancy_upsample;
  174130. else
  174131. upsample->methods[ci] = h2v1_upsample;
  174132. } else if (h_in_group * 2 == h_out_group &&
  174133. v_in_group * 2 == v_out_group) {
  174134. /* Special cases for 2h2v upsampling */
  174135. if (do_fancy && compptr->downsampled_width > 2) {
  174136. upsample->methods[ci] = h2v2_fancy_upsample;
  174137. upsample->pub.need_context_rows = TRUE;
  174138. } else
  174139. upsample->methods[ci] = h2v2_upsample;
  174140. } else if ((h_out_group % h_in_group) == 0 &&
  174141. (v_out_group % v_in_group) == 0) {
  174142. /* Generic integral-factors upsampling method */
  174143. upsample->methods[ci] = int_upsample;
  174144. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174145. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174146. } else
  174147. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174148. if (need_buffer) {
  174149. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174150. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174151. (JDIMENSION) jround_up((long) cinfo->output_width,
  174152. (long) cinfo->max_h_samp_factor),
  174153. (JDIMENSION) cinfo->max_v_samp_factor);
  174154. }
  174155. }
  174156. }
  174157. /*** End of inlined file: jdsample.c ***/
  174158. /*** Start of inlined file: jdtrans.c ***/
  174159. #define JPEG_INTERNALS
  174160. /* Forward declarations */
  174161. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174162. /*
  174163. * Read the coefficient arrays from a JPEG file.
  174164. * jpeg_read_header must be completed before calling this.
  174165. *
  174166. * The entire image is read into a set of virtual coefficient-block arrays,
  174167. * one per component. The return value is a pointer to the array of
  174168. * virtual-array descriptors. These can be manipulated directly via the
  174169. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174170. * To release the memory occupied by the virtual arrays, call
  174171. * jpeg_finish_decompress() when done with the data.
  174172. *
  174173. * An alternative usage is to simply obtain access to the coefficient arrays
  174174. * during a buffered-image-mode decompression operation. This is allowed
  174175. * after any jpeg_finish_output() call. The arrays can be accessed until
  174176. * jpeg_finish_decompress() is called. (Note that any call to the library
  174177. * may reposition the arrays, so don't rely on access_virt_barray() results
  174178. * to stay valid across library calls.)
  174179. *
  174180. * Returns NULL if suspended. This case need be checked only if
  174181. * a suspending data source is used.
  174182. */
  174183. GLOBAL(jvirt_barray_ptr *)
  174184. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174185. {
  174186. if (cinfo->global_state == DSTATE_READY) {
  174187. /* First call: initialize active modules */
  174188. transdecode_master_selection(cinfo);
  174189. cinfo->global_state = DSTATE_RDCOEFS;
  174190. }
  174191. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174192. /* Absorb whole file into the coef buffer */
  174193. for (;;) {
  174194. int retcode;
  174195. /* Call progress monitor hook if present */
  174196. if (cinfo->progress != NULL)
  174197. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174198. /* Absorb some more input */
  174199. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174200. if (retcode == JPEG_SUSPENDED)
  174201. return NULL;
  174202. if (retcode == JPEG_REACHED_EOI)
  174203. break;
  174204. /* Advance progress counter if appropriate */
  174205. if (cinfo->progress != NULL &&
  174206. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174207. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174208. /* startup underestimated number of scans; ratchet up one scan */
  174209. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174210. }
  174211. }
  174212. }
  174213. /* Set state so that jpeg_finish_decompress does the right thing */
  174214. cinfo->global_state = DSTATE_STOPPING;
  174215. }
  174216. /* At this point we should be in state DSTATE_STOPPING if being used
  174217. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174218. * to the coefficients during a full buffered-image-mode decompression.
  174219. */
  174220. if ((cinfo->global_state == DSTATE_STOPPING ||
  174221. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174222. return cinfo->coef->coef_arrays;
  174223. }
  174224. /* Oops, improper usage */
  174225. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174226. return NULL; /* keep compiler happy */
  174227. }
  174228. /*
  174229. * Master selection of decompression modules for transcoding.
  174230. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174231. */
  174232. LOCAL(void)
  174233. transdecode_master_selection (j_decompress_ptr cinfo)
  174234. {
  174235. /* This is effectively a buffered-image operation. */
  174236. cinfo->buffered_image = TRUE;
  174237. /* Entropy decoding: either Huffman or arithmetic coding. */
  174238. if (cinfo->arith_code) {
  174239. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174240. } else {
  174241. if (cinfo->progressive_mode) {
  174242. #ifdef D_PROGRESSIVE_SUPPORTED
  174243. jinit_phuff_decoder(cinfo);
  174244. #else
  174245. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174246. #endif
  174247. } else
  174248. jinit_huff_decoder(cinfo);
  174249. }
  174250. /* Always get a full-image coefficient buffer. */
  174251. jinit_d_coef_controller(cinfo, TRUE);
  174252. /* We can now tell the memory manager to allocate virtual arrays. */
  174253. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174254. /* Initialize input side of decompressor to consume first scan. */
  174255. (*cinfo->inputctl->start_input_pass) (cinfo);
  174256. /* Initialize progress monitoring. */
  174257. if (cinfo->progress != NULL) {
  174258. int nscans;
  174259. /* Estimate number of scans to set pass_limit. */
  174260. if (cinfo->progressive_mode) {
  174261. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174262. nscans = 2 + 3 * cinfo->num_components;
  174263. } else if (cinfo->inputctl->has_multiple_scans) {
  174264. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174265. nscans = cinfo->num_components;
  174266. } else {
  174267. nscans = 1;
  174268. }
  174269. cinfo->progress->pass_counter = 0L;
  174270. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174271. cinfo->progress->completed_passes = 0;
  174272. cinfo->progress->total_passes = 1;
  174273. }
  174274. }
  174275. /*** End of inlined file: jdtrans.c ***/
  174276. /*** Start of inlined file: jfdctflt.c ***/
  174277. #define JPEG_INTERNALS
  174278. #ifdef DCT_FLOAT_SUPPORTED
  174279. /*
  174280. * This module is specialized to the case DCTSIZE = 8.
  174281. */
  174282. #if DCTSIZE != 8
  174283. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174284. #endif
  174285. /*
  174286. * Perform the forward DCT on one block of samples.
  174287. */
  174288. GLOBAL(void)
  174289. jpeg_fdct_float (FAST_FLOAT * data)
  174290. {
  174291. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174292. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174293. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174294. FAST_FLOAT *dataptr;
  174295. int ctr;
  174296. /* Pass 1: process rows. */
  174297. dataptr = data;
  174298. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174299. tmp0 = dataptr[0] + dataptr[7];
  174300. tmp7 = dataptr[0] - dataptr[7];
  174301. tmp1 = dataptr[1] + dataptr[6];
  174302. tmp6 = dataptr[1] - dataptr[6];
  174303. tmp2 = dataptr[2] + dataptr[5];
  174304. tmp5 = dataptr[2] - dataptr[5];
  174305. tmp3 = dataptr[3] + dataptr[4];
  174306. tmp4 = dataptr[3] - dataptr[4];
  174307. /* Even part */
  174308. tmp10 = tmp0 + tmp3; /* phase 2 */
  174309. tmp13 = tmp0 - tmp3;
  174310. tmp11 = tmp1 + tmp2;
  174311. tmp12 = tmp1 - tmp2;
  174312. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174313. dataptr[4] = tmp10 - tmp11;
  174314. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174315. dataptr[2] = tmp13 + z1; /* phase 5 */
  174316. dataptr[6] = tmp13 - z1;
  174317. /* Odd part */
  174318. tmp10 = tmp4 + tmp5; /* phase 2 */
  174319. tmp11 = tmp5 + tmp6;
  174320. tmp12 = tmp6 + tmp7;
  174321. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174322. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174323. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174324. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174325. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174326. z11 = tmp7 + z3; /* phase 5 */
  174327. z13 = tmp7 - z3;
  174328. dataptr[5] = z13 + z2; /* phase 6 */
  174329. dataptr[3] = z13 - z2;
  174330. dataptr[1] = z11 + z4;
  174331. dataptr[7] = z11 - z4;
  174332. dataptr += DCTSIZE; /* advance pointer to next row */
  174333. }
  174334. /* Pass 2: process columns. */
  174335. dataptr = data;
  174336. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174337. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174338. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174339. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174340. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174341. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174342. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174343. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174344. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174345. /* Even part */
  174346. tmp10 = tmp0 + tmp3; /* phase 2 */
  174347. tmp13 = tmp0 - tmp3;
  174348. tmp11 = tmp1 + tmp2;
  174349. tmp12 = tmp1 - tmp2;
  174350. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174351. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174352. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174353. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174354. dataptr[DCTSIZE*6] = tmp13 - z1;
  174355. /* Odd part */
  174356. tmp10 = tmp4 + tmp5; /* phase 2 */
  174357. tmp11 = tmp5 + tmp6;
  174358. tmp12 = tmp6 + tmp7;
  174359. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174360. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174361. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174362. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174363. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174364. z11 = tmp7 + z3; /* phase 5 */
  174365. z13 = tmp7 - z3;
  174366. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174367. dataptr[DCTSIZE*3] = z13 - z2;
  174368. dataptr[DCTSIZE*1] = z11 + z4;
  174369. dataptr[DCTSIZE*7] = z11 - z4;
  174370. dataptr++; /* advance pointer to next column */
  174371. }
  174372. }
  174373. #endif /* DCT_FLOAT_SUPPORTED */
  174374. /*** End of inlined file: jfdctflt.c ***/
  174375. /*** Start of inlined file: jfdctint.c ***/
  174376. #define JPEG_INTERNALS
  174377. #ifdef DCT_ISLOW_SUPPORTED
  174378. /*
  174379. * This module is specialized to the case DCTSIZE = 8.
  174380. */
  174381. #if DCTSIZE != 8
  174382. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174383. #endif
  174384. /*
  174385. * The poop on this scaling stuff is as follows:
  174386. *
  174387. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174388. * larger than the true DCT outputs. The final outputs are therefore
  174389. * a factor of N larger than desired; since N=8 this can be cured by
  174390. * a simple right shift at the end of the algorithm. The advantage of
  174391. * this arrangement is that we save two multiplications per 1-D DCT,
  174392. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174393. * In the IJG code, this factor of 8 is removed by the quantization step
  174394. * (in jcdctmgr.c), NOT in this module.
  174395. *
  174396. * We have to do addition and subtraction of the integer inputs, which
  174397. * is no problem, and multiplication by fractional constants, which is
  174398. * a problem to do in integer arithmetic. We multiply all the constants
  174399. * by CONST_SCALE and convert them to integer constants (thus retaining
  174400. * CONST_BITS bits of precision in the constants). After doing a
  174401. * multiplication we have to divide the product by CONST_SCALE, with proper
  174402. * rounding, to produce the correct output. This division can be done
  174403. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174404. * as long as possible so that partial sums can be added together with
  174405. * full fractional precision.
  174406. *
  174407. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174408. * they are represented to better-than-integral precision. These outputs
  174409. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174410. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174411. * array is INT32 anyway.)
  174412. *
  174413. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174414. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174415. * shows that the values given below are the most effective.
  174416. */
  174417. #if BITS_IN_JSAMPLE == 8
  174418. #define CONST_BITS 13
  174419. #define PASS1_BITS 2
  174420. #else
  174421. #define CONST_BITS 13
  174422. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174423. #endif
  174424. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174425. * causing a lot of useless floating-point operations at run time.
  174426. * To get around this we use the following pre-calculated constants.
  174427. * If you change CONST_BITS you may want to add appropriate values.
  174428. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174429. */
  174430. #if CONST_BITS == 13
  174431. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174432. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174433. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174434. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174435. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174436. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174437. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174438. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174439. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174440. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174441. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174442. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174443. #else
  174444. #define FIX_0_298631336 FIX(0.298631336)
  174445. #define FIX_0_390180644 FIX(0.390180644)
  174446. #define FIX_0_541196100 FIX(0.541196100)
  174447. #define FIX_0_765366865 FIX(0.765366865)
  174448. #define FIX_0_899976223 FIX(0.899976223)
  174449. #define FIX_1_175875602 FIX(1.175875602)
  174450. #define FIX_1_501321110 FIX(1.501321110)
  174451. #define FIX_1_847759065 FIX(1.847759065)
  174452. #define FIX_1_961570560 FIX(1.961570560)
  174453. #define FIX_2_053119869 FIX(2.053119869)
  174454. #define FIX_2_562915447 FIX(2.562915447)
  174455. #define FIX_3_072711026 FIX(3.072711026)
  174456. #endif
  174457. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174458. * For 8-bit samples with the recommended scaling, all the variable
  174459. * and constant values involved are no more than 16 bits wide, so a
  174460. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174461. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174462. */
  174463. #if BITS_IN_JSAMPLE == 8
  174464. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174465. #else
  174466. #define MULTIPLY(var,const) ((var) * (const))
  174467. #endif
  174468. /*
  174469. * Perform the forward DCT on one block of samples.
  174470. */
  174471. GLOBAL(void)
  174472. jpeg_fdct_islow (DCTELEM * data)
  174473. {
  174474. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174475. INT32 tmp10, tmp11, tmp12, tmp13;
  174476. INT32 z1, z2, z3, z4, z5;
  174477. DCTELEM *dataptr;
  174478. int ctr;
  174479. SHIFT_TEMPS
  174480. /* Pass 1: process rows. */
  174481. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174482. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174483. dataptr = data;
  174484. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174485. tmp0 = dataptr[0] + dataptr[7];
  174486. tmp7 = dataptr[0] - dataptr[7];
  174487. tmp1 = dataptr[1] + dataptr[6];
  174488. tmp6 = dataptr[1] - dataptr[6];
  174489. tmp2 = dataptr[2] + dataptr[5];
  174490. tmp5 = dataptr[2] - dataptr[5];
  174491. tmp3 = dataptr[3] + dataptr[4];
  174492. tmp4 = dataptr[3] - dataptr[4];
  174493. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174494. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174495. */
  174496. tmp10 = tmp0 + tmp3;
  174497. tmp13 = tmp0 - tmp3;
  174498. tmp11 = tmp1 + tmp2;
  174499. tmp12 = tmp1 - tmp2;
  174500. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174501. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174502. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174503. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174504. CONST_BITS-PASS1_BITS);
  174505. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174506. CONST_BITS-PASS1_BITS);
  174507. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174508. * cK represents cos(K*pi/16).
  174509. * i0..i3 in the paper are tmp4..tmp7 here.
  174510. */
  174511. z1 = tmp4 + tmp7;
  174512. z2 = tmp5 + tmp6;
  174513. z3 = tmp4 + tmp6;
  174514. z4 = tmp5 + tmp7;
  174515. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174516. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174517. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174518. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174519. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174520. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174521. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174522. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174523. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174524. z3 += z5;
  174525. z4 += z5;
  174526. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174527. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174528. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174529. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174530. dataptr += DCTSIZE; /* advance pointer to next row */
  174531. }
  174532. /* Pass 2: process columns.
  174533. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174534. * by an overall factor of 8.
  174535. */
  174536. dataptr = data;
  174537. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174538. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174539. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174540. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174541. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174542. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174543. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174544. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174545. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174546. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174547. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174548. */
  174549. tmp10 = tmp0 + tmp3;
  174550. tmp13 = tmp0 - tmp3;
  174551. tmp11 = tmp1 + tmp2;
  174552. tmp12 = tmp1 - tmp2;
  174553. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174554. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174555. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174556. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174557. CONST_BITS+PASS1_BITS);
  174558. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174559. CONST_BITS+PASS1_BITS);
  174560. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174561. * cK represents cos(K*pi/16).
  174562. * i0..i3 in the paper are tmp4..tmp7 here.
  174563. */
  174564. z1 = tmp4 + tmp7;
  174565. z2 = tmp5 + tmp6;
  174566. z3 = tmp4 + tmp6;
  174567. z4 = tmp5 + tmp7;
  174568. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174569. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174570. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174571. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174572. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174573. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174574. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174575. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174576. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174577. z3 += z5;
  174578. z4 += z5;
  174579. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174580. CONST_BITS+PASS1_BITS);
  174581. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174582. CONST_BITS+PASS1_BITS);
  174583. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174584. CONST_BITS+PASS1_BITS);
  174585. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174586. CONST_BITS+PASS1_BITS);
  174587. dataptr++; /* advance pointer to next column */
  174588. }
  174589. }
  174590. #endif /* DCT_ISLOW_SUPPORTED */
  174591. /*** End of inlined file: jfdctint.c ***/
  174592. #undef CONST_BITS
  174593. #undef MULTIPLY
  174594. #undef FIX_0_541196100
  174595. /*** Start of inlined file: jfdctfst.c ***/
  174596. #define JPEG_INTERNALS
  174597. #ifdef DCT_IFAST_SUPPORTED
  174598. /*
  174599. * This module is specialized to the case DCTSIZE = 8.
  174600. */
  174601. #if DCTSIZE != 8
  174602. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174603. #endif
  174604. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174605. * see jfdctint.c for more details. However, we choose to descale
  174606. * (right shift) multiplication products as soon as they are formed,
  174607. * rather than carrying additional fractional bits into subsequent additions.
  174608. * This compromises accuracy slightly, but it lets us save a few shifts.
  174609. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174610. * everywhere except in the multiplications proper; this saves a good deal
  174611. * of work on 16-bit-int machines.
  174612. *
  174613. * Again to save a few shifts, the intermediate results between pass 1 and
  174614. * pass 2 are not upscaled, but are represented only to integral precision.
  174615. *
  174616. * A final compromise is to represent the multiplicative constants to only
  174617. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174618. * machines, and may also reduce the cost of multiplication (since there
  174619. * are fewer one-bits in the constants).
  174620. */
  174621. #define CONST_BITS 8
  174622. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174623. * causing a lot of useless floating-point operations at run time.
  174624. * To get around this we use the following pre-calculated constants.
  174625. * If you change CONST_BITS you may want to add appropriate values.
  174626. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174627. */
  174628. #if CONST_BITS == 8
  174629. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174630. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174631. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174632. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174633. #else
  174634. #define FIX_0_382683433 FIX(0.382683433)
  174635. #define FIX_0_541196100 FIX(0.541196100)
  174636. #define FIX_0_707106781 FIX(0.707106781)
  174637. #define FIX_1_306562965 FIX(1.306562965)
  174638. #endif
  174639. /* We can gain a little more speed, with a further compromise in accuracy,
  174640. * by omitting the addition in a descaling shift. This yields an incorrectly
  174641. * rounded result half the time...
  174642. */
  174643. #ifndef USE_ACCURATE_ROUNDING
  174644. #undef DESCALE
  174645. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174646. #endif
  174647. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174648. * descale to yield a DCTELEM result.
  174649. */
  174650. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174651. /*
  174652. * Perform the forward DCT on one block of samples.
  174653. */
  174654. GLOBAL(void)
  174655. jpeg_fdct_ifast (DCTELEM * data)
  174656. {
  174657. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174658. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174659. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174660. DCTELEM *dataptr;
  174661. int ctr;
  174662. SHIFT_TEMPS
  174663. /* Pass 1: process rows. */
  174664. dataptr = data;
  174665. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174666. tmp0 = dataptr[0] + dataptr[7];
  174667. tmp7 = dataptr[0] - dataptr[7];
  174668. tmp1 = dataptr[1] + dataptr[6];
  174669. tmp6 = dataptr[1] - dataptr[6];
  174670. tmp2 = dataptr[2] + dataptr[5];
  174671. tmp5 = dataptr[2] - dataptr[5];
  174672. tmp3 = dataptr[3] + dataptr[4];
  174673. tmp4 = dataptr[3] - dataptr[4];
  174674. /* Even part */
  174675. tmp10 = tmp0 + tmp3; /* phase 2 */
  174676. tmp13 = tmp0 - tmp3;
  174677. tmp11 = tmp1 + tmp2;
  174678. tmp12 = tmp1 - tmp2;
  174679. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174680. dataptr[4] = tmp10 - tmp11;
  174681. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174682. dataptr[2] = tmp13 + z1; /* phase 5 */
  174683. dataptr[6] = tmp13 - z1;
  174684. /* Odd part */
  174685. tmp10 = tmp4 + tmp5; /* phase 2 */
  174686. tmp11 = tmp5 + tmp6;
  174687. tmp12 = tmp6 + tmp7;
  174688. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174689. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174690. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174691. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174692. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174693. z11 = tmp7 + z3; /* phase 5 */
  174694. z13 = tmp7 - z3;
  174695. dataptr[5] = z13 + z2; /* phase 6 */
  174696. dataptr[3] = z13 - z2;
  174697. dataptr[1] = z11 + z4;
  174698. dataptr[7] = z11 - z4;
  174699. dataptr += DCTSIZE; /* advance pointer to next row */
  174700. }
  174701. /* Pass 2: process columns. */
  174702. dataptr = data;
  174703. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174704. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174705. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174706. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174707. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174708. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174709. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174710. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174711. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174712. /* Even part */
  174713. tmp10 = tmp0 + tmp3; /* phase 2 */
  174714. tmp13 = tmp0 - tmp3;
  174715. tmp11 = tmp1 + tmp2;
  174716. tmp12 = tmp1 - tmp2;
  174717. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174718. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174719. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174720. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174721. dataptr[DCTSIZE*6] = tmp13 - z1;
  174722. /* Odd part */
  174723. tmp10 = tmp4 + tmp5; /* phase 2 */
  174724. tmp11 = tmp5 + tmp6;
  174725. tmp12 = tmp6 + tmp7;
  174726. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174727. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174728. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174729. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174730. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174731. z11 = tmp7 + z3; /* phase 5 */
  174732. z13 = tmp7 - z3;
  174733. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174734. dataptr[DCTSIZE*3] = z13 - z2;
  174735. dataptr[DCTSIZE*1] = z11 + z4;
  174736. dataptr[DCTSIZE*7] = z11 - z4;
  174737. dataptr++; /* advance pointer to next column */
  174738. }
  174739. }
  174740. #endif /* DCT_IFAST_SUPPORTED */
  174741. /*** End of inlined file: jfdctfst.c ***/
  174742. #undef FIX_0_541196100
  174743. /*** Start of inlined file: jidctflt.c ***/
  174744. #define JPEG_INTERNALS
  174745. #ifdef DCT_FLOAT_SUPPORTED
  174746. /*
  174747. * This module is specialized to the case DCTSIZE = 8.
  174748. */
  174749. #if DCTSIZE != 8
  174750. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174751. #endif
  174752. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174753. * entry; produce a float result.
  174754. */
  174755. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174756. /*
  174757. * Perform dequantization and inverse DCT on one block of coefficients.
  174758. */
  174759. GLOBAL(void)
  174760. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174761. JCOEFPTR coef_block,
  174762. JSAMPARRAY output_buf, JDIMENSION output_col)
  174763. {
  174764. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174765. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174766. FAST_FLOAT z5, z10, z11, z12, z13;
  174767. JCOEFPTR inptr;
  174768. FLOAT_MULT_TYPE * quantptr;
  174769. FAST_FLOAT * wsptr;
  174770. JSAMPROW outptr;
  174771. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174772. int ctr;
  174773. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174774. SHIFT_TEMPS
  174775. /* Pass 1: process columns from input, store into work array. */
  174776. inptr = coef_block;
  174777. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174778. wsptr = workspace;
  174779. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174780. /* Due to quantization, we will usually find that many of the input
  174781. * coefficients are zero, especially the AC terms. We can exploit this
  174782. * by short-circuiting the IDCT calculation for any column in which all
  174783. * the AC terms are zero. In that case each output is equal to the
  174784. * DC coefficient (with scale factor as needed).
  174785. * With typical images and quantization tables, half or more of the
  174786. * column DCT calculations can be simplified this way.
  174787. */
  174788. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174789. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174790. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174791. inptr[DCTSIZE*7] == 0) {
  174792. /* AC terms all zero */
  174793. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174794. wsptr[DCTSIZE*0] = dcval;
  174795. wsptr[DCTSIZE*1] = dcval;
  174796. wsptr[DCTSIZE*2] = dcval;
  174797. wsptr[DCTSIZE*3] = dcval;
  174798. wsptr[DCTSIZE*4] = dcval;
  174799. wsptr[DCTSIZE*5] = dcval;
  174800. wsptr[DCTSIZE*6] = dcval;
  174801. wsptr[DCTSIZE*7] = dcval;
  174802. inptr++; /* advance pointers to next column */
  174803. quantptr++;
  174804. wsptr++;
  174805. continue;
  174806. }
  174807. /* Even part */
  174808. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174809. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174810. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174811. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174812. tmp10 = tmp0 + tmp2; /* phase 3 */
  174813. tmp11 = tmp0 - tmp2;
  174814. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174815. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174816. tmp0 = tmp10 + tmp13; /* phase 2 */
  174817. tmp3 = tmp10 - tmp13;
  174818. tmp1 = tmp11 + tmp12;
  174819. tmp2 = tmp11 - tmp12;
  174820. /* Odd part */
  174821. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174822. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174823. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174824. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174825. z13 = tmp6 + tmp5; /* phase 6 */
  174826. z10 = tmp6 - tmp5;
  174827. z11 = tmp4 + tmp7;
  174828. z12 = tmp4 - tmp7;
  174829. tmp7 = z11 + z13; /* phase 5 */
  174830. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174831. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174832. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174833. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174834. tmp6 = tmp12 - tmp7; /* phase 2 */
  174835. tmp5 = tmp11 - tmp6;
  174836. tmp4 = tmp10 + tmp5;
  174837. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174838. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174839. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174840. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174841. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174842. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174843. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174844. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174845. inptr++; /* advance pointers to next column */
  174846. quantptr++;
  174847. wsptr++;
  174848. }
  174849. /* Pass 2: process rows from work array, store into output array. */
  174850. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174851. wsptr = workspace;
  174852. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174853. outptr = output_buf[ctr] + output_col;
  174854. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174855. * However, the column calculation has created many nonzero AC terms, so
  174856. * the simplification applies less often (typically 5% to 10% of the time).
  174857. * And testing floats for zero is relatively expensive, so we don't bother.
  174858. */
  174859. /* Even part */
  174860. tmp10 = wsptr[0] + wsptr[4];
  174861. tmp11 = wsptr[0] - wsptr[4];
  174862. tmp13 = wsptr[2] + wsptr[6];
  174863. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174864. tmp0 = tmp10 + tmp13;
  174865. tmp3 = tmp10 - tmp13;
  174866. tmp1 = tmp11 + tmp12;
  174867. tmp2 = tmp11 - tmp12;
  174868. /* Odd part */
  174869. z13 = wsptr[5] + wsptr[3];
  174870. z10 = wsptr[5] - wsptr[3];
  174871. z11 = wsptr[1] + wsptr[7];
  174872. z12 = wsptr[1] - wsptr[7];
  174873. tmp7 = z11 + z13;
  174874. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174875. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174876. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174877. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174878. tmp6 = tmp12 - tmp7;
  174879. tmp5 = tmp11 - tmp6;
  174880. tmp4 = tmp10 + tmp5;
  174881. /* Final output stage: scale down by a factor of 8 and range-limit */
  174882. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174883. & RANGE_MASK];
  174884. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174885. & RANGE_MASK];
  174886. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174887. & RANGE_MASK];
  174888. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174889. & RANGE_MASK];
  174890. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174891. & RANGE_MASK];
  174892. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174893. & RANGE_MASK];
  174894. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174895. & RANGE_MASK];
  174896. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174897. & RANGE_MASK];
  174898. wsptr += DCTSIZE; /* advance pointer to next row */
  174899. }
  174900. }
  174901. #endif /* DCT_FLOAT_SUPPORTED */
  174902. /*** End of inlined file: jidctflt.c ***/
  174903. #undef CONST_BITS
  174904. #undef FIX_1_847759065
  174905. #undef MULTIPLY
  174906. #undef DEQUANTIZE
  174907. #undef DESCALE
  174908. /*** Start of inlined file: jidctfst.c ***/
  174909. #define JPEG_INTERNALS
  174910. #ifdef DCT_IFAST_SUPPORTED
  174911. /*
  174912. * This module is specialized to the case DCTSIZE = 8.
  174913. */
  174914. #if DCTSIZE != 8
  174915. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174916. #endif
  174917. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174918. * see jidctint.c for more details. However, we choose to descale
  174919. * (right shift) multiplication products as soon as they are formed,
  174920. * rather than carrying additional fractional bits into subsequent additions.
  174921. * This compromises accuracy slightly, but it lets us save a few shifts.
  174922. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174923. * everywhere except in the multiplications proper; this saves a good deal
  174924. * of work on 16-bit-int machines.
  174925. *
  174926. * The dequantized coefficients are not integers because the AA&N scaling
  174927. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174928. * so that the first and second IDCT rounds have the same input scaling.
  174929. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174930. * avoid a descaling shift; this compromises accuracy rather drastically
  174931. * for small quantization table entries, but it saves a lot of shifts.
  174932. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174933. * so we use a much larger scaling factor to preserve accuracy.
  174934. *
  174935. * A final compromise is to represent the multiplicative constants to only
  174936. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174937. * machines, and may also reduce the cost of multiplication (since there
  174938. * are fewer one-bits in the constants).
  174939. */
  174940. #if BITS_IN_JSAMPLE == 8
  174941. #define CONST_BITS 8
  174942. #define PASS1_BITS 2
  174943. #else
  174944. #define CONST_BITS 8
  174945. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174946. #endif
  174947. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174948. * causing a lot of useless floating-point operations at run time.
  174949. * To get around this we use the following pre-calculated constants.
  174950. * If you change CONST_BITS you may want to add appropriate values.
  174951. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174952. */
  174953. #if CONST_BITS == 8
  174954. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174955. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174956. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174957. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174958. #else
  174959. #define FIX_1_082392200 FIX(1.082392200)
  174960. #define FIX_1_414213562 FIX(1.414213562)
  174961. #define FIX_1_847759065 FIX(1.847759065)
  174962. #define FIX_2_613125930 FIX(2.613125930)
  174963. #endif
  174964. /* We can gain a little more speed, with a further compromise in accuracy,
  174965. * by omitting the addition in a descaling shift. This yields an incorrectly
  174966. * rounded result half the time...
  174967. */
  174968. #ifndef USE_ACCURATE_ROUNDING
  174969. #undef DESCALE
  174970. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174971. #endif
  174972. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174973. * descale to yield a DCTELEM result.
  174974. */
  174975. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174976. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174977. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174978. * multiplication will do. For 12-bit data, the multiplier table is
  174979. * declared INT32, so a 32-bit multiply will be used.
  174980. */
  174981. #if BITS_IN_JSAMPLE == 8
  174982. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174983. #else
  174984. #define DEQUANTIZE(coef,quantval) \
  174985. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174986. #endif
  174987. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174988. * We assume that int right shift is unsigned if INT32 right shift is.
  174989. */
  174990. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174991. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174992. #if BITS_IN_JSAMPLE == 8
  174993. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174994. #else
  174995. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174996. #endif
  174997. #define IRIGHT_SHIFT(x,shft) \
  174998. ((ishift_temp = (x)) < 0 ? \
  174999. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  175000. (ishift_temp >> (shft)))
  175001. #else
  175002. #define ISHIFT_TEMPS
  175003. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  175004. #endif
  175005. #ifdef USE_ACCURATE_ROUNDING
  175006. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  175007. #else
  175008. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  175009. #endif
  175010. /*
  175011. * Perform dequantization and inverse DCT on one block of coefficients.
  175012. */
  175013. GLOBAL(void)
  175014. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175015. JCOEFPTR coef_block,
  175016. JSAMPARRAY output_buf, JDIMENSION output_col)
  175017. {
  175018. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175019. DCTELEM tmp10, tmp11, tmp12, tmp13;
  175020. DCTELEM z5, z10, z11, z12, z13;
  175021. JCOEFPTR inptr;
  175022. IFAST_MULT_TYPE * quantptr;
  175023. int * wsptr;
  175024. JSAMPROW outptr;
  175025. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175026. int ctr;
  175027. int workspace[DCTSIZE2]; /* buffers data between passes */
  175028. SHIFT_TEMPS /* for DESCALE */
  175029. ISHIFT_TEMPS /* for IDESCALE */
  175030. /* Pass 1: process columns from input, store into work array. */
  175031. inptr = coef_block;
  175032. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  175033. wsptr = workspace;
  175034. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175035. /* Due to quantization, we will usually find that many of the input
  175036. * coefficients are zero, especially the AC terms. We can exploit this
  175037. * by short-circuiting the IDCT calculation for any column in which all
  175038. * the AC terms are zero. In that case each output is equal to the
  175039. * DC coefficient (with scale factor as needed).
  175040. * With typical images and quantization tables, half or more of the
  175041. * column DCT calculations can be simplified this way.
  175042. */
  175043. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175044. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175045. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175046. inptr[DCTSIZE*7] == 0) {
  175047. /* AC terms all zero */
  175048. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175049. wsptr[DCTSIZE*0] = dcval;
  175050. wsptr[DCTSIZE*1] = dcval;
  175051. wsptr[DCTSIZE*2] = dcval;
  175052. wsptr[DCTSIZE*3] = dcval;
  175053. wsptr[DCTSIZE*4] = dcval;
  175054. wsptr[DCTSIZE*5] = dcval;
  175055. wsptr[DCTSIZE*6] = dcval;
  175056. wsptr[DCTSIZE*7] = dcval;
  175057. inptr++; /* advance pointers to next column */
  175058. quantptr++;
  175059. wsptr++;
  175060. continue;
  175061. }
  175062. /* Even part */
  175063. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175064. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175065. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175066. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175067. tmp10 = tmp0 + tmp2; /* phase 3 */
  175068. tmp11 = tmp0 - tmp2;
  175069. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175070. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175071. tmp0 = tmp10 + tmp13; /* phase 2 */
  175072. tmp3 = tmp10 - tmp13;
  175073. tmp1 = tmp11 + tmp12;
  175074. tmp2 = tmp11 - tmp12;
  175075. /* Odd part */
  175076. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175077. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175078. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175079. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175080. z13 = tmp6 + tmp5; /* phase 6 */
  175081. z10 = tmp6 - tmp5;
  175082. z11 = tmp4 + tmp7;
  175083. z12 = tmp4 - tmp7;
  175084. tmp7 = z11 + z13; /* phase 5 */
  175085. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175086. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175087. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175088. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175089. tmp6 = tmp12 - tmp7; /* phase 2 */
  175090. tmp5 = tmp11 - tmp6;
  175091. tmp4 = tmp10 + tmp5;
  175092. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175093. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175094. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175095. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175096. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175097. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175098. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175099. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175100. inptr++; /* advance pointers to next column */
  175101. quantptr++;
  175102. wsptr++;
  175103. }
  175104. /* Pass 2: process rows from work array, store into output array. */
  175105. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175106. /* and also undo the PASS1_BITS scaling. */
  175107. wsptr = workspace;
  175108. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175109. outptr = output_buf[ctr] + output_col;
  175110. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175111. * However, the column calculation has created many nonzero AC terms, so
  175112. * the simplification applies less often (typically 5% to 10% of the time).
  175113. * On machines with very fast multiplication, it's possible that the
  175114. * test takes more time than it's worth. In that case this section
  175115. * may be commented out.
  175116. */
  175117. #ifndef NO_ZERO_ROW_TEST
  175118. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175119. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175120. /* AC terms all zero */
  175121. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175122. & RANGE_MASK];
  175123. outptr[0] = dcval;
  175124. outptr[1] = dcval;
  175125. outptr[2] = dcval;
  175126. outptr[3] = dcval;
  175127. outptr[4] = dcval;
  175128. outptr[5] = dcval;
  175129. outptr[6] = dcval;
  175130. outptr[7] = dcval;
  175131. wsptr += DCTSIZE; /* advance pointer to next row */
  175132. continue;
  175133. }
  175134. #endif
  175135. /* Even part */
  175136. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175137. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175138. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175139. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175140. - tmp13;
  175141. tmp0 = tmp10 + tmp13;
  175142. tmp3 = tmp10 - tmp13;
  175143. tmp1 = tmp11 + tmp12;
  175144. tmp2 = tmp11 - tmp12;
  175145. /* Odd part */
  175146. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175147. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175148. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175149. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175150. tmp7 = z11 + z13; /* phase 5 */
  175151. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175152. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175153. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175154. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175155. tmp6 = tmp12 - tmp7; /* phase 2 */
  175156. tmp5 = tmp11 - tmp6;
  175157. tmp4 = tmp10 + tmp5;
  175158. /* Final output stage: scale down by a factor of 8 and range-limit */
  175159. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175160. & RANGE_MASK];
  175161. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175162. & RANGE_MASK];
  175163. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175164. & RANGE_MASK];
  175165. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175166. & RANGE_MASK];
  175167. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175168. & RANGE_MASK];
  175169. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175170. & RANGE_MASK];
  175171. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175172. & RANGE_MASK];
  175173. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175174. & RANGE_MASK];
  175175. wsptr += DCTSIZE; /* advance pointer to next row */
  175176. }
  175177. }
  175178. #endif /* DCT_IFAST_SUPPORTED */
  175179. /*** End of inlined file: jidctfst.c ***/
  175180. #undef CONST_BITS
  175181. #undef FIX_1_847759065
  175182. #undef MULTIPLY
  175183. #undef DEQUANTIZE
  175184. /*** Start of inlined file: jidctint.c ***/
  175185. #define JPEG_INTERNALS
  175186. #ifdef DCT_ISLOW_SUPPORTED
  175187. /*
  175188. * This module is specialized to the case DCTSIZE = 8.
  175189. */
  175190. #if DCTSIZE != 8
  175191. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175192. #endif
  175193. /*
  175194. * The poop on this scaling stuff is as follows:
  175195. *
  175196. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175197. * larger than the true IDCT outputs. The final outputs are therefore
  175198. * a factor of N larger than desired; since N=8 this can be cured by
  175199. * a simple right shift at the end of the algorithm. The advantage of
  175200. * this arrangement is that we save two multiplications per 1-D IDCT,
  175201. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175202. *
  175203. * We have to do addition and subtraction of the integer inputs, which
  175204. * is no problem, and multiplication by fractional constants, which is
  175205. * a problem to do in integer arithmetic. We multiply all the constants
  175206. * by CONST_SCALE and convert them to integer constants (thus retaining
  175207. * CONST_BITS bits of precision in the constants). After doing a
  175208. * multiplication we have to divide the product by CONST_SCALE, with proper
  175209. * rounding, to produce the correct output. This division can be done
  175210. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175211. * as long as possible so that partial sums can be added together with
  175212. * full fractional precision.
  175213. *
  175214. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175215. * they are represented to better-than-integral precision. These outputs
  175216. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175217. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175218. * intermediate INT32 array would be needed.)
  175219. *
  175220. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175221. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175222. * shows that the values given below are the most effective.
  175223. */
  175224. #if BITS_IN_JSAMPLE == 8
  175225. #define CONST_BITS 13
  175226. #define PASS1_BITS 2
  175227. #else
  175228. #define CONST_BITS 13
  175229. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175230. #endif
  175231. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175232. * causing a lot of useless floating-point operations at run time.
  175233. * To get around this we use the following pre-calculated constants.
  175234. * If you change CONST_BITS you may want to add appropriate values.
  175235. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175236. */
  175237. #if CONST_BITS == 13
  175238. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175239. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175240. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175241. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175242. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175243. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175244. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175245. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175246. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175247. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175248. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175249. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175250. #else
  175251. #define FIX_0_298631336 FIX(0.298631336)
  175252. #define FIX_0_390180644 FIX(0.390180644)
  175253. #define FIX_0_541196100 FIX(0.541196100)
  175254. #define FIX_0_765366865 FIX(0.765366865)
  175255. #define FIX_0_899976223 FIX(0.899976223)
  175256. #define FIX_1_175875602 FIX(1.175875602)
  175257. #define FIX_1_501321110 FIX(1.501321110)
  175258. #define FIX_1_847759065 FIX(1.847759065)
  175259. #define FIX_1_961570560 FIX(1.961570560)
  175260. #define FIX_2_053119869 FIX(2.053119869)
  175261. #define FIX_2_562915447 FIX(2.562915447)
  175262. #define FIX_3_072711026 FIX(3.072711026)
  175263. #endif
  175264. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175265. * For 8-bit samples with the recommended scaling, all the variable
  175266. * and constant values involved are no more than 16 bits wide, so a
  175267. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175268. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175269. */
  175270. #if BITS_IN_JSAMPLE == 8
  175271. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175272. #else
  175273. #define MULTIPLY(var,const) ((var) * (const))
  175274. #endif
  175275. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175276. * entry; produce an int result. In this module, both inputs and result
  175277. * are 16 bits or less, so either int or short multiply will work.
  175278. */
  175279. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175280. /*
  175281. * Perform dequantization and inverse DCT on one block of coefficients.
  175282. */
  175283. GLOBAL(void)
  175284. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175285. JCOEFPTR coef_block,
  175286. JSAMPARRAY output_buf, JDIMENSION output_col)
  175287. {
  175288. INT32 tmp0, tmp1, tmp2, tmp3;
  175289. INT32 tmp10, tmp11, tmp12, tmp13;
  175290. INT32 z1, z2, z3, z4, z5;
  175291. JCOEFPTR inptr;
  175292. ISLOW_MULT_TYPE * quantptr;
  175293. int * wsptr;
  175294. JSAMPROW outptr;
  175295. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175296. int ctr;
  175297. int workspace[DCTSIZE2]; /* buffers data between passes */
  175298. SHIFT_TEMPS
  175299. /* Pass 1: process columns from input, store into work array. */
  175300. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175301. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175302. inptr = coef_block;
  175303. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175304. wsptr = workspace;
  175305. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175306. /* Due to quantization, we will usually find that many of the input
  175307. * coefficients are zero, especially the AC terms. We can exploit this
  175308. * by short-circuiting the IDCT calculation for any column in which all
  175309. * the AC terms are zero. In that case each output is equal to the
  175310. * DC coefficient (with scale factor as needed).
  175311. * With typical images and quantization tables, half or more of the
  175312. * column DCT calculations can be simplified this way.
  175313. */
  175314. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175315. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175316. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175317. inptr[DCTSIZE*7] == 0) {
  175318. /* AC terms all zero */
  175319. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175320. wsptr[DCTSIZE*0] = dcval;
  175321. wsptr[DCTSIZE*1] = dcval;
  175322. wsptr[DCTSIZE*2] = dcval;
  175323. wsptr[DCTSIZE*3] = dcval;
  175324. wsptr[DCTSIZE*4] = dcval;
  175325. wsptr[DCTSIZE*5] = dcval;
  175326. wsptr[DCTSIZE*6] = dcval;
  175327. wsptr[DCTSIZE*7] = dcval;
  175328. inptr++; /* advance pointers to next column */
  175329. quantptr++;
  175330. wsptr++;
  175331. continue;
  175332. }
  175333. /* Even part: reverse the even part of the forward DCT. */
  175334. /* The rotator is sqrt(2)*c(-6). */
  175335. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175336. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175337. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175338. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175339. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175340. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175341. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175342. tmp0 = (z2 + z3) << CONST_BITS;
  175343. tmp1 = (z2 - z3) << CONST_BITS;
  175344. tmp10 = tmp0 + tmp3;
  175345. tmp13 = tmp0 - tmp3;
  175346. tmp11 = tmp1 + tmp2;
  175347. tmp12 = tmp1 - tmp2;
  175348. /* Odd part per figure 8; the matrix is unitary and hence its
  175349. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175350. */
  175351. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175352. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175353. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175354. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175355. z1 = tmp0 + tmp3;
  175356. z2 = tmp1 + tmp2;
  175357. z3 = tmp0 + tmp2;
  175358. z4 = tmp1 + tmp3;
  175359. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175360. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175361. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175362. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175363. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175364. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175365. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175366. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175367. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175368. z3 += z5;
  175369. z4 += z5;
  175370. tmp0 += z1 + z3;
  175371. tmp1 += z2 + z4;
  175372. tmp2 += z2 + z3;
  175373. tmp3 += z1 + z4;
  175374. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175375. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175376. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175377. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175378. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175379. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175380. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175381. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175382. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175383. inptr++; /* advance pointers to next column */
  175384. quantptr++;
  175385. wsptr++;
  175386. }
  175387. /* Pass 2: process rows from work array, store into output array. */
  175388. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175389. /* and also undo the PASS1_BITS scaling. */
  175390. wsptr = workspace;
  175391. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175392. outptr = output_buf[ctr] + output_col;
  175393. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175394. * However, the column calculation has created many nonzero AC terms, so
  175395. * the simplification applies less often (typically 5% to 10% of the time).
  175396. * On machines with very fast multiplication, it's possible that the
  175397. * test takes more time than it's worth. In that case this section
  175398. * may be commented out.
  175399. */
  175400. #ifndef NO_ZERO_ROW_TEST
  175401. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175402. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175403. /* AC terms all zero */
  175404. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175405. & RANGE_MASK];
  175406. outptr[0] = dcval;
  175407. outptr[1] = dcval;
  175408. outptr[2] = dcval;
  175409. outptr[3] = dcval;
  175410. outptr[4] = dcval;
  175411. outptr[5] = dcval;
  175412. outptr[6] = dcval;
  175413. outptr[7] = dcval;
  175414. wsptr += DCTSIZE; /* advance pointer to next row */
  175415. continue;
  175416. }
  175417. #endif
  175418. /* Even part: reverse the even part of the forward DCT. */
  175419. /* The rotator is sqrt(2)*c(-6). */
  175420. z2 = (INT32) wsptr[2];
  175421. z3 = (INT32) wsptr[6];
  175422. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175423. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175424. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175425. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175426. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175427. tmp10 = tmp0 + tmp3;
  175428. tmp13 = tmp0 - tmp3;
  175429. tmp11 = tmp1 + tmp2;
  175430. tmp12 = tmp1 - tmp2;
  175431. /* Odd part per figure 8; the matrix is unitary and hence its
  175432. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175433. */
  175434. tmp0 = (INT32) wsptr[7];
  175435. tmp1 = (INT32) wsptr[5];
  175436. tmp2 = (INT32) wsptr[3];
  175437. tmp3 = (INT32) wsptr[1];
  175438. z1 = tmp0 + tmp3;
  175439. z2 = tmp1 + tmp2;
  175440. z3 = tmp0 + tmp2;
  175441. z4 = tmp1 + tmp3;
  175442. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175443. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175444. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175445. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175446. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175447. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175448. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175449. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175450. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175451. z3 += z5;
  175452. z4 += z5;
  175453. tmp0 += z1 + z3;
  175454. tmp1 += z2 + z4;
  175455. tmp2 += z2 + z3;
  175456. tmp3 += z1 + z4;
  175457. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175458. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175459. CONST_BITS+PASS1_BITS+3)
  175460. & RANGE_MASK];
  175461. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175462. CONST_BITS+PASS1_BITS+3)
  175463. & RANGE_MASK];
  175464. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175465. CONST_BITS+PASS1_BITS+3)
  175466. & RANGE_MASK];
  175467. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175468. CONST_BITS+PASS1_BITS+3)
  175469. & RANGE_MASK];
  175470. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175471. CONST_BITS+PASS1_BITS+3)
  175472. & RANGE_MASK];
  175473. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175474. CONST_BITS+PASS1_BITS+3)
  175475. & RANGE_MASK];
  175476. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175477. CONST_BITS+PASS1_BITS+3)
  175478. & RANGE_MASK];
  175479. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175480. CONST_BITS+PASS1_BITS+3)
  175481. & RANGE_MASK];
  175482. wsptr += DCTSIZE; /* advance pointer to next row */
  175483. }
  175484. }
  175485. #endif /* DCT_ISLOW_SUPPORTED */
  175486. /*** End of inlined file: jidctint.c ***/
  175487. /*** Start of inlined file: jidctred.c ***/
  175488. #define JPEG_INTERNALS
  175489. #ifdef IDCT_SCALING_SUPPORTED
  175490. /*
  175491. * This module is specialized to the case DCTSIZE = 8.
  175492. */
  175493. #if DCTSIZE != 8
  175494. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175495. #endif
  175496. /* Scaling is the same as in jidctint.c. */
  175497. #if BITS_IN_JSAMPLE == 8
  175498. #define CONST_BITS 13
  175499. #define PASS1_BITS 2
  175500. #else
  175501. #define CONST_BITS 13
  175502. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175503. #endif
  175504. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175505. * causing a lot of useless floating-point operations at run time.
  175506. * To get around this we use the following pre-calculated constants.
  175507. * If you change CONST_BITS you may want to add appropriate values.
  175508. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175509. */
  175510. #if CONST_BITS == 13
  175511. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175512. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175513. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175514. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175515. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175516. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175517. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175518. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175519. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175520. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175521. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175522. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175523. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175524. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175525. #else
  175526. #define FIX_0_211164243 FIX(0.211164243)
  175527. #define FIX_0_509795579 FIX(0.509795579)
  175528. #define FIX_0_601344887 FIX(0.601344887)
  175529. #define FIX_0_720959822 FIX(0.720959822)
  175530. #define FIX_0_765366865 FIX(0.765366865)
  175531. #define FIX_0_850430095 FIX(0.850430095)
  175532. #define FIX_0_899976223 FIX(0.899976223)
  175533. #define FIX_1_061594337 FIX(1.061594337)
  175534. #define FIX_1_272758580 FIX(1.272758580)
  175535. #define FIX_1_451774981 FIX(1.451774981)
  175536. #define FIX_1_847759065 FIX(1.847759065)
  175537. #define FIX_2_172734803 FIX(2.172734803)
  175538. #define FIX_2_562915447 FIX(2.562915447)
  175539. #define FIX_3_624509785 FIX(3.624509785)
  175540. #endif
  175541. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175542. * For 8-bit samples with the recommended scaling, all the variable
  175543. * and constant values involved are no more than 16 bits wide, so a
  175544. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175545. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175546. */
  175547. #if BITS_IN_JSAMPLE == 8
  175548. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175549. #else
  175550. #define MULTIPLY(var,const) ((var) * (const))
  175551. #endif
  175552. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175553. * entry; produce an int result. In this module, both inputs and result
  175554. * are 16 bits or less, so either int or short multiply will work.
  175555. */
  175556. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175557. /*
  175558. * Perform dequantization and inverse DCT on one block of coefficients,
  175559. * producing a reduced-size 4x4 output block.
  175560. */
  175561. GLOBAL(void)
  175562. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175563. JCOEFPTR coef_block,
  175564. JSAMPARRAY output_buf, JDIMENSION output_col)
  175565. {
  175566. INT32 tmp0, tmp2, tmp10, tmp12;
  175567. INT32 z1, z2, z3, z4;
  175568. JCOEFPTR inptr;
  175569. ISLOW_MULT_TYPE * quantptr;
  175570. int * wsptr;
  175571. JSAMPROW outptr;
  175572. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175573. int ctr;
  175574. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175575. SHIFT_TEMPS
  175576. /* Pass 1: process columns from input, store into work array. */
  175577. inptr = coef_block;
  175578. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175579. wsptr = workspace;
  175580. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175581. /* Don't bother to process column 4, because second pass won't use it */
  175582. if (ctr == DCTSIZE-4)
  175583. continue;
  175584. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175585. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175586. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175587. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175588. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175589. wsptr[DCTSIZE*0] = dcval;
  175590. wsptr[DCTSIZE*1] = dcval;
  175591. wsptr[DCTSIZE*2] = dcval;
  175592. wsptr[DCTSIZE*3] = dcval;
  175593. continue;
  175594. }
  175595. /* Even part */
  175596. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175597. tmp0 <<= (CONST_BITS+1);
  175598. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175599. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175600. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175601. tmp10 = tmp0 + tmp2;
  175602. tmp12 = tmp0 - tmp2;
  175603. /* Odd part */
  175604. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175605. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175606. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175607. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175608. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175609. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175610. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175611. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175612. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175613. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175614. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175615. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175616. /* Final output stage */
  175617. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175618. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175619. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175620. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175621. }
  175622. /* Pass 2: process 4 rows from work array, store into output array. */
  175623. wsptr = workspace;
  175624. for (ctr = 0; ctr < 4; ctr++) {
  175625. outptr = output_buf[ctr] + output_col;
  175626. /* It's not clear whether a zero row test is worthwhile here ... */
  175627. #ifndef NO_ZERO_ROW_TEST
  175628. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175629. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175630. /* AC terms all zero */
  175631. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175632. & RANGE_MASK];
  175633. outptr[0] = dcval;
  175634. outptr[1] = dcval;
  175635. outptr[2] = dcval;
  175636. outptr[3] = dcval;
  175637. wsptr += DCTSIZE; /* advance pointer to next row */
  175638. continue;
  175639. }
  175640. #endif
  175641. /* Even part */
  175642. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175643. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175644. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175645. tmp10 = tmp0 + tmp2;
  175646. tmp12 = tmp0 - tmp2;
  175647. /* Odd part */
  175648. z1 = (INT32) wsptr[7];
  175649. z2 = (INT32) wsptr[5];
  175650. z3 = (INT32) wsptr[3];
  175651. z4 = (INT32) wsptr[1];
  175652. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175653. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175654. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175655. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175656. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175657. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175658. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175659. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175660. /* Final output stage */
  175661. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175662. CONST_BITS+PASS1_BITS+3+1)
  175663. & RANGE_MASK];
  175664. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175665. CONST_BITS+PASS1_BITS+3+1)
  175666. & RANGE_MASK];
  175667. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175668. CONST_BITS+PASS1_BITS+3+1)
  175669. & RANGE_MASK];
  175670. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175671. CONST_BITS+PASS1_BITS+3+1)
  175672. & RANGE_MASK];
  175673. wsptr += DCTSIZE; /* advance pointer to next row */
  175674. }
  175675. }
  175676. /*
  175677. * Perform dequantization and inverse DCT on one block of coefficients,
  175678. * producing a reduced-size 2x2 output block.
  175679. */
  175680. GLOBAL(void)
  175681. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175682. JCOEFPTR coef_block,
  175683. JSAMPARRAY output_buf, JDIMENSION output_col)
  175684. {
  175685. INT32 tmp0, tmp10, z1;
  175686. JCOEFPTR inptr;
  175687. ISLOW_MULT_TYPE * quantptr;
  175688. int * wsptr;
  175689. JSAMPROW outptr;
  175690. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175691. int ctr;
  175692. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175693. SHIFT_TEMPS
  175694. /* Pass 1: process columns from input, store into work array. */
  175695. inptr = coef_block;
  175696. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175697. wsptr = workspace;
  175698. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175699. /* Don't bother to process columns 2,4,6 */
  175700. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175701. continue;
  175702. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175703. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175704. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175705. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175706. wsptr[DCTSIZE*0] = dcval;
  175707. wsptr[DCTSIZE*1] = dcval;
  175708. continue;
  175709. }
  175710. /* Even part */
  175711. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175712. tmp10 = z1 << (CONST_BITS+2);
  175713. /* Odd part */
  175714. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175715. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175716. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175717. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175718. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175719. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175720. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175721. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175722. /* Final output stage */
  175723. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175724. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175725. }
  175726. /* Pass 2: process 2 rows from work array, store into output array. */
  175727. wsptr = workspace;
  175728. for (ctr = 0; ctr < 2; ctr++) {
  175729. outptr = output_buf[ctr] + output_col;
  175730. /* It's not clear whether a zero row test is worthwhile here ... */
  175731. #ifndef NO_ZERO_ROW_TEST
  175732. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175733. /* AC terms all zero */
  175734. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175735. & RANGE_MASK];
  175736. outptr[0] = dcval;
  175737. outptr[1] = dcval;
  175738. wsptr += DCTSIZE; /* advance pointer to next row */
  175739. continue;
  175740. }
  175741. #endif
  175742. /* Even part */
  175743. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175744. /* Odd part */
  175745. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175746. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175747. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175748. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175749. /* Final output stage */
  175750. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175751. CONST_BITS+PASS1_BITS+3+2)
  175752. & RANGE_MASK];
  175753. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175754. CONST_BITS+PASS1_BITS+3+2)
  175755. & RANGE_MASK];
  175756. wsptr += DCTSIZE; /* advance pointer to next row */
  175757. }
  175758. }
  175759. /*
  175760. * Perform dequantization and inverse DCT on one block of coefficients,
  175761. * producing a reduced-size 1x1 output block.
  175762. */
  175763. GLOBAL(void)
  175764. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175765. JCOEFPTR coef_block,
  175766. JSAMPARRAY output_buf, JDIMENSION output_col)
  175767. {
  175768. int dcval;
  175769. ISLOW_MULT_TYPE * quantptr;
  175770. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175771. SHIFT_TEMPS
  175772. /* We hardly need an inverse DCT routine for this: just take the
  175773. * average pixel value, which is one-eighth of the DC coefficient.
  175774. */
  175775. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175776. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175777. dcval = (int) DESCALE((INT32) dcval, 3);
  175778. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175779. }
  175780. #endif /* IDCT_SCALING_SUPPORTED */
  175781. /*** End of inlined file: jidctred.c ***/
  175782. /*** Start of inlined file: jmemmgr.c ***/
  175783. #define JPEG_INTERNALS
  175784. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175785. /*** Start of inlined file: jmemsys.h ***/
  175786. #ifndef __jmemsys_h__
  175787. #define __jmemsys_h__
  175788. /* Short forms of external names for systems with brain-damaged linkers. */
  175789. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175790. #define jpeg_get_small jGetSmall
  175791. #define jpeg_free_small jFreeSmall
  175792. #define jpeg_get_large jGetLarge
  175793. #define jpeg_free_large jFreeLarge
  175794. #define jpeg_mem_available jMemAvail
  175795. #define jpeg_open_backing_store jOpenBackStore
  175796. #define jpeg_mem_init jMemInit
  175797. #define jpeg_mem_term jMemTerm
  175798. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175799. /*
  175800. * These two functions are used to allocate and release small chunks of
  175801. * memory. (Typically the total amount requested through jpeg_get_small is
  175802. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175803. * Behavior should be the same as for the standard library functions malloc
  175804. * and free; in particular, jpeg_get_small must return NULL on failure.
  175805. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175806. * size of the object being freed, just in case it's needed.
  175807. * On an 80x86 machine using small-data memory model, these manage near heap.
  175808. */
  175809. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175810. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175811. size_t sizeofobject));
  175812. /*
  175813. * These two functions are used to allocate and release large chunks of
  175814. * memory (up to the total free space designated by jpeg_mem_available).
  175815. * The interface is the same as above, except that on an 80x86 machine,
  175816. * far pointers are used. On most other machines these are identical to
  175817. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175818. * in case a different allocation strategy is desirable for large chunks.
  175819. */
  175820. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175821. size_t sizeofobject));
  175822. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175823. size_t sizeofobject));
  175824. /*
  175825. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175826. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175827. * matter, but that case should never come into play). This macro is needed
  175828. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175829. * On those machines, we expect that jconfig.h will provide a proper value.
  175830. * On machines with 32-bit flat address spaces, any large constant may be used.
  175831. *
  175832. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175833. * size_t and will be a multiple of sizeof(align_type).
  175834. */
  175835. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175836. #define MAX_ALLOC_CHUNK 1000000000L
  175837. #endif
  175838. /*
  175839. * This routine computes the total space still available for allocation by
  175840. * jpeg_get_large. If more space than this is needed, backing store will be
  175841. * used. NOTE: any memory already allocated must not be counted.
  175842. *
  175843. * There is a minimum space requirement, corresponding to the minimum
  175844. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175845. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175846. * all working storage in memory, is also passed in case it is useful.
  175847. * Finally, the total space already allocated is passed. If no better
  175848. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175849. * is often a suitable calculation.
  175850. *
  175851. * It is OK for jpeg_mem_available to underestimate the space available
  175852. * (that'll just lead to more backing-store access than is really necessary).
  175853. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175854. * a slop factor from the true available space. 5% should be enough.
  175855. *
  175856. * On machines with lots of virtual memory, any large constant may be returned.
  175857. * Conversely, zero may be returned to always use the minimum amount of memory.
  175858. */
  175859. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175860. long min_bytes_needed,
  175861. long max_bytes_needed,
  175862. long already_allocated));
  175863. /*
  175864. * This structure holds whatever state is needed to access a single
  175865. * backing-store object. The read/write/close method pointers are called
  175866. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175867. * are private to the system-dependent backing store routines.
  175868. */
  175869. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175870. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175871. typedef unsigned short XMSH; /* type of extended-memory handles */
  175872. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175873. typedef union {
  175874. short file_handle; /* DOS file handle if it's a temp file */
  175875. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175876. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175877. } handle_union;
  175878. #endif /* USE_MSDOS_MEMMGR */
  175879. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175880. #include <Files.h>
  175881. #endif /* USE_MAC_MEMMGR */
  175882. //typedef struct backing_store_struct * backing_store_ptr;
  175883. typedef struct backing_store_struct {
  175884. /* Methods for reading/writing/closing this backing-store object */
  175885. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175886. struct backing_store_struct *info,
  175887. void FAR * buffer_address,
  175888. long file_offset, long byte_count));
  175889. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175890. struct backing_store_struct *info,
  175891. void FAR * buffer_address,
  175892. long file_offset, long byte_count));
  175893. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175894. struct backing_store_struct *info));
  175895. /* Private fields for system-dependent backing-store management */
  175896. #ifdef USE_MSDOS_MEMMGR
  175897. /* For the MS-DOS manager (jmemdos.c), we need: */
  175898. handle_union handle; /* reference to backing-store storage object */
  175899. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175900. #else
  175901. #ifdef USE_MAC_MEMMGR
  175902. /* For the Mac manager (jmemmac.c), we need: */
  175903. short temp_file; /* file reference number to temp file */
  175904. FSSpec tempSpec; /* the FSSpec for the temp file */
  175905. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175906. #else
  175907. /* For a typical implementation with temp files, we need: */
  175908. FILE * temp_file; /* stdio reference to temp file */
  175909. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175910. #endif
  175911. #endif
  175912. } backing_store_info;
  175913. /*
  175914. * Initial opening of a backing-store object. This must fill in the
  175915. * read/write/close pointers in the object. The read/write routines
  175916. * may take an error exit if the specified maximum file size is exceeded.
  175917. * (If jpeg_mem_available always returns a large value, this routine can
  175918. * just take an error exit.)
  175919. */
  175920. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175921. struct backing_store_struct *info,
  175922. long total_bytes_needed));
  175923. /*
  175924. * These routines take care of any system-dependent initialization and
  175925. * cleanup required. jpeg_mem_init will be called before anything is
  175926. * allocated (and, therefore, nothing in cinfo is of use except the error
  175927. * manager pointer). It should return a suitable default value for
  175928. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175929. * application. (Note that max_memory_to_use is only important if
  175930. * jpeg_mem_available chooses to consult it ... no one else will.)
  175931. * jpeg_mem_term may assume that all requested memory has been freed and that
  175932. * all opened backing-store objects have been closed.
  175933. */
  175934. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175935. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175936. #endif
  175937. /*** End of inlined file: jmemsys.h ***/
  175938. /* import the system-dependent declarations */
  175939. #ifndef NO_GETENV
  175940. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175941. extern char * getenv JPP((const char * name));
  175942. #endif
  175943. #endif
  175944. /*
  175945. * Some important notes:
  175946. * The allocation routines provided here must never return NULL.
  175947. * They should exit to error_exit if unsuccessful.
  175948. *
  175949. * It's not a good idea to try to merge the sarray and barray routines,
  175950. * even though they are textually almost the same, because samples are
  175951. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175952. * in machines where byte pointers have a different representation from
  175953. * word pointers, the resulting machine code could not be the same.
  175954. */
  175955. /*
  175956. * Many machines require storage alignment: longs must start on 4-byte
  175957. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175958. * always returns pointers that are multiples of the worst-case alignment
  175959. * requirement, and we had better do so too.
  175960. * There isn't any really portable way to determine the worst-case alignment
  175961. * requirement. This module assumes that the alignment requirement is
  175962. * multiples of sizeof(ALIGN_TYPE).
  175963. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175964. * workstations (where doubles really do need 8-byte alignment) and will work
  175965. * fine on nearly everything. If your machine has lesser alignment needs,
  175966. * you can save a few bytes by making ALIGN_TYPE smaller.
  175967. * The only place I know of where this will NOT work is certain Macintosh
  175968. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175969. * Doing 10-byte alignment is counterproductive because longwords won't be
  175970. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175971. * such a compiler.
  175972. */
  175973. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175974. #define ALIGN_TYPE double
  175975. #endif
  175976. /*
  175977. * We allocate objects from "pools", where each pool is gotten with a single
  175978. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175979. * overhead within a pool, except for alignment padding. Each pool has a
  175980. * header with a link to the next pool of the same class.
  175981. * Small and large pool headers are identical except that the latter's
  175982. * link pointer must be FAR on 80x86 machines.
  175983. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175984. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175985. * of the alignment requirement of ALIGN_TYPE.
  175986. */
  175987. typedef union small_pool_struct * small_pool_ptr;
  175988. typedef union small_pool_struct {
  175989. struct {
  175990. small_pool_ptr next; /* next in list of pools */
  175991. size_t bytes_used; /* how many bytes already used within pool */
  175992. size_t bytes_left; /* bytes still available in this pool */
  175993. } hdr;
  175994. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175995. } small_pool_hdr;
  175996. typedef union large_pool_struct FAR * large_pool_ptr;
  175997. typedef union large_pool_struct {
  175998. struct {
  175999. large_pool_ptr next; /* next in list of pools */
  176000. size_t bytes_used; /* how many bytes already used within pool */
  176001. size_t bytes_left; /* bytes still available in this pool */
  176002. } hdr;
  176003. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176004. } large_pool_hdr;
  176005. /*
  176006. * Here is the full definition of a memory manager object.
  176007. */
  176008. typedef struct {
  176009. struct jpeg_memory_mgr pub; /* public fields */
  176010. /* Each pool identifier (lifetime class) names a linked list of pools. */
  176011. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  176012. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  176013. /* Since we only have one lifetime class of virtual arrays, only one
  176014. * linked list is necessary (for each datatype). Note that the virtual
  176015. * array control blocks being linked together are actually stored somewhere
  176016. * in the small-pool list.
  176017. */
  176018. jvirt_sarray_ptr virt_sarray_list;
  176019. jvirt_barray_ptr virt_barray_list;
  176020. /* This counts total space obtained from jpeg_get_small/large */
  176021. long total_space_allocated;
  176022. /* alloc_sarray and alloc_barray set this value for use by virtual
  176023. * array routines.
  176024. */
  176025. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  176026. } my_memory_mgr;
  176027. typedef my_memory_mgr * my_mem_ptr;
  176028. /*
  176029. * The control blocks for virtual arrays.
  176030. * Note that these blocks are allocated in the "small" pool area.
  176031. * System-dependent info for the associated backing store (if any) is hidden
  176032. * inside the backing_store_info struct.
  176033. */
  176034. struct jvirt_sarray_control {
  176035. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  176036. JDIMENSION rows_in_array; /* total virtual array height */
  176037. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  176038. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  176039. JDIMENSION rows_in_mem; /* height of memory buffer */
  176040. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176041. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176042. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176043. boolean pre_zero; /* pre-zero mode requested? */
  176044. boolean dirty; /* do current buffer contents need written? */
  176045. boolean b_s_open; /* is backing-store data valid? */
  176046. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  176047. backing_store_info b_s_info; /* System-dependent control info */
  176048. };
  176049. struct jvirt_barray_control {
  176050. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  176051. JDIMENSION rows_in_array; /* total virtual array height */
  176052. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  176053. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  176054. JDIMENSION rows_in_mem; /* height of memory buffer */
  176055. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176056. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176057. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176058. boolean pre_zero; /* pre-zero mode requested? */
  176059. boolean dirty; /* do current buffer contents need written? */
  176060. boolean b_s_open; /* is backing-store data valid? */
  176061. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176062. backing_store_info b_s_info; /* System-dependent control info */
  176063. };
  176064. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176065. LOCAL(void)
  176066. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176067. {
  176068. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176069. small_pool_ptr shdr_ptr;
  176070. large_pool_ptr lhdr_ptr;
  176071. /* Since this is only a debugging stub, we can cheat a little by using
  176072. * fprintf directly rather than going through the trace message code.
  176073. * This is helpful because message parm array can't handle longs.
  176074. */
  176075. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176076. pool_id, mem->total_space_allocated);
  176077. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176078. lhdr_ptr = lhdr_ptr->hdr.next) {
  176079. fprintf(stderr, " Large chunk used %ld\n",
  176080. (long) lhdr_ptr->hdr.bytes_used);
  176081. }
  176082. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176083. shdr_ptr = shdr_ptr->hdr.next) {
  176084. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176085. (long) shdr_ptr->hdr.bytes_used,
  176086. (long) shdr_ptr->hdr.bytes_left);
  176087. }
  176088. }
  176089. #endif /* MEM_STATS */
  176090. LOCAL(void)
  176091. out_of_memory (j_common_ptr cinfo, int which)
  176092. /* Report an out-of-memory error and stop execution */
  176093. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176094. {
  176095. #ifdef MEM_STATS
  176096. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176097. #endif
  176098. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176099. }
  176100. /*
  176101. * Allocation of "small" objects.
  176102. *
  176103. * For these, we use pooled storage. When a new pool must be created,
  176104. * we try to get enough space for the current request plus a "slop" factor,
  176105. * where the slop will be the amount of leftover space in the new pool.
  176106. * The speed vs. space tradeoff is largely determined by the slop values.
  176107. * A different slop value is provided for each pool class (lifetime),
  176108. * and we also distinguish the first pool of a class from later ones.
  176109. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176110. * machines, but may be too small if longs are 64 bits or more.
  176111. */
  176112. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176113. {
  176114. 1600, /* first PERMANENT pool */
  176115. 16000 /* first IMAGE pool */
  176116. };
  176117. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176118. {
  176119. 0, /* additional PERMANENT pools */
  176120. 5000 /* additional IMAGE pools */
  176121. };
  176122. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176123. METHODDEF(void *)
  176124. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176125. /* Allocate a "small" object */
  176126. {
  176127. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176128. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176129. char * data_ptr;
  176130. size_t odd_bytes, min_request, slop;
  176131. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176132. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176133. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176134. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176135. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176136. if (odd_bytes > 0)
  176137. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176138. /* See if space is available in any existing pool */
  176139. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176140. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176141. prev_hdr_ptr = NULL;
  176142. hdr_ptr = mem->small_list[pool_id];
  176143. while (hdr_ptr != NULL) {
  176144. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176145. break; /* found pool with enough space */
  176146. prev_hdr_ptr = hdr_ptr;
  176147. hdr_ptr = hdr_ptr->hdr.next;
  176148. }
  176149. /* Time to make a new pool? */
  176150. if (hdr_ptr == NULL) {
  176151. /* min_request is what we need now, slop is what will be leftover */
  176152. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176153. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176154. slop = first_pool_slop[pool_id];
  176155. else
  176156. slop = extra_pool_slop[pool_id];
  176157. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176158. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176159. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176160. /* Try to get space, if fail reduce slop and try again */
  176161. for (;;) {
  176162. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176163. if (hdr_ptr != NULL)
  176164. break;
  176165. slop /= 2;
  176166. if (slop < MIN_SLOP) /* give up when it gets real small */
  176167. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176168. }
  176169. mem->total_space_allocated += min_request + slop;
  176170. /* Success, initialize the new pool header and add to end of list */
  176171. hdr_ptr->hdr.next = NULL;
  176172. hdr_ptr->hdr.bytes_used = 0;
  176173. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176174. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176175. mem->small_list[pool_id] = hdr_ptr;
  176176. else
  176177. prev_hdr_ptr->hdr.next = hdr_ptr;
  176178. }
  176179. /* OK, allocate the object from the current pool */
  176180. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176181. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176182. hdr_ptr->hdr.bytes_used += sizeofobject;
  176183. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176184. return (void *) data_ptr;
  176185. }
  176186. /*
  176187. * Allocation of "large" objects.
  176188. *
  176189. * The external semantics of these are the same as "small" objects,
  176190. * except that FAR pointers are used on 80x86. However the pool
  176191. * management heuristics are quite different. We assume that each
  176192. * request is large enough that it may as well be passed directly to
  176193. * jpeg_get_large; the pool management just links everything together
  176194. * so that we can free it all on demand.
  176195. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176196. * structures. The routines that create these structures (see below)
  176197. * deliberately bunch rows together to ensure a large request size.
  176198. */
  176199. METHODDEF(void FAR *)
  176200. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176201. /* Allocate a "large" object */
  176202. {
  176203. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176204. large_pool_ptr hdr_ptr;
  176205. size_t odd_bytes;
  176206. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176207. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176208. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176209. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176210. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176211. if (odd_bytes > 0)
  176212. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176213. /* Always make a new pool */
  176214. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176215. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176216. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176217. SIZEOF(large_pool_hdr));
  176218. if (hdr_ptr == NULL)
  176219. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176220. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176221. /* Success, initialize the new pool header and add to list */
  176222. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176223. /* We maintain space counts in each pool header for statistical purposes,
  176224. * even though they are not needed for allocation.
  176225. */
  176226. hdr_ptr->hdr.bytes_used = sizeofobject;
  176227. hdr_ptr->hdr.bytes_left = 0;
  176228. mem->large_list[pool_id] = hdr_ptr;
  176229. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176230. }
  176231. /*
  176232. * Creation of 2-D sample arrays.
  176233. * The pointers are in near heap, the samples themselves in FAR heap.
  176234. *
  176235. * To minimize allocation overhead and to allow I/O of large contiguous
  176236. * blocks, we allocate the sample rows in groups of as many rows as possible
  176237. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176238. * NB: the virtual array control routines, later in this file, know about
  176239. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176240. * object so that it can be saved away if this sarray is the workspace for
  176241. * a virtual array.
  176242. */
  176243. METHODDEF(JSAMPARRAY)
  176244. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176245. JDIMENSION samplesperrow, JDIMENSION numrows)
  176246. /* Allocate a 2-D sample array */
  176247. {
  176248. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176249. JSAMPARRAY result;
  176250. JSAMPROW workspace;
  176251. JDIMENSION rowsperchunk, currow, i;
  176252. long ltemp;
  176253. /* Calculate max # of rows allowed in one allocation chunk */
  176254. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176255. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176256. if (ltemp <= 0)
  176257. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176258. if (ltemp < (long) numrows)
  176259. rowsperchunk = (JDIMENSION) ltemp;
  176260. else
  176261. rowsperchunk = numrows;
  176262. mem->last_rowsperchunk = rowsperchunk;
  176263. /* Get space for row pointers (small object) */
  176264. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176265. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176266. /* Get the rows themselves (large objects) */
  176267. currow = 0;
  176268. while (currow < numrows) {
  176269. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176270. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176271. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176272. * SIZEOF(JSAMPLE)));
  176273. for (i = rowsperchunk; i > 0; i--) {
  176274. result[currow++] = workspace;
  176275. workspace += samplesperrow;
  176276. }
  176277. }
  176278. return result;
  176279. }
  176280. /*
  176281. * Creation of 2-D coefficient-block arrays.
  176282. * This is essentially the same as the code for sample arrays, above.
  176283. */
  176284. METHODDEF(JBLOCKARRAY)
  176285. alloc_barray (j_common_ptr cinfo, int pool_id,
  176286. JDIMENSION blocksperrow, JDIMENSION numrows)
  176287. /* Allocate a 2-D coefficient-block array */
  176288. {
  176289. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176290. JBLOCKARRAY result;
  176291. JBLOCKROW workspace;
  176292. JDIMENSION rowsperchunk, currow, i;
  176293. long ltemp;
  176294. /* Calculate max # of rows allowed in one allocation chunk */
  176295. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176296. ((long) blocksperrow * SIZEOF(JBLOCK));
  176297. if (ltemp <= 0)
  176298. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176299. if (ltemp < (long) numrows)
  176300. rowsperchunk = (JDIMENSION) ltemp;
  176301. else
  176302. rowsperchunk = numrows;
  176303. mem->last_rowsperchunk = rowsperchunk;
  176304. /* Get space for row pointers (small object) */
  176305. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176306. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176307. /* Get the rows themselves (large objects) */
  176308. currow = 0;
  176309. while (currow < numrows) {
  176310. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176311. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176312. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176313. * SIZEOF(JBLOCK)));
  176314. for (i = rowsperchunk; i > 0; i--) {
  176315. result[currow++] = workspace;
  176316. workspace += blocksperrow;
  176317. }
  176318. }
  176319. return result;
  176320. }
  176321. /*
  176322. * About virtual array management:
  176323. *
  176324. * The above "normal" array routines are only used to allocate strip buffers
  176325. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176326. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176327. * time, but the memory manager must save the whole array for repeated
  176328. * accesses. The intended implementation is that there is a strip buffer in
  176329. * memory (as high as is possible given the desired memory limit), plus a
  176330. * backing file that holds the rest of the array.
  176331. *
  176332. * The request_virt_array routines are told the total size of the image and
  176333. * the maximum number of rows that will be accessed at once. The in-memory
  176334. * buffer must be at least as large as the maxaccess value.
  176335. *
  176336. * The request routines create control blocks but not the in-memory buffers.
  176337. * That is postponed until realize_virt_arrays is called. At that time the
  176338. * total amount of space needed is known (approximately, anyway), so free
  176339. * memory can be divided up fairly.
  176340. *
  176341. * The access_virt_array routines are responsible for making a specific strip
  176342. * area accessible (after reading or writing the backing file, if necessary).
  176343. * Note that the access routines are told whether the caller intends to modify
  176344. * the accessed strip; during a read-only pass this saves having to rewrite
  176345. * data to disk. The access routines are also responsible for pre-zeroing
  176346. * any newly accessed rows, if pre-zeroing was requested.
  176347. *
  176348. * In current usage, the access requests are usually for nonoverlapping
  176349. * strips; that is, successive access start_row numbers differ by exactly
  176350. * num_rows = maxaccess. This means we can get good performance with simple
  176351. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176352. * of the access height; then there will never be accesses across bufferload
  176353. * boundaries. The code will still work with overlapping access requests,
  176354. * but it doesn't handle bufferload overlaps very efficiently.
  176355. */
  176356. METHODDEF(jvirt_sarray_ptr)
  176357. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176358. JDIMENSION samplesperrow, JDIMENSION numrows,
  176359. JDIMENSION maxaccess)
  176360. /* Request a virtual 2-D sample array */
  176361. {
  176362. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176363. jvirt_sarray_ptr result;
  176364. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176365. if (pool_id != JPOOL_IMAGE)
  176366. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176367. /* get control block */
  176368. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176369. SIZEOF(struct jvirt_sarray_control));
  176370. result->mem_buffer = NULL; /* marks array not yet realized */
  176371. result->rows_in_array = numrows;
  176372. result->samplesperrow = samplesperrow;
  176373. result->maxaccess = maxaccess;
  176374. result->pre_zero = pre_zero;
  176375. result->b_s_open = FALSE; /* no associated backing-store object */
  176376. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176377. mem->virt_sarray_list = result;
  176378. return result;
  176379. }
  176380. METHODDEF(jvirt_barray_ptr)
  176381. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176382. JDIMENSION blocksperrow, JDIMENSION numrows,
  176383. JDIMENSION maxaccess)
  176384. /* Request a virtual 2-D coefficient-block array */
  176385. {
  176386. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176387. jvirt_barray_ptr result;
  176388. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176389. if (pool_id != JPOOL_IMAGE)
  176390. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176391. /* get control block */
  176392. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176393. SIZEOF(struct jvirt_barray_control));
  176394. result->mem_buffer = NULL; /* marks array not yet realized */
  176395. result->rows_in_array = numrows;
  176396. result->blocksperrow = blocksperrow;
  176397. result->maxaccess = maxaccess;
  176398. result->pre_zero = pre_zero;
  176399. result->b_s_open = FALSE; /* no associated backing-store object */
  176400. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176401. mem->virt_barray_list = result;
  176402. return result;
  176403. }
  176404. METHODDEF(void)
  176405. realize_virt_arrays (j_common_ptr cinfo)
  176406. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176407. {
  176408. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176409. long space_per_minheight, maximum_space, avail_mem;
  176410. long minheights, max_minheights;
  176411. jvirt_sarray_ptr sptr;
  176412. jvirt_barray_ptr bptr;
  176413. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176414. * and the maximum space needed (full image height in each buffer).
  176415. * These may be of use to the system-dependent jpeg_mem_available routine.
  176416. */
  176417. space_per_minheight = 0;
  176418. maximum_space = 0;
  176419. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176420. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176421. space_per_minheight += (long) sptr->maxaccess *
  176422. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176423. maximum_space += (long) sptr->rows_in_array *
  176424. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176425. }
  176426. }
  176427. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176428. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176429. space_per_minheight += (long) bptr->maxaccess *
  176430. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176431. maximum_space += (long) bptr->rows_in_array *
  176432. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176433. }
  176434. }
  176435. if (space_per_minheight <= 0)
  176436. return; /* no unrealized arrays, no work */
  176437. /* Determine amount of memory to actually use; this is system-dependent. */
  176438. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176439. mem->total_space_allocated);
  176440. /* If the maximum space needed is available, make all the buffers full
  176441. * height; otherwise parcel it out with the same number of minheights
  176442. * in each buffer.
  176443. */
  176444. if (avail_mem >= maximum_space)
  176445. max_minheights = 1000000000L;
  176446. else {
  176447. max_minheights = avail_mem / space_per_minheight;
  176448. /* If there doesn't seem to be enough space, try to get the minimum
  176449. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176450. */
  176451. if (max_minheights <= 0)
  176452. max_minheights = 1;
  176453. }
  176454. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176455. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176456. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176457. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176458. if (minheights <= max_minheights) {
  176459. /* This buffer fits in memory */
  176460. sptr->rows_in_mem = sptr->rows_in_array;
  176461. } else {
  176462. /* It doesn't fit in memory, create backing store. */
  176463. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176464. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176465. (long) sptr->rows_in_array *
  176466. (long) sptr->samplesperrow *
  176467. (long) SIZEOF(JSAMPLE));
  176468. sptr->b_s_open = TRUE;
  176469. }
  176470. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176471. sptr->samplesperrow, sptr->rows_in_mem);
  176472. sptr->rowsperchunk = mem->last_rowsperchunk;
  176473. sptr->cur_start_row = 0;
  176474. sptr->first_undef_row = 0;
  176475. sptr->dirty = FALSE;
  176476. }
  176477. }
  176478. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176479. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176480. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176481. if (minheights <= max_minheights) {
  176482. /* This buffer fits in memory */
  176483. bptr->rows_in_mem = bptr->rows_in_array;
  176484. } else {
  176485. /* It doesn't fit in memory, create backing store. */
  176486. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176487. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176488. (long) bptr->rows_in_array *
  176489. (long) bptr->blocksperrow *
  176490. (long) SIZEOF(JBLOCK));
  176491. bptr->b_s_open = TRUE;
  176492. }
  176493. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176494. bptr->blocksperrow, bptr->rows_in_mem);
  176495. bptr->rowsperchunk = mem->last_rowsperchunk;
  176496. bptr->cur_start_row = 0;
  176497. bptr->first_undef_row = 0;
  176498. bptr->dirty = FALSE;
  176499. }
  176500. }
  176501. }
  176502. LOCAL(void)
  176503. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176504. /* Do backing store read or write of a virtual sample array */
  176505. {
  176506. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176507. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176508. file_offset = ptr->cur_start_row * bytesperrow;
  176509. /* Loop to read or write each allocation chunk in mem_buffer */
  176510. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176511. /* One chunk, but check for short chunk at end of buffer */
  176512. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176513. /* Transfer no more than is currently defined */
  176514. thisrow = (long) ptr->cur_start_row + i;
  176515. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176516. /* Transfer no more than fits in file */
  176517. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176518. if (rows <= 0) /* this chunk might be past end of file! */
  176519. break;
  176520. byte_count = rows * bytesperrow;
  176521. if (writing)
  176522. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176523. (void FAR *) ptr->mem_buffer[i],
  176524. file_offset, byte_count);
  176525. else
  176526. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176527. (void FAR *) ptr->mem_buffer[i],
  176528. file_offset, byte_count);
  176529. file_offset += byte_count;
  176530. }
  176531. }
  176532. LOCAL(void)
  176533. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176534. /* Do backing store read or write of a virtual coefficient-block array */
  176535. {
  176536. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176537. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176538. file_offset = ptr->cur_start_row * bytesperrow;
  176539. /* Loop to read or write each allocation chunk in mem_buffer */
  176540. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176541. /* One chunk, but check for short chunk at end of buffer */
  176542. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176543. /* Transfer no more than is currently defined */
  176544. thisrow = (long) ptr->cur_start_row + i;
  176545. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176546. /* Transfer no more than fits in file */
  176547. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176548. if (rows <= 0) /* this chunk might be past end of file! */
  176549. break;
  176550. byte_count = rows * bytesperrow;
  176551. if (writing)
  176552. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176553. (void FAR *) ptr->mem_buffer[i],
  176554. file_offset, byte_count);
  176555. else
  176556. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176557. (void FAR *) ptr->mem_buffer[i],
  176558. file_offset, byte_count);
  176559. file_offset += byte_count;
  176560. }
  176561. }
  176562. METHODDEF(JSAMPARRAY)
  176563. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176564. JDIMENSION start_row, JDIMENSION num_rows,
  176565. boolean writable)
  176566. /* Access the part of a virtual sample array starting at start_row */
  176567. /* and extending for num_rows rows. writable is true if */
  176568. /* caller intends to modify the accessed area. */
  176569. {
  176570. JDIMENSION end_row = start_row + num_rows;
  176571. JDIMENSION undef_row;
  176572. /* debugging check */
  176573. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176574. ptr->mem_buffer == NULL)
  176575. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176576. /* Make the desired part of the virtual array accessible */
  176577. if (start_row < ptr->cur_start_row ||
  176578. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176579. if (! ptr->b_s_open)
  176580. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176581. /* Flush old buffer contents if necessary */
  176582. if (ptr->dirty) {
  176583. do_sarray_io(cinfo, ptr, TRUE);
  176584. ptr->dirty = FALSE;
  176585. }
  176586. /* Decide what part of virtual array to access.
  176587. * Algorithm: if target address > current window, assume forward scan,
  176588. * load starting at target address. If target address < current window,
  176589. * assume backward scan, load so that target area is top of window.
  176590. * Note that when switching from forward write to forward read, will have
  176591. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176592. */
  176593. if (start_row > ptr->cur_start_row) {
  176594. ptr->cur_start_row = start_row;
  176595. } else {
  176596. /* use long arithmetic here to avoid overflow & unsigned problems */
  176597. long ltemp;
  176598. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176599. if (ltemp < 0)
  176600. ltemp = 0; /* don't fall off front end of file */
  176601. ptr->cur_start_row = (JDIMENSION) ltemp;
  176602. }
  176603. /* Read in the selected part of the array.
  176604. * During the initial write pass, we will do no actual read
  176605. * because the selected part is all undefined.
  176606. */
  176607. do_sarray_io(cinfo, ptr, FALSE);
  176608. }
  176609. /* Ensure the accessed part of the array is defined; prezero if needed.
  176610. * To improve locality of access, we only prezero the part of the array
  176611. * that the caller is about to access, not the entire in-memory array.
  176612. */
  176613. if (ptr->first_undef_row < end_row) {
  176614. if (ptr->first_undef_row < start_row) {
  176615. if (writable) /* writer skipped over a section of array */
  176616. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176617. undef_row = start_row; /* but reader is allowed to read ahead */
  176618. } else {
  176619. undef_row = ptr->first_undef_row;
  176620. }
  176621. if (writable)
  176622. ptr->first_undef_row = end_row;
  176623. if (ptr->pre_zero) {
  176624. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176625. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176626. end_row -= ptr->cur_start_row;
  176627. while (undef_row < end_row) {
  176628. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176629. undef_row++;
  176630. }
  176631. } else {
  176632. if (! writable) /* reader looking at undefined data */
  176633. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176634. }
  176635. }
  176636. /* Flag the buffer dirty if caller will write in it */
  176637. if (writable)
  176638. ptr->dirty = TRUE;
  176639. /* Return address of proper part of the buffer */
  176640. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176641. }
  176642. METHODDEF(JBLOCKARRAY)
  176643. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176644. JDIMENSION start_row, JDIMENSION num_rows,
  176645. boolean writable)
  176646. /* Access the part of a virtual block array starting at start_row */
  176647. /* and extending for num_rows rows. writable is true if */
  176648. /* caller intends to modify the accessed area. */
  176649. {
  176650. JDIMENSION end_row = start_row + num_rows;
  176651. JDIMENSION undef_row;
  176652. /* debugging check */
  176653. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176654. ptr->mem_buffer == NULL)
  176655. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176656. /* Make the desired part of the virtual array accessible */
  176657. if (start_row < ptr->cur_start_row ||
  176658. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176659. if (! ptr->b_s_open)
  176660. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176661. /* Flush old buffer contents if necessary */
  176662. if (ptr->dirty) {
  176663. do_barray_io(cinfo, ptr, TRUE);
  176664. ptr->dirty = FALSE;
  176665. }
  176666. /* Decide what part of virtual array to access.
  176667. * Algorithm: if target address > current window, assume forward scan,
  176668. * load starting at target address. If target address < current window,
  176669. * assume backward scan, load so that target area is top of window.
  176670. * Note that when switching from forward write to forward read, will have
  176671. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176672. */
  176673. if (start_row > ptr->cur_start_row) {
  176674. ptr->cur_start_row = start_row;
  176675. } else {
  176676. /* use long arithmetic here to avoid overflow & unsigned problems */
  176677. long ltemp;
  176678. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176679. if (ltemp < 0)
  176680. ltemp = 0; /* don't fall off front end of file */
  176681. ptr->cur_start_row = (JDIMENSION) ltemp;
  176682. }
  176683. /* Read in the selected part of the array.
  176684. * During the initial write pass, we will do no actual read
  176685. * because the selected part is all undefined.
  176686. */
  176687. do_barray_io(cinfo, ptr, FALSE);
  176688. }
  176689. /* Ensure the accessed part of the array is defined; prezero if needed.
  176690. * To improve locality of access, we only prezero the part of the array
  176691. * that the caller is about to access, not the entire in-memory array.
  176692. */
  176693. if (ptr->first_undef_row < end_row) {
  176694. if (ptr->first_undef_row < start_row) {
  176695. if (writable) /* writer skipped over a section of array */
  176696. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176697. undef_row = start_row; /* but reader is allowed to read ahead */
  176698. } else {
  176699. undef_row = ptr->first_undef_row;
  176700. }
  176701. if (writable)
  176702. ptr->first_undef_row = end_row;
  176703. if (ptr->pre_zero) {
  176704. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176705. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176706. end_row -= ptr->cur_start_row;
  176707. while (undef_row < end_row) {
  176708. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176709. undef_row++;
  176710. }
  176711. } else {
  176712. if (! writable) /* reader looking at undefined data */
  176713. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176714. }
  176715. }
  176716. /* Flag the buffer dirty if caller will write in it */
  176717. if (writable)
  176718. ptr->dirty = TRUE;
  176719. /* Return address of proper part of the buffer */
  176720. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176721. }
  176722. /*
  176723. * Release all objects belonging to a specified pool.
  176724. */
  176725. METHODDEF(void)
  176726. free_pool (j_common_ptr cinfo, int pool_id)
  176727. {
  176728. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176729. small_pool_ptr shdr_ptr;
  176730. large_pool_ptr lhdr_ptr;
  176731. size_t space_freed;
  176732. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176733. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176734. #ifdef MEM_STATS
  176735. if (cinfo->err->trace_level > 1)
  176736. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176737. #endif
  176738. /* If freeing IMAGE pool, close any virtual arrays first */
  176739. if (pool_id == JPOOL_IMAGE) {
  176740. jvirt_sarray_ptr sptr;
  176741. jvirt_barray_ptr bptr;
  176742. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176743. if (sptr->b_s_open) { /* there may be no backing store */
  176744. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176745. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176746. }
  176747. }
  176748. mem->virt_sarray_list = NULL;
  176749. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176750. if (bptr->b_s_open) { /* there may be no backing store */
  176751. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176752. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176753. }
  176754. }
  176755. mem->virt_barray_list = NULL;
  176756. }
  176757. /* Release large objects */
  176758. lhdr_ptr = mem->large_list[pool_id];
  176759. mem->large_list[pool_id] = NULL;
  176760. while (lhdr_ptr != NULL) {
  176761. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176762. space_freed = lhdr_ptr->hdr.bytes_used +
  176763. lhdr_ptr->hdr.bytes_left +
  176764. SIZEOF(large_pool_hdr);
  176765. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176766. mem->total_space_allocated -= space_freed;
  176767. lhdr_ptr = next_lhdr_ptr;
  176768. }
  176769. /* Release small objects */
  176770. shdr_ptr = mem->small_list[pool_id];
  176771. mem->small_list[pool_id] = NULL;
  176772. while (shdr_ptr != NULL) {
  176773. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176774. space_freed = shdr_ptr->hdr.bytes_used +
  176775. shdr_ptr->hdr.bytes_left +
  176776. SIZEOF(small_pool_hdr);
  176777. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176778. mem->total_space_allocated -= space_freed;
  176779. shdr_ptr = next_shdr_ptr;
  176780. }
  176781. }
  176782. /*
  176783. * Close up shop entirely.
  176784. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176785. */
  176786. METHODDEF(void)
  176787. self_destruct (j_common_ptr cinfo)
  176788. {
  176789. int pool;
  176790. /* Close all backing store, release all memory.
  176791. * Releasing pools in reverse order might help avoid fragmentation
  176792. * with some (brain-damaged) malloc libraries.
  176793. */
  176794. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176795. free_pool(cinfo, pool);
  176796. }
  176797. /* Release the memory manager control block too. */
  176798. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176799. cinfo->mem = NULL; /* ensures I will be called only once */
  176800. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176801. }
  176802. /*
  176803. * Memory manager initialization.
  176804. * When this is called, only the error manager pointer is valid in cinfo!
  176805. */
  176806. GLOBAL(void)
  176807. jinit_memory_mgr (j_common_ptr cinfo)
  176808. {
  176809. my_mem_ptr mem;
  176810. long max_to_use;
  176811. int pool;
  176812. size_t test_mac;
  176813. cinfo->mem = NULL; /* for safety if init fails */
  176814. /* Check for configuration errors.
  176815. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176816. * doesn't reflect any real hardware alignment requirement.
  176817. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176818. * in common if and only if X is a power of 2, ie has only one one-bit.
  176819. * Some compilers may give an "unreachable code" warning here; ignore it.
  176820. */
  176821. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176822. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176823. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176824. * a multiple of SIZEOF(ALIGN_TYPE).
  176825. * Again, an "unreachable code" warning may be ignored here.
  176826. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176827. */
  176828. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176829. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176830. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176831. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176832. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176833. /* Attempt to allocate memory manager's control block */
  176834. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176835. if (mem == NULL) {
  176836. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176837. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176838. }
  176839. /* OK, fill in the method pointers */
  176840. mem->pub.alloc_small = alloc_small;
  176841. mem->pub.alloc_large = alloc_large;
  176842. mem->pub.alloc_sarray = alloc_sarray;
  176843. mem->pub.alloc_barray = alloc_barray;
  176844. mem->pub.request_virt_sarray = request_virt_sarray;
  176845. mem->pub.request_virt_barray = request_virt_barray;
  176846. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176847. mem->pub.access_virt_sarray = access_virt_sarray;
  176848. mem->pub.access_virt_barray = access_virt_barray;
  176849. mem->pub.free_pool = free_pool;
  176850. mem->pub.self_destruct = self_destruct;
  176851. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176852. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176853. /* Initialize working state */
  176854. mem->pub.max_memory_to_use = max_to_use;
  176855. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176856. mem->small_list[pool] = NULL;
  176857. mem->large_list[pool] = NULL;
  176858. }
  176859. mem->virt_sarray_list = NULL;
  176860. mem->virt_barray_list = NULL;
  176861. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176862. /* Declare ourselves open for business */
  176863. cinfo->mem = & mem->pub;
  176864. /* Check for an environment variable JPEGMEM; if found, override the
  176865. * default max_memory setting from jpeg_mem_init. Note that the
  176866. * surrounding application may again override this value.
  176867. * If your system doesn't support getenv(), define NO_GETENV to disable
  176868. * this feature.
  176869. */
  176870. #ifndef NO_GETENV
  176871. { char * memenv;
  176872. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176873. char ch = 'x';
  176874. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176875. if (ch == 'm' || ch == 'M')
  176876. max_to_use *= 1000L;
  176877. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176878. }
  176879. }
  176880. }
  176881. #endif
  176882. }
  176883. /*** End of inlined file: jmemmgr.c ***/
  176884. /*** Start of inlined file: jmemnobs.c ***/
  176885. #define JPEG_INTERNALS
  176886. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176887. extern void * malloc JPP((size_t size));
  176888. extern void free JPP((void *ptr));
  176889. #endif
  176890. /*
  176891. * Memory allocation and freeing are controlled by the regular library
  176892. * routines malloc() and free().
  176893. */
  176894. GLOBAL(void *)
  176895. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176896. {
  176897. return (void *) malloc(sizeofobject);
  176898. }
  176899. GLOBAL(void)
  176900. jpeg_free_small (j_common_ptr , void * object, size_t)
  176901. {
  176902. free(object);
  176903. }
  176904. /*
  176905. * "Large" objects are treated the same as "small" ones.
  176906. * NB: although we include FAR keywords in the routine declarations,
  176907. * this file won't actually work in 80x86 small/medium model; at least,
  176908. * you probably won't be able to process useful-size images in only 64KB.
  176909. */
  176910. GLOBAL(void FAR *)
  176911. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176912. {
  176913. return (void FAR *) malloc(sizeofobject);
  176914. }
  176915. GLOBAL(void)
  176916. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176917. {
  176918. free(object);
  176919. }
  176920. /*
  176921. * This routine computes the total memory space available for allocation.
  176922. * Here we always say, "we got all you want bud!"
  176923. */
  176924. GLOBAL(long)
  176925. jpeg_mem_available (j_common_ptr, long,
  176926. long max_bytes_needed, long)
  176927. {
  176928. return max_bytes_needed;
  176929. }
  176930. /*
  176931. * Backing store (temporary file) management.
  176932. * Since jpeg_mem_available always promised the moon,
  176933. * this should never be called and we can just error out.
  176934. */
  176935. GLOBAL(void)
  176936. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176937. long )
  176938. {
  176939. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176940. }
  176941. /*
  176942. * These routines take care of any system-dependent initialization and
  176943. * cleanup required. Here, there isn't any.
  176944. */
  176945. GLOBAL(long)
  176946. jpeg_mem_init (j_common_ptr)
  176947. {
  176948. return 0; /* just set max_memory_to_use to 0 */
  176949. }
  176950. GLOBAL(void)
  176951. jpeg_mem_term (j_common_ptr)
  176952. {
  176953. /* no work */
  176954. }
  176955. /*** End of inlined file: jmemnobs.c ***/
  176956. /*** Start of inlined file: jquant1.c ***/
  176957. #define JPEG_INTERNALS
  176958. #ifdef QUANT_1PASS_SUPPORTED
  176959. /*
  176960. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176961. * high quality, colormapped output capability. A 2-pass quantizer usually
  176962. * gives better visual quality; however, for quantized grayscale output this
  176963. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176964. * quantizer, though you can turn it off if you really want to.
  176965. *
  176966. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176967. * image. We use a map consisting of all combinations of Ncolors[i] color
  176968. * values for the i'th component. The Ncolors[] values are chosen so that
  176969. * their product, the total number of colors, is no more than that requested.
  176970. * (In most cases, the product will be somewhat less.)
  176971. *
  176972. * Since the colormap is orthogonal, the representative value for each color
  176973. * component can be determined without considering the other components;
  176974. * then these indexes can be combined into a colormap index by a standard
  176975. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176976. * can be precalculated and stored in the lookup table colorindex[].
  176977. * colorindex[i][j] maps pixel value j in component i to the nearest
  176978. * representative value (grid plane) for that component; this index is
  176979. * multiplied by the array stride for component i, so that the
  176980. * index of the colormap entry closest to a given pixel value is just
  176981. * sum( colorindex[component-number][pixel-component-value] )
  176982. * Aside from being fast, this scheme allows for variable spacing between
  176983. * representative values with no additional lookup cost.
  176984. *
  176985. * If gamma correction has been applied in color conversion, it might be wise
  176986. * to adjust the color grid spacing so that the representative colors are
  176987. * equidistant in linear space. At this writing, gamma correction is not
  176988. * implemented by jdcolor, so nothing is done here.
  176989. */
  176990. /* Declarations for ordered dithering.
  176991. *
  176992. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176993. * dithering is described in many references, for instance Dale Schumacher's
  176994. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176995. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176996. * "dither" value to the input pixel and then round the result to the nearest
  176997. * output value. The dither value is equivalent to (0.5 - threshold) times
  176998. * the distance between output values. For ordered dithering, we assume that
  176999. * the output colors are equally spaced; if not, results will probably be
  177000. * worse, since the dither may be too much or too little at a given point.
  177001. *
  177002. * The normal calculation would be to form pixel value + dither, range-limit
  177003. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  177004. * We can skip the separate range-limiting step by extending the colorindex
  177005. * table in both directions.
  177006. */
  177007. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  177008. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  177009. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  177010. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  177011. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  177012. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  177013. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  177014. /* Bayer's order-4 dither array. Generated by the code given in
  177015. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  177016. * The values in this array must range from 0 to ODITHER_CELLS-1.
  177017. */
  177018. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  177019. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  177020. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  177021. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  177022. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  177023. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  177024. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  177025. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  177026. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  177027. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  177028. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  177029. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  177030. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  177031. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  177032. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  177033. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  177034. };
  177035. /* Declarations for Floyd-Steinberg dithering.
  177036. *
  177037. * Errors are accumulated into the array fserrors[], at a resolution of
  177038. * 1/16th of a pixel count. The error at a given pixel is propagated
  177039. * to its not-yet-processed neighbors using the standard F-S fractions,
  177040. * ... (here) 7/16
  177041. * 3/16 5/16 1/16
  177042. * We work left-to-right on even rows, right-to-left on odd rows.
  177043. *
  177044. * We can get away with a single array (holding one row's worth of errors)
  177045. * by using it to store the current row's errors at pixel columns not yet
  177046. * processed, but the next row's errors at columns already processed. We
  177047. * need only a few extra variables to hold the errors immediately around the
  177048. * current column. (If we are lucky, those variables are in registers, but
  177049. * even if not, they're probably cheaper to access than array elements are.)
  177050. *
  177051. * The fserrors[] array is indexed [component#][position].
  177052. * We provide (#columns + 2) entries per component; the extra entry at each
  177053. * end saves us from special-casing the first and last pixels.
  177054. *
  177055. * Note: on a wide image, we might not have enough room in a PC's near data
  177056. * segment to hold the error array; so it is allocated with alloc_large.
  177057. */
  177058. #if BITS_IN_JSAMPLE == 8
  177059. typedef INT16 FSERROR; /* 16 bits should be enough */
  177060. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177061. #else
  177062. typedef INT32 FSERROR; /* may need more than 16 bits */
  177063. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177064. #endif
  177065. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177066. /* Private subobject */
  177067. #define MAX_Q_COMPS 4 /* max components I can handle */
  177068. typedef struct {
  177069. struct jpeg_color_quantizer pub; /* public fields */
  177070. /* Initially allocated colormap is saved here */
  177071. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177072. int sv_actual; /* number of entries in use */
  177073. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177074. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177075. * premultiplied as described above. Since colormap indexes must fit into
  177076. * JSAMPLEs, the entries of this array will too.
  177077. */
  177078. boolean is_padded; /* is the colorindex padded for odither? */
  177079. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177080. /* Variables for ordered dithering */
  177081. int row_index; /* cur row's vertical index in dither matrix */
  177082. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177083. /* Variables for Floyd-Steinberg dithering */
  177084. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177085. boolean on_odd_row; /* flag to remember which row we are on */
  177086. } my_cquantizer;
  177087. typedef my_cquantizer * my_cquantize_ptr;
  177088. /*
  177089. * Policy-making subroutines for create_colormap and create_colorindex.
  177090. * These routines determine the colormap to be used. The rest of the module
  177091. * only assumes that the colormap is orthogonal.
  177092. *
  177093. * * select_ncolors decides how to divvy up the available colors
  177094. * among the components.
  177095. * * output_value defines the set of representative values for a component.
  177096. * * largest_input_value defines the mapping from input values to
  177097. * representative values for a component.
  177098. * Note that the latter two routines may impose different policies for
  177099. * different components, though this is not currently done.
  177100. */
  177101. LOCAL(int)
  177102. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177103. /* Determine allocation of desired colors to components, */
  177104. /* and fill in Ncolors[] array to indicate choice. */
  177105. /* Return value is total number of colors (product of Ncolors[] values). */
  177106. {
  177107. int nc = cinfo->out_color_components; /* number of color components */
  177108. int max_colors = cinfo->desired_number_of_colors;
  177109. int total_colors, iroot, i, j;
  177110. boolean changed;
  177111. long temp;
  177112. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177113. /* We can allocate at least the nc'th root of max_colors per component. */
  177114. /* Compute floor(nc'th root of max_colors). */
  177115. iroot = 1;
  177116. do {
  177117. iroot++;
  177118. temp = iroot; /* set temp = iroot ** nc */
  177119. for (i = 1; i < nc; i++)
  177120. temp *= iroot;
  177121. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177122. iroot--; /* now iroot = floor(root) */
  177123. /* Must have at least 2 color values per component */
  177124. if (iroot < 2)
  177125. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177126. /* Initialize to iroot color values for each component */
  177127. total_colors = 1;
  177128. for (i = 0; i < nc; i++) {
  177129. Ncolors[i] = iroot;
  177130. total_colors *= iroot;
  177131. }
  177132. /* We may be able to increment the count for one or more components without
  177133. * exceeding max_colors, though we know not all can be incremented.
  177134. * Sometimes, the first component can be incremented more than once!
  177135. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177136. * In RGB colorspace, try to increment G first, then R, then B.
  177137. */
  177138. do {
  177139. changed = FALSE;
  177140. for (i = 0; i < nc; i++) {
  177141. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177142. /* calculate new total_colors if Ncolors[j] is incremented */
  177143. temp = total_colors / Ncolors[j];
  177144. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177145. if (temp > (long) max_colors)
  177146. break; /* won't fit, done with this pass */
  177147. Ncolors[j]++; /* OK, apply the increment */
  177148. total_colors = (int) temp;
  177149. changed = TRUE;
  177150. }
  177151. } while (changed);
  177152. return total_colors;
  177153. }
  177154. LOCAL(int)
  177155. output_value (j_decompress_ptr, int, int j, int maxj)
  177156. /* Return j'th output value, where j will range from 0 to maxj */
  177157. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177158. {
  177159. /* We always provide values 0 and MAXJSAMPLE for each component;
  177160. * any additional values are equally spaced between these limits.
  177161. * (Forcing the upper and lower values to the limits ensures that
  177162. * dithering can't produce a color outside the selected gamut.)
  177163. */
  177164. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177165. }
  177166. LOCAL(int)
  177167. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177168. /* Return largest input value that should map to j'th output value */
  177169. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177170. {
  177171. /* Breakpoints are halfway between values returned by output_value */
  177172. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177173. }
  177174. /*
  177175. * Create the colormap.
  177176. */
  177177. LOCAL(void)
  177178. create_colormap (j_decompress_ptr cinfo)
  177179. {
  177180. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177181. JSAMPARRAY colormap; /* Created colormap */
  177182. int total_colors; /* Number of distinct output colors */
  177183. int i,j,k, nci, blksize, blkdist, ptr, val;
  177184. /* Select number of colors for each component */
  177185. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177186. /* Report selected color counts */
  177187. if (cinfo->out_color_components == 3)
  177188. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177189. total_colors, cquantize->Ncolors[0],
  177190. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177191. else
  177192. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177193. /* Allocate and fill in the colormap. */
  177194. /* The colors are ordered in the map in standard row-major order, */
  177195. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177196. colormap = (*cinfo->mem->alloc_sarray)
  177197. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177198. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177199. /* blksize is number of adjacent repeated entries for a component */
  177200. /* blkdist is distance between groups of identical entries for a component */
  177201. blkdist = total_colors;
  177202. for (i = 0; i < cinfo->out_color_components; i++) {
  177203. /* fill in colormap entries for i'th color component */
  177204. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177205. blksize = blkdist / nci;
  177206. for (j = 0; j < nci; j++) {
  177207. /* Compute j'th output value (out of nci) for component */
  177208. val = output_value(cinfo, i, j, nci-1);
  177209. /* Fill in all colormap entries that have this value of this component */
  177210. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177211. /* fill in blksize entries beginning at ptr */
  177212. for (k = 0; k < blksize; k++)
  177213. colormap[i][ptr+k] = (JSAMPLE) val;
  177214. }
  177215. }
  177216. blkdist = blksize; /* blksize of this color is blkdist of next */
  177217. }
  177218. /* Save the colormap in private storage,
  177219. * where it will survive color quantization mode changes.
  177220. */
  177221. cquantize->sv_colormap = colormap;
  177222. cquantize->sv_actual = total_colors;
  177223. }
  177224. /*
  177225. * Create the color index table.
  177226. */
  177227. LOCAL(void)
  177228. create_colorindex (j_decompress_ptr cinfo)
  177229. {
  177230. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177231. JSAMPROW indexptr;
  177232. int i,j,k, nci, blksize, val, pad;
  177233. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177234. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177235. * This is not necessary in the other dithering modes. However, we
  177236. * flag whether it was done in case user changes dithering mode.
  177237. */
  177238. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177239. pad = MAXJSAMPLE*2;
  177240. cquantize->is_padded = TRUE;
  177241. } else {
  177242. pad = 0;
  177243. cquantize->is_padded = FALSE;
  177244. }
  177245. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177246. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177247. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177248. (JDIMENSION) cinfo->out_color_components);
  177249. /* blksize is number of adjacent repeated entries for a component */
  177250. blksize = cquantize->sv_actual;
  177251. for (i = 0; i < cinfo->out_color_components; i++) {
  177252. /* fill in colorindex entries for i'th color component */
  177253. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177254. blksize = blksize / nci;
  177255. /* adjust colorindex pointers to provide padding at negative indexes. */
  177256. if (pad)
  177257. cquantize->colorindex[i] += MAXJSAMPLE;
  177258. /* in loop, val = index of current output value, */
  177259. /* and k = largest j that maps to current val */
  177260. indexptr = cquantize->colorindex[i];
  177261. val = 0;
  177262. k = largest_input_value(cinfo, i, 0, nci-1);
  177263. for (j = 0; j <= MAXJSAMPLE; j++) {
  177264. while (j > k) /* advance val if past boundary */
  177265. k = largest_input_value(cinfo, i, ++val, nci-1);
  177266. /* premultiply so that no multiplication needed in main processing */
  177267. indexptr[j] = (JSAMPLE) (val * blksize);
  177268. }
  177269. /* Pad at both ends if necessary */
  177270. if (pad)
  177271. for (j = 1; j <= MAXJSAMPLE; j++) {
  177272. indexptr[-j] = indexptr[0];
  177273. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177274. }
  177275. }
  177276. }
  177277. /*
  177278. * Create an ordered-dither array for a component having ncolors
  177279. * distinct output values.
  177280. */
  177281. LOCAL(ODITHER_MATRIX_PTR)
  177282. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177283. {
  177284. ODITHER_MATRIX_PTR odither;
  177285. int j,k;
  177286. INT32 num,den;
  177287. odither = (ODITHER_MATRIX_PTR)
  177288. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177289. SIZEOF(ODITHER_MATRIX));
  177290. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177291. * Hence the dither value for the matrix cell with fill order f
  177292. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177293. * On 16-bit-int machine, be careful to avoid overflow.
  177294. */
  177295. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177296. for (j = 0; j < ODITHER_SIZE; j++) {
  177297. for (k = 0; k < ODITHER_SIZE; k++) {
  177298. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177299. * MAXJSAMPLE;
  177300. /* Ensure round towards zero despite C's lack of consistency
  177301. * about rounding negative values in integer division...
  177302. */
  177303. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177304. }
  177305. }
  177306. return odither;
  177307. }
  177308. /*
  177309. * Create the ordered-dither tables.
  177310. * Components having the same number of representative colors may
  177311. * share a dither table.
  177312. */
  177313. LOCAL(void)
  177314. create_odither_tables (j_decompress_ptr cinfo)
  177315. {
  177316. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177317. ODITHER_MATRIX_PTR odither;
  177318. int i, j, nci;
  177319. for (i = 0; i < cinfo->out_color_components; i++) {
  177320. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177321. odither = NULL; /* search for matching prior component */
  177322. for (j = 0; j < i; j++) {
  177323. if (nci == cquantize->Ncolors[j]) {
  177324. odither = cquantize->odither[j];
  177325. break;
  177326. }
  177327. }
  177328. if (odither == NULL) /* need a new table? */
  177329. odither = make_odither_array(cinfo, nci);
  177330. cquantize->odither[i] = odither;
  177331. }
  177332. }
  177333. /*
  177334. * Map some rows of pixels to the output colormapped representation.
  177335. */
  177336. METHODDEF(void)
  177337. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177338. JSAMPARRAY output_buf, int num_rows)
  177339. /* General case, no dithering */
  177340. {
  177341. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177342. JSAMPARRAY colorindex = cquantize->colorindex;
  177343. register int pixcode, ci;
  177344. register JSAMPROW ptrin, ptrout;
  177345. int row;
  177346. JDIMENSION col;
  177347. JDIMENSION width = cinfo->output_width;
  177348. register int nc = cinfo->out_color_components;
  177349. for (row = 0; row < num_rows; row++) {
  177350. ptrin = input_buf[row];
  177351. ptrout = output_buf[row];
  177352. for (col = width; col > 0; col--) {
  177353. pixcode = 0;
  177354. for (ci = 0; ci < nc; ci++) {
  177355. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177356. }
  177357. *ptrout++ = (JSAMPLE) pixcode;
  177358. }
  177359. }
  177360. }
  177361. METHODDEF(void)
  177362. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177363. JSAMPARRAY output_buf, int num_rows)
  177364. /* Fast path for out_color_components==3, no dithering */
  177365. {
  177366. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177367. register int pixcode;
  177368. register JSAMPROW ptrin, ptrout;
  177369. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177370. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177371. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177372. int row;
  177373. JDIMENSION col;
  177374. JDIMENSION width = cinfo->output_width;
  177375. for (row = 0; row < num_rows; row++) {
  177376. ptrin = input_buf[row];
  177377. ptrout = output_buf[row];
  177378. for (col = width; col > 0; col--) {
  177379. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177380. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177381. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177382. *ptrout++ = (JSAMPLE) pixcode;
  177383. }
  177384. }
  177385. }
  177386. METHODDEF(void)
  177387. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177388. JSAMPARRAY output_buf, int num_rows)
  177389. /* General case, with ordered dithering */
  177390. {
  177391. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177392. register JSAMPROW input_ptr;
  177393. register JSAMPROW output_ptr;
  177394. JSAMPROW colorindex_ci;
  177395. int * dither; /* points to active row of dither matrix */
  177396. int row_index, col_index; /* current indexes into dither matrix */
  177397. int nc = cinfo->out_color_components;
  177398. int ci;
  177399. int row;
  177400. JDIMENSION col;
  177401. JDIMENSION width = cinfo->output_width;
  177402. for (row = 0; row < num_rows; row++) {
  177403. /* Initialize output values to 0 so can process components separately */
  177404. jzero_far((void FAR *) output_buf[row],
  177405. (size_t) (width * SIZEOF(JSAMPLE)));
  177406. row_index = cquantize->row_index;
  177407. for (ci = 0; ci < nc; ci++) {
  177408. input_ptr = input_buf[row] + ci;
  177409. output_ptr = output_buf[row];
  177410. colorindex_ci = cquantize->colorindex[ci];
  177411. dither = cquantize->odither[ci][row_index];
  177412. col_index = 0;
  177413. for (col = width; col > 0; col--) {
  177414. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177415. * select output value, accumulate into output code for this pixel.
  177416. * Range-limiting need not be done explicitly, as we have extended
  177417. * the colorindex table to produce the right answers for out-of-range
  177418. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177419. * required amount of padding.
  177420. */
  177421. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177422. input_ptr += nc;
  177423. output_ptr++;
  177424. col_index = (col_index + 1) & ODITHER_MASK;
  177425. }
  177426. }
  177427. /* Advance row index for next row */
  177428. row_index = (row_index + 1) & ODITHER_MASK;
  177429. cquantize->row_index = row_index;
  177430. }
  177431. }
  177432. METHODDEF(void)
  177433. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177434. JSAMPARRAY output_buf, int num_rows)
  177435. /* Fast path for out_color_components==3, with ordered dithering */
  177436. {
  177437. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177438. register int pixcode;
  177439. register JSAMPROW input_ptr;
  177440. register JSAMPROW output_ptr;
  177441. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177442. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177443. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177444. int * dither0; /* points to active row of dither matrix */
  177445. int * dither1;
  177446. int * dither2;
  177447. int row_index, col_index; /* current indexes into dither matrix */
  177448. int row;
  177449. JDIMENSION col;
  177450. JDIMENSION width = cinfo->output_width;
  177451. for (row = 0; row < num_rows; row++) {
  177452. row_index = cquantize->row_index;
  177453. input_ptr = input_buf[row];
  177454. output_ptr = output_buf[row];
  177455. dither0 = cquantize->odither[0][row_index];
  177456. dither1 = cquantize->odither[1][row_index];
  177457. dither2 = cquantize->odither[2][row_index];
  177458. col_index = 0;
  177459. for (col = width; col > 0; col--) {
  177460. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177461. dither0[col_index]]);
  177462. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177463. dither1[col_index]]);
  177464. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177465. dither2[col_index]]);
  177466. *output_ptr++ = (JSAMPLE) pixcode;
  177467. col_index = (col_index + 1) & ODITHER_MASK;
  177468. }
  177469. row_index = (row_index + 1) & ODITHER_MASK;
  177470. cquantize->row_index = row_index;
  177471. }
  177472. }
  177473. METHODDEF(void)
  177474. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177475. JSAMPARRAY output_buf, int num_rows)
  177476. /* General case, with Floyd-Steinberg dithering */
  177477. {
  177478. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177479. register LOCFSERROR cur; /* current error or pixel value */
  177480. LOCFSERROR belowerr; /* error for pixel below cur */
  177481. LOCFSERROR bpreverr; /* error for below/prev col */
  177482. LOCFSERROR bnexterr; /* error for below/next col */
  177483. LOCFSERROR delta;
  177484. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177485. register JSAMPROW input_ptr;
  177486. register JSAMPROW output_ptr;
  177487. JSAMPROW colorindex_ci;
  177488. JSAMPROW colormap_ci;
  177489. int pixcode;
  177490. int nc = cinfo->out_color_components;
  177491. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177492. int dirnc; /* dir * nc */
  177493. int ci;
  177494. int row;
  177495. JDIMENSION col;
  177496. JDIMENSION width = cinfo->output_width;
  177497. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177498. SHIFT_TEMPS
  177499. for (row = 0; row < num_rows; row++) {
  177500. /* Initialize output values to 0 so can process components separately */
  177501. jzero_far((void FAR *) output_buf[row],
  177502. (size_t) (width * SIZEOF(JSAMPLE)));
  177503. for (ci = 0; ci < nc; ci++) {
  177504. input_ptr = input_buf[row] + ci;
  177505. output_ptr = output_buf[row];
  177506. if (cquantize->on_odd_row) {
  177507. /* work right to left in this row */
  177508. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177509. output_ptr += width-1;
  177510. dir = -1;
  177511. dirnc = -nc;
  177512. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177513. } else {
  177514. /* work left to right in this row */
  177515. dir = 1;
  177516. dirnc = nc;
  177517. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177518. }
  177519. colorindex_ci = cquantize->colorindex[ci];
  177520. colormap_ci = cquantize->sv_colormap[ci];
  177521. /* Preset error values: no error propagated to first pixel from left */
  177522. cur = 0;
  177523. /* and no error propagated to row below yet */
  177524. belowerr = bpreverr = 0;
  177525. for (col = width; col > 0; col--) {
  177526. /* cur holds the error propagated from the previous pixel on the
  177527. * current line. Add the error propagated from the previous line
  177528. * to form the complete error correction term for this pixel, and
  177529. * round the error term (which is expressed * 16) to an integer.
  177530. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177531. * for either sign of the error value.
  177532. * Note: errorptr points to *previous* column's array entry.
  177533. */
  177534. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177535. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177536. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177537. * of the range_limit array.
  177538. */
  177539. cur += GETJSAMPLE(*input_ptr);
  177540. cur = GETJSAMPLE(range_limit[cur]);
  177541. /* Select output value, accumulate into output code for this pixel */
  177542. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177543. *output_ptr += (JSAMPLE) pixcode;
  177544. /* Compute actual representation error at this pixel */
  177545. /* Note: we can do this even though we don't have the final */
  177546. /* pixel code, because the colormap is orthogonal. */
  177547. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177548. /* Compute error fractions to be propagated to adjacent pixels.
  177549. * Add these into the running sums, and simultaneously shift the
  177550. * next-line error sums left by 1 column.
  177551. */
  177552. bnexterr = cur;
  177553. delta = cur * 2;
  177554. cur += delta; /* form error * 3 */
  177555. errorptr[0] = (FSERROR) (bpreverr + cur);
  177556. cur += delta; /* form error * 5 */
  177557. bpreverr = belowerr + cur;
  177558. belowerr = bnexterr;
  177559. cur += delta; /* form error * 7 */
  177560. /* At this point cur contains the 7/16 error value to be propagated
  177561. * to the next pixel on the current line, and all the errors for the
  177562. * next line have been shifted over. We are therefore ready to move on.
  177563. */
  177564. input_ptr += dirnc; /* advance input ptr to next column */
  177565. output_ptr += dir; /* advance output ptr to next column */
  177566. errorptr += dir; /* advance errorptr to current column */
  177567. }
  177568. /* Post-loop cleanup: we must unload the final error value into the
  177569. * final fserrors[] entry. Note we need not unload belowerr because
  177570. * it is for the dummy column before or after the actual array.
  177571. */
  177572. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177573. }
  177574. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177575. }
  177576. }
  177577. /*
  177578. * Allocate workspace for Floyd-Steinberg errors.
  177579. */
  177580. LOCAL(void)
  177581. alloc_fs_workspace (j_decompress_ptr cinfo)
  177582. {
  177583. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177584. size_t arraysize;
  177585. int i;
  177586. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177587. for (i = 0; i < cinfo->out_color_components; i++) {
  177588. cquantize->fserrors[i] = (FSERRPTR)
  177589. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177590. }
  177591. }
  177592. /*
  177593. * Initialize for one-pass color quantization.
  177594. */
  177595. METHODDEF(void)
  177596. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177597. {
  177598. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177599. size_t arraysize;
  177600. int i;
  177601. /* Install my colormap. */
  177602. cinfo->colormap = cquantize->sv_colormap;
  177603. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177604. /* Initialize for desired dithering mode. */
  177605. switch (cinfo->dither_mode) {
  177606. case JDITHER_NONE:
  177607. if (cinfo->out_color_components == 3)
  177608. cquantize->pub.color_quantize = color_quantize3;
  177609. else
  177610. cquantize->pub.color_quantize = color_quantize;
  177611. break;
  177612. case JDITHER_ORDERED:
  177613. if (cinfo->out_color_components == 3)
  177614. cquantize->pub.color_quantize = quantize3_ord_dither;
  177615. else
  177616. cquantize->pub.color_quantize = quantize_ord_dither;
  177617. cquantize->row_index = 0; /* initialize state for ordered dither */
  177618. /* If user changed to ordered dither from another mode,
  177619. * we must recreate the color index table with padding.
  177620. * This will cost extra space, but probably isn't very likely.
  177621. */
  177622. if (! cquantize->is_padded)
  177623. create_colorindex(cinfo);
  177624. /* Create ordered-dither tables if we didn't already. */
  177625. if (cquantize->odither[0] == NULL)
  177626. create_odither_tables(cinfo);
  177627. break;
  177628. case JDITHER_FS:
  177629. cquantize->pub.color_quantize = quantize_fs_dither;
  177630. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177631. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177632. if (cquantize->fserrors[0] == NULL)
  177633. alloc_fs_workspace(cinfo);
  177634. /* Initialize the propagated errors to zero. */
  177635. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177636. for (i = 0; i < cinfo->out_color_components; i++)
  177637. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177638. break;
  177639. default:
  177640. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177641. break;
  177642. }
  177643. }
  177644. /*
  177645. * Finish up at the end of the pass.
  177646. */
  177647. METHODDEF(void)
  177648. finish_pass_1_quant (j_decompress_ptr)
  177649. {
  177650. /* no work in 1-pass case */
  177651. }
  177652. /*
  177653. * Switch to a new external colormap between output passes.
  177654. * Shouldn't get to this module!
  177655. */
  177656. METHODDEF(void)
  177657. new_color_map_1_quant (j_decompress_ptr cinfo)
  177658. {
  177659. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177660. }
  177661. /*
  177662. * Module initialization routine for 1-pass color quantization.
  177663. */
  177664. GLOBAL(void)
  177665. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177666. {
  177667. my_cquantize_ptr cquantize;
  177668. cquantize = (my_cquantize_ptr)
  177669. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177670. SIZEOF(my_cquantizer));
  177671. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177672. cquantize->pub.start_pass = start_pass_1_quant;
  177673. cquantize->pub.finish_pass = finish_pass_1_quant;
  177674. cquantize->pub.new_color_map = new_color_map_1_quant;
  177675. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177676. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177677. /* Make sure my internal arrays won't overflow */
  177678. if (cinfo->out_color_components > MAX_Q_COMPS)
  177679. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177680. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177681. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177682. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177683. /* Create the colormap and color index table. */
  177684. create_colormap(cinfo);
  177685. create_colorindex(cinfo);
  177686. /* Allocate Floyd-Steinberg workspace now if requested.
  177687. * We do this now since it is FAR storage and may affect the memory
  177688. * manager's space calculations. If the user changes to FS dither
  177689. * mode in a later pass, we will allocate the space then, and will
  177690. * possibly overrun the max_memory_to_use setting.
  177691. */
  177692. if (cinfo->dither_mode == JDITHER_FS)
  177693. alloc_fs_workspace(cinfo);
  177694. }
  177695. #endif /* QUANT_1PASS_SUPPORTED */
  177696. /*** End of inlined file: jquant1.c ***/
  177697. /*** Start of inlined file: jquant2.c ***/
  177698. #define JPEG_INTERNALS
  177699. #ifdef QUANT_2PASS_SUPPORTED
  177700. /*
  177701. * This module implements the well-known Heckbert paradigm for color
  177702. * quantization. Most of the ideas used here can be traced back to
  177703. * Heckbert's seminal paper
  177704. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177705. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177706. *
  177707. * In the first pass over the image, we accumulate a histogram showing the
  177708. * usage count of each possible color. To keep the histogram to a reasonable
  177709. * size, we reduce the precision of the input; typical practice is to retain
  177710. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177711. * in the same histogram cell.
  177712. *
  177713. * Next, the color-selection step begins with a box representing the whole
  177714. * color space, and repeatedly splits the "largest" remaining box until we
  177715. * have as many boxes as desired colors. Then the mean color in each
  177716. * remaining box becomes one of the possible output colors.
  177717. *
  177718. * The second pass over the image maps each input pixel to the closest output
  177719. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177720. * This mapping is logically trivial, but making it go fast enough requires
  177721. * considerable care.
  177722. *
  177723. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177724. * the "largest" box and deciding where to cut it. The particular policies
  177725. * used here have proved out well in experimental comparisons, but better ones
  177726. * may yet be found.
  177727. *
  177728. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177729. * space, processing the raw upsampled data without a color conversion step.
  177730. * This allowed the color conversion math to be done only once per colormap
  177731. * entry, not once per pixel. However, that optimization precluded other
  177732. * useful optimizations (such as merging color conversion with upsampling)
  177733. * and it also interfered with desired capabilities such as quantizing to an
  177734. * externally-supplied colormap. We have therefore abandoned that approach.
  177735. * The present code works in the post-conversion color space, typically RGB.
  177736. *
  177737. * To improve the visual quality of the results, we actually work in scaled
  177738. * RGB space, giving G distances more weight than R, and R in turn more than
  177739. * B. To do everything in integer math, we must use integer scale factors.
  177740. * The 2/3/1 scale factors used here correspond loosely to the relative
  177741. * weights of the colors in the NTSC grayscale equation.
  177742. * If you want to use this code to quantize a non-RGB color space, you'll
  177743. * probably need to change these scale factors.
  177744. */
  177745. #define R_SCALE 2 /* scale R distances by this much */
  177746. #define G_SCALE 3 /* scale G distances by this much */
  177747. #define B_SCALE 1 /* and B by this much */
  177748. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177749. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177750. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177751. * you'll get compile errors until you extend this logic. In that case
  177752. * you'll probably want to tweak the histogram sizes too.
  177753. */
  177754. #if RGB_RED == 0
  177755. #define C0_SCALE R_SCALE
  177756. #endif
  177757. #if RGB_BLUE == 0
  177758. #define C0_SCALE B_SCALE
  177759. #endif
  177760. #if RGB_GREEN == 1
  177761. #define C1_SCALE G_SCALE
  177762. #endif
  177763. #if RGB_RED == 2
  177764. #define C2_SCALE R_SCALE
  177765. #endif
  177766. #if RGB_BLUE == 2
  177767. #define C2_SCALE B_SCALE
  177768. #endif
  177769. /*
  177770. * First we have the histogram data structure and routines for creating it.
  177771. *
  177772. * The number of bits of precision can be adjusted by changing these symbols.
  177773. * We recommend keeping 6 bits for G and 5 each for R and B.
  177774. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177775. * better results; if you are short of memory, 5 bits all around will save
  177776. * some space but degrade the results.
  177777. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177778. * (preferably unsigned long) for each cell. In practice this is overkill;
  177779. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177780. * and clamping those that do overflow to the maximum value will give close-
  177781. * enough results. This reduces the recommended histogram size from 256Kb
  177782. * to 128Kb, which is a useful savings on PC-class machines.
  177783. * (In the second pass the histogram space is re-used for pixel mapping data;
  177784. * in that capacity, each cell must be able to store zero to the number of
  177785. * desired colors. 16 bits/cell is plenty for that too.)
  177786. * Since the JPEG code is intended to run in small memory model on 80x86
  177787. * machines, we can't just allocate the histogram in one chunk. Instead
  177788. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177789. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177790. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177791. * on 80x86 machines, the pointer row is in near memory but the actual
  177792. * arrays are in far memory (same arrangement as we use for image arrays).
  177793. */
  177794. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177795. /* These will do the right thing for either R,G,B or B,G,R color order,
  177796. * but you may not like the results for other color orders.
  177797. */
  177798. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177799. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177800. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177801. /* Number of elements along histogram axes. */
  177802. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177803. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177804. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177805. /* These are the amounts to shift an input value to get a histogram index. */
  177806. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177807. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177808. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177809. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177810. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177811. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177812. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177813. typedef hist2d * hist3d; /* type for top-level pointer */
  177814. /* Declarations for Floyd-Steinberg dithering.
  177815. *
  177816. * Errors are accumulated into the array fserrors[], at a resolution of
  177817. * 1/16th of a pixel count. The error at a given pixel is propagated
  177818. * to its not-yet-processed neighbors using the standard F-S fractions,
  177819. * ... (here) 7/16
  177820. * 3/16 5/16 1/16
  177821. * We work left-to-right on even rows, right-to-left on odd rows.
  177822. *
  177823. * We can get away with a single array (holding one row's worth of errors)
  177824. * by using it to store the current row's errors at pixel columns not yet
  177825. * processed, but the next row's errors at columns already processed. We
  177826. * need only a few extra variables to hold the errors immediately around the
  177827. * current column. (If we are lucky, those variables are in registers, but
  177828. * even if not, they're probably cheaper to access than array elements are.)
  177829. *
  177830. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177831. * each end saves us from special-casing the first and last pixels.
  177832. * Each entry is three values long, one value for each color component.
  177833. *
  177834. * Note: on a wide image, we might not have enough room in a PC's near data
  177835. * segment to hold the error array; so it is allocated with alloc_large.
  177836. */
  177837. #if BITS_IN_JSAMPLE == 8
  177838. typedef INT16 FSERROR; /* 16 bits should be enough */
  177839. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177840. #else
  177841. typedef INT32 FSERROR; /* may need more than 16 bits */
  177842. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177843. #endif
  177844. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177845. /* Private subobject */
  177846. typedef struct {
  177847. struct jpeg_color_quantizer pub; /* public fields */
  177848. /* Space for the eventually created colormap is stashed here */
  177849. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177850. int desired; /* desired # of colors = size of colormap */
  177851. /* Variables for accumulating image statistics */
  177852. hist3d histogram; /* pointer to the histogram */
  177853. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177854. /* Variables for Floyd-Steinberg dithering */
  177855. FSERRPTR fserrors; /* accumulated errors */
  177856. boolean on_odd_row; /* flag to remember which row we are on */
  177857. int * error_limiter; /* table for clamping the applied error */
  177858. } my_cquantizer2;
  177859. typedef my_cquantizer2 * my_cquantize_ptr2;
  177860. /*
  177861. * Prescan some rows of pixels.
  177862. * In this module the prescan simply updates the histogram, which has been
  177863. * initialized to zeroes by start_pass.
  177864. * An output_buf parameter is required by the method signature, but no data
  177865. * is actually output (in fact the buffer controller is probably passing a
  177866. * NULL pointer).
  177867. */
  177868. METHODDEF(void)
  177869. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177870. JSAMPARRAY, int num_rows)
  177871. {
  177872. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177873. register JSAMPROW ptr;
  177874. register histptr histp;
  177875. register hist3d histogram = cquantize->histogram;
  177876. int row;
  177877. JDIMENSION col;
  177878. JDIMENSION width = cinfo->output_width;
  177879. for (row = 0; row < num_rows; row++) {
  177880. ptr = input_buf[row];
  177881. for (col = width; col > 0; col--) {
  177882. /* get pixel value and index into the histogram */
  177883. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177884. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177885. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177886. /* increment, check for overflow and undo increment if so. */
  177887. if (++(*histp) <= 0)
  177888. (*histp)--;
  177889. ptr += 3;
  177890. }
  177891. }
  177892. }
  177893. /*
  177894. * Next we have the really interesting routines: selection of a colormap
  177895. * given the completed histogram.
  177896. * These routines work with a list of "boxes", each representing a rectangular
  177897. * subset of the input color space (to histogram precision).
  177898. */
  177899. typedef struct {
  177900. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177901. int c0min, c0max;
  177902. int c1min, c1max;
  177903. int c2min, c2max;
  177904. /* The volume (actually 2-norm) of the box */
  177905. INT32 volume;
  177906. /* The number of nonzero histogram cells within this box */
  177907. long colorcount;
  177908. } box;
  177909. typedef box * boxptr;
  177910. LOCAL(boxptr)
  177911. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177912. /* Find the splittable box with the largest color population */
  177913. /* Returns NULL if no splittable boxes remain */
  177914. {
  177915. register boxptr boxp;
  177916. register int i;
  177917. register long maxc = 0;
  177918. boxptr which = NULL;
  177919. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177920. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177921. which = boxp;
  177922. maxc = boxp->colorcount;
  177923. }
  177924. }
  177925. return which;
  177926. }
  177927. LOCAL(boxptr)
  177928. find_biggest_volume (boxptr boxlist, int numboxes)
  177929. /* Find the splittable box with the largest (scaled) volume */
  177930. /* Returns NULL if no splittable boxes remain */
  177931. {
  177932. register boxptr boxp;
  177933. register int i;
  177934. register INT32 maxv = 0;
  177935. boxptr which = NULL;
  177936. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177937. if (boxp->volume > maxv) {
  177938. which = boxp;
  177939. maxv = boxp->volume;
  177940. }
  177941. }
  177942. return which;
  177943. }
  177944. LOCAL(void)
  177945. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177946. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177947. /* and recompute its volume and population */
  177948. {
  177949. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177950. hist3d histogram = cquantize->histogram;
  177951. histptr histp;
  177952. int c0,c1,c2;
  177953. int c0min,c0max,c1min,c1max,c2min,c2max;
  177954. INT32 dist0,dist1,dist2;
  177955. long ccount;
  177956. c0min = boxp->c0min; c0max = boxp->c0max;
  177957. c1min = boxp->c1min; c1max = boxp->c1max;
  177958. c2min = boxp->c2min; c2max = boxp->c2max;
  177959. if (c0max > c0min)
  177960. for (c0 = c0min; c0 <= c0max; c0++)
  177961. for (c1 = c1min; c1 <= c1max; c1++) {
  177962. histp = & histogram[c0][c1][c2min];
  177963. for (c2 = c2min; c2 <= c2max; c2++)
  177964. if (*histp++ != 0) {
  177965. boxp->c0min = c0min = c0;
  177966. goto have_c0min;
  177967. }
  177968. }
  177969. have_c0min:
  177970. if (c0max > c0min)
  177971. for (c0 = c0max; c0 >= c0min; c0--)
  177972. for (c1 = c1min; c1 <= c1max; c1++) {
  177973. histp = & histogram[c0][c1][c2min];
  177974. for (c2 = c2min; c2 <= c2max; c2++)
  177975. if (*histp++ != 0) {
  177976. boxp->c0max = c0max = c0;
  177977. goto have_c0max;
  177978. }
  177979. }
  177980. have_c0max:
  177981. if (c1max > c1min)
  177982. for (c1 = c1min; c1 <= c1max; c1++)
  177983. for (c0 = c0min; c0 <= c0max; c0++) {
  177984. histp = & histogram[c0][c1][c2min];
  177985. for (c2 = c2min; c2 <= c2max; c2++)
  177986. if (*histp++ != 0) {
  177987. boxp->c1min = c1min = c1;
  177988. goto have_c1min;
  177989. }
  177990. }
  177991. have_c1min:
  177992. if (c1max > c1min)
  177993. for (c1 = c1max; c1 >= c1min; c1--)
  177994. for (c0 = c0min; c0 <= c0max; c0++) {
  177995. histp = & histogram[c0][c1][c2min];
  177996. for (c2 = c2min; c2 <= c2max; c2++)
  177997. if (*histp++ != 0) {
  177998. boxp->c1max = c1max = c1;
  177999. goto have_c1max;
  178000. }
  178001. }
  178002. have_c1max:
  178003. if (c2max > c2min)
  178004. for (c2 = c2min; c2 <= c2max; c2++)
  178005. for (c0 = c0min; c0 <= c0max; c0++) {
  178006. histp = & histogram[c0][c1min][c2];
  178007. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178008. if (*histp != 0) {
  178009. boxp->c2min = c2min = c2;
  178010. goto have_c2min;
  178011. }
  178012. }
  178013. have_c2min:
  178014. if (c2max > c2min)
  178015. for (c2 = c2max; c2 >= c2min; c2--)
  178016. for (c0 = c0min; c0 <= c0max; c0++) {
  178017. histp = & histogram[c0][c1min][c2];
  178018. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178019. if (*histp != 0) {
  178020. boxp->c2max = c2max = c2;
  178021. goto have_c2max;
  178022. }
  178023. }
  178024. have_c2max:
  178025. /* Update box volume.
  178026. * We use 2-norm rather than real volume here; this biases the method
  178027. * against making long narrow boxes, and it has the side benefit that
  178028. * a box is splittable iff norm > 0.
  178029. * Since the differences are expressed in histogram-cell units,
  178030. * we have to shift back to JSAMPLE units to get consistent distances;
  178031. * after which, we scale according to the selected distance scale factors.
  178032. */
  178033. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  178034. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  178035. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  178036. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  178037. /* Now scan remaining volume of box and compute population */
  178038. ccount = 0;
  178039. for (c0 = c0min; c0 <= c0max; c0++)
  178040. for (c1 = c1min; c1 <= c1max; c1++) {
  178041. histp = & histogram[c0][c1][c2min];
  178042. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  178043. if (*histp != 0) {
  178044. ccount++;
  178045. }
  178046. }
  178047. boxp->colorcount = ccount;
  178048. }
  178049. LOCAL(int)
  178050. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  178051. int desired_colors)
  178052. /* Repeatedly select and split the largest box until we have enough boxes */
  178053. {
  178054. int n,lb;
  178055. int c0,c1,c2,cmax;
  178056. register boxptr b1,b2;
  178057. while (numboxes < desired_colors) {
  178058. /* Select box to split.
  178059. * Current algorithm: by population for first half, then by volume.
  178060. */
  178061. if (numboxes*2 <= desired_colors) {
  178062. b1 = find_biggest_color_pop(boxlist, numboxes);
  178063. } else {
  178064. b1 = find_biggest_volume(boxlist, numboxes);
  178065. }
  178066. if (b1 == NULL) /* no splittable boxes left! */
  178067. break;
  178068. b2 = &boxlist[numboxes]; /* where new box will go */
  178069. /* Copy the color bounds to the new box. */
  178070. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178071. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178072. /* Choose which axis to split the box on.
  178073. * Current algorithm: longest scaled axis.
  178074. * See notes in update_box about scaling distances.
  178075. */
  178076. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178077. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178078. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178079. /* We want to break any ties in favor of green, then red, blue last.
  178080. * This code does the right thing for R,G,B or B,G,R color orders only.
  178081. */
  178082. #if RGB_RED == 0
  178083. cmax = c1; n = 1;
  178084. if (c0 > cmax) { cmax = c0; n = 0; }
  178085. if (c2 > cmax) { n = 2; }
  178086. #else
  178087. cmax = c1; n = 1;
  178088. if (c2 > cmax) { cmax = c2; n = 2; }
  178089. if (c0 > cmax) { n = 0; }
  178090. #endif
  178091. /* Choose split point along selected axis, and update box bounds.
  178092. * Current algorithm: split at halfway point.
  178093. * (Since the box has been shrunk to minimum volume,
  178094. * any split will produce two nonempty subboxes.)
  178095. * Note that lb value is max for lower box, so must be < old max.
  178096. */
  178097. switch (n) {
  178098. case 0:
  178099. lb = (b1->c0max + b1->c0min) / 2;
  178100. b1->c0max = lb;
  178101. b2->c0min = lb+1;
  178102. break;
  178103. case 1:
  178104. lb = (b1->c1max + b1->c1min) / 2;
  178105. b1->c1max = lb;
  178106. b2->c1min = lb+1;
  178107. break;
  178108. case 2:
  178109. lb = (b1->c2max + b1->c2min) / 2;
  178110. b1->c2max = lb;
  178111. b2->c2min = lb+1;
  178112. break;
  178113. }
  178114. /* Update stats for boxes */
  178115. update_box(cinfo, b1);
  178116. update_box(cinfo, b2);
  178117. numboxes++;
  178118. }
  178119. return numboxes;
  178120. }
  178121. LOCAL(void)
  178122. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178123. /* Compute representative color for a box, put it in colormap[icolor] */
  178124. {
  178125. /* Current algorithm: mean weighted by pixels (not colors) */
  178126. /* Note it is important to get the rounding correct! */
  178127. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178128. hist3d histogram = cquantize->histogram;
  178129. histptr histp;
  178130. int c0,c1,c2;
  178131. int c0min,c0max,c1min,c1max,c2min,c2max;
  178132. long count;
  178133. long total = 0;
  178134. long c0total = 0;
  178135. long c1total = 0;
  178136. long c2total = 0;
  178137. c0min = boxp->c0min; c0max = boxp->c0max;
  178138. c1min = boxp->c1min; c1max = boxp->c1max;
  178139. c2min = boxp->c2min; c2max = boxp->c2max;
  178140. for (c0 = c0min; c0 <= c0max; c0++)
  178141. for (c1 = c1min; c1 <= c1max; c1++) {
  178142. histp = & histogram[c0][c1][c2min];
  178143. for (c2 = c2min; c2 <= c2max; c2++) {
  178144. if ((count = *histp++) != 0) {
  178145. total += count;
  178146. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178147. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178148. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178149. }
  178150. }
  178151. }
  178152. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178153. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178154. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178155. }
  178156. LOCAL(void)
  178157. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178158. /* Master routine for color selection */
  178159. {
  178160. boxptr boxlist;
  178161. int numboxes;
  178162. int i;
  178163. /* Allocate workspace for box list */
  178164. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178165. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178166. /* Initialize one box containing whole space */
  178167. numboxes = 1;
  178168. boxlist[0].c0min = 0;
  178169. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178170. boxlist[0].c1min = 0;
  178171. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178172. boxlist[0].c2min = 0;
  178173. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178174. /* Shrink it to actually-used volume and set its statistics */
  178175. update_box(cinfo, & boxlist[0]);
  178176. /* Perform median-cut to produce final box list */
  178177. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178178. /* Compute the representative color for each box, fill colormap */
  178179. for (i = 0; i < numboxes; i++)
  178180. compute_color(cinfo, & boxlist[i], i);
  178181. cinfo->actual_number_of_colors = numboxes;
  178182. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178183. }
  178184. /*
  178185. * These routines are concerned with the time-critical task of mapping input
  178186. * colors to the nearest color in the selected colormap.
  178187. *
  178188. * We re-use the histogram space as an "inverse color map", essentially a
  178189. * cache for the results of nearest-color searches. All colors within a
  178190. * histogram cell will be mapped to the same colormap entry, namely the one
  178191. * closest to the cell's center. This may not be quite the closest entry to
  178192. * the actual input color, but it's almost as good. A zero in the cache
  178193. * indicates we haven't found the nearest color for that cell yet; the array
  178194. * is cleared to zeroes before starting the mapping pass. When we find the
  178195. * nearest color for a cell, its colormap index plus one is recorded in the
  178196. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178197. * when they need to use an unfilled entry in the cache.
  178198. *
  178199. * Our method of efficiently finding nearest colors is based on the "locally
  178200. * sorted search" idea described by Heckbert and on the incremental distance
  178201. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178202. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178203. * the distances from a given colormap entry to each cell of the histogram can
  178204. * be computed quickly using an incremental method: the differences between
  178205. * distances to adjacent cells themselves differ by a constant. This allows a
  178206. * fairly fast implementation of the "brute force" approach of computing the
  178207. * distance from every colormap entry to every histogram cell. Unfortunately,
  178208. * it needs a work array to hold the best-distance-so-far for each histogram
  178209. * cell (because the inner loop has to be over cells, not colormap entries).
  178210. * The work array elements have to be INT32s, so the work array would need
  178211. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178212. *
  178213. * To get around these problems, we apply Thomas' method to compute the
  178214. * nearest colors for only the cells within a small subbox of the histogram.
  178215. * The work array need be only as big as the subbox, so the memory usage
  178216. * problem is solved. Furthermore, we need not fill subboxes that are never
  178217. * referenced in pass2; many images use only part of the color gamut, so a
  178218. * fair amount of work is saved. An additional advantage of this
  178219. * approach is that we can apply Heckbert's locality criterion to quickly
  178220. * eliminate colormap entries that are far away from the subbox; typically
  178221. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178222. * and we need not compute their distances to individual cells in the subbox.
  178223. * The speed of this approach is heavily influenced by the subbox size: too
  178224. * small means too much overhead, too big loses because Heckbert's criterion
  178225. * can't eliminate as many colormap entries. Empirically the best subbox
  178226. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178227. *
  178228. * Thomas' article also describes a refined method which is asymptotically
  178229. * faster than the brute-force method, but it is also far more complex and
  178230. * cannot efficiently be applied to small subboxes. It is therefore not
  178231. * useful for programs intended to be portable to DOS machines. On machines
  178232. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178233. * refined method might be faster than the present code --- but then again,
  178234. * it might not be any faster, and it's certainly more complicated.
  178235. */
  178236. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178237. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178238. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178239. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178240. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178241. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178242. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178243. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178244. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178245. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178246. /*
  178247. * The next three routines implement inverse colormap filling. They could
  178248. * all be folded into one big routine, but splitting them up this way saves
  178249. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178250. * and may allow some compilers to produce better code by registerizing more
  178251. * inner-loop variables.
  178252. */
  178253. LOCAL(int)
  178254. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178255. JSAMPLE colorlist[])
  178256. /* Locate the colormap entries close enough to an update box to be candidates
  178257. * for the nearest entry to some cell(s) in the update box. The update box
  178258. * is specified by the center coordinates of its first cell. The number of
  178259. * candidate colormap entries is returned, and their colormap indexes are
  178260. * placed in colorlist[].
  178261. * This routine uses Heckbert's "locally sorted search" criterion to select
  178262. * the colors that need further consideration.
  178263. */
  178264. {
  178265. int numcolors = cinfo->actual_number_of_colors;
  178266. int maxc0, maxc1, maxc2;
  178267. int centerc0, centerc1, centerc2;
  178268. int i, x, ncolors;
  178269. INT32 minmaxdist, min_dist, max_dist, tdist;
  178270. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178271. /* Compute true coordinates of update box's upper corner and center.
  178272. * Actually we compute the coordinates of the center of the upper-corner
  178273. * histogram cell, which are the upper bounds of the volume we care about.
  178274. * Note that since ">>" rounds down, the "center" values may be closer to
  178275. * min than to max; hence comparisons to them must be "<=", not "<".
  178276. */
  178277. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178278. centerc0 = (minc0 + maxc0) >> 1;
  178279. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178280. centerc1 = (minc1 + maxc1) >> 1;
  178281. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178282. centerc2 = (minc2 + maxc2) >> 1;
  178283. /* For each color in colormap, find:
  178284. * 1. its minimum squared-distance to any point in the update box
  178285. * (zero if color is within update box);
  178286. * 2. its maximum squared-distance to any point in the update box.
  178287. * Both of these can be found by considering only the corners of the box.
  178288. * We save the minimum distance for each color in mindist[];
  178289. * only the smallest maximum distance is of interest.
  178290. */
  178291. minmaxdist = 0x7FFFFFFFL;
  178292. for (i = 0; i < numcolors; i++) {
  178293. /* We compute the squared-c0-distance term, then add in the other two. */
  178294. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178295. if (x < minc0) {
  178296. tdist = (x - minc0) * C0_SCALE;
  178297. min_dist = tdist*tdist;
  178298. tdist = (x - maxc0) * C0_SCALE;
  178299. max_dist = tdist*tdist;
  178300. } else if (x > maxc0) {
  178301. tdist = (x - maxc0) * C0_SCALE;
  178302. min_dist = tdist*tdist;
  178303. tdist = (x - minc0) * C0_SCALE;
  178304. max_dist = tdist*tdist;
  178305. } else {
  178306. /* within cell range so no contribution to min_dist */
  178307. min_dist = 0;
  178308. if (x <= centerc0) {
  178309. tdist = (x - maxc0) * C0_SCALE;
  178310. max_dist = tdist*tdist;
  178311. } else {
  178312. tdist = (x - minc0) * C0_SCALE;
  178313. max_dist = tdist*tdist;
  178314. }
  178315. }
  178316. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178317. if (x < minc1) {
  178318. tdist = (x - minc1) * C1_SCALE;
  178319. min_dist += tdist*tdist;
  178320. tdist = (x - maxc1) * C1_SCALE;
  178321. max_dist += tdist*tdist;
  178322. } else if (x > maxc1) {
  178323. tdist = (x - maxc1) * C1_SCALE;
  178324. min_dist += tdist*tdist;
  178325. tdist = (x - minc1) * C1_SCALE;
  178326. max_dist += tdist*tdist;
  178327. } else {
  178328. /* within cell range so no contribution to min_dist */
  178329. if (x <= centerc1) {
  178330. tdist = (x - maxc1) * C1_SCALE;
  178331. max_dist += tdist*tdist;
  178332. } else {
  178333. tdist = (x - minc1) * C1_SCALE;
  178334. max_dist += tdist*tdist;
  178335. }
  178336. }
  178337. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178338. if (x < minc2) {
  178339. tdist = (x - minc2) * C2_SCALE;
  178340. min_dist += tdist*tdist;
  178341. tdist = (x - maxc2) * C2_SCALE;
  178342. max_dist += tdist*tdist;
  178343. } else if (x > maxc2) {
  178344. tdist = (x - maxc2) * C2_SCALE;
  178345. min_dist += tdist*tdist;
  178346. tdist = (x - minc2) * C2_SCALE;
  178347. max_dist += tdist*tdist;
  178348. } else {
  178349. /* within cell range so no contribution to min_dist */
  178350. if (x <= centerc2) {
  178351. tdist = (x - maxc2) * C2_SCALE;
  178352. max_dist += tdist*tdist;
  178353. } else {
  178354. tdist = (x - minc2) * C2_SCALE;
  178355. max_dist += tdist*tdist;
  178356. }
  178357. }
  178358. mindist[i] = min_dist; /* save away the results */
  178359. if (max_dist < minmaxdist)
  178360. minmaxdist = max_dist;
  178361. }
  178362. /* Now we know that no cell in the update box is more than minmaxdist
  178363. * away from some colormap entry. Therefore, only colors that are
  178364. * within minmaxdist of some part of the box need be considered.
  178365. */
  178366. ncolors = 0;
  178367. for (i = 0; i < numcolors; i++) {
  178368. if (mindist[i] <= minmaxdist)
  178369. colorlist[ncolors++] = (JSAMPLE) i;
  178370. }
  178371. return ncolors;
  178372. }
  178373. LOCAL(void)
  178374. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178375. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178376. /* Find the closest colormap entry for each cell in the update box,
  178377. * given the list of candidate colors prepared by find_nearby_colors.
  178378. * Return the indexes of the closest entries in the bestcolor[] array.
  178379. * This routine uses Thomas' incremental distance calculation method to
  178380. * find the distance from a colormap entry to successive cells in the box.
  178381. */
  178382. {
  178383. int ic0, ic1, ic2;
  178384. int i, icolor;
  178385. register INT32 * bptr; /* pointer into bestdist[] array */
  178386. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178387. INT32 dist0, dist1; /* initial distance values */
  178388. register INT32 dist2; /* current distance in inner loop */
  178389. INT32 xx0, xx1; /* distance increments */
  178390. register INT32 xx2;
  178391. INT32 inc0, inc1, inc2; /* initial values for increments */
  178392. /* This array holds the distance to the nearest-so-far color for each cell */
  178393. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178394. /* Initialize best-distance for each cell of the update box */
  178395. bptr = bestdist;
  178396. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178397. *bptr++ = 0x7FFFFFFFL;
  178398. /* For each color selected by find_nearby_colors,
  178399. * compute its distance to the center of each cell in the box.
  178400. * If that's less than best-so-far, update best distance and color number.
  178401. */
  178402. /* Nominal steps between cell centers ("x" in Thomas article) */
  178403. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178404. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178405. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178406. for (i = 0; i < numcolors; i++) {
  178407. icolor = GETJSAMPLE(colorlist[i]);
  178408. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178409. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178410. dist0 = inc0*inc0;
  178411. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178412. dist0 += inc1*inc1;
  178413. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178414. dist0 += inc2*inc2;
  178415. /* Form the initial difference increments */
  178416. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178417. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178418. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178419. /* Now loop over all cells in box, updating distance per Thomas method */
  178420. bptr = bestdist;
  178421. cptr = bestcolor;
  178422. xx0 = inc0;
  178423. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178424. dist1 = dist0;
  178425. xx1 = inc1;
  178426. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178427. dist2 = dist1;
  178428. xx2 = inc2;
  178429. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178430. if (dist2 < *bptr) {
  178431. *bptr = dist2;
  178432. *cptr = (JSAMPLE) icolor;
  178433. }
  178434. dist2 += xx2;
  178435. xx2 += 2 * STEP_C2 * STEP_C2;
  178436. bptr++;
  178437. cptr++;
  178438. }
  178439. dist1 += xx1;
  178440. xx1 += 2 * STEP_C1 * STEP_C1;
  178441. }
  178442. dist0 += xx0;
  178443. xx0 += 2 * STEP_C0 * STEP_C0;
  178444. }
  178445. }
  178446. }
  178447. LOCAL(void)
  178448. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178449. /* Fill the inverse-colormap entries in the update box that contains */
  178450. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178451. /* we can fill as many others as we wish.) */
  178452. {
  178453. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178454. hist3d histogram = cquantize->histogram;
  178455. int minc0, minc1, minc2; /* lower left corner of update box */
  178456. int ic0, ic1, ic2;
  178457. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178458. register histptr cachep; /* pointer into main cache array */
  178459. /* This array lists the candidate colormap indexes. */
  178460. JSAMPLE colorlist[MAXNUMCOLORS];
  178461. int numcolors; /* number of candidate colors */
  178462. /* This array holds the actually closest colormap index for each cell. */
  178463. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178464. /* Convert cell coordinates to update box ID */
  178465. c0 >>= BOX_C0_LOG;
  178466. c1 >>= BOX_C1_LOG;
  178467. c2 >>= BOX_C2_LOG;
  178468. /* Compute true coordinates of update box's origin corner.
  178469. * Actually we compute the coordinates of the center of the corner
  178470. * histogram cell, which are the lower bounds of the volume we care about.
  178471. */
  178472. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178473. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178474. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178475. /* Determine which colormap entries are close enough to be candidates
  178476. * for the nearest entry to some cell in the update box.
  178477. */
  178478. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178479. /* Determine the actually nearest colors. */
  178480. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178481. bestcolor);
  178482. /* Save the best color numbers (plus 1) in the main cache array */
  178483. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178484. c1 <<= BOX_C1_LOG;
  178485. c2 <<= BOX_C2_LOG;
  178486. cptr = bestcolor;
  178487. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178488. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178489. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178490. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178491. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178492. }
  178493. }
  178494. }
  178495. }
  178496. /*
  178497. * Map some rows of pixels to the output colormapped representation.
  178498. */
  178499. METHODDEF(void)
  178500. pass2_no_dither (j_decompress_ptr cinfo,
  178501. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178502. /* This version performs no dithering */
  178503. {
  178504. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178505. hist3d histogram = cquantize->histogram;
  178506. register JSAMPROW inptr, outptr;
  178507. register histptr cachep;
  178508. register int c0, c1, c2;
  178509. int row;
  178510. JDIMENSION col;
  178511. JDIMENSION width = cinfo->output_width;
  178512. for (row = 0; row < num_rows; row++) {
  178513. inptr = input_buf[row];
  178514. outptr = output_buf[row];
  178515. for (col = width; col > 0; col--) {
  178516. /* get pixel value and index into the cache */
  178517. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178518. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178519. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178520. cachep = & histogram[c0][c1][c2];
  178521. /* If we have not seen this color before, find nearest colormap entry */
  178522. /* and update the cache */
  178523. if (*cachep == 0)
  178524. fill_inverse_cmap(cinfo, c0,c1,c2);
  178525. /* Now emit the colormap index for this cell */
  178526. *outptr++ = (JSAMPLE) (*cachep - 1);
  178527. }
  178528. }
  178529. }
  178530. METHODDEF(void)
  178531. pass2_fs_dither (j_decompress_ptr cinfo,
  178532. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178533. /* This version performs Floyd-Steinberg dithering */
  178534. {
  178535. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178536. hist3d histogram = cquantize->histogram;
  178537. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178538. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178539. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178540. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178541. JSAMPROW inptr; /* => current input pixel */
  178542. JSAMPROW outptr; /* => current output pixel */
  178543. histptr cachep;
  178544. int dir; /* +1 or -1 depending on direction */
  178545. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178546. int row;
  178547. JDIMENSION col;
  178548. JDIMENSION width = cinfo->output_width;
  178549. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178550. int *error_limit = cquantize->error_limiter;
  178551. JSAMPROW colormap0 = cinfo->colormap[0];
  178552. JSAMPROW colormap1 = cinfo->colormap[1];
  178553. JSAMPROW colormap2 = cinfo->colormap[2];
  178554. SHIFT_TEMPS
  178555. for (row = 0; row < num_rows; row++) {
  178556. inptr = input_buf[row];
  178557. outptr = output_buf[row];
  178558. if (cquantize->on_odd_row) {
  178559. /* work right to left in this row */
  178560. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178561. outptr += width-1;
  178562. dir = -1;
  178563. dir3 = -3;
  178564. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178565. cquantize->on_odd_row = FALSE; /* flip for next time */
  178566. } else {
  178567. /* work left to right in this row */
  178568. dir = 1;
  178569. dir3 = 3;
  178570. errorptr = cquantize->fserrors; /* => entry before first real column */
  178571. cquantize->on_odd_row = TRUE; /* flip for next time */
  178572. }
  178573. /* Preset error values: no error propagated to first pixel from left */
  178574. cur0 = cur1 = cur2 = 0;
  178575. /* and no error propagated to row below yet */
  178576. belowerr0 = belowerr1 = belowerr2 = 0;
  178577. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178578. for (col = width; col > 0; col--) {
  178579. /* curN holds the error propagated from the previous pixel on the
  178580. * current line. Add the error propagated from the previous line
  178581. * to form the complete error correction term for this pixel, and
  178582. * round the error term (which is expressed * 16) to an integer.
  178583. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178584. * for either sign of the error value.
  178585. * Note: errorptr points to *previous* column's array entry.
  178586. */
  178587. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178588. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178589. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178590. /* Limit the error using transfer function set by init_error_limit.
  178591. * See comments with init_error_limit for rationale.
  178592. */
  178593. cur0 = error_limit[cur0];
  178594. cur1 = error_limit[cur1];
  178595. cur2 = error_limit[cur2];
  178596. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178597. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178598. * this sets the required size of the range_limit array.
  178599. */
  178600. cur0 += GETJSAMPLE(inptr[0]);
  178601. cur1 += GETJSAMPLE(inptr[1]);
  178602. cur2 += GETJSAMPLE(inptr[2]);
  178603. cur0 = GETJSAMPLE(range_limit[cur0]);
  178604. cur1 = GETJSAMPLE(range_limit[cur1]);
  178605. cur2 = GETJSAMPLE(range_limit[cur2]);
  178606. /* Index into the cache with adjusted pixel value */
  178607. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178608. /* If we have not seen this color before, find nearest colormap */
  178609. /* entry and update the cache */
  178610. if (*cachep == 0)
  178611. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178612. /* Now emit the colormap index for this cell */
  178613. { register int pixcode = *cachep - 1;
  178614. *outptr = (JSAMPLE) pixcode;
  178615. /* Compute representation error for this pixel */
  178616. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178617. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178618. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178619. }
  178620. /* Compute error fractions to be propagated to adjacent pixels.
  178621. * Add these into the running sums, and simultaneously shift the
  178622. * next-line error sums left by 1 column.
  178623. */
  178624. { register LOCFSERROR bnexterr, delta;
  178625. bnexterr = cur0; /* Process component 0 */
  178626. delta = cur0 * 2;
  178627. cur0 += delta; /* form error * 3 */
  178628. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178629. cur0 += delta; /* form error * 5 */
  178630. bpreverr0 = belowerr0 + cur0;
  178631. belowerr0 = bnexterr;
  178632. cur0 += delta; /* form error * 7 */
  178633. bnexterr = cur1; /* Process component 1 */
  178634. delta = cur1 * 2;
  178635. cur1 += delta; /* form error * 3 */
  178636. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178637. cur1 += delta; /* form error * 5 */
  178638. bpreverr1 = belowerr1 + cur1;
  178639. belowerr1 = bnexterr;
  178640. cur1 += delta; /* form error * 7 */
  178641. bnexterr = cur2; /* Process component 2 */
  178642. delta = cur2 * 2;
  178643. cur2 += delta; /* form error * 3 */
  178644. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178645. cur2 += delta; /* form error * 5 */
  178646. bpreverr2 = belowerr2 + cur2;
  178647. belowerr2 = bnexterr;
  178648. cur2 += delta; /* form error * 7 */
  178649. }
  178650. /* At this point curN contains the 7/16 error value to be propagated
  178651. * to the next pixel on the current line, and all the errors for the
  178652. * next line have been shifted over. We are therefore ready to move on.
  178653. */
  178654. inptr += dir3; /* Advance pixel pointers to next column */
  178655. outptr += dir;
  178656. errorptr += dir3; /* advance errorptr to current column */
  178657. }
  178658. /* Post-loop cleanup: we must unload the final error values into the
  178659. * final fserrors[] entry. Note we need not unload belowerrN because
  178660. * it is for the dummy column before or after the actual array.
  178661. */
  178662. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178663. errorptr[1] = (FSERROR) bpreverr1;
  178664. errorptr[2] = (FSERROR) bpreverr2;
  178665. }
  178666. }
  178667. /*
  178668. * Initialize the error-limiting transfer function (lookup table).
  178669. * The raw F-S error computation can potentially compute error values of up to
  178670. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178671. * much less, otherwise obviously wrong pixels will be created. (Typical
  178672. * effects include weird fringes at color-area boundaries, isolated bright
  178673. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178674. * is to ensure that the "corners" of the color cube are allocated as output
  178675. * colors; then repeated errors in the same direction cannot cause cascading
  178676. * error buildup. However, that only prevents the error from getting
  178677. * completely out of hand; Aaron Giles reports that error limiting improves
  178678. * the results even with corner colors allocated.
  178679. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178680. * well, but the smoother transfer function used below is even better. Thanks
  178681. * to Aaron Giles for this idea.
  178682. */
  178683. LOCAL(void)
  178684. init_error_limit (j_decompress_ptr cinfo)
  178685. /* Allocate and fill in the error_limiter table */
  178686. {
  178687. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178688. int * table;
  178689. int in, out;
  178690. table = (int *) (*cinfo->mem->alloc_small)
  178691. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178692. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178693. cquantize->error_limiter = table;
  178694. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178695. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178696. out = 0;
  178697. for (in = 0; in < STEPSIZE; in++, out++) {
  178698. table[in] = out; table[-in] = -out;
  178699. }
  178700. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178701. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178702. table[in] = out; table[-in] = -out;
  178703. }
  178704. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178705. for (; in <= MAXJSAMPLE; in++) {
  178706. table[in] = out; table[-in] = -out;
  178707. }
  178708. #undef STEPSIZE
  178709. }
  178710. /*
  178711. * Finish up at the end of each pass.
  178712. */
  178713. METHODDEF(void)
  178714. finish_pass1 (j_decompress_ptr cinfo)
  178715. {
  178716. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178717. /* Select the representative colors and fill in cinfo->colormap */
  178718. cinfo->colormap = cquantize->sv_colormap;
  178719. select_colors(cinfo, cquantize->desired);
  178720. /* Force next pass to zero the color index table */
  178721. cquantize->needs_zeroed = TRUE;
  178722. }
  178723. METHODDEF(void)
  178724. finish_pass2 (j_decompress_ptr)
  178725. {
  178726. /* no work */
  178727. }
  178728. /*
  178729. * Initialize for each processing pass.
  178730. */
  178731. METHODDEF(void)
  178732. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178733. {
  178734. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178735. hist3d histogram = cquantize->histogram;
  178736. int i;
  178737. /* Only F-S dithering or no dithering is supported. */
  178738. /* If user asks for ordered dither, give him F-S. */
  178739. if (cinfo->dither_mode != JDITHER_NONE)
  178740. cinfo->dither_mode = JDITHER_FS;
  178741. if (is_pre_scan) {
  178742. /* Set up method pointers */
  178743. cquantize->pub.color_quantize = prescan_quantize;
  178744. cquantize->pub.finish_pass = finish_pass1;
  178745. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178746. } else {
  178747. /* Set up method pointers */
  178748. if (cinfo->dither_mode == JDITHER_FS)
  178749. cquantize->pub.color_quantize = pass2_fs_dither;
  178750. else
  178751. cquantize->pub.color_quantize = pass2_no_dither;
  178752. cquantize->pub.finish_pass = finish_pass2;
  178753. /* Make sure color count is acceptable */
  178754. i = cinfo->actual_number_of_colors;
  178755. if (i < 1)
  178756. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178757. if (i > MAXNUMCOLORS)
  178758. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178759. if (cinfo->dither_mode == JDITHER_FS) {
  178760. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178761. (3 * SIZEOF(FSERROR)));
  178762. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178763. if (cquantize->fserrors == NULL)
  178764. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178765. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178766. /* Initialize the propagated errors to zero. */
  178767. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178768. /* Make the error-limit table if we didn't already. */
  178769. if (cquantize->error_limiter == NULL)
  178770. init_error_limit(cinfo);
  178771. cquantize->on_odd_row = FALSE;
  178772. }
  178773. }
  178774. /* Zero the histogram or inverse color map, if necessary */
  178775. if (cquantize->needs_zeroed) {
  178776. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178777. jzero_far((void FAR *) histogram[i],
  178778. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178779. }
  178780. cquantize->needs_zeroed = FALSE;
  178781. }
  178782. }
  178783. /*
  178784. * Switch to a new external colormap between output passes.
  178785. */
  178786. METHODDEF(void)
  178787. new_color_map_2_quant (j_decompress_ptr cinfo)
  178788. {
  178789. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178790. /* Reset the inverse color map */
  178791. cquantize->needs_zeroed = TRUE;
  178792. }
  178793. /*
  178794. * Module initialization routine for 2-pass color quantization.
  178795. */
  178796. GLOBAL(void)
  178797. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178798. {
  178799. my_cquantize_ptr2 cquantize;
  178800. int i;
  178801. cquantize = (my_cquantize_ptr2)
  178802. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178803. SIZEOF(my_cquantizer2));
  178804. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178805. cquantize->pub.start_pass = start_pass_2_quant;
  178806. cquantize->pub.new_color_map = new_color_map_2_quant;
  178807. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178808. cquantize->error_limiter = NULL;
  178809. /* Make sure jdmaster didn't give me a case I can't handle */
  178810. if (cinfo->out_color_components != 3)
  178811. ERREXIT(cinfo, JERR_NOTIMPL);
  178812. /* Allocate the histogram/inverse colormap storage */
  178813. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178814. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178815. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178816. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178817. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178818. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178819. }
  178820. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178821. /* Allocate storage for the completed colormap, if required.
  178822. * We do this now since it is FAR storage and may affect
  178823. * the memory manager's space calculations.
  178824. */
  178825. if (cinfo->enable_2pass_quant) {
  178826. /* Make sure color count is acceptable */
  178827. int desired = cinfo->desired_number_of_colors;
  178828. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178829. if (desired < 8)
  178830. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178831. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178832. if (desired > MAXNUMCOLORS)
  178833. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178834. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178835. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178836. cquantize->desired = desired;
  178837. } else
  178838. cquantize->sv_colormap = NULL;
  178839. /* Only F-S dithering or no dithering is supported. */
  178840. /* If user asks for ordered dither, give him F-S. */
  178841. if (cinfo->dither_mode != JDITHER_NONE)
  178842. cinfo->dither_mode = JDITHER_FS;
  178843. /* Allocate Floyd-Steinberg workspace if necessary.
  178844. * This isn't really needed until pass 2, but again it is FAR storage.
  178845. * Although we will cope with a later change in dither_mode,
  178846. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178847. */
  178848. if (cinfo->dither_mode == JDITHER_FS) {
  178849. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178850. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178851. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178852. /* Might as well create the error-limiting table too. */
  178853. init_error_limit(cinfo);
  178854. }
  178855. }
  178856. #endif /* QUANT_2PASS_SUPPORTED */
  178857. /*** End of inlined file: jquant2.c ***/
  178858. /*** Start of inlined file: jutils.c ***/
  178859. #define JPEG_INTERNALS
  178860. /*
  178861. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178862. * of a DCT block read in natural order (left to right, top to bottom).
  178863. */
  178864. #if 0 /* This table is not actually needed in v6a */
  178865. const int jpeg_zigzag_order[DCTSIZE2] = {
  178866. 0, 1, 5, 6, 14, 15, 27, 28,
  178867. 2, 4, 7, 13, 16, 26, 29, 42,
  178868. 3, 8, 12, 17, 25, 30, 41, 43,
  178869. 9, 11, 18, 24, 31, 40, 44, 53,
  178870. 10, 19, 23, 32, 39, 45, 52, 54,
  178871. 20, 22, 33, 38, 46, 51, 55, 60,
  178872. 21, 34, 37, 47, 50, 56, 59, 61,
  178873. 35, 36, 48, 49, 57, 58, 62, 63
  178874. };
  178875. #endif
  178876. /*
  178877. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178878. * of zigzag order.
  178879. *
  178880. * When reading corrupted data, the Huffman decoders could attempt
  178881. * to reference an entry beyond the end of this array (if the decoded
  178882. * zero run length reaches past the end of the block). To prevent
  178883. * wild stores without adding an inner-loop test, we put some extra
  178884. * "63"s after the real entries. This will cause the extra coefficient
  178885. * to be stored in location 63 of the block, not somewhere random.
  178886. * The worst case would be a run-length of 15, which means we need 16
  178887. * fake entries.
  178888. */
  178889. const int jpeg_natural_order[DCTSIZE2+16] = {
  178890. 0, 1, 8, 16, 9, 2, 3, 10,
  178891. 17, 24, 32, 25, 18, 11, 4, 5,
  178892. 12, 19, 26, 33, 40, 48, 41, 34,
  178893. 27, 20, 13, 6, 7, 14, 21, 28,
  178894. 35, 42, 49, 56, 57, 50, 43, 36,
  178895. 29, 22, 15, 23, 30, 37, 44, 51,
  178896. 58, 59, 52, 45, 38, 31, 39, 46,
  178897. 53, 60, 61, 54, 47, 55, 62, 63,
  178898. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178899. 63, 63, 63, 63, 63, 63, 63, 63
  178900. };
  178901. /*
  178902. * Arithmetic utilities
  178903. */
  178904. GLOBAL(long)
  178905. jdiv_round_up (long a, long b)
  178906. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178907. /* Assumes a >= 0, b > 0 */
  178908. {
  178909. return (a + b - 1L) / b;
  178910. }
  178911. GLOBAL(long)
  178912. jround_up (long a, long b)
  178913. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178914. /* Assumes a >= 0, b > 0 */
  178915. {
  178916. a += b - 1L;
  178917. return a - (a % b);
  178918. }
  178919. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178920. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178921. * are FAR and we're assuming a small-pointer memory model. However, some
  178922. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178923. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178924. * Otherwise, the routines below do it the hard way. (The performance cost
  178925. * is not all that great, because these routines aren't very heavily used.)
  178926. */
  178927. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178928. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178929. #define FMEMZERO(target,size) MEMZERO(target,size)
  178930. #else /* 80x86 case, define if we can */
  178931. #ifdef USE_FMEM
  178932. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178933. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178934. #endif
  178935. #endif
  178936. GLOBAL(void)
  178937. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178938. JSAMPARRAY output_array, int dest_row,
  178939. int num_rows, JDIMENSION num_cols)
  178940. /* Copy some rows of samples from one place to another.
  178941. * num_rows rows are copied from input_array[source_row++]
  178942. * to output_array[dest_row++]; these areas may overlap for duplication.
  178943. * The source and destination arrays must be at least as wide as num_cols.
  178944. */
  178945. {
  178946. register JSAMPROW inptr, outptr;
  178947. #ifdef FMEMCOPY
  178948. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178949. #else
  178950. register JDIMENSION count;
  178951. #endif
  178952. register int row;
  178953. input_array += source_row;
  178954. output_array += dest_row;
  178955. for (row = num_rows; row > 0; row--) {
  178956. inptr = *input_array++;
  178957. outptr = *output_array++;
  178958. #ifdef FMEMCOPY
  178959. FMEMCOPY(outptr, inptr, count);
  178960. #else
  178961. for (count = num_cols; count > 0; count--)
  178962. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178963. #endif
  178964. }
  178965. }
  178966. GLOBAL(void)
  178967. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178968. JDIMENSION num_blocks)
  178969. /* Copy a row of coefficient blocks from one place to another. */
  178970. {
  178971. #ifdef FMEMCOPY
  178972. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178973. #else
  178974. register JCOEFPTR inptr, outptr;
  178975. register long count;
  178976. inptr = (JCOEFPTR) input_row;
  178977. outptr = (JCOEFPTR) output_row;
  178978. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178979. *outptr++ = *inptr++;
  178980. }
  178981. #endif
  178982. }
  178983. GLOBAL(void)
  178984. jzero_far (void FAR * target, size_t bytestozero)
  178985. /* Zero out a chunk of FAR memory. */
  178986. /* This might be sample-array data, block-array data, or alloc_large data. */
  178987. {
  178988. #ifdef FMEMZERO
  178989. FMEMZERO(target, bytestozero);
  178990. #else
  178991. register char FAR * ptr = (char FAR *) target;
  178992. register size_t count;
  178993. for (count = bytestozero; count > 0; count--) {
  178994. *ptr++ = 0;
  178995. }
  178996. #endif
  178997. }
  178998. /*** End of inlined file: jutils.c ***/
  178999. /*** Start of inlined file: transupp.c ***/
  179000. /* Although this file really shouldn't have access to the library internals,
  179001. * it's helpful to let it call jround_up() and jcopy_block_row().
  179002. */
  179003. #define JPEG_INTERNALS
  179004. /*** Start of inlined file: transupp.h ***/
  179005. /* If you happen not to want the image transform support, disable it here */
  179006. #ifndef TRANSFORMS_SUPPORTED
  179007. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  179008. #endif
  179009. /* Short forms of external names for systems with brain-damaged linkers. */
  179010. #ifdef NEED_SHORT_EXTERNAL_NAMES
  179011. #define jtransform_request_workspace jTrRequest
  179012. #define jtransform_adjust_parameters jTrAdjust
  179013. #define jtransform_execute_transformation jTrExec
  179014. #define jcopy_markers_setup jCMrkSetup
  179015. #define jcopy_markers_execute jCMrkExec
  179016. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  179017. /*
  179018. * Codes for supported types of image transformations.
  179019. */
  179020. typedef enum {
  179021. JXFORM_NONE, /* no transformation */
  179022. JXFORM_FLIP_H, /* horizontal flip */
  179023. JXFORM_FLIP_V, /* vertical flip */
  179024. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  179025. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  179026. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  179027. JXFORM_ROT_180, /* 180-degree rotation */
  179028. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  179029. } JXFORM_CODE;
  179030. /*
  179031. * Although rotating and flipping data expressed as DCT coefficients is not
  179032. * hard, there is an asymmetry in the JPEG format specification for images
  179033. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  179034. * image edges are padded out to the next iMCU boundary with junk data; but
  179035. * no padding is possible at the top and left edges. If we were to flip
  179036. * the whole image including the pad data, then pad garbage would become
  179037. * visible at the top and/or left, and real pixels would disappear into the
  179038. * pad margins --- perhaps permanently, since encoders & decoders may not
  179039. * bother to preserve DCT blocks that appear to be completely outside the
  179040. * nominal image area. So, we have to exclude any partial iMCUs from the
  179041. * basic transformation.
  179042. *
  179043. * Transpose is the only transformation that can handle partial iMCUs at the
  179044. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  179045. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  179046. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  179047. * The other transforms are defined as combinations of these basic transforms
  179048. * and process edge blocks in a way that preserves the equivalence.
  179049. *
  179050. * The "trim" option causes untransformable partial iMCUs to be dropped;
  179051. * this is not strictly lossless, but it usually gives the best-looking
  179052. * result for odd-size images. Note that when this option is active,
  179053. * the expected mathematical equivalences between the transforms may not hold.
  179054. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  179055. * followed by -rot 180 -trim trims both edges.)
  179056. *
  179057. * We also offer a "force to grayscale" option, which simply discards the
  179058. * chrominance channels of a YCbCr image. This is lossless in the sense that
  179059. * the luminance channel is preserved exactly. It's not the same kind of
  179060. * thing as the rotate/flip transformations, but it's convenient to handle it
  179061. * as part of this package, mainly because the transformation routines have to
  179062. * be aware of the option to know how many components to work on.
  179063. */
  179064. typedef struct {
  179065. /* Options: set by caller */
  179066. JXFORM_CODE transform; /* image transform operator */
  179067. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179068. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179069. /* Internal workspace: caller should not touch these */
  179070. int num_components; /* # of components in workspace */
  179071. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179072. } jpeg_transform_info;
  179073. #if TRANSFORMS_SUPPORTED
  179074. /* Request any required workspace */
  179075. EXTERN(void) jtransform_request_workspace
  179076. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179077. /* Adjust output image parameters */
  179078. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179079. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179080. jvirt_barray_ptr *src_coef_arrays,
  179081. jpeg_transform_info *info));
  179082. /* Execute the actual transformation, if any */
  179083. EXTERN(void) jtransform_execute_transformation
  179084. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179085. jvirt_barray_ptr *src_coef_arrays,
  179086. jpeg_transform_info *info));
  179087. #endif /* TRANSFORMS_SUPPORTED */
  179088. /*
  179089. * Support for copying optional markers from source to destination file.
  179090. */
  179091. typedef enum {
  179092. JCOPYOPT_NONE, /* copy no optional markers */
  179093. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179094. JCOPYOPT_ALL /* copy all optional markers */
  179095. } JCOPY_OPTION;
  179096. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179097. /* Setup decompression object to save desired markers in memory */
  179098. EXTERN(void) jcopy_markers_setup
  179099. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179100. /* Copy markers saved in the given source object to the destination object */
  179101. EXTERN(void) jcopy_markers_execute
  179102. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179103. JCOPY_OPTION option));
  179104. /*** End of inlined file: transupp.h ***/
  179105. /* My own external interface */
  179106. #if TRANSFORMS_SUPPORTED
  179107. /*
  179108. * Lossless image transformation routines. These routines work on DCT
  179109. * coefficient arrays and thus do not require any lossy decompression
  179110. * or recompression of the image.
  179111. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179112. *
  179113. * Horizontal flipping is done in-place, using a single top-to-bottom
  179114. * pass through the virtual source array. It will thus be much the
  179115. * fastest option for images larger than main memory.
  179116. *
  179117. * The other routines require a set of destination virtual arrays, so they
  179118. * need twice as much memory as jpegtran normally does. The destination
  179119. * arrays are always written in normal scan order (top to bottom) because
  179120. * the virtual array manager expects this. The source arrays will be scanned
  179121. * in the corresponding order, which means multiple passes through the source
  179122. * arrays for most of the transforms. That could result in much thrashing
  179123. * if the image is larger than main memory.
  179124. *
  179125. * Some notes about the operating environment of the individual transform
  179126. * routines:
  179127. * 1. Both the source and destination virtual arrays are allocated from the
  179128. * source JPEG object, and therefore should be manipulated by calling the
  179129. * source's memory manager.
  179130. * 2. The destination's component count should be used. It may be smaller
  179131. * than the source's when forcing to grayscale.
  179132. * 3. Likewise the destination's sampling factors should be used. When
  179133. * forcing to grayscale the destination's sampling factors will be all 1,
  179134. * and we may as well take that as the effective iMCU size.
  179135. * 4. When "trim" is in effect, the destination's dimensions will be the
  179136. * trimmed values but the source's will be untrimmed.
  179137. * 5. All the routines assume that the source and destination buffers are
  179138. * padded out to a full iMCU boundary. This is true, although for the
  179139. * source buffer it is an undocumented property of jdcoefct.c.
  179140. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179141. * dimensions and ignore the source's.
  179142. */
  179143. LOCAL(void)
  179144. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179145. jvirt_barray_ptr *src_coef_arrays)
  179146. /* Horizontal flip; done in-place, so no separate dest array is required */
  179147. {
  179148. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179149. int ci, k, offset_y;
  179150. JBLOCKARRAY buffer;
  179151. JCOEFPTR ptr1, ptr2;
  179152. JCOEF temp1, temp2;
  179153. jpeg_component_info *compptr;
  179154. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179155. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179156. * mirroring by changing the signs of odd-numbered columns.
  179157. * Partial iMCUs at the right edge are left untouched.
  179158. */
  179159. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179160. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179161. compptr = dstinfo->comp_info + ci;
  179162. comp_width = MCU_cols * compptr->h_samp_factor;
  179163. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179164. blk_y += compptr->v_samp_factor) {
  179165. buffer = (*srcinfo->mem->access_virt_barray)
  179166. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179167. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179168. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179169. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179170. ptr1 = buffer[offset_y][blk_x];
  179171. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179172. /* this unrolled loop doesn't need to know which row it's on... */
  179173. for (k = 0; k < DCTSIZE2; k += 2) {
  179174. temp1 = *ptr1; /* swap even column */
  179175. temp2 = *ptr2;
  179176. *ptr1++ = temp2;
  179177. *ptr2++ = temp1;
  179178. temp1 = *ptr1; /* swap odd column with sign change */
  179179. temp2 = *ptr2;
  179180. *ptr1++ = -temp2;
  179181. *ptr2++ = -temp1;
  179182. }
  179183. }
  179184. }
  179185. }
  179186. }
  179187. }
  179188. LOCAL(void)
  179189. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179190. jvirt_barray_ptr *src_coef_arrays,
  179191. jvirt_barray_ptr *dst_coef_arrays)
  179192. /* Vertical flip */
  179193. {
  179194. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179195. int ci, i, j, offset_y;
  179196. JBLOCKARRAY src_buffer, dst_buffer;
  179197. JBLOCKROW src_row_ptr, dst_row_ptr;
  179198. JCOEFPTR src_ptr, dst_ptr;
  179199. jpeg_component_info *compptr;
  179200. /* We output into a separate array because we can't touch different
  179201. * rows of the source virtual array simultaneously. Otherwise, this
  179202. * is a pretty straightforward analog of horizontal flip.
  179203. * Within a DCT block, vertical mirroring is done by changing the signs
  179204. * of odd-numbered rows.
  179205. * Partial iMCUs at the bottom edge are copied verbatim.
  179206. */
  179207. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179208. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179209. compptr = dstinfo->comp_info + ci;
  179210. comp_height = MCU_rows * compptr->v_samp_factor;
  179211. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179212. dst_blk_y += compptr->v_samp_factor) {
  179213. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179214. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179215. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179216. if (dst_blk_y < comp_height) {
  179217. /* Row is within the mirrorable area. */
  179218. src_buffer = (*srcinfo->mem->access_virt_barray)
  179219. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179220. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179221. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179222. } else {
  179223. /* Bottom-edge blocks will be copied verbatim. */
  179224. src_buffer = (*srcinfo->mem->access_virt_barray)
  179225. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179226. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179227. }
  179228. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179229. if (dst_blk_y < comp_height) {
  179230. /* Row is within the mirrorable area. */
  179231. dst_row_ptr = dst_buffer[offset_y];
  179232. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179233. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179234. dst_blk_x++) {
  179235. dst_ptr = dst_row_ptr[dst_blk_x];
  179236. src_ptr = src_row_ptr[dst_blk_x];
  179237. for (i = 0; i < DCTSIZE; i += 2) {
  179238. /* copy even row */
  179239. for (j = 0; j < DCTSIZE; j++)
  179240. *dst_ptr++ = *src_ptr++;
  179241. /* copy odd row with sign change */
  179242. for (j = 0; j < DCTSIZE; j++)
  179243. *dst_ptr++ = - *src_ptr++;
  179244. }
  179245. }
  179246. } else {
  179247. /* Just copy row verbatim. */
  179248. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179249. compptr->width_in_blocks);
  179250. }
  179251. }
  179252. }
  179253. }
  179254. }
  179255. LOCAL(void)
  179256. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179257. jvirt_barray_ptr *src_coef_arrays,
  179258. jvirt_barray_ptr *dst_coef_arrays)
  179259. /* Transpose source into destination */
  179260. {
  179261. JDIMENSION dst_blk_x, dst_blk_y;
  179262. int ci, i, j, offset_x, offset_y;
  179263. JBLOCKARRAY src_buffer, dst_buffer;
  179264. JCOEFPTR src_ptr, dst_ptr;
  179265. jpeg_component_info *compptr;
  179266. /* Transposing pixels within a block just requires transposing the
  179267. * DCT coefficients.
  179268. * Partial iMCUs at the edges require no special treatment; we simply
  179269. * process all the available DCT blocks for every component.
  179270. */
  179271. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179272. compptr = dstinfo->comp_info + ci;
  179273. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179274. dst_blk_y += compptr->v_samp_factor) {
  179275. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179276. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179277. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179278. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179279. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179280. dst_blk_x += compptr->h_samp_factor) {
  179281. src_buffer = (*srcinfo->mem->access_virt_barray)
  179282. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179283. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179284. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179285. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179286. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179287. for (i = 0; i < DCTSIZE; i++)
  179288. for (j = 0; j < DCTSIZE; j++)
  179289. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179290. }
  179291. }
  179292. }
  179293. }
  179294. }
  179295. }
  179296. LOCAL(void)
  179297. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179298. jvirt_barray_ptr *src_coef_arrays,
  179299. jvirt_barray_ptr *dst_coef_arrays)
  179300. /* 90 degree rotation is equivalent to
  179301. * 1. Transposing the image;
  179302. * 2. Horizontal mirroring.
  179303. * These two steps are merged into a single processing routine.
  179304. */
  179305. {
  179306. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179307. int ci, i, j, offset_x, offset_y;
  179308. JBLOCKARRAY src_buffer, dst_buffer;
  179309. JCOEFPTR src_ptr, dst_ptr;
  179310. jpeg_component_info *compptr;
  179311. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179312. * at the (output) right edge properly. They just get transposed and
  179313. * not mirrored.
  179314. */
  179315. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179316. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179317. compptr = dstinfo->comp_info + ci;
  179318. comp_width = MCU_cols * compptr->h_samp_factor;
  179319. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179320. dst_blk_y += compptr->v_samp_factor) {
  179321. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179322. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179323. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179324. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179325. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179326. dst_blk_x += compptr->h_samp_factor) {
  179327. src_buffer = (*srcinfo->mem->access_virt_barray)
  179328. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179329. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179330. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179331. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179332. if (dst_blk_x < comp_width) {
  179333. /* Block is within the mirrorable area. */
  179334. dst_ptr = dst_buffer[offset_y]
  179335. [comp_width - dst_blk_x - offset_x - 1];
  179336. for (i = 0; i < DCTSIZE; i++) {
  179337. for (j = 0; j < DCTSIZE; j++)
  179338. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179339. i++;
  179340. for (j = 0; j < DCTSIZE; j++)
  179341. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179342. }
  179343. } else {
  179344. /* Edge blocks are transposed but not mirrored. */
  179345. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179346. for (i = 0; i < DCTSIZE; i++)
  179347. for (j = 0; j < DCTSIZE; j++)
  179348. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179349. }
  179350. }
  179351. }
  179352. }
  179353. }
  179354. }
  179355. }
  179356. LOCAL(void)
  179357. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179358. jvirt_barray_ptr *src_coef_arrays,
  179359. jvirt_barray_ptr *dst_coef_arrays)
  179360. /* 270 degree rotation is equivalent to
  179361. * 1. Horizontal mirroring;
  179362. * 2. Transposing the image.
  179363. * These two steps are merged into a single processing routine.
  179364. */
  179365. {
  179366. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179367. int ci, i, j, offset_x, offset_y;
  179368. JBLOCKARRAY src_buffer, dst_buffer;
  179369. JCOEFPTR src_ptr, dst_ptr;
  179370. jpeg_component_info *compptr;
  179371. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179372. * at the (output) bottom edge properly. They just get transposed and
  179373. * not mirrored.
  179374. */
  179375. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179376. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179377. compptr = dstinfo->comp_info + ci;
  179378. comp_height = MCU_rows * compptr->v_samp_factor;
  179379. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179380. dst_blk_y += compptr->v_samp_factor) {
  179381. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179382. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179383. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179384. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179385. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179386. dst_blk_x += compptr->h_samp_factor) {
  179387. src_buffer = (*srcinfo->mem->access_virt_barray)
  179388. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179389. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179390. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179391. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179392. if (dst_blk_y < comp_height) {
  179393. /* Block is within the mirrorable area. */
  179394. src_ptr = src_buffer[offset_x]
  179395. [comp_height - dst_blk_y - offset_y - 1];
  179396. for (i = 0; i < DCTSIZE; i++) {
  179397. for (j = 0; j < DCTSIZE; j++) {
  179398. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179399. j++;
  179400. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179401. }
  179402. }
  179403. } else {
  179404. /* Edge blocks are transposed but not mirrored. */
  179405. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179406. for (i = 0; i < DCTSIZE; i++)
  179407. for (j = 0; j < DCTSIZE; j++)
  179408. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179409. }
  179410. }
  179411. }
  179412. }
  179413. }
  179414. }
  179415. }
  179416. LOCAL(void)
  179417. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179418. jvirt_barray_ptr *src_coef_arrays,
  179419. jvirt_barray_ptr *dst_coef_arrays)
  179420. /* 180 degree rotation is equivalent to
  179421. * 1. Vertical mirroring;
  179422. * 2. Horizontal mirroring.
  179423. * These two steps are merged into a single processing routine.
  179424. */
  179425. {
  179426. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179427. int ci, i, j, offset_y;
  179428. JBLOCKARRAY src_buffer, dst_buffer;
  179429. JBLOCKROW src_row_ptr, dst_row_ptr;
  179430. JCOEFPTR src_ptr, dst_ptr;
  179431. jpeg_component_info *compptr;
  179432. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179433. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179434. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179435. compptr = dstinfo->comp_info + ci;
  179436. comp_width = MCU_cols * compptr->h_samp_factor;
  179437. comp_height = MCU_rows * compptr->v_samp_factor;
  179438. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179439. dst_blk_y += compptr->v_samp_factor) {
  179440. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179441. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179442. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179443. if (dst_blk_y < comp_height) {
  179444. /* Row is within the vertically mirrorable area. */
  179445. src_buffer = (*srcinfo->mem->access_virt_barray)
  179446. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179447. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179448. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179449. } else {
  179450. /* Bottom-edge rows are only mirrored horizontally. */
  179451. src_buffer = (*srcinfo->mem->access_virt_barray)
  179452. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179453. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179454. }
  179455. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179456. if (dst_blk_y < comp_height) {
  179457. /* Row is within the mirrorable area. */
  179458. dst_row_ptr = dst_buffer[offset_y];
  179459. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179460. /* Process the blocks that can be mirrored both ways. */
  179461. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179462. dst_ptr = dst_row_ptr[dst_blk_x];
  179463. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179464. for (i = 0; i < DCTSIZE; i += 2) {
  179465. /* For even row, negate every odd column. */
  179466. for (j = 0; j < DCTSIZE; j += 2) {
  179467. *dst_ptr++ = *src_ptr++;
  179468. *dst_ptr++ = - *src_ptr++;
  179469. }
  179470. /* For odd row, negate every even column. */
  179471. for (j = 0; j < DCTSIZE; j += 2) {
  179472. *dst_ptr++ = - *src_ptr++;
  179473. *dst_ptr++ = *src_ptr++;
  179474. }
  179475. }
  179476. }
  179477. /* Any remaining right-edge blocks are only mirrored vertically. */
  179478. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179479. dst_ptr = dst_row_ptr[dst_blk_x];
  179480. src_ptr = src_row_ptr[dst_blk_x];
  179481. for (i = 0; i < DCTSIZE; i += 2) {
  179482. for (j = 0; j < DCTSIZE; j++)
  179483. *dst_ptr++ = *src_ptr++;
  179484. for (j = 0; j < DCTSIZE; j++)
  179485. *dst_ptr++ = - *src_ptr++;
  179486. }
  179487. }
  179488. } else {
  179489. /* Remaining rows are just mirrored horizontally. */
  179490. dst_row_ptr = dst_buffer[offset_y];
  179491. src_row_ptr = src_buffer[offset_y];
  179492. /* Process the blocks that can be mirrored. */
  179493. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179494. dst_ptr = dst_row_ptr[dst_blk_x];
  179495. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179496. for (i = 0; i < DCTSIZE2; i += 2) {
  179497. *dst_ptr++ = *src_ptr++;
  179498. *dst_ptr++ = - *src_ptr++;
  179499. }
  179500. }
  179501. /* Any remaining right-edge blocks are only copied. */
  179502. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179503. dst_ptr = dst_row_ptr[dst_blk_x];
  179504. src_ptr = src_row_ptr[dst_blk_x];
  179505. for (i = 0; i < DCTSIZE2; i++)
  179506. *dst_ptr++ = *src_ptr++;
  179507. }
  179508. }
  179509. }
  179510. }
  179511. }
  179512. }
  179513. LOCAL(void)
  179514. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179515. jvirt_barray_ptr *src_coef_arrays,
  179516. jvirt_barray_ptr *dst_coef_arrays)
  179517. /* Transverse transpose is equivalent to
  179518. * 1. 180 degree rotation;
  179519. * 2. Transposition;
  179520. * or
  179521. * 1. Horizontal mirroring;
  179522. * 2. Transposition;
  179523. * 3. Horizontal mirroring.
  179524. * These steps are merged into a single processing routine.
  179525. */
  179526. {
  179527. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179528. int ci, i, j, offset_x, offset_y;
  179529. JBLOCKARRAY src_buffer, dst_buffer;
  179530. JCOEFPTR src_ptr, dst_ptr;
  179531. jpeg_component_info *compptr;
  179532. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179533. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179534. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179535. compptr = dstinfo->comp_info + ci;
  179536. comp_width = MCU_cols * compptr->h_samp_factor;
  179537. comp_height = MCU_rows * compptr->v_samp_factor;
  179538. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179539. dst_blk_y += compptr->v_samp_factor) {
  179540. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179541. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179542. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179543. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179544. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179545. dst_blk_x += compptr->h_samp_factor) {
  179546. src_buffer = (*srcinfo->mem->access_virt_barray)
  179547. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179548. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179549. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179550. if (dst_blk_y < comp_height) {
  179551. src_ptr = src_buffer[offset_x]
  179552. [comp_height - dst_blk_y - offset_y - 1];
  179553. if (dst_blk_x < comp_width) {
  179554. /* Block is within the mirrorable area. */
  179555. dst_ptr = dst_buffer[offset_y]
  179556. [comp_width - dst_blk_x - offset_x - 1];
  179557. for (i = 0; i < DCTSIZE; i++) {
  179558. for (j = 0; j < DCTSIZE; j++) {
  179559. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179560. j++;
  179561. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179562. }
  179563. i++;
  179564. for (j = 0; j < DCTSIZE; j++) {
  179565. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179566. j++;
  179567. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179568. }
  179569. }
  179570. } else {
  179571. /* Right-edge blocks are mirrored in y only */
  179572. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179573. for (i = 0; i < DCTSIZE; i++) {
  179574. for (j = 0; j < DCTSIZE; j++) {
  179575. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179576. j++;
  179577. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179578. }
  179579. }
  179580. }
  179581. } else {
  179582. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179583. if (dst_blk_x < comp_width) {
  179584. /* Bottom-edge blocks are mirrored in x only */
  179585. dst_ptr = dst_buffer[offset_y]
  179586. [comp_width - dst_blk_x - offset_x - 1];
  179587. for (i = 0; i < DCTSIZE; i++) {
  179588. for (j = 0; j < DCTSIZE; j++)
  179589. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179590. i++;
  179591. for (j = 0; j < DCTSIZE; j++)
  179592. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179593. }
  179594. } else {
  179595. /* At lower right corner, just transpose, no mirroring */
  179596. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179597. for (i = 0; i < DCTSIZE; i++)
  179598. for (j = 0; j < DCTSIZE; j++)
  179599. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179600. }
  179601. }
  179602. }
  179603. }
  179604. }
  179605. }
  179606. }
  179607. }
  179608. /* Request any required workspace.
  179609. *
  179610. * We allocate the workspace virtual arrays from the source decompression
  179611. * object, so that all the arrays (both the original data and the workspace)
  179612. * will be taken into account while making memory management decisions.
  179613. * Hence, this routine must be called after jpeg_read_header (which reads
  179614. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179615. * the source's virtual arrays).
  179616. */
  179617. GLOBAL(void)
  179618. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179619. jpeg_transform_info *info)
  179620. {
  179621. jvirt_barray_ptr *coef_arrays = NULL;
  179622. jpeg_component_info *compptr;
  179623. int ci;
  179624. if (info->force_grayscale &&
  179625. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179626. srcinfo->num_components == 3) {
  179627. /* We'll only process the first component */
  179628. info->num_components = 1;
  179629. } else {
  179630. /* Process all the components */
  179631. info->num_components = srcinfo->num_components;
  179632. }
  179633. switch (info->transform) {
  179634. case JXFORM_NONE:
  179635. case JXFORM_FLIP_H:
  179636. /* Don't need a workspace array */
  179637. break;
  179638. case JXFORM_FLIP_V:
  179639. case JXFORM_ROT_180:
  179640. /* Need workspace arrays having same dimensions as source image.
  179641. * Note that we allocate arrays padded out to the next iMCU boundary,
  179642. * so that transform routines need not worry about missing edge blocks.
  179643. */
  179644. coef_arrays = (jvirt_barray_ptr *)
  179645. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179646. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179647. for (ci = 0; ci < info->num_components; ci++) {
  179648. compptr = srcinfo->comp_info + ci;
  179649. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179650. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179651. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179652. (long) compptr->h_samp_factor),
  179653. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179654. (long) compptr->v_samp_factor),
  179655. (JDIMENSION) compptr->v_samp_factor);
  179656. }
  179657. break;
  179658. case JXFORM_TRANSPOSE:
  179659. case JXFORM_TRANSVERSE:
  179660. case JXFORM_ROT_90:
  179661. case JXFORM_ROT_270:
  179662. /* Need workspace arrays having transposed dimensions.
  179663. * Note that we allocate arrays padded out to the next iMCU boundary,
  179664. * so that transform routines need not worry about missing edge blocks.
  179665. */
  179666. coef_arrays = (jvirt_barray_ptr *)
  179667. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179668. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179669. for (ci = 0; ci < info->num_components; ci++) {
  179670. compptr = srcinfo->comp_info + ci;
  179671. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179672. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179673. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179674. (long) compptr->v_samp_factor),
  179675. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179676. (long) compptr->h_samp_factor),
  179677. (JDIMENSION) compptr->h_samp_factor);
  179678. }
  179679. break;
  179680. }
  179681. info->workspace_coef_arrays = coef_arrays;
  179682. }
  179683. /* Transpose destination image parameters */
  179684. LOCAL(void)
  179685. transpose_critical_parameters (j_compress_ptr dstinfo)
  179686. {
  179687. int tblno, i, j, ci, itemp;
  179688. jpeg_component_info *compptr;
  179689. JQUANT_TBL *qtblptr;
  179690. JDIMENSION dtemp;
  179691. UINT16 qtemp;
  179692. /* Transpose basic image dimensions */
  179693. dtemp = dstinfo->image_width;
  179694. dstinfo->image_width = dstinfo->image_height;
  179695. dstinfo->image_height = dtemp;
  179696. /* Transpose sampling factors */
  179697. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179698. compptr = dstinfo->comp_info + ci;
  179699. itemp = compptr->h_samp_factor;
  179700. compptr->h_samp_factor = compptr->v_samp_factor;
  179701. compptr->v_samp_factor = itemp;
  179702. }
  179703. /* Transpose quantization tables */
  179704. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179705. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179706. if (qtblptr != NULL) {
  179707. for (i = 0; i < DCTSIZE; i++) {
  179708. for (j = 0; j < i; j++) {
  179709. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179710. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179711. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179712. }
  179713. }
  179714. }
  179715. }
  179716. }
  179717. /* Trim off any partial iMCUs on the indicated destination edge */
  179718. LOCAL(void)
  179719. trim_right_edge (j_compress_ptr dstinfo)
  179720. {
  179721. int ci, max_h_samp_factor;
  179722. JDIMENSION MCU_cols;
  179723. /* We have to compute max_h_samp_factor ourselves,
  179724. * because it hasn't been set yet in the destination
  179725. * (and we don't want to use the source's value).
  179726. */
  179727. max_h_samp_factor = 1;
  179728. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179729. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179730. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179731. }
  179732. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179733. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179734. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179735. }
  179736. LOCAL(void)
  179737. trim_bottom_edge (j_compress_ptr dstinfo)
  179738. {
  179739. int ci, max_v_samp_factor;
  179740. JDIMENSION MCU_rows;
  179741. /* We have to compute max_v_samp_factor ourselves,
  179742. * because it hasn't been set yet in the destination
  179743. * (and we don't want to use the source's value).
  179744. */
  179745. max_v_samp_factor = 1;
  179746. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179747. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179748. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179749. }
  179750. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179751. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179752. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179753. }
  179754. /* Adjust output image parameters as needed.
  179755. *
  179756. * This must be called after jpeg_copy_critical_parameters()
  179757. * and before jpeg_write_coefficients().
  179758. *
  179759. * The return value is the set of virtual coefficient arrays to be written
  179760. * (either the ones allocated by jtransform_request_workspace, or the
  179761. * original source data arrays). The caller will need to pass this value
  179762. * to jpeg_write_coefficients().
  179763. */
  179764. GLOBAL(jvirt_barray_ptr *)
  179765. jtransform_adjust_parameters (j_decompress_ptr,
  179766. j_compress_ptr dstinfo,
  179767. jvirt_barray_ptr *src_coef_arrays,
  179768. jpeg_transform_info *info)
  179769. {
  179770. /* If force-to-grayscale is requested, adjust destination parameters */
  179771. if (info->force_grayscale) {
  179772. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179773. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179774. * will get set to 1, which typically won't match the source.
  179775. * In fact we do this even if the source is already grayscale; that
  179776. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179777. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179778. */
  179779. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179780. dstinfo->num_components == 3) ||
  179781. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179782. dstinfo->num_components == 1)) {
  179783. /* We have to preserve the source's quantization table number. */
  179784. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179785. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179786. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179787. } else {
  179788. /* Sorry, can't do it */
  179789. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179790. }
  179791. }
  179792. /* Correct the destination's image dimensions etc if necessary */
  179793. switch (info->transform) {
  179794. case JXFORM_NONE:
  179795. /* Nothing to do */
  179796. break;
  179797. case JXFORM_FLIP_H:
  179798. if (info->trim)
  179799. trim_right_edge(dstinfo);
  179800. break;
  179801. case JXFORM_FLIP_V:
  179802. if (info->trim)
  179803. trim_bottom_edge(dstinfo);
  179804. break;
  179805. case JXFORM_TRANSPOSE:
  179806. transpose_critical_parameters(dstinfo);
  179807. /* transpose does NOT have to trim anything */
  179808. break;
  179809. case JXFORM_TRANSVERSE:
  179810. transpose_critical_parameters(dstinfo);
  179811. if (info->trim) {
  179812. trim_right_edge(dstinfo);
  179813. trim_bottom_edge(dstinfo);
  179814. }
  179815. break;
  179816. case JXFORM_ROT_90:
  179817. transpose_critical_parameters(dstinfo);
  179818. if (info->trim)
  179819. trim_right_edge(dstinfo);
  179820. break;
  179821. case JXFORM_ROT_180:
  179822. if (info->trim) {
  179823. trim_right_edge(dstinfo);
  179824. trim_bottom_edge(dstinfo);
  179825. }
  179826. break;
  179827. case JXFORM_ROT_270:
  179828. transpose_critical_parameters(dstinfo);
  179829. if (info->trim)
  179830. trim_bottom_edge(dstinfo);
  179831. break;
  179832. }
  179833. /* Return the appropriate output data set */
  179834. if (info->workspace_coef_arrays != NULL)
  179835. return info->workspace_coef_arrays;
  179836. return src_coef_arrays;
  179837. }
  179838. /* Execute the actual transformation, if any.
  179839. *
  179840. * This must be called *after* jpeg_write_coefficients, because it depends
  179841. * on jpeg_write_coefficients to have computed subsidiary values such as
  179842. * the per-component width and height fields in the destination object.
  179843. *
  179844. * Note that some transformations will modify the source data arrays!
  179845. */
  179846. GLOBAL(void)
  179847. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179848. j_compress_ptr dstinfo,
  179849. jvirt_barray_ptr *src_coef_arrays,
  179850. jpeg_transform_info *info)
  179851. {
  179852. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179853. switch (info->transform) {
  179854. case JXFORM_NONE:
  179855. break;
  179856. case JXFORM_FLIP_H:
  179857. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179858. break;
  179859. case JXFORM_FLIP_V:
  179860. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179861. break;
  179862. case JXFORM_TRANSPOSE:
  179863. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179864. break;
  179865. case JXFORM_TRANSVERSE:
  179866. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179867. break;
  179868. case JXFORM_ROT_90:
  179869. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179870. break;
  179871. case JXFORM_ROT_180:
  179872. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179873. break;
  179874. case JXFORM_ROT_270:
  179875. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179876. break;
  179877. }
  179878. }
  179879. #endif /* TRANSFORMS_SUPPORTED */
  179880. /* Setup decompression object to save desired markers in memory.
  179881. * This must be called before jpeg_read_header() to have the desired effect.
  179882. */
  179883. GLOBAL(void)
  179884. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179885. {
  179886. #ifdef SAVE_MARKERS_SUPPORTED
  179887. int m;
  179888. /* Save comments except under NONE option */
  179889. if (option != JCOPYOPT_NONE) {
  179890. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179891. }
  179892. /* Save all types of APPn markers iff ALL option */
  179893. if (option == JCOPYOPT_ALL) {
  179894. for (m = 0; m < 16; m++)
  179895. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179896. }
  179897. #endif /* SAVE_MARKERS_SUPPORTED */
  179898. }
  179899. /* Copy markers saved in the given source object to the destination object.
  179900. * This should be called just after jpeg_start_compress() or
  179901. * jpeg_write_coefficients().
  179902. * Note that those routines will have written the SOI, and also the
  179903. * JFIF APP0 or Adobe APP14 markers if selected.
  179904. */
  179905. GLOBAL(void)
  179906. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179907. JCOPY_OPTION)
  179908. {
  179909. jpeg_saved_marker_ptr marker;
  179910. /* In the current implementation, we don't actually need to examine the
  179911. * option flag here; we just copy everything that got saved.
  179912. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179913. * if the encoder library already wrote one.
  179914. */
  179915. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179916. if (dstinfo->write_JFIF_header &&
  179917. marker->marker == JPEG_APP0 &&
  179918. marker->data_length >= 5 &&
  179919. GETJOCTET(marker->data[0]) == 0x4A &&
  179920. GETJOCTET(marker->data[1]) == 0x46 &&
  179921. GETJOCTET(marker->data[2]) == 0x49 &&
  179922. GETJOCTET(marker->data[3]) == 0x46 &&
  179923. GETJOCTET(marker->data[4]) == 0)
  179924. continue; /* reject duplicate JFIF */
  179925. if (dstinfo->write_Adobe_marker &&
  179926. marker->marker == JPEG_APP0+14 &&
  179927. marker->data_length >= 5 &&
  179928. GETJOCTET(marker->data[0]) == 0x41 &&
  179929. GETJOCTET(marker->data[1]) == 0x64 &&
  179930. GETJOCTET(marker->data[2]) == 0x6F &&
  179931. GETJOCTET(marker->data[3]) == 0x62 &&
  179932. GETJOCTET(marker->data[4]) == 0x65)
  179933. continue; /* reject duplicate Adobe */
  179934. #ifdef NEED_FAR_POINTERS
  179935. /* We could use jpeg_write_marker if the data weren't FAR... */
  179936. {
  179937. unsigned int i;
  179938. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179939. for (i = 0; i < marker->data_length; i++)
  179940. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179941. }
  179942. #else
  179943. jpeg_write_marker(dstinfo, marker->marker,
  179944. marker->data, marker->data_length);
  179945. #endif
  179946. }
  179947. }
  179948. /*** End of inlined file: transupp.c ***/
  179949. #else
  179950. #define JPEG_INTERNALS
  179951. #undef FAR
  179952. #include <jpeglib.h>
  179953. #endif
  179954. }
  179955. #undef max
  179956. #undef min
  179957. #if JUCE_MSVC
  179958. #pragma warning (pop)
  179959. #endif
  179960. BEGIN_JUCE_NAMESPACE
  179961. namespace JPEGHelpers
  179962. {
  179963. using namespace jpeglibNamespace;
  179964. #if ! JUCE_MSVC
  179965. using jpeglibNamespace::boolean;
  179966. #endif
  179967. struct JPEGDecodingFailure {};
  179968. static void fatalErrorHandler (j_common_ptr)
  179969. {
  179970. throw JPEGDecodingFailure();
  179971. }
  179972. static void silentErrorCallback1 (j_common_ptr) {}
  179973. static void silentErrorCallback2 (j_common_ptr, int) {}
  179974. static void silentErrorCallback3 (j_common_ptr, char*) {}
  179975. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179976. {
  179977. zerostruct (err);
  179978. err.error_exit = fatalErrorHandler;
  179979. err.emit_message = silentErrorCallback2;
  179980. err.output_message = silentErrorCallback1;
  179981. err.format_message = silentErrorCallback3;
  179982. err.reset_error_mgr = silentErrorCallback1;
  179983. }
  179984. static void dummyCallback1 (j_decompress_ptr)
  179985. {
  179986. }
  179987. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  179988. {
  179989. decompStruct->src->next_input_byte += num;
  179990. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179991. decompStruct->src->bytes_in_buffer -= num;
  179992. }
  179993. static boolean jpegFill (j_decompress_ptr)
  179994. {
  179995. return 0;
  179996. }
  179997. static const int jpegBufferSize = 512;
  179998. struct JuceJpegDest : public jpeg_destination_mgr
  179999. {
  180000. OutputStream* output;
  180001. char* buffer;
  180002. };
  180003. static void jpegWriteInit (j_compress_ptr)
  180004. {
  180005. }
  180006. static void jpegWriteTerminate (j_compress_ptr cinfo)
  180007. {
  180008. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180009. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  180010. dest->output->write (dest->buffer, (int) numToWrite);
  180011. }
  180012. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  180013. {
  180014. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180015. const int numToWrite = jpegBufferSize;
  180016. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  180017. dest->free_in_buffer = jpegBufferSize;
  180018. return dest->output->write (dest->buffer, numToWrite);
  180019. }
  180020. }
  180021. JPEGImageFormat::JPEGImageFormat()
  180022. : quality (-1.0f)
  180023. {
  180024. }
  180025. JPEGImageFormat::~JPEGImageFormat() {}
  180026. void JPEGImageFormat::setQuality (const float newQuality)
  180027. {
  180028. quality = newQuality;
  180029. }
  180030. const String JPEGImageFormat::getFormatName()
  180031. {
  180032. return "JPEG";
  180033. }
  180034. bool JPEGImageFormat::canUnderstand (InputStream& in)
  180035. {
  180036. const int bytesNeeded = 10;
  180037. uint8 header [bytesNeeded];
  180038. if (in.read (header, bytesNeeded) == bytesNeeded)
  180039. {
  180040. return header[0] == 0xff
  180041. && header[1] == 0xd8
  180042. && header[2] == 0xff
  180043. && (header[3] == 0xe0 || header[3] == 0xe1);
  180044. }
  180045. return false;
  180046. }
  180047. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180048. const Image juce_loadWithCoreImage (InputStream& input);
  180049. #endif
  180050. const Image JPEGImageFormat::decodeImage (InputStream& in)
  180051. {
  180052. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180053. return juce_loadWithCoreImage (in);
  180054. #else
  180055. using namespace jpeglibNamespace;
  180056. using namespace JPEGHelpers;
  180057. MemoryOutputStream mb;
  180058. mb.writeFromInputStream (in, -1);
  180059. Image image;
  180060. if (mb.getDataSize() > 16)
  180061. {
  180062. struct jpeg_decompress_struct jpegDecompStruct;
  180063. struct jpeg_error_mgr jerr;
  180064. setupSilentErrorHandler (jerr);
  180065. jpegDecompStruct.err = &jerr;
  180066. jpeg_create_decompress (&jpegDecompStruct);
  180067. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180068. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180069. jpegDecompStruct.src->init_source = dummyCallback1;
  180070. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180071. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180072. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180073. jpegDecompStruct.src->term_source = dummyCallback1;
  180074. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180075. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180076. try
  180077. {
  180078. jpeg_read_header (&jpegDecompStruct, TRUE);
  180079. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180080. const int width = jpegDecompStruct.output_width;
  180081. const int height = jpegDecompStruct.output_height;
  180082. jpegDecompStruct.out_color_space = JCS_RGB;
  180083. JSAMPARRAY buffer
  180084. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180085. JPOOL_IMAGE,
  180086. width * 3, 1);
  180087. if (jpeg_start_decompress (&jpegDecompStruct))
  180088. {
  180089. image = Image (Image::RGB, width, height, false);
  180090. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180091. const Image::BitmapData destData (image, true);
  180092. for (int y = 0; y < height; ++y)
  180093. {
  180094. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180095. const uint8* src = *buffer;
  180096. uint8* dest = destData.getLinePointer (y);
  180097. if (hasAlphaChan)
  180098. {
  180099. for (int i = width; --i >= 0;)
  180100. {
  180101. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180102. ((PixelARGB*) dest)->premultiply();
  180103. dest += destData.pixelStride;
  180104. src += 3;
  180105. }
  180106. }
  180107. else
  180108. {
  180109. for (int i = width; --i >= 0;)
  180110. {
  180111. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180112. dest += destData.pixelStride;
  180113. src += 3;
  180114. }
  180115. }
  180116. }
  180117. jpeg_finish_decompress (&jpegDecompStruct);
  180118. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180119. }
  180120. jpeg_destroy_decompress (&jpegDecompStruct);
  180121. }
  180122. catch (...)
  180123. {}
  180124. }
  180125. return image;
  180126. #endif
  180127. }
  180128. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180129. {
  180130. using namespace jpeglibNamespace;
  180131. using namespace JPEGHelpers;
  180132. if (image.hasAlphaChannel())
  180133. {
  180134. // this method could fill the background in white and still save the image..
  180135. jassertfalse;
  180136. return true;
  180137. }
  180138. struct jpeg_compress_struct jpegCompStruct;
  180139. struct jpeg_error_mgr jerr;
  180140. setupSilentErrorHandler (jerr);
  180141. jpegCompStruct.err = &jerr;
  180142. jpeg_create_compress (&jpegCompStruct);
  180143. JuceJpegDest dest;
  180144. jpegCompStruct.dest = &dest;
  180145. dest.output = &out;
  180146. HeapBlock <char> tempBuffer (jpegBufferSize);
  180147. dest.buffer = tempBuffer;
  180148. dest.next_output_byte = (JOCTET*) dest.buffer;
  180149. dest.free_in_buffer = jpegBufferSize;
  180150. dest.init_destination = jpegWriteInit;
  180151. dest.empty_output_buffer = jpegWriteFlush;
  180152. dest.term_destination = jpegWriteTerminate;
  180153. jpegCompStruct.image_width = image.getWidth();
  180154. jpegCompStruct.image_height = image.getHeight();
  180155. jpegCompStruct.input_components = 3;
  180156. jpegCompStruct.in_color_space = JCS_RGB;
  180157. jpegCompStruct.write_JFIF_header = 1;
  180158. jpegCompStruct.X_density = 72;
  180159. jpegCompStruct.Y_density = 72;
  180160. jpeg_set_defaults (&jpegCompStruct);
  180161. jpegCompStruct.dct_method = JDCT_FLOAT;
  180162. jpegCompStruct.optimize_coding = 1;
  180163. //jpegCompStruct.smoothing_factor = 10;
  180164. if (quality < 0.0f)
  180165. quality = 0.85f;
  180166. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180167. jpeg_start_compress (&jpegCompStruct, TRUE);
  180168. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180169. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180170. JPOOL_IMAGE, strideBytes, 1);
  180171. const Image::BitmapData srcData (image, false);
  180172. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180173. {
  180174. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180175. uint8* dst = *buffer;
  180176. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180177. {
  180178. *dst++ = ((const PixelRGB*) src)->getRed();
  180179. *dst++ = ((const PixelRGB*) src)->getGreen();
  180180. *dst++ = ((const PixelRGB*) src)->getBlue();
  180181. src += srcData.pixelStride;
  180182. }
  180183. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180184. }
  180185. jpeg_finish_compress (&jpegCompStruct);
  180186. jpeg_destroy_compress (&jpegCompStruct);
  180187. out.flush();
  180188. return true;
  180189. }
  180190. END_JUCE_NAMESPACE
  180191. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180192. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180193. #if JUCE_MSVC
  180194. #pragma warning (push)
  180195. #pragma warning (disable: 4390 4611)
  180196. #endif
  180197. namespace zlibNamespace
  180198. {
  180199. #if JUCE_INCLUDE_ZLIB_CODE
  180200. #undef OS_CODE
  180201. #undef fdopen
  180202. #undef OS_CODE
  180203. #else
  180204. #include <zlib.h>
  180205. #endif
  180206. }
  180207. namespace pnglibNamespace
  180208. {
  180209. using namespace zlibNamespace;
  180210. #if JUCE_INCLUDE_PNGLIB_CODE
  180211. #if _MSC_VER != 1310
  180212. using ::calloc; // (causes conflict in VS.NET 2003)
  180213. using ::malloc;
  180214. using ::free;
  180215. #endif
  180216. using ::abs;
  180217. #define PNG_INTERNAL
  180218. #define NO_DUMMY_DECL
  180219. #define PNG_SETJMP_NOT_SUPPORTED
  180220. /*** Start of inlined file: png.h ***/
  180221. /* png.h - header file for PNG reference library
  180222. *
  180223. * libpng version 1.2.21 - October 4, 2007
  180224. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180225. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180226. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180227. *
  180228. * Authors and maintainers:
  180229. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180230. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180231. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180232. * See also "Contributing Authors", below.
  180233. *
  180234. * Note about libpng version numbers:
  180235. *
  180236. * Due to various miscommunications, unforeseen code incompatibilities
  180237. * and occasional factors outside the authors' control, version numbering
  180238. * on the library has not always been consistent and straightforward.
  180239. * The following table summarizes matters since version 0.89c, which was
  180240. * the first widely used release:
  180241. *
  180242. * source png.h png.h shared-lib
  180243. * version string int version
  180244. * ------- ------ ----- ----------
  180245. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180246. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180247. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180248. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180249. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180250. * 0.97c 0.97 97 2.0.97
  180251. * 0.98 0.98 98 2.0.98
  180252. * 0.99 0.99 98 2.0.99
  180253. * 0.99a-m 0.99 99 2.0.99
  180254. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180255. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180256. * 1.0.1 png.h string is 10001 2.1.0
  180257. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180258. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180259. * 1.0.2a-b 10003 version, except as noted.
  180260. * 1.0.3 10003
  180261. * 1.0.3a-d 10004
  180262. * 1.0.4 10004
  180263. * 1.0.4a-f 10005
  180264. * 1.0.5 (+ 2 patches) 10005
  180265. * 1.0.5a-d 10006
  180266. * 1.0.5e-r 10100 (not source compatible)
  180267. * 1.0.5s-v 10006 (not binary compatible)
  180268. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180269. * 1.0.6d-f 10007 (still binary incompatible)
  180270. * 1.0.6g 10007
  180271. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180272. * 1.0.6i 10007 10.6i
  180273. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180274. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180275. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180276. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180277. * 1.0.7 1 10007 (still compatible)
  180278. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180279. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180280. * 1.0.8 1 10008 2.1.0.8
  180281. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180282. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180283. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180284. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180285. * 1.0.9 1 10009 2.1.0.9
  180286. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180287. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180288. * 1.0.10 1 10010 2.1.0.10
  180289. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180290. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180291. * 1.0.11 1 10011 2.1.0.11
  180292. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180293. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180294. * 1.0.12 2 10012 2.1.0.12
  180295. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180296. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180297. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180298. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180299. * 1.2.0 3 10200 3.1.2.0
  180300. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180301. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180302. * 1.2.1 3 10201 3.1.2.1
  180303. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180304. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180305. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180306. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180307. * 1.0.13 10 10013 10.so.0.1.0.13
  180308. * 1.2.2 12 10202 12.so.0.1.2.2
  180309. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180310. * 1.2.3 12 10203 12.so.0.1.2.3
  180311. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180312. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180313. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180314. * 1.0.14 10 10014 10.so.0.1.0.14
  180315. * 1.2.4 13 10204 12.so.0.1.2.4
  180316. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180317. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180318. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180319. * 1.0.15 10 10015 10.so.0.1.0.15
  180320. * 1.2.5 13 10205 12.so.0.1.2.5
  180321. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180322. * 1.0.16 10 10016 10.so.0.1.0.16
  180323. * 1.2.6 13 10206 12.so.0.1.2.6
  180324. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180325. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180326. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180327. * 1.0.17 10 10017 10.so.0.1.0.17
  180328. * 1.2.7 13 10207 12.so.0.1.2.7
  180329. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180330. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180331. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180332. * 1.0.18 10 10018 10.so.0.1.0.18
  180333. * 1.2.8 13 10208 12.so.0.1.2.8
  180334. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180335. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180336. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180337. * 1.2.9 13 10209 12.so.0.9[.0]
  180338. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180339. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180340. * 1.2.10 13 10210 12.so.0.10[.0]
  180341. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180342. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180343. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180344. * 1.0.19 10 10019 10.so.0.19[.0]
  180345. * 1.2.11 13 10211 12.so.0.11[.0]
  180346. * 1.0.20 10 10020 10.so.0.20[.0]
  180347. * 1.2.12 13 10212 12.so.0.12[.0]
  180348. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180349. * 1.0.21 10 10021 10.so.0.21[.0]
  180350. * 1.2.13 13 10213 12.so.0.13[.0]
  180351. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180352. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180353. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180354. * 1.0.22 10 10022 10.so.0.22[.0]
  180355. * 1.2.14 13 10214 12.so.0.14[.0]
  180356. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180357. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180358. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180359. * 1.0.23 10 10023 10.so.0.23[.0]
  180360. * 1.2.15 13 10215 12.so.0.15[.0]
  180361. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180362. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180363. * 1.0.24 10 10024 10.so.0.24[.0]
  180364. * 1.2.16 13 10216 12.so.0.16[.0]
  180365. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180366. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180367. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180368. * 1.0.25 10 10025 10.so.0.25[.0]
  180369. * 1.2.17 13 10217 12.so.0.17[.0]
  180370. * 1.0.26 10 10026 10.so.0.26[.0]
  180371. * 1.2.18 13 10218 12.so.0.18[.0]
  180372. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180373. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180374. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180375. * 1.0.27 10 10027 10.so.0.27[.0]
  180376. * 1.2.19 13 10219 12.so.0.19[.0]
  180377. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180378. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180379. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180380. * 1.0.28 10 10028 10.so.0.28[.0]
  180381. * 1.2.20 13 10220 12.so.0.20[.0]
  180382. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180383. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180384. * 1.0.29 10 10029 10.so.0.29[.0]
  180385. * 1.2.21 13 10221 12.so.0.21[.0]
  180386. *
  180387. * Henceforth the source version will match the shared-library major
  180388. * and minor numbers; the shared-library major version number will be
  180389. * used for changes in backward compatibility, as it is intended. The
  180390. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180391. * for applications, is an unsigned integer of the form xyyzz corresponding
  180392. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180393. * were given the previous public release number plus a letter, until
  180394. * version 1.0.6j; from then on they were given the upcoming public
  180395. * release number plus "betaNN" or "rcN".
  180396. *
  180397. * Binary incompatibility exists only when applications make direct access
  180398. * to the info_ptr or png_ptr members through png.h, and the compiled
  180399. * application is loaded with a different version of the library.
  180400. *
  180401. * DLLNUM will change each time there are forward or backward changes
  180402. * in binary compatibility (e.g., when a new feature is added).
  180403. *
  180404. * See libpng.txt or libpng.3 for more information. The PNG specification
  180405. * is available as a W3C Recommendation and as an ISO Specification,
  180406. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180407. */
  180408. /*
  180409. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180410. *
  180411. * If you modify libpng you may insert additional notices immediately following
  180412. * this sentence.
  180413. *
  180414. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180415. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180416. * distributed according to the same disclaimer and license as libpng-1.2.5
  180417. * with the following individual added to the list of Contributing Authors:
  180418. *
  180419. * Cosmin Truta
  180420. *
  180421. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180422. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180423. * distributed according to the same disclaimer and license as libpng-1.0.6
  180424. * with the following individuals added to the list of Contributing Authors:
  180425. *
  180426. * Simon-Pierre Cadieux
  180427. * Eric S. Raymond
  180428. * Gilles Vollant
  180429. *
  180430. * and with the following additions to the disclaimer:
  180431. *
  180432. * There is no warranty against interference with your enjoyment of the
  180433. * library or against infringement. There is no warranty that our
  180434. * efforts or the library will fulfill any of your particular purposes
  180435. * or needs. This library is provided with all faults, and the entire
  180436. * risk of satisfactory quality, performance, accuracy, and effort is with
  180437. * the user.
  180438. *
  180439. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180440. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180441. * distributed according to the same disclaimer and license as libpng-0.96,
  180442. * with the following individuals added to the list of Contributing Authors:
  180443. *
  180444. * Tom Lane
  180445. * Glenn Randers-Pehrson
  180446. * Willem van Schaik
  180447. *
  180448. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180449. * Copyright (c) 1996, 1997 Andreas Dilger
  180450. * Distributed according to the same disclaimer and license as libpng-0.88,
  180451. * with the following individuals added to the list of Contributing Authors:
  180452. *
  180453. * John Bowler
  180454. * Kevin Bracey
  180455. * Sam Bushell
  180456. * Magnus Holmgren
  180457. * Greg Roelofs
  180458. * Tom Tanner
  180459. *
  180460. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180461. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180462. *
  180463. * For the purposes of this copyright and license, "Contributing Authors"
  180464. * is defined as the following set of individuals:
  180465. *
  180466. * Andreas Dilger
  180467. * Dave Martindale
  180468. * Guy Eric Schalnat
  180469. * Paul Schmidt
  180470. * Tim Wegner
  180471. *
  180472. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180473. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180474. * including, without limitation, the warranties of merchantability and of
  180475. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180476. * assume no liability for direct, indirect, incidental, special, exemplary,
  180477. * or consequential damages, which may result from the use of the PNG
  180478. * Reference Library, even if advised of the possibility of such damage.
  180479. *
  180480. * Permission is hereby granted to use, copy, modify, and distribute this
  180481. * source code, or portions hereof, for any purpose, without fee, subject
  180482. * to the following restrictions:
  180483. *
  180484. * 1. The origin of this source code must not be misrepresented.
  180485. *
  180486. * 2. Altered versions must be plainly marked as such and
  180487. * must not be misrepresented as being the original source.
  180488. *
  180489. * 3. This Copyright notice may not be removed or altered from
  180490. * any source or altered source distribution.
  180491. *
  180492. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180493. * fee, and encourage the use of this source code as a component to
  180494. * supporting the PNG file format in commercial products. If you use this
  180495. * source code in a product, acknowledgment is not required but would be
  180496. * appreciated.
  180497. */
  180498. /*
  180499. * A "png_get_copyright" function is available, for convenient use in "about"
  180500. * boxes and the like:
  180501. *
  180502. * printf("%s",png_get_copyright(NULL));
  180503. *
  180504. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180505. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180506. */
  180507. /*
  180508. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180509. * certification mark of the Open Source Initiative.
  180510. */
  180511. /*
  180512. * The contributing authors would like to thank all those who helped
  180513. * with testing, bug fixes, and patience. This wouldn't have been
  180514. * possible without all of you.
  180515. *
  180516. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180517. */
  180518. /*
  180519. * Y2K compliance in libpng:
  180520. * =========================
  180521. *
  180522. * October 4, 2007
  180523. *
  180524. * Since the PNG Development group is an ad-hoc body, we can't make
  180525. * an official declaration.
  180526. *
  180527. * This is your unofficial assurance that libpng from version 0.71 and
  180528. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180529. * versions were also Y2K compliant.
  180530. *
  180531. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180532. * that will hold years up to 65535. The other two hold the date in text
  180533. * format, and will hold years up to 9999.
  180534. *
  180535. * The integer is
  180536. * "png_uint_16 year" in png_time_struct.
  180537. *
  180538. * The strings are
  180539. * "png_charp time_buffer" in png_struct and
  180540. * "near_time_buffer", which is a local character string in png.c.
  180541. *
  180542. * There are seven time-related functions:
  180543. * png.c: png_convert_to_rfc_1123() in png.c
  180544. * (formerly png_convert_to_rfc_1152() in error)
  180545. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180546. * png_convert_from_time_t() in pngwrite.c
  180547. * png_get_tIME() in pngget.c
  180548. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180549. * png_set_tIME() in pngset.c
  180550. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180551. *
  180552. * All handle dates properly in a Y2K environment. The
  180553. * png_convert_from_time_t() function calls gmtime() to convert from system
  180554. * clock time, which returns (year - 1900), which we properly convert to
  180555. * the full 4-digit year. There is a possibility that applications using
  180556. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180557. * function, or that they are incorrectly passing only a 2-digit year
  180558. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180559. * but this is not under our control. The libpng documentation has always
  180560. * stated that it works with 4-digit years, and the APIs have been
  180561. * documented as such.
  180562. *
  180563. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180564. * integer to hold the year, and can hold years as large as 65535.
  180565. *
  180566. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180567. * no date-related code.
  180568. *
  180569. * Glenn Randers-Pehrson
  180570. * libpng maintainer
  180571. * PNG Development Group
  180572. */
  180573. #ifndef PNG_H
  180574. #define PNG_H
  180575. /* This is not the place to learn how to use libpng. The file libpng.txt
  180576. * describes how to use libpng, and the file example.c summarizes it
  180577. * with some code on which to build. This file is useful for looking
  180578. * at the actual function definitions and structure components.
  180579. */
  180580. /* Version information for png.h - this should match the version in png.c */
  180581. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180582. #define PNG_HEADER_VERSION_STRING \
  180583. " libpng version 1.2.21 - October 4, 2007\n"
  180584. #define PNG_LIBPNG_VER_SONUM 0
  180585. #define PNG_LIBPNG_VER_DLLNUM 13
  180586. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180587. #define PNG_LIBPNG_VER_MAJOR 1
  180588. #define PNG_LIBPNG_VER_MINOR 2
  180589. #define PNG_LIBPNG_VER_RELEASE 21
  180590. /* This should match the numeric part of the final component of
  180591. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180592. #define PNG_LIBPNG_VER_BUILD 0
  180593. /* Release Status */
  180594. #define PNG_LIBPNG_BUILD_ALPHA 1
  180595. #define PNG_LIBPNG_BUILD_BETA 2
  180596. #define PNG_LIBPNG_BUILD_RC 3
  180597. #define PNG_LIBPNG_BUILD_STABLE 4
  180598. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180599. /* Release-Specific Flags */
  180600. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180601. PNG_LIBPNG_BUILD_STABLE only */
  180602. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180603. PNG_LIBPNG_BUILD_SPECIAL */
  180604. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180605. PNG_LIBPNG_BUILD_PRIVATE */
  180606. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180607. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180608. * We must not include leading zeros.
  180609. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180610. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180611. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180612. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180613. #ifndef PNG_VERSION_INFO_ONLY
  180614. /* include the compression library's header */
  180615. #endif
  180616. /* include all user configurable info, including optional assembler routines */
  180617. /*** Start of inlined file: pngconf.h ***/
  180618. /* pngconf.h - machine configurable file for libpng
  180619. *
  180620. * libpng version 1.2.21 - October 4, 2007
  180621. * For conditions of distribution and use, see copyright notice in png.h
  180622. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180623. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180624. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180625. */
  180626. /* Any machine specific code is near the front of this file, so if you
  180627. * are configuring libpng for a machine, you may want to read the section
  180628. * starting here down to where it starts to typedef png_color, png_text,
  180629. * and png_info.
  180630. */
  180631. #ifndef PNGCONF_H
  180632. #define PNGCONF_H
  180633. #define PNG_1_2_X
  180634. // These are some Juce config settings that should remove any unnecessary code bloat..
  180635. #define PNG_NO_STDIO 1
  180636. #define PNG_DEBUG 0
  180637. #define PNG_NO_WARNINGS 1
  180638. #define PNG_NO_ERROR_TEXT 1
  180639. #define PNG_NO_ERROR_NUMBERS 1
  180640. #define PNG_NO_USER_MEM 1
  180641. #define PNG_NO_READ_iCCP 1
  180642. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180643. #define PNG_NO_READ_USER_CHUNKS 1
  180644. #define PNG_NO_READ_iTXt 1
  180645. #define PNG_NO_READ_sCAL 1
  180646. #define PNG_NO_READ_sPLT 1
  180647. #define png_error(a, b) png_err(a)
  180648. #define png_warning(a, b)
  180649. #define png_chunk_error(a, b) png_err(a)
  180650. #define png_chunk_warning(a, b)
  180651. /*
  180652. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180653. * includes the resource compiler for Windows DLL configurations.
  180654. */
  180655. #ifdef PNG_USER_CONFIG
  180656. # ifndef PNG_USER_PRIVATEBUILD
  180657. # define PNG_USER_PRIVATEBUILD
  180658. # endif
  180659. #include "pngusr.h"
  180660. #endif
  180661. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180662. #ifdef PNG_CONFIGURE_LIBPNG
  180663. #ifdef HAVE_CONFIG_H
  180664. #include "config.h"
  180665. #endif
  180666. #endif
  180667. /*
  180668. * Added at libpng-1.2.8
  180669. *
  180670. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180671. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180672. * the DLL was built>
  180673. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180674. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180675. * distinguish your DLL from those of the official release. These
  180676. * correspond to the trailing letters that come after the version
  180677. * number and must match your private DLL name>
  180678. * e.g. // private DLL "libpng13gx.dll"
  180679. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180680. *
  180681. * The following macros are also at your disposal if you want to complete the
  180682. * DLL VERSIONINFO structure.
  180683. * - PNG_USER_VERSIONINFO_COMMENTS
  180684. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180685. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180686. */
  180687. #ifdef __STDC__
  180688. #ifdef SPECIALBUILD
  180689. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180690. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180691. #endif
  180692. #ifdef PRIVATEBUILD
  180693. # pragma message("PRIVATEBUILD is deprecated.\
  180694. Use PNG_USER_PRIVATEBUILD instead.")
  180695. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180696. #endif
  180697. #endif /* __STDC__ */
  180698. #ifndef PNG_VERSION_INFO_ONLY
  180699. /* End of material added to libpng-1.2.8 */
  180700. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180701. Restored at libpng-1.2.21 */
  180702. # define PNG_WARN_UNINITIALIZED_ROW 1
  180703. /* End of material added at libpng-1.2.19/1.2.21 */
  180704. /* This is the size of the compression buffer, and thus the size of
  180705. * an IDAT chunk. Make this whatever size you feel is best for your
  180706. * machine. One of these will be allocated per png_struct. When this
  180707. * is full, it writes the data to the disk, and does some other
  180708. * calculations. Making this an extremely small size will slow
  180709. * the library down, but you may want to experiment to determine
  180710. * where it becomes significant, if you are concerned with memory
  180711. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180712. * this describes the size of the buffer available to read the data in.
  180713. * Unless this gets smaller than the size of a row (compressed),
  180714. * it should not make much difference how big this is.
  180715. */
  180716. #ifndef PNG_ZBUF_SIZE
  180717. # define PNG_ZBUF_SIZE 8192
  180718. #endif
  180719. /* Enable if you want a write-only libpng */
  180720. #ifndef PNG_NO_READ_SUPPORTED
  180721. # define PNG_READ_SUPPORTED
  180722. #endif
  180723. /* Enable if you want a read-only libpng */
  180724. #ifndef PNG_NO_WRITE_SUPPORTED
  180725. # define PNG_WRITE_SUPPORTED
  180726. #endif
  180727. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180728. support PNGs that are embedded in MNG datastreams */
  180729. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180730. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180731. # define PNG_MNG_FEATURES_SUPPORTED
  180732. # endif
  180733. #endif
  180734. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180735. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180736. # define PNG_FLOATING_POINT_SUPPORTED
  180737. # endif
  180738. #endif
  180739. /* If you are running on a machine where you cannot allocate more
  180740. * than 64K of memory at once, uncomment this. While libpng will not
  180741. * normally need that much memory in a chunk (unless you load up a very
  180742. * large file), zlib needs to know how big of a chunk it can use, and
  180743. * libpng thus makes sure to check any memory allocation to verify it
  180744. * will fit into memory.
  180745. #define PNG_MAX_MALLOC_64K
  180746. */
  180747. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180748. # define PNG_MAX_MALLOC_64K
  180749. #endif
  180750. /* Special munging to support doing things the 'cygwin' way:
  180751. * 'Normal' png-on-win32 defines/defaults:
  180752. * PNG_BUILD_DLL -- building dll
  180753. * PNG_USE_DLL -- building an application, linking to dll
  180754. * (no define) -- building static library, or building an
  180755. * application and linking to the static lib
  180756. * 'Cygwin' defines/defaults:
  180757. * PNG_BUILD_DLL -- (ignored) building the dll
  180758. * (no define) -- (ignored) building an application, linking to the dll
  180759. * PNG_STATIC -- (ignored) building the static lib, or building an
  180760. * application that links to the static lib.
  180761. * ALL_STATIC -- (ignored) building various static libs, or building an
  180762. * application that links to the static libs.
  180763. * Thus,
  180764. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180765. * this bit of #ifdefs will define the 'correct' config variables based on
  180766. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180767. * unnecessary.
  180768. *
  180769. * Also, the precedence order is:
  180770. * ALL_STATIC (since we can't #undef something outside our namespace)
  180771. * PNG_BUILD_DLL
  180772. * PNG_STATIC
  180773. * (nothing) == PNG_USE_DLL
  180774. *
  180775. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180776. * of auto-import in binutils, we no longer need to worry about
  180777. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180778. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180779. * to __declspec() stuff. However, we DO need to worry about
  180780. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180781. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180782. */
  180783. #if defined(__CYGWIN__)
  180784. # if defined(ALL_STATIC)
  180785. # if defined(PNG_BUILD_DLL)
  180786. # undef PNG_BUILD_DLL
  180787. # endif
  180788. # if defined(PNG_USE_DLL)
  180789. # undef PNG_USE_DLL
  180790. # endif
  180791. # if defined(PNG_DLL)
  180792. # undef PNG_DLL
  180793. # endif
  180794. # if !defined(PNG_STATIC)
  180795. # define PNG_STATIC
  180796. # endif
  180797. # else
  180798. # if defined (PNG_BUILD_DLL)
  180799. # if defined(PNG_STATIC)
  180800. # undef PNG_STATIC
  180801. # endif
  180802. # if defined(PNG_USE_DLL)
  180803. # undef PNG_USE_DLL
  180804. # endif
  180805. # if !defined(PNG_DLL)
  180806. # define PNG_DLL
  180807. # endif
  180808. # else
  180809. # if defined(PNG_STATIC)
  180810. # if defined(PNG_USE_DLL)
  180811. # undef PNG_USE_DLL
  180812. # endif
  180813. # if defined(PNG_DLL)
  180814. # undef PNG_DLL
  180815. # endif
  180816. # else
  180817. # if !defined(PNG_USE_DLL)
  180818. # define PNG_USE_DLL
  180819. # endif
  180820. # if !defined(PNG_DLL)
  180821. # define PNG_DLL
  180822. # endif
  180823. # endif
  180824. # endif
  180825. # endif
  180826. #endif
  180827. /* This protects us against compilers that run on a windowing system
  180828. * and thus don't have or would rather us not use the stdio types:
  180829. * stdin, stdout, and stderr. The only one currently used is stderr
  180830. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180831. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180832. * will also prevent these, plus will prevent the entire set of stdio
  180833. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180834. * unless (PNG_DEBUG > 0) has been #defined.
  180835. *
  180836. * #define PNG_NO_CONSOLE_IO
  180837. * #define PNG_NO_STDIO
  180838. */
  180839. #if defined(_WIN32_WCE)
  180840. # include <windows.h>
  180841. /* Console I/O functions are not supported on WindowsCE */
  180842. # define PNG_NO_CONSOLE_IO
  180843. # ifdef PNG_DEBUG
  180844. # undef PNG_DEBUG
  180845. # endif
  180846. #endif
  180847. #ifdef PNG_BUILD_DLL
  180848. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180849. # ifndef PNG_NO_CONSOLE_IO
  180850. # define PNG_NO_CONSOLE_IO
  180851. # endif
  180852. # endif
  180853. #endif
  180854. # ifdef PNG_NO_STDIO
  180855. # ifndef PNG_NO_CONSOLE_IO
  180856. # define PNG_NO_CONSOLE_IO
  180857. # endif
  180858. # ifdef PNG_DEBUG
  180859. # if (PNG_DEBUG > 0)
  180860. # include <stdio.h>
  180861. # endif
  180862. # endif
  180863. # else
  180864. # if !defined(_WIN32_WCE)
  180865. /* "stdio.h" functions are not supported on WindowsCE */
  180866. # include <stdio.h>
  180867. # endif
  180868. # endif
  180869. /* This macro protects us against machines that don't have function
  180870. * prototypes (ie K&R style headers). If your compiler does not handle
  180871. * function prototypes, define this macro and use the included ansi2knr.
  180872. * I've always been able to use _NO_PROTO as the indicator, but you may
  180873. * need to drag the empty declaration out in front of here, or change the
  180874. * ifdef to suit your own needs.
  180875. */
  180876. #ifndef PNGARG
  180877. #ifdef OF /* zlib prototype munger */
  180878. # define PNGARG(arglist) OF(arglist)
  180879. #else
  180880. #ifdef _NO_PROTO
  180881. # define PNGARG(arglist) ()
  180882. # ifndef PNG_TYPECAST_NULL
  180883. # define PNG_TYPECAST_NULL
  180884. # endif
  180885. #else
  180886. # define PNGARG(arglist) arglist
  180887. #endif /* _NO_PROTO */
  180888. #endif /* OF */
  180889. #endif /* PNGARG */
  180890. /* Try to determine if we are compiling on a Mac. Note that testing for
  180891. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180892. * on non-Mac platforms.
  180893. */
  180894. #ifndef MACOS
  180895. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180896. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180897. # define MACOS
  180898. # endif
  180899. #endif
  180900. /* enough people need this for various reasons to include it here */
  180901. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180902. # include <sys/types.h>
  180903. #endif
  180904. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180905. # define PNG_SETJMP_SUPPORTED
  180906. #endif
  180907. #ifdef PNG_SETJMP_SUPPORTED
  180908. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180909. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180910. */
  180911. # ifdef __linux__
  180912. # ifdef _BSD_SOURCE
  180913. # define PNG_SAVE_BSD_SOURCE
  180914. # undef _BSD_SOURCE
  180915. # endif
  180916. # ifdef _SETJMP_H
  180917. /* If you encounter a compiler error here, see the explanation
  180918. * near the end of INSTALL.
  180919. */
  180920. __png.h__ already includes setjmp.h;
  180921. __dont__ include it again.;
  180922. # endif
  180923. # endif /* __linux__ */
  180924. /* include setjmp.h for error handling */
  180925. # include <setjmp.h>
  180926. # ifdef __linux__
  180927. # ifdef PNG_SAVE_BSD_SOURCE
  180928. # define _BSD_SOURCE
  180929. # undef PNG_SAVE_BSD_SOURCE
  180930. # endif
  180931. # endif /* __linux__ */
  180932. #endif /* PNG_SETJMP_SUPPORTED */
  180933. #ifdef BSD
  180934. #if ! JUCE_MAC
  180935. # include <strings.h>
  180936. #endif
  180937. #else
  180938. # include <string.h>
  180939. #endif
  180940. /* Other defines for things like memory and the like can go here. */
  180941. #ifdef PNG_INTERNAL
  180942. #include <stdlib.h>
  180943. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180944. * aren't usually used outside the library (as far as I know), so it is
  180945. * debatable if they should be exported at all. In the future, when it is
  180946. * possible to have run-time registry of chunk-handling functions, some of
  180947. * these will be made available again.
  180948. #define PNG_EXTERN extern
  180949. */
  180950. #define PNG_EXTERN
  180951. /* Other defines specific to compilers can go here. Try to keep
  180952. * them inside an appropriate ifdef/endif pair for portability.
  180953. */
  180954. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180955. # if defined(MACOS)
  180956. /* We need to check that <math.h> hasn't already been included earlier
  180957. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180958. * <fp.h> if possible.
  180959. */
  180960. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180961. # include <fp.h>
  180962. # endif
  180963. # else
  180964. # include <math.h>
  180965. # endif
  180966. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180967. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180968. * MATH=68881
  180969. */
  180970. # include <m68881.h>
  180971. # endif
  180972. #endif
  180973. /* Codewarrior on NT has linking problems without this. */
  180974. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180975. # define PNG_ALWAYS_EXTERN
  180976. #endif
  180977. /* This provides the non-ANSI (far) memory allocation routines. */
  180978. #if defined(__TURBOC__) && defined(__MSDOS__)
  180979. # include <mem.h>
  180980. # include <alloc.h>
  180981. #endif
  180982. /* I have no idea why is this necessary... */
  180983. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180984. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180985. # include <malloc.h>
  180986. #endif
  180987. /* This controls how fine the dithering gets. As this allocates
  180988. * a largish chunk of memory (32K), those who are not as concerned
  180989. * with dithering quality can decrease some or all of these.
  180990. */
  180991. #ifndef PNG_DITHER_RED_BITS
  180992. # define PNG_DITHER_RED_BITS 5
  180993. #endif
  180994. #ifndef PNG_DITHER_GREEN_BITS
  180995. # define PNG_DITHER_GREEN_BITS 5
  180996. #endif
  180997. #ifndef PNG_DITHER_BLUE_BITS
  180998. # define PNG_DITHER_BLUE_BITS 5
  180999. #endif
  181000. /* This controls how fine the gamma correction becomes when you
  181001. * are only interested in 8 bits anyway. Increasing this value
  181002. * results in more memory being used, and more pow() functions
  181003. * being called to fill in the gamma tables. Don't set this value
  181004. * less then 8, and even that may not work (I haven't tested it).
  181005. */
  181006. #ifndef PNG_MAX_GAMMA_8
  181007. # define PNG_MAX_GAMMA_8 11
  181008. #endif
  181009. /* This controls how much a difference in gamma we can tolerate before
  181010. * we actually start doing gamma conversion.
  181011. */
  181012. #ifndef PNG_GAMMA_THRESHOLD
  181013. # define PNG_GAMMA_THRESHOLD 0.05
  181014. #endif
  181015. #endif /* PNG_INTERNAL */
  181016. /* The following uses const char * instead of char * for error
  181017. * and warning message functions, so some compilers won't complain.
  181018. * If you do not want to use const, define PNG_NO_CONST here.
  181019. */
  181020. #ifndef PNG_NO_CONST
  181021. # define PNG_CONST const
  181022. #else
  181023. # define PNG_CONST
  181024. #endif
  181025. /* The following defines give you the ability to remove code from the
  181026. * library that you will not be using. I wish I could figure out how to
  181027. * automate this, but I can't do that without making it seriously hard
  181028. * on the users. So if you are not using an ability, change the #define
  181029. * to and #undef, and that part of the library will not be compiled. If
  181030. * your linker can't find a function, you may want to make sure the
  181031. * ability is defined here. Some of these depend upon some others being
  181032. * defined. I haven't figured out all the interactions here, so you may
  181033. * have to experiment awhile to get everything to compile. If you are
  181034. * creating or using a shared library, you probably shouldn't touch this,
  181035. * as it will affect the size of the structures, and this will cause bad
  181036. * things to happen if the library and/or application ever change.
  181037. */
  181038. /* Any features you will not be using can be undef'ed here */
  181039. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  181040. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  181041. * on the compile line, then pick and choose which ones to define without
  181042. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181043. * if you only want to have a png-compliant reader/writer but don't need
  181044. * any of the extra transformations. This saves about 80 kbytes in a
  181045. * typical installation of the library. (PNG_NO_* form added in version
  181046. * 1.0.1c, for consistency)
  181047. */
  181048. /* The size of the png_text structure changed in libpng-1.0.6 when
  181049. * iTXt support was added. iTXt support was turned off by default through
  181050. * libpng-1.2.x, to support old apps that malloc the png_text structure
  181051. * instead of calling png_set_text() and letting libpng malloc it. It
  181052. * was turned on by default in libpng-1.3.0.
  181053. */
  181054. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181055. # ifndef PNG_NO_iTXt_SUPPORTED
  181056. # define PNG_NO_iTXt_SUPPORTED
  181057. # endif
  181058. # ifndef PNG_NO_READ_iTXt
  181059. # define PNG_NO_READ_iTXt
  181060. # endif
  181061. # ifndef PNG_NO_WRITE_iTXt
  181062. # define PNG_NO_WRITE_iTXt
  181063. # endif
  181064. #endif
  181065. #if !defined(PNG_NO_iTXt_SUPPORTED)
  181066. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181067. # define PNG_READ_iTXt
  181068. # endif
  181069. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181070. # define PNG_WRITE_iTXt
  181071. # endif
  181072. #endif
  181073. /* The following support, added after version 1.0.0, can be turned off here en
  181074. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181075. * with old applications that require the length of png_struct and png_info
  181076. * to remain unchanged.
  181077. */
  181078. #ifdef PNG_LEGACY_SUPPORTED
  181079. # define PNG_NO_FREE_ME
  181080. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181081. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181082. # define PNG_NO_READ_USER_CHUNKS
  181083. # define PNG_NO_READ_iCCP
  181084. # define PNG_NO_WRITE_iCCP
  181085. # define PNG_NO_READ_iTXt
  181086. # define PNG_NO_WRITE_iTXt
  181087. # define PNG_NO_READ_sCAL
  181088. # define PNG_NO_WRITE_sCAL
  181089. # define PNG_NO_READ_sPLT
  181090. # define PNG_NO_WRITE_sPLT
  181091. # define PNG_NO_INFO_IMAGE
  181092. # define PNG_NO_READ_RGB_TO_GRAY
  181093. # define PNG_NO_READ_USER_TRANSFORM
  181094. # define PNG_NO_WRITE_USER_TRANSFORM
  181095. # define PNG_NO_USER_MEM
  181096. # define PNG_NO_READ_EMPTY_PLTE
  181097. # define PNG_NO_MNG_FEATURES
  181098. # define PNG_NO_FIXED_POINT_SUPPORTED
  181099. #endif
  181100. /* Ignore attempt to turn off both floating and fixed point support */
  181101. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181102. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181103. # define PNG_FIXED_POINT_SUPPORTED
  181104. #endif
  181105. #ifndef PNG_NO_FREE_ME
  181106. # define PNG_FREE_ME_SUPPORTED
  181107. #endif
  181108. #if defined(PNG_READ_SUPPORTED)
  181109. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181110. !defined(PNG_NO_READ_TRANSFORMS)
  181111. # define PNG_READ_TRANSFORMS_SUPPORTED
  181112. #endif
  181113. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181114. # ifndef PNG_NO_READ_EXPAND
  181115. # define PNG_READ_EXPAND_SUPPORTED
  181116. # endif
  181117. # ifndef PNG_NO_READ_SHIFT
  181118. # define PNG_READ_SHIFT_SUPPORTED
  181119. # endif
  181120. # ifndef PNG_NO_READ_PACK
  181121. # define PNG_READ_PACK_SUPPORTED
  181122. # endif
  181123. # ifndef PNG_NO_READ_BGR
  181124. # define PNG_READ_BGR_SUPPORTED
  181125. # endif
  181126. # ifndef PNG_NO_READ_SWAP
  181127. # define PNG_READ_SWAP_SUPPORTED
  181128. # endif
  181129. # ifndef PNG_NO_READ_PACKSWAP
  181130. # define PNG_READ_PACKSWAP_SUPPORTED
  181131. # endif
  181132. # ifndef PNG_NO_READ_INVERT
  181133. # define PNG_READ_INVERT_SUPPORTED
  181134. # endif
  181135. # ifndef PNG_NO_READ_DITHER
  181136. # define PNG_READ_DITHER_SUPPORTED
  181137. # endif
  181138. # ifndef PNG_NO_READ_BACKGROUND
  181139. # define PNG_READ_BACKGROUND_SUPPORTED
  181140. # endif
  181141. # ifndef PNG_NO_READ_16_TO_8
  181142. # define PNG_READ_16_TO_8_SUPPORTED
  181143. # endif
  181144. # ifndef PNG_NO_READ_FILLER
  181145. # define PNG_READ_FILLER_SUPPORTED
  181146. # endif
  181147. # ifndef PNG_NO_READ_GAMMA
  181148. # define PNG_READ_GAMMA_SUPPORTED
  181149. # endif
  181150. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181151. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181152. # endif
  181153. # ifndef PNG_NO_READ_SWAP_ALPHA
  181154. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181155. # endif
  181156. # ifndef PNG_NO_READ_INVERT_ALPHA
  181157. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181158. # endif
  181159. # ifndef PNG_NO_READ_STRIP_ALPHA
  181160. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181161. # endif
  181162. # ifndef PNG_NO_READ_USER_TRANSFORM
  181163. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181164. # endif
  181165. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181166. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181167. # endif
  181168. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181169. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181170. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181171. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181172. #endif /* about interlacing capability! You'll */
  181173. /* still have interlacing unless you change the following line: */
  181174. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181175. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181176. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181177. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181178. # endif
  181179. #endif
  181180. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181181. /* Deprecated, will be removed from version 2.0.0.
  181182. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181183. #ifndef PNG_NO_READ_EMPTY_PLTE
  181184. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181185. #endif
  181186. #endif
  181187. #endif /* PNG_READ_SUPPORTED */
  181188. #if defined(PNG_WRITE_SUPPORTED)
  181189. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181190. !defined(PNG_NO_WRITE_TRANSFORMS)
  181191. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181192. #endif
  181193. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181194. # ifndef PNG_NO_WRITE_SHIFT
  181195. # define PNG_WRITE_SHIFT_SUPPORTED
  181196. # endif
  181197. # ifndef PNG_NO_WRITE_PACK
  181198. # define PNG_WRITE_PACK_SUPPORTED
  181199. # endif
  181200. # ifndef PNG_NO_WRITE_BGR
  181201. # define PNG_WRITE_BGR_SUPPORTED
  181202. # endif
  181203. # ifndef PNG_NO_WRITE_SWAP
  181204. # define PNG_WRITE_SWAP_SUPPORTED
  181205. # endif
  181206. # ifndef PNG_NO_WRITE_PACKSWAP
  181207. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181208. # endif
  181209. # ifndef PNG_NO_WRITE_INVERT
  181210. # define PNG_WRITE_INVERT_SUPPORTED
  181211. # endif
  181212. # ifndef PNG_NO_WRITE_FILLER
  181213. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181214. # endif
  181215. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181216. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181217. # endif
  181218. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181219. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181220. # endif
  181221. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181222. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181223. # endif
  181224. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181225. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181226. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181227. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181228. encoders, but can cause trouble
  181229. if left undefined */
  181230. #endif
  181231. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181232. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181233. defined(PNG_FLOATING_POINT_SUPPORTED)
  181234. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181235. #endif
  181236. #ifndef PNG_NO_WRITE_FLUSH
  181237. # define PNG_WRITE_FLUSH_SUPPORTED
  181238. #endif
  181239. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181240. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181241. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181242. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181243. #endif
  181244. #endif
  181245. #endif /* PNG_WRITE_SUPPORTED */
  181246. #ifndef PNG_1_0_X
  181247. # ifndef PNG_NO_ERROR_NUMBERS
  181248. # define PNG_ERROR_NUMBERS_SUPPORTED
  181249. # endif
  181250. #endif /* PNG_1_0_X */
  181251. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181252. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181253. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181254. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181255. # endif
  181256. #endif
  181257. #ifndef PNG_NO_STDIO
  181258. # define PNG_TIME_RFC1123_SUPPORTED
  181259. #endif
  181260. /* This adds extra functions in pngget.c for accessing data from the
  181261. * info pointer (added in version 0.99)
  181262. * png_get_image_width()
  181263. * png_get_image_height()
  181264. * png_get_bit_depth()
  181265. * png_get_color_type()
  181266. * png_get_compression_type()
  181267. * png_get_filter_type()
  181268. * png_get_interlace_type()
  181269. * png_get_pixel_aspect_ratio()
  181270. * png_get_pixels_per_meter()
  181271. * png_get_x_offset_pixels()
  181272. * png_get_y_offset_pixels()
  181273. * png_get_x_offset_microns()
  181274. * png_get_y_offset_microns()
  181275. */
  181276. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181277. # define PNG_EASY_ACCESS_SUPPORTED
  181278. #endif
  181279. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181280. * and removed from version 1.2.20. The following will be removed
  181281. * from libpng-1.4.0
  181282. */
  181283. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181284. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181285. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181286. # endif
  181287. #endif
  181288. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181289. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181290. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181291. # endif
  181292. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181293. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181294. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181295. # define PNG_NO_MMX_CODE
  181296. # endif
  181297. # endif
  181298. # if defined(__APPLE__)
  181299. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181300. # define PNG_NO_MMX_CODE
  181301. # endif
  181302. # endif
  181303. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181304. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181305. # define PNG_NO_MMX_CODE
  181306. # endif
  181307. # endif
  181308. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181309. # define PNG_MMX_CODE_SUPPORTED
  181310. # endif
  181311. #endif
  181312. /* end of obsolete code to be removed from libpng-1.4.0 */
  181313. #if !defined(PNG_1_0_X)
  181314. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181315. # define PNG_USER_MEM_SUPPORTED
  181316. #endif
  181317. #endif /* PNG_1_0_X */
  181318. /* Added at libpng-1.2.6 */
  181319. #if !defined(PNG_1_0_X)
  181320. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181321. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181322. # define PNG_SET_USER_LIMITS_SUPPORTED
  181323. #endif
  181324. #endif
  181325. #endif /* PNG_1_0_X */
  181326. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181327. * how large, set these limits to 0x7fffffffL
  181328. */
  181329. #ifndef PNG_USER_WIDTH_MAX
  181330. # define PNG_USER_WIDTH_MAX 1000000L
  181331. #endif
  181332. #ifndef PNG_USER_HEIGHT_MAX
  181333. # define PNG_USER_HEIGHT_MAX 1000000L
  181334. #endif
  181335. /* These are currently experimental features, define them if you want */
  181336. /* very little testing */
  181337. /*
  181338. #ifdef PNG_READ_SUPPORTED
  181339. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181340. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181341. # endif
  181342. #endif
  181343. */
  181344. /* This is only for PowerPC big-endian and 680x0 systems */
  181345. /* some testing */
  181346. /*
  181347. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181348. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181349. #endif
  181350. */
  181351. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181352. /*
  181353. #define PNG_NO_POINTER_INDEXING
  181354. */
  181355. /* These functions are turned off by default, as they will be phased out. */
  181356. /*
  181357. #define PNG_USELESS_TESTS_SUPPORTED
  181358. #define PNG_CORRECT_PALETTE_SUPPORTED
  181359. */
  181360. /* Any chunks you are not interested in, you can undef here. The
  181361. * ones that allocate memory may be expecially important (hIST,
  181362. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181363. * a bit smaller.
  181364. */
  181365. #if defined(PNG_READ_SUPPORTED) && \
  181366. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181367. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181368. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181369. #endif
  181370. #if defined(PNG_WRITE_SUPPORTED) && \
  181371. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181372. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181373. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181374. #endif
  181375. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181376. #ifdef PNG_NO_READ_TEXT
  181377. # define PNG_NO_READ_iTXt
  181378. # define PNG_NO_READ_tEXt
  181379. # define PNG_NO_READ_zTXt
  181380. #endif
  181381. #ifndef PNG_NO_READ_bKGD
  181382. # define PNG_READ_bKGD_SUPPORTED
  181383. # define PNG_bKGD_SUPPORTED
  181384. #endif
  181385. #ifndef PNG_NO_READ_cHRM
  181386. # define PNG_READ_cHRM_SUPPORTED
  181387. # define PNG_cHRM_SUPPORTED
  181388. #endif
  181389. #ifndef PNG_NO_READ_gAMA
  181390. # define PNG_READ_gAMA_SUPPORTED
  181391. # define PNG_gAMA_SUPPORTED
  181392. #endif
  181393. #ifndef PNG_NO_READ_hIST
  181394. # define PNG_READ_hIST_SUPPORTED
  181395. # define PNG_hIST_SUPPORTED
  181396. #endif
  181397. #ifndef PNG_NO_READ_iCCP
  181398. # define PNG_READ_iCCP_SUPPORTED
  181399. # define PNG_iCCP_SUPPORTED
  181400. #endif
  181401. #ifndef PNG_NO_READ_iTXt
  181402. # ifndef PNG_READ_iTXt_SUPPORTED
  181403. # define PNG_READ_iTXt_SUPPORTED
  181404. # endif
  181405. # ifndef PNG_iTXt_SUPPORTED
  181406. # define PNG_iTXt_SUPPORTED
  181407. # endif
  181408. #endif
  181409. #ifndef PNG_NO_READ_oFFs
  181410. # define PNG_READ_oFFs_SUPPORTED
  181411. # define PNG_oFFs_SUPPORTED
  181412. #endif
  181413. #ifndef PNG_NO_READ_pCAL
  181414. # define PNG_READ_pCAL_SUPPORTED
  181415. # define PNG_pCAL_SUPPORTED
  181416. #endif
  181417. #ifndef PNG_NO_READ_sCAL
  181418. # define PNG_READ_sCAL_SUPPORTED
  181419. # define PNG_sCAL_SUPPORTED
  181420. #endif
  181421. #ifndef PNG_NO_READ_pHYs
  181422. # define PNG_READ_pHYs_SUPPORTED
  181423. # define PNG_pHYs_SUPPORTED
  181424. #endif
  181425. #ifndef PNG_NO_READ_sBIT
  181426. # define PNG_READ_sBIT_SUPPORTED
  181427. # define PNG_sBIT_SUPPORTED
  181428. #endif
  181429. #ifndef PNG_NO_READ_sPLT
  181430. # define PNG_READ_sPLT_SUPPORTED
  181431. # define PNG_sPLT_SUPPORTED
  181432. #endif
  181433. #ifndef PNG_NO_READ_sRGB
  181434. # define PNG_READ_sRGB_SUPPORTED
  181435. # define PNG_sRGB_SUPPORTED
  181436. #endif
  181437. #ifndef PNG_NO_READ_tEXt
  181438. # define PNG_READ_tEXt_SUPPORTED
  181439. # define PNG_tEXt_SUPPORTED
  181440. #endif
  181441. #ifndef PNG_NO_READ_tIME
  181442. # define PNG_READ_tIME_SUPPORTED
  181443. # define PNG_tIME_SUPPORTED
  181444. #endif
  181445. #ifndef PNG_NO_READ_tRNS
  181446. # define PNG_READ_tRNS_SUPPORTED
  181447. # define PNG_tRNS_SUPPORTED
  181448. #endif
  181449. #ifndef PNG_NO_READ_zTXt
  181450. # define PNG_READ_zTXt_SUPPORTED
  181451. # define PNG_zTXt_SUPPORTED
  181452. #endif
  181453. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181454. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181455. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181456. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181457. # endif
  181458. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181459. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181460. # endif
  181461. #endif
  181462. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181463. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181464. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181465. # define PNG_USER_CHUNKS_SUPPORTED
  181466. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181467. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181468. # endif
  181469. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181470. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181471. # endif
  181472. #endif
  181473. #ifndef PNG_NO_READ_OPT_PLTE
  181474. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181475. #endif /* optional PLTE chunk in RGB and RGBA images */
  181476. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181477. defined(PNG_READ_zTXt_SUPPORTED)
  181478. # define PNG_READ_TEXT_SUPPORTED
  181479. # define PNG_TEXT_SUPPORTED
  181480. #endif
  181481. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181482. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181483. #ifdef PNG_NO_WRITE_TEXT
  181484. # define PNG_NO_WRITE_iTXt
  181485. # define PNG_NO_WRITE_tEXt
  181486. # define PNG_NO_WRITE_zTXt
  181487. #endif
  181488. #ifndef PNG_NO_WRITE_bKGD
  181489. # define PNG_WRITE_bKGD_SUPPORTED
  181490. # ifndef PNG_bKGD_SUPPORTED
  181491. # define PNG_bKGD_SUPPORTED
  181492. # endif
  181493. #endif
  181494. #ifndef PNG_NO_WRITE_cHRM
  181495. # define PNG_WRITE_cHRM_SUPPORTED
  181496. # ifndef PNG_cHRM_SUPPORTED
  181497. # define PNG_cHRM_SUPPORTED
  181498. # endif
  181499. #endif
  181500. #ifndef PNG_NO_WRITE_gAMA
  181501. # define PNG_WRITE_gAMA_SUPPORTED
  181502. # ifndef PNG_gAMA_SUPPORTED
  181503. # define PNG_gAMA_SUPPORTED
  181504. # endif
  181505. #endif
  181506. #ifndef PNG_NO_WRITE_hIST
  181507. # define PNG_WRITE_hIST_SUPPORTED
  181508. # ifndef PNG_hIST_SUPPORTED
  181509. # define PNG_hIST_SUPPORTED
  181510. # endif
  181511. #endif
  181512. #ifndef PNG_NO_WRITE_iCCP
  181513. # define PNG_WRITE_iCCP_SUPPORTED
  181514. # ifndef PNG_iCCP_SUPPORTED
  181515. # define PNG_iCCP_SUPPORTED
  181516. # endif
  181517. #endif
  181518. #ifndef PNG_NO_WRITE_iTXt
  181519. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181520. # define PNG_WRITE_iTXt_SUPPORTED
  181521. # endif
  181522. # ifndef PNG_iTXt_SUPPORTED
  181523. # define PNG_iTXt_SUPPORTED
  181524. # endif
  181525. #endif
  181526. #ifndef PNG_NO_WRITE_oFFs
  181527. # define PNG_WRITE_oFFs_SUPPORTED
  181528. # ifndef PNG_oFFs_SUPPORTED
  181529. # define PNG_oFFs_SUPPORTED
  181530. # endif
  181531. #endif
  181532. #ifndef PNG_NO_WRITE_pCAL
  181533. # define PNG_WRITE_pCAL_SUPPORTED
  181534. # ifndef PNG_pCAL_SUPPORTED
  181535. # define PNG_pCAL_SUPPORTED
  181536. # endif
  181537. #endif
  181538. #ifndef PNG_NO_WRITE_sCAL
  181539. # define PNG_WRITE_sCAL_SUPPORTED
  181540. # ifndef PNG_sCAL_SUPPORTED
  181541. # define PNG_sCAL_SUPPORTED
  181542. # endif
  181543. #endif
  181544. #ifndef PNG_NO_WRITE_pHYs
  181545. # define PNG_WRITE_pHYs_SUPPORTED
  181546. # ifndef PNG_pHYs_SUPPORTED
  181547. # define PNG_pHYs_SUPPORTED
  181548. # endif
  181549. #endif
  181550. #ifndef PNG_NO_WRITE_sBIT
  181551. # define PNG_WRITE_sBIT_SUPPORTED
  181552. # ifndef PNG_sBIT_SUPPORTED
  181553. # define PNG_sBIT_SUPPORTED
  181554. # endif
  181555. #endif
  181556. #ifndef PNG_NO_WRITE_sPLT
  181557. # define PNG_WRITE_sPLT_SUPPORTED
  181558. # ifndef PNG_sPLT_SUPPORTED
  181559. # define PNG_sPLT_SUPPORTED
  181560. # endif
  181561. #endif
  181562. #ifndef PNG_NO_WRITE_sRGB
  181563. # define PNG_WRITE_sRGB_SUPPORTED
  181564. # ifndef PNG_sRGB_SUPPORTED
  181565. # define PNG_sRGB_SUPPORTED
  181566. # endif
  181567. #endif
  181568. #ifndef PNG_NO_WRITE_tEXt
  181569. # define PNG_WRITE_tEXt_SUPPORTED
  181570. # ifndef PNG_tEXt_SUPPORTED
  181571. # define PNG_tEXt_SUPPORTED
  181572. # endif
  181573. #endif
  181574. #ifndef PNG_NO_WRITE_tIME
  181575. # define PNG_WRITE_tIME_SUPPORTED
  181576. # ifndef PNG_tIME_SUPPORTED
  181577. # define PNG_tIME_SUPPORTED
  181578. # endif
  181579. #endif
  181580. #ifndef PNG_NO_WRITE_tRNS
  181581. # define PNG_WRITE_tRNS_SUPPORTED
  181582. # ifndef PNG_tRNS_SUPPORTED
  181583. # define PNG_tRNS_SUPPORTED
  181584. # endif
  181585. #endif
  181586. #ifndef PNG_NO_WRITE_zTXt
  181587. # define PNG_WRITE_zTXt_SUPPORTED
  181588. # ifndef PNG_zTXt_SUPPORTED
  181589. # define PNG_zTXt_SUPPORTED
  181590. # endif
  181591. #endif
  181592. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181593. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181594. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181595. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181596. # endif
  181597. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181598. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181599. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181600. # endif
  181601. # endif
  181602. #endif
  181603. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181604. defined(PNG_WRITE_zTXt_SUPPORTED)
  181605. # define PNG_WRITE_TEXT_SUPPORTED
  181606. # ifndef PNG_TEXT_SUPPORTED
  181607. # define PNG_TEXT_SUPPORTED
  181608. # endif
  181609. #endif
  181610. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181611. /* Turn this off to disable png_read_png() and
  181612. * png_write_png() and leave the row_pointers member
  181613. * out of the info structure.
  181614. */
  181615. #ifndef PNG_NO_INFO_IMAGE
  181616. # define PNG_INFO_IMAGE_SUPPORTED
  181617. #endif
  181618. /* need the time information for reading tIME chunks */
  181619. #if defined(PNG_tIME_SUPPORTED)
  181620. # if !defined(_WIN32_WCE)
  181621. /* "time.h" functions are not supported on WindowsCE */
  181622. # include <time.h>
  181623. # endif
  181624. #endif
  181625. /* Some typedefs to get us started. These should be safe on most of the
  181626. * common platforms. The typedefs should be at least as large as the
  181627. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181628. * don't have to be exactly that size. Some compilers dislike passing
  181629. * unsigned shorts as function parameters, so you may be better off using
  181630. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181631. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181632. */
  181633. typedef unsigned long png_uint_32;
  181634. typedef long png_int_32;
  181635. typedef unsigned short png_uint_16;
  181636. typedef short png_int_16;
  181637. typedef unsigned char png_byte;
  181638. /* This is usually size_t. It is typedef'ed just in case you need it to
  181639. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181640. #ifdef PNG_SIZE_T
  181641. typedef PNG_SIZE_T png_size_t;
  181642. # define png_sizeof(x) png_convert_size(sizeof (x))
  181643. #else
  181644. typedef size_t png_size_t;
  181645. # define png_sizeof(x) sizeof (x)
  181646. #endif
  181647. /* The following is needed for medium model support. It cannot be in the
  181648. * PNG_INTERNAL section. Needs modification for other compilers besides
  181649. * MSC. Model independent support declares all arrays and pointers to be
  181650. * large using the far keyword. The zlib version used must also support
  181651. * model independent data. As of version zlib 1.0.4, the necessary changes
  181652. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181653. * changes that are needed. (Tim Wegner)
  181654. */
  181655. /* Separate compiler dependencies (problem here is that zlib.h always
  181656. defines FAR. (SJT) */
  181657. #ifdef __BORLANDC__
  181658. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181659. # define LDATA 1
  181660. # else
  181661. # define LDATA 0
  181662. # endif
  181663. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181664. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181665. # define PNG_MAX_MALLOC_64K
  181666. # if (LDATA != 1)
  181667. # ifndef FAR
  181668. # define FAR __far
  181669. # endif
  181670. # define USE_FAR_KEYWORD
  181671. # endif /* LDATA != 1 */
  181672. /* Possibly useful for moving data out of default segment.
  181673. * Uncomment it if you want. Could also define FARDATA as
  181674. * const if your compiler supports it. (SJT)
  181675. # define FARDATA FAR
  181676. */
  181677. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181678. #endif /* __BORLANDC__ */
  181679. /* Suggest testing for specific compiler first before testing for
  181680. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181681. * making reliance oncertain keywords suspect. (SJT)
  181682. */
  181683. /* MSC Medium model */
  181684. #if defined(FAR)
  181685. # if defined(M_I86MM)
  181686. # define USE_FAR_KEYWORD
  181687. # define FARDATA FAR
  181688. # include <dos.h>
  181689. # endif
  181690. #endif
  181691. /* SJT: default case */
  181692. #ifndef FAR
  181693. # define FAR
  181694. #endif
  181695. /* At this point FAR is always defined */
  181696. #ifndef FARDATA
  181697. # define FARDATA
  181698. #endif
  181699. /* Typedef for floating-point numbers that are converted
  181700. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181701. typedef png_int_32 png_fixed_point;
  181702. /* Add typedefs for pointers */
  181703. typedef void FAR * png_voidp;
  181704. typedef png_byte FAR * png_bytep;
  181705. typedef png_uint_32 FAR * png_uint_32p;
  181706. typedef png_int_32 FAR * png_int_32p;
  181707. typedef png_uint_16 FAR * png_uint_16p;
  181708. typedef png_int_16 FAR * png_int_16p;
  181709. typedef PNG_CONST char FAR * png_const_charp;
  181710. typedef char FAR * png_charp;
  181711. typedef png_fixed_point FAR * png_fixed_point_p;
  181712. #ifndef PNG_NO_STDIO
  181713. #if defined(_WIN32_WCE)
  181714. typedef HANDLE png_FILE_p;
  181715. #else
  181716. typedef FILE * png_FILE_p;
  181717. #endif
  181718. #endif
  181719. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181720. typedef double FAR * png_doublep;
  181721. #endif
  181722. /* Pointers to pointers; i.e. arrays */
  181723. typedef png_byte FAR * FAR * png_bytepp;
  181724. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181725. typedef png_int_32 FAR * FAR * png_int_32pp;
  181726. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181727. typedef png_int_16 FAR * FAR * png_int_16pp;
  181728. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181729. typedef char FAR * FAR * png_charpp;
  181730. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181731. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181732. typedef double FAR * FAR * png_doublepp;
  181733. #endif
  181734. /* Pointers to pointers to pointers; i.e., pointer to array */
  181735. typedef char FAR * FAR * FAR * png_charppp;
  181736. #if 0
  181737. /* SPC - Is this stuff deprecated? */
  181738. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181739. /* libpng typedefs for types in zlib. If zlib changes
  181740. * or another compression library is used, then change these.
  181741. * Eliminates need to change all the source files.
  181742. */
  181743. typedef charf * png_zcharp;
  181744. typedef charf * FAR * png_zcharpp;
  181745. typedef z_stream FAR * png_zstreamp;
  181746. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181747. /*
  181748. * Define PNG_BUILD_DLL if the module being built is a Windows
  181749. * LIBPNG DLL.
  181750. *
  181751. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181752. * It is equivalent to Microsoft predefined macro _DLL that is
  181753. * automatically defined when you compile using the share
  181754. * version of the CRT (C Run-Time library)
  181755. *
  181756. * The cygwin mods make this behavior a little different:
  181757. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181758. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181759. * -or- if you are building an application that you want to link to the
  181760. * static library.
  181761. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181762. * the other flags is defined.
  181763. */
  181764. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181765. # define PNG_DLL
  181766. #endif
  181767. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181768. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181769. * command-line override
  181770. */
  181771. #if defined(__CYGWIN__)
  181772. # if !defined(PNG_STATIC)
  181773. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181774. # undef PNG_USE_GLOBAL_ARRAYS
  181775. # endif
  181776. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181777. # define PNG_USE_LOCAL_ARRAYS
  181778. # endif
  181779. # else
  181780. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181781. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181782. # undef PNG_USE_GLOBAL_ARRAYS
  181783. # endif
  181784. # endif
  181785. # endif
  181786. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181787. # define PNG_USE_LOCAL_ARRAYS
  181788. # endif
  181789. #endif
  181790. /* Do not use global arrays (helps with building DLL's)
  181791. * They are no longer used in libpng itself, since version 1.0.5c,
  181792. * but might be required for some pre-1.0.5c applications.
  181793. */
  181794. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181795. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181796. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181797. # define PNG_USE_LOCAL_ARRAYS
  181798. # else
  181799. # define PNG_USE_GLOBAL_ARRAYS
  181800. # endif
  181801. #endif
  181802. #if defined(__CYGWIN__)
  181803. # undef PNGAPI
  181804. # define PNGAPI __cdecl
  181805. # undef PNG_IMPEXP
  181806. # define PNG_IMPEXP
  181807. #endif
  181808. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181809. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181810. * Don't ignore those warnings; you must also reset the default calling
  181811. * convention in your compiler to match your PNGAPI, and you must build
  181812. * zlib and your applications the same way you build libpng.
  181813. */
  181814. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181815. # ifndef PNG_NO_MODULEDEF
  181816. # define PNG_NO_MODULEDEF
  181817. # endif
  181818. #endif
  181819. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181820. # define PNG_IMPEXP
  181821. #endif
  181822. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181823. (( defined(_Windows) || defined(_WINDOWS) || \
  181824. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181825. # ifndef PNGAPI
  181826. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181827. # define PNGAPI __cdecl
  181828. # else
  181829. # define PNGAPI _cdecl
  181830. # endif
  181831. # endif
  181832. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181833. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181834. # define PNG_IMPEXP
  181835. # endif
  181836. # if !defined(PNG_IMPEXP)
  181837. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181838. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181839. /* Borland/Microsoft */
  181840. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181841. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181842. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181843. # else
  181844. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181845. # if defined(PNG_BUILD_DLL)
  181846. # define PNG_IMPEXP __export
  181847. # else
  181848. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181849. VC++ */
  181850. # endif /* Exists in Borland C++ for
  181851. C++ classes (== huge) */
  181852. # endif
  181853. # endif
  181854. # if !defined(PNG_IMPEXP)
  181855. # if defined(PNG_BUILD_DLL)
  181856. # define PNG_IMPEXP __declspec(dllexport)
  181857. # else
  181858. # define PNG_IMPEXP __declspec(dllimport)
  181859. # endif
  181860. # endif
  181861. # endif /* PNG_IMPEXP */
  181862. #else /* !(DLL || non-cygwin WINDOWS) */
  181863. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181864. # ifndef PNGAPI
  181865. # define PNGAPI _System
  181866. # endif
  181867. # else
  181868. # if 0 /* ... other platforms, with other meanings */
  181869. # endif
  181870. # endif
  181871. #endif
  181872. #ifndef PNGAPI
  181873. # define PNGAPI
  181874. #endif
  181875. #ifndef PNG_IMPEXP
  181876. # define PNG_IMPEXP
  181877. #endif
  181878. #ifdef PNG_BUILDSYMS
  181879. # ifndef PNG_EXPORT
  181880. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181881. # endif
  181882. # ifdef PNG_USE_GLOBAL_ARRAYS
  181883. # ifndef PNG_EXPORT_VAR
  181884. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181885. # endif
  181886. # endif
  181887. #endif
  181888. #ifndef PNG_EXPORT
  181889. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181890. #endif
  181891. #ifdef PNG_USE_GLOBAL_ARRAYS
  181892. # ifndef PNG_EXPORT_VAR
  181893. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181894. # endif
  181895. #endif
  181896. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181897. * functions that are passed far data must be model independent.
  181898. */
  181899. #ifndef PNG_ABORT
  181900. # define PNG_ABORT() abort()
  181901. #endif
  181902. #ifdef PNG_SETJMP_SUPPORTED
  181903. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181904. #else
  181905. # define png_jmpbuf(png_ptr) \
  181906. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181907. #endif
  181908. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181909. /* use this to make far-to-near assignments */
  181910. # define CHECK 1
  181911. # define NOCHECK 0
  181912. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181913. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181914. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181915. # define png_strcpy _fstrcpy
  181916. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181917. # define png_strlen _fstrlen
  181918. # define png_memcmp _fmemcmp /* SJT: added */
  181919. # define png_memcpy _fmemcpy
  181920. # define png_memset _fmemset
  181921. #else /* use the usual functions */
  181922. # define CVT_PTR(ptr) (ptr)
  181923. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181924. # ifndef PNG_NO_SNPRINTF
  181925. # ifdef _MSC_VER
  181926. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181927. # define png_snprintf2 _snprintf
  181928. # define png_snprintf6 _snprintf
  181929. # else
  181930. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181931. # define png_snprintf2 snprintf
  181932. # define png_snprintf6 snprintf
  181933. # endif
  181934. # else
  181935. /* You don't have or don't want to use snprintf(). Caution: Using
  181936. * sprintf instead of snprintf exposes your application to accidental
  181937. * or malevolent buffer overflows. If you don't have snprintf()
  181938. * as a general rule you should provide one (you can get one from
  181939. * Portable OpenSSH). */
  181940. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181941. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181942. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181943. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181944. # endif
  181945. # define png_strcpy strcpy
  181946. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181947. # define png_strlen strlen
  181948. # define png_memcmp memcmp /* SJT: added */
  181949. # define png_memcpy memcpy
  181950. # define png_memset memset
  181951. #endif
  181952. /* End of memory model independent support */
  181953. /* Just a little check that someone hasn't tried to define something
  181954. * contradictory.
  181955. */
  181956. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181957. # undef PNG_ZBUF_SIZE
  181958. # define PNG_ZBUF_SIZE 65536L
  181959. #endif
  181960. /* Added at libpng-1.2.8 */
  181961. #endif /* PNG_VERSION_INFO_ONLY */
  181962. #endif /* PNGCONF_H */
  181963. /*** End of inlined file: pngconf.h ***/
  181964. #ifdef _MSC_VER
  181965. #pragma warning (disable: 4996 4100)
  181966. #endif
  181967. /*
  181968. * Added at libpng-1.2.8 */
  181969. /* Ref MSDN: Private as priority over Special
  181970. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181971. * procedures. If this value is given, the StringFileInfo block must
  181972. * contain a PrivateBuild string.
  181973. *
  181974. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181975. * standard release procedures but is a variation of the standard
  181976. * file of the same version number. If this value is given, the
  181977. * StringFileInfo block must contain a SpecialBuild string.
  181978. */
  181979. #if defined(PNG_USER_PRIVATEBUILD)
  181980. # define PNG_LIBPNG_BUILD_TYPE \
  181981. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181982. #else
  181983. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181984. # define PNG_LIBPNG_BUILD_TYPE \
  181985. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181986. # else
  181987. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181988. # endif
  181989. #endif
  181990. #ifndef PNG_VERSION_INFO_ONLY
  181991. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181992. #ifdef __cplusplus
  181993. //extern "C" {
  181994. #endif /* __cplusplus */
  181995. /* This file is arranged in several sections. The first section contains
  181996. * structure and type definitions. The second section contains the external
  181997. * library functions, while the third has the internal library functions,
  181998. * which applications aren't expected to use directly.
  181999. */
  182000. #ifndef PNG_NO_TYPECAST_NULL
  182001. #define int_p_NULL (int *)NULL
  182002. #define png_bytep_NULL (png_bytep)NULL
  182003. #define png_bytepp_NULL (png_bytepp)NULL
  182004. #define png_doublep_NULL (png_doublep)NULL
  182005. #define png_error_ptr_NULL (png_error_ptr)NULL
  182006. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  182007. #define png_free_ptr_NULL (png_free_ptr)NULL
  182008. #define png_infopp_NULL (png_infopp)NULL
  182009. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  182010. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  182011. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  182012. #define png_structp_NULL (png_structp)NULL
  182013. #define png_uint_16p_NULL (png_uint_16p)NULL
  182014. #define png_voidp_NULL (png_voidp)NULL
  182015. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  182016. #else
  182017. #define int_p_NULL NULL
  182018. #define png_bytep_NULL NULL
  182019. #define png_bytepp_NULL NULL
  182020. #define png_doublep_NULL NULL
  182021. #define png_error_ptr_NULL NULL
  182022. #define png_flush_ptr_NULL NULL
  182023. #define png_free_ptr_NULL NULL
  182024. #define png_infopp_NULL NULL
  182025. #define png_malloc_ptr_NULL NULL
  182026. #define png_read_status_ptr_NULL NULL
  182027. #define png_rw_ptr_NULL NULL
  182028. #define png_structp_NULL NULL
  182029. #define png_uint_16p_NULL NULL
  182030. #define png_voidp_NULL NULL
  182031. #define png_write_status_ptr_NULL NULL
  182032. #endif
  182033. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182034. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182035. /* Version information for C files, stored in png.c. This had better match
  182036. * the version above.
  182037. */
  182038. #ifdef PNG_USE_GLOBAL_ARRAYS
  182039. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  182040. /* need room for 99.99.99beta99z */
  182041. #else
  182042. #define png_libpng_ver png_get_header_ver(NULL)
  182043. #endif
  182044. #ifdef PNG_USE_GLOBAL_ARRAYS
  182045. /* This was removed in version 1.0.5c */
  182046. /* Structures to facilitate easy interlacing. See png.c for more details */
  182047. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182048. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  182049. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  182050. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  182051. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  182052. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  182053. /* This isn't currently used. If you need it, see png.c for more details.
  182054. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  182055. */
  182056. #endif
  182057. #endif /* PNG_NO_EXTERN */
  182058. /* Three color definitions. The order of the red, green, and blue, (and the
  182059. * exact size) is not important, although the size of the fields need to
  182060. * be png_byte or png_uint_16 (as defined below).
  182061. */
  182062. typedef struct png_color_struct
  182063. {
  182064. png_byte red;
  182065. png_byte green;
  182066. png_byte blue;
  182067. } png_color;
  182068. typedef png_color FAR * png_colorp;
  182069. typedef png_color FAR * FAR * png_colorpp;
  182070. typedef struct png_color_16_struct
  182071. {
  182072. png_byte index; /* used for palette files */
  182073. png_uint_16 red; /* for use in red green blue files */
  182074. png_uint_16 green;
  182075. png_uint_16 blue;
  182076. png_uint_16 gray; /* for use in grayscale files */
  182077. } png_color_16;
  182078. typedef png_color_16 FAR * png_color_16p;
  182079. typedef png_color_16 FAR * FAR * png_color_16pp;
  182080. typedef struct png_color_8_struct
  182081. {
  182082. png_byte red; /* for use in red green blue files */
  182083. png_byte green;
  182084. png_byte blue;
  182085. png_byte gray; /* for use in grayscale files */
  182086. png_byte alpha; /* for alpha channel files */
  182087. } png_color_8;
  182088. typedef png_color_8 FAR * png_color_8p;
  182089. typedef png_color_8 FAR * FAR * png_color_8pp;
  182090. /*
  182091. * The following two structures are used for the in-core representation
  182092. * of sPLT chunks.
  182093. */
  182094. typedef struct png_sPLT_entry_struct
  182095. {
  182096. png_uint_16 red;
  182097. png_uint_16 green;
  182098. png_uint_16 blue;
  182099. png_uint_16 alpha;
  182100. png_uint_16 frequency;
  182101. } png_sPLT_entry;
  182102. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182103. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182104. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182105. * occupy the LSB of their respective members, and the MSB of each member
  182106. * is zero-filled. The frequency member always occupies the full 16 bits.
  182107. */
  182108. typedef struct png_sPLT_struct
  182109. {
  182110. png_charp name; /* palette name */
  182111. png_byte depth; /* depth of palette samples */
  182112. png_sPLT_entryp entries; /* palette entries */
  182113. png_int_32 nentries; /* number of palette entries */
  182114. } png_sPLT_t;
  182115. typedef png_sPLT_t FAR * png_sPLT_tp;
  182116. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182117. #ifdef PNG_TEXT_SUPPORTED
  182118. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182119. * and whether that contents is compressed or not. The "key" field
  182120. * points to a regular zero-terminated C string. The "text", "lang", and
  182121. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182122. * However, the * structure returned by png_get_text() will always contain
  182123. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182124. * so they can be safely used in printf() and other string-handling functions.
  182125. */
  182126. typedef struct png_text_struct
  182127. {
  182128. int compression; /* compression value:
  182129. -1: tEXt, none
  182130. 0: zTXt, deflate
  182131. 1: iTXt, none
  182132. 2: iTXt, deflate */
  182133. png_charp key; /* keyword, 1-79 character description of "text" */
  182134. png_charp text; /* comment, may be an empty string (ie "")
  182135. or a NULL pointer */
  182136. png_size_t text_length; /* length of the text string */
  182137. #ifdef PNG_iTXt_SUPPORTED
  182138. png_size_t itxt_length; /* length of the itxt string */
  182139. png_charp lang; /* language code, 0-79 characters
  182140. or a NULL pointer */
  182141. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182142. chars or a NULL pointer */
  182143. #endif
  182144. } png_text;
  182145. typedef png_text FAR * png_textp;
  182146. typedef png_text FAR * FAR * png_textpp;
  182147. #endif
  182148. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182149. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182150. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182151. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182152. #define PNG_TEXT_COMPRESSION_NONE -1
  182153. #define PNG_TEXT_COMPRESSION_zTXt 0
  182154. #define PNG_ITXT_COMPRESSION_NONE 1
  182155. #define PNG_ITXT_COMPRESSION_zTXt 2
  182156. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182157. /* png_time is a way to hold the time in an machine independent way.
  182158. * Two conversions are provided, both from time_t and struct tm. There
  182159. * is no portable way to convert to either of these structures, as far
  182160. * as I know. If you know of a portable way, send it to me. As a side
  182161. * note - PNG has always been Year 2000 compliant!
  182162. */
  182163. typedef struct png_time_struct
  182164. {
  182165. png_uint_16 year; /* full year, as in, 1995 */
  182166. png_byte month; /* month of year, 1 - 12 */
  182167. png_byte day; /* day of month, 1 - 31 */
  182168. png_byte hour; /* hour of day, 0 - 23 */
  182169. png_byte minute; /* minute of hour, 0 - 59 */
  182170. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182171. } png_time;
  182172. typedef png_time FAR * png_timep;
  182173. typedef png_time FAR * FAR * png_timepp;
  182174. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182175. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182176. * no specific support. The idea is that we can use this to queue
  182177. * up private chunks for output even though the library doesn't actually
  182178. * know about their semantics.
  182179. */
  182180. typedef struct png_unknown_chunk_t
  182181. {
  182182. png_byte name[5];
  182183. png_byte *data;
  182184. png_size_t size;
  182185. /* libpng-using applications should NOT directly modify this byte. */
  182186. png_byte location; /* mode of operation at read time */
  182187. }
  182188. png_unknown_chunk;
  182189. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182190. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182191. #endif
  182192. /* png_info is a structure that holds the information in a PNG file so
  182193. * that the application can find out the characteristics of the image.
  182194. * If you are reading the file, this structure will tell you what is
  182195. * in the PNG file. If you are writing the file, fill in the information
  182196. * you want to put into the PNG file, then call png_write_info().
  182197. * The names chosen should be very close to the PNG specification, so
  182198. * consult that document for information about the meaning of each field.
  182199. *
  182200. * With libpng < 0.95, it was only possible to directly set and read the
  182201. * the values in the png_info_struct, which meant that the contents and
  182202. * order of the values had to remain fixed. With libpng 0.95 and later,
  182203. * however, there are now functions that abstract the contents of
  182204. * png_info_struct from the application, so this makes it easier to use
  182205. * libpng with dynamic libraries, and even makes it possible to use
  182206. * libraries that don't have all of the libpng ancillary chunk-handing
  182207. * functionality.
  182208. *
  182209. * In any case, the order of the parameters in png_info_struct should NOT
  182210. * be changed for as long as possible to keep compatibility with applications
  182211. * that use the old direct-access method with png_info_struct.
  182212. *
  182213. * The following members may have allocated storage attached that should be
  182214. * cleaned up before the structure is discarded: palette, trans, text,
  182215. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182216. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182217. * are automatically freed when the info structure is deallocated, if they were
  182218. * allocated internally by libpng. This behavior can be changed by means
  182219. * of the png_data_freer() function.
  182220. *
  182221. * More allocation details: all the chunk-reading functions that
  182222. * change these members go through the corresponding png_set_*
  182223. * functions. A function to clear these members is available: see
  182224. * png_free_data(). The png_set_* functions do not depend on being
  182225. * able to point info structure members to any of the storage they are
  182226. * passed (they make their own copies), EXCEPT that the png_set_text
  182227. * functions use the same storage passed to them in the text_ptr or
  182228. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182229. * functions do not make their own copies.
  182230. */
  182231. typedef struct png_info_struct
  182232. {
  182233. /* the following are necessary for every PNG file */
  182234. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182235. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182236. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182237. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182238. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182239. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182240. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182241. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182242. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182243. /* The following three should have been named *_method not *_type */
  182244. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182245. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182246. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182247. /* The following is informational only on read, and not used on writes. */
  182248. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182249. png_byte pixel_depth; /* number of bits per pixel */
  182250. png_byte spare_byte; /* to align the data, and for future use */
  182251. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182252. /* The rest of the data is optional. If you are reading, check the
  182253. * valid field to see if the information in these are valid. If you
  182254. * are writing, set the valid field to those chunks you want written,
  182255. * and initialize the appropriate fields below.
  182256. */
  182257. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182258. /* The gAMA chunk describes the gamma characteristics of the system
  182259. * on which the image was created, normally in the range [1.0, 2.5].
  182260. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182261. */
  182262. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182263. #endif
  182264. #if defined(PNG_sRGB_SUPPORTED)
  182265. /* GR-P, 0.96a */
  182266. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182267. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182268. #endif
  182269. #if defined(PNG_TEXT_SUPPORTED)
  182270. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182271. * uncompressed, compressed, and optionally compressed forms, respectively.
  182272. * The data in "text" is an array of pointers to uncompressed,
  182273. * null-terminated C strings. Each chunk has a keyword that describes the
  182274. * textual data contained in that chunk. Keywords are not required to be
  182275. * unique, and the text string may be empty. Any number of text chunks may
  182276. * be in an image.
  182277. */
  182278. int num_text; /* number of comments read/to write */
  182279. int max_text; /* current size of text array */
  182280. png_textp text; /* array of comments read/to write */
  182281. #endif /* PNG_TEXT_SUPPORTED */
  182282. #if defined(PNG_tIME_SUPPORTED)
  182283. /* The tIME chunk holds the last time the displayed image data was
  182284. * modified. See the png_time struct for the contents of this struct.
  182285. */
  182286. png_time mod_time;
  182287. #endif
  182288. #if defined(PNG_sBIT_SUPPORTED)
  182289. /* The sBIT chunk specifies the number of significant high-order bits
  182290. * in the pixel data. Values are in the range [1, bit_depth], and are
  182291. * only specified for the channels in the pixel data. The contents of
  182292. * the low-order bits is not specified. Data is valid if
  182293. * (valid & PNG_INFO_sBIT) is non-zero.
  182294. */
  182295. png_color_8 sig_bit; /* significant bits in color channels */
  182296. #endif
  182297. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182298. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182299. /* The tRNS chunk supplies transparency data for paletted images and
  182300. * other image types that don't need a full alpha channel. There are
  182301. * "num_trans" transparency values for a paletted image, stored in the
  182302. * same order as the palette colors, starting from index 0. Values
  182303. * for the data are in the range [0, 255], ranging from fully transparent
  182304. * to fully opaque, respectively. For non-paletted images, there is a
  182305. * single color specified that should be treated as fully transparent.
  182306. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182307. */
  182308. png_bytep trans; /* transparent values for paletted image */
  182309. png_color_16 trans_values; /* transparent color for non-palette image */
  182310. #endif
  182311. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182312. /* The bKGD chunk gives the suggested image background color if the
  182313. * display program does not have its own background color and the image
  182314. * is needs to composited onto a background before display. The colors
  182315. * in "background" are normally in the same color space/depth as the
  182316. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182317. */
  182318. png_color_16 background;
  182319. #endif
  182320. #if defined(PNG_oFFs_SUPPORTED)
  182321. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182322. * and downwards from the top-left corner of the display, page, or other
  182323. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182324. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182325. */
  182326. png_int_32 x_offset; /* x offset on page */
  182327. png_int_32 y_offset; /* y offset on page */
  182328. png_byte offset_unit_type; /* offset units type */
  182329. #endif
  182330. #if defined(PNG_pHYs_SUPPORTED)
  182331. /* The pHYs chunk gives the physical pixel density of the image for
  182332. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182333. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182334. */
  182335. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182336. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182337. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182338. #endif
  182339. #if defined(PNG_hIST_SUPPORTED)
  182340. /* The hIST chunk contains the relative frequency or importance of the
  182341. * various palette entries, so that a viewer can intelligently select a
  182342. * reduced-color palette, if required. Data is an array of "num_palette"
  182343. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182344. * is non-zero.
  182345. */
  182346. png_uint_16p hist;
  182347. #endif
  182348. #ifdef PNG_cHRM_SUPPORTED
  182349. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182350. * on which the PNG was created. This data allows the viewer to do gamut
  182351. * mapping of the input image to ensure that the viewer sees the same
  182352. * colors in the image as the creator. Values are in the range
  182353. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182354. */
  182355. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182356. float x_white;
  182357. float y_white;
  182358. float x_red;
  182359. float y_red;
  182360. float x_green;
  182361. float y_green;
  182362. float x_blue;
  182363. float y_blue;
  182364. #endif
  182365. #endif
  182366. #if defined(PNG_pCAL_SUPPORTED)
  182367. /* The pCAL chunk describes a transformation between the stored pixel
  182368. * values and original physical data values used to create the image.
  182369. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182370. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182371. * (possibly non-linear) transformation function given by "pcal_type"
  182372. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182373. * defines below, and the PNG-Group's PNG extensions document for a
  182374. * complete description of the transformations and how they should be
  182375. * implemented, and for a description of the ASCII parameter strings.
  182376. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182377. */
  182378. png_charp pcal_purpose; /* pCAL chunk description string */
  182379. png_int_32 pcal_X0; /* minimum value */
  182380. png_int_32 pcal_X1; /* maximum value */
  182381. png_charp pcal_units; /* Latin-1 string giving physical units */
  182382. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182383. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182384. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182385. #endif
  182386. /* New members added in libpng-1.0.6 */
  182387. #ifdef PNG_FREE_ME_SUPPORTED
  182388. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182389. #endif
  182390. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182391. /* storage for unknown chunks that the library doesn't recognize. */
  182392. png_unknown_chunkp unknown_chunks;
  182393. png_size_t unknown_chunks_num;
  182394. #endif
  182395. #if defined(PNG_iCCP_SUPPORTED)
  182396. /* iCCP chunk data. */
  182397. png_charp iccp_name; /* profile name */
  182398. png_charp iccp_profile; /* International Color Consortium profile data */
  182399. /* Note to maintainer: should be png_bytep */
  182400. png_uint_32 iccp_proflen; /* ICC profile data length */
  182401. png_byte iccp_compression; /* Always zero */
  182402. #endif
  182403. #if defined(PNG_sPLT_SUPPORTED)
  182404. /* data on sPLT chunks (there may be more than one). */
  182405. png_sPLT_tp splt_palettes;
  182406. png_uint_32 splt_palettes_num;
  182407. #endif
  182408. #if defined(PNG_sCAL_SUPPORTED)
  182409. /* The sCAL chunk describes the actual physical dimensions of the
  182410. * subject matter of the graphic. The chunk contains a unit specification
  182411. * a byte value, and two ASCII strings representing floating-point
  182412. * values. The values are width and height corresponsing to one pixel
  182413. * in the image. This external representation is converted to double
  182414. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182415. */
  182416. png_byte scal_unit; /* unit of physical scale */
  182417. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182418. double scal_pixel_width; /* width of one pixel */
  182419. double scal_pixel_height; /* height of one pixel */
  182420. #endif
  182421. #ifdef PNG_FIXED_POINT_SUPPORTED
  182422. png_charp scal_s_width; /* string containing height */
  182423. png_charp scal_s_height; /* string containing width */
  182424. #endif
  182425. #endif
  182426. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182427. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182428. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182429. png_bytepp row_pointers; /* the image bits */
  182430. #endif
  182431. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182432. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182433. #endif
  182434. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182435. png_fixed_point int_x_white;
  182436. png_fixed_point int_y_white;
  182437. png_fixed_point int_x_red;
  182438. png_fixed_point int_y_red;
  182439. png_fixed_point int_x_green;
  182440. png_fixed_point int_y_green;
  182441. png_fixed_point int_x_blue;
  182442. png_fixed_point int_y_blue;
  182443. #endif
  182444. } png_info;
  182445. typedef png_info FAR * png_infop;
  182446. typedef png_info FAR * FAR * png_infopp;
  182447. /* Maximum positive integer used in PNG is (2^31)-1 */
  182448. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182449. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182450. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182451. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182452. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182453. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182454. #endif
  182455. /* These describe the color_type field in png_info. */
  182456. /* color type masks */
  182457. #define PNG_COLOR_MASK_PALETTE 1
  182458. #define PNG_COLOR_MASK_COLOR 2
  182459. #define PNG_COLOR_MASK_ALPHA 4
  182460. /* color types. Note that not all combinations are legal */
  182461. #define PNG_COLOR_TYPE_GRAY 0
  182462. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182463. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182464. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182465. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182466. /* aliases */
  182467. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182468. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182469. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182470. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182471. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182472. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182473. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182474. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182475. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182476. /* These are for the interlacing type. These values should NOT be changed. */
  182477. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182478. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182479. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182480. /* These are for the oFFs chunk. These values should NOT be changed. */
  182481. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182482. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182483. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182484. /* These are for the pCAL chunk. These values should NOT be changed. */
  182485. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182486. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182487. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182488. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182489. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182490. /* These are for the sCAL chunk. These values should NOT be changed. */
  182491. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182492. #define PNG_SCALE_METER 1 /* meters per pixel */
  182493. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182494. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182495. /* These are for the pHYs chunk. These values should NOT be changed. */
  182496. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182497. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182498. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182499. /* These are for the sRGB chunk. These values should NOT be changed. */
  182500. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182501. #define PNG_sRGB_INTENT_RELATIVE 1
  182502. #define PNG_sRGB_INTENT_SATURATION 2
  182503. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182504. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182505. /* This is for text chunks */
  182506. #define PNG_KEYWORD_MAX_LENGTH 79
  182507. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182508. #define PNG_MAX_PALETTE_LENGTH 256
  182509. /* These determine if an ancillary chunk's data has been successfully read
  182510. * from the PNG header, or if the application has filled in the corresponding
  182511. * data in the info_struct to be written into the output file. The values
  182512. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182513. */
  182514. #define PNG_INFO_gAMA 0x0001
  182515. #define PNG_INFO_sBIT 0x0002
  182516. #define PNG_INFO_cHRM 0x0004
  182517. #define PNG_INFO_PLTE 0x0008
  182518. #define PNG_INFO_tRNS 0x0010
  182519. #define PNG_INFO_bKGD 0x0020
  182520. #define PNG_INFO_hIST 0x0040
  182521. #define PNG_INFO_pHYs 0x0080
  182522. #define PNG_INFO_oFFs 0x0100
  182523. #define PNG_INFO_tIME 0x0200
  182524. #define PNG_INFO_pCAL 0x0400
  182525. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182526. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182527. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182528. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182529. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182530. /* This is used for the transformation routines, as some of them
  182531. * change these values for the row. It also should enable using
  182532. * the routines for other purposes.
  182533. */
  182534. typedef struct png_row_info_struct
  182535. {
  182536. png_uint_32 width; /* width of row */
  182537. png_uint_32 rowbytes; /* number of bytes in row */
  182538. png_byte color_type; /* color type of row */
  182539. png_byte bit_depth; /* bit depth of row */
  182540. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182541. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182542. } png_row_info;
  182543. typedef png_row_info FAR * png_row_infop;
  182544. typedef png_row_info FAR * FAR * png_row_infopp;
  182545. /* These are the function types for the I/O functions and for the functions
  182546. * that allow the user to override the default I/O functions with his or her
  182547. * own. The png_error_ptr type should match that of user-supplied warning
  182548. * and error functions, while the png_rw_ptr type should match that of the
  182549. * user read/write data functions.
  182550. */
  182551. typedef struct png_struct_def png_struct;
  182552. typedef png_struct FAR * png_structp;
  182553. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182554. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182555. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182556. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182557. int));
  182558. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182559. int));
  182560. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182561. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182562. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182563. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182564. png_uint_32, int));
  182565. #endif
  182566. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182567. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182568. defined(PNG_LEGACY_SUPPORTED)
  182569. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182570. png_row_infop, png_bytep));
  182571. #endif
  182572. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182573. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182574. #endif
  182575. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182576. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182577. #endif
  182578. /* Transform masks for the high-level interface */
  182579. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182580. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182581. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182582. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182583. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182584. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182585. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182586. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182587. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182588. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182589. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182590. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182591. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182592. /* Flags for MNG supported features */
  182593. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182594. #define PNG_FLAG_MNG_FILTER_64 0x04
  182595. #define PNG_ALL_MNG_FEATURES 0x05
  182596. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182597. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182598. /* The structure that holds the information to read and write PNG files.
  182599. * The only people who need to care about what is inside of this are the
  182600. * people who will be modifying the library for their own special needs.
  182601. * It should NOT be accessed directly by an application, except to store
  182602. * the jmp_buf.
  182603. */
  182604. struct png_struct_def
  182605. {
  182606. #ifdef PNG_SETJMP_SUPPORTED
  182607. jmp_buf jmpbuf; /* used in png_error */
  182608. #endif
  182609. png_error_ptr error_fn; /* function for printing errors and aborting */
  182610. png_error_ptr warning_fn; /* function for printing warnings */
  182611. png_voidp error_ptr; /* user supplied struct for error functions */
  182612. png_rw_ptr write_data_fn; /* function for writing output data */
  182613. png_rw_ptr read_data_fn; /* function for reading input data */
  182614. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182615. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182616. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182617. #endif
  182618. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182619. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182620. #endif
  182621. /* These were added in libpng-1.0.2 */
  182622. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182623. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182624. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182625. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182626. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182627. png_byte user_transform_channels; /* channels in user transformed pixels */
  182628. #endif
  182629. #endif
  182630. png_uint_32 mode; /* tells us where we are in the PNG file */
  182631. png_uint_32 flags; /* flags indicating various things to libpng */
  182632. png_uint_32 transformations; /* which transformations to perform */
  182633. z_stream zstream; /* pointer to decompression structure (below) */
  182634. png_bytep zbuf; /* buffer for zlib */
  182635. png_size_t zbuf_size; /* size of zbuf */
  182636. int zlib_level; /* holds zlib compression level */
  182637. int zlib_method; /* holds zlib compression method */
  182638. int zlib_window_bits; /* holds zlib compression window bits */
  182639. int zlib_mem_level; /* holds zlib compression memory level */
  182640. int zlib_strategy; /* holds zlib compression strategy */
  182641. png_uint_32 width; /* width of image in pixels */
  182642. png_uint_32 height; /* height of image in pixels */
  182643. png_uint_32 num_rows; /* number of rows in current pass */
  182644. png_uint_32 usr_width; /* width of row at start of write */
  182645. png_uint_32 rowbytes; /* size of row in bytes */
  182646. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182647. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182648. png_uint_32 row_number; /* current row in interlace pass */
  182649. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182650. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182651. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182652. png_bytep up_row; /* buffer to save "up" row when filtering */
  182653. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182654. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182655. png_row_info row_info; /* used for transformation routines */
  182656. png_uint_32 idat_size; /* current IDAT size for read */
  182657. png_uint_32 crc; /* current chunk CRC value */
  182658. png_colorp palette; /* palette from the input file */
  182659. png_uint_16 num_palette; /* number of color entries in palette */
  182660. png_uint_16 num_trans; /* number of transparency values */
  182661. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182662. png_byte compression; /* file compression type (always 0) */
  182663. png_byte filter; /* file filter type (always 0) */
  182664. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182665. png_byte pass; /* current interlace pass (0 - 6) */
  182666. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182667. png_byte color_type; /* color type of file */
  182668. png_byte bit_depth; /* bit depth of file */
  182669. png_byte usr_bit_depth; /* bit depth of users row */
  182670. png_byte pixel_depth; /* number of bits per pixel */
  182671. png_byte channels; /* number of channels in file */
  182672. png_byte usr_channels; /* channels at start of write */
  182673. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182674. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182675. #ifdef PNG_LEGACY_SUPPORTED
  182676. png_byte filler; /* filler byte for pixel expansion */
  182677. #else
  182678. png_uint_16 filler; /* filler bytes for pixel expansion */
  182679. #endif
  182680. #endif
  182681. #if defined(PNG_bKGD_SUPPORTED)
  182682. png_byte background_gamma_type;
  182683. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182684. float background_gamma;
  182685. # endif
  182686. png_color_16 background; /* background color in screen gamma space */
  182687. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182688. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182689. #endif
  182690. #endif /* PNG_bKGD_SUPPORTED */
  182691. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182692. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182693. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182694. png_uint_32 flush_rows; /* number of rows written since last flush */
  182695. #endif
  182696. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182697. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182698. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182699. float gamma; /* file gamma value */
  182700. float screen_gamma; /* screen gamma value (display_exponent) */
  182701. #endif
  182702. #endif
  182703. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182704. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182705. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182706. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182707. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182708. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182709. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182710. #endif
  182711. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182712. png_color_8 sig_bit; /* significant bits in each available channel */
  182713. #endif
  182714. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182715. png_color_8 shift; /* shift for significant bit tranformation */
  182716. #endif
  182717. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182718. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182719. png_bytep trans; /* transparency values for paletted files */
  182720. png_color_16 trans_values; /* transparency values for non-paletted files */
  182721. #endif
  182722. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182723. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182724. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182725. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182726. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182727. png_progressive_end_ptr end_fn; /* called after image is complete */
  182728. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182729. png_bytep save_buffer; /* buffer for previously read data */
  182730. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182731. png_bytep current_buffer; /* buffer for recently used data */
  182732. png_uint_32 push_length; /* size of current input chunk */
  182733. png_uint_32 skip_length; /* bytes to skip in input data */
  182734. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182735. png_size_t save_buffer_max; /* total size of save_buffer */
  182736. png_size_t buffer_size; /* total amount of available input data */
  182737. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182738. int process_mode; /* what push library is currently doing */
  182739. int cur_palette; /* current push library palette index */
  182740. # if defined(PNG_TEXT_SUPPORTED)
  182741. png_size_t current_text_size; /* current size of text input data */
  182742. png_size_t current_text_left; /* how much text left to read in input */
  182743. png_charp current_text; /* current text chunk buffer */
  182744. png_charp current_text_ptr; /* current location in current_text */
  182745. # endif /* PNG_TEXT_SUPPORTED */
  182746. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182747. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182748. /* for the Borland special 64K segment handler */
  182749. png_bytepp offset_table_ptr;
  182750. png_bytep offset_table;
  182751. png_uint_16 offset_table_number;
  182752. png_uint_16 offset_table_count;
  182753. png_uint_16 offset_table_count_free;
  182754. #endif
  182755. #if defined(PNG_READ_DITHER_SUPPORTED)
  182756. png_bytep palette_lookup; /* lookup table for dithering */
  182757. png_bytep dither_index; /* index translation for palette files */
  182758. #endif
  182759. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182760. png_uint_16p hist; /* histogram */
  182761. #endif
  182762. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182763. png_byte heuristic_method; /* heuristic for row filter selection */
  182764. png_byte num_prev_filters; /* number of weights for previous rows */
  182765. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182766. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182767. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182768. png_uint_16p filter_costs; /* relative filter calculation cost */
  182769. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182770. #endif
  182771. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182772. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182773. #endif
  182774. /* New members added in libpng-1.0.6 */
  182775. #ifdef PNG_FREE_ME_SUPPORTED
  182776. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182777. #endif
  182778. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182779. png_voidp user_chunk_ptr;
  182780. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182781. #endif
  182782. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182783. int num_chunk_list;
  182784. png_bytep chunk_list;
  182785. #endif
  182786. /* New members added in libpng-1.0.3 */
  182787. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182788. png_byte rgb_to_gray_status;
  182789. /* These were changed from png_byte in libpng-1.0.6 */
  182790. png_uint_16 rgb_to_gray_red_coeff;
  182791. png_uint_16 rgb_to_gray_green_coeff;
  182792. png_uint_16 rgb_to_gray_blue_coeff;
  182793. #endif
  182794. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182795. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182796. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182797. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182798. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182799. #ifdef PNG_1_0_X
  182800. png_byte mng_features_permitted;
  182801. #else
  182802. png_uint_32 mng_features_permitted;
  182803. #endif /* PNG_1_0_X */
  182804. #endif
  182805. /* New member added in libpng-1.0.7 */
  182806. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182807. png_fixed_point int_gamma;
  182808. #endif
  182809. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182810. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182811. png_byte filter_type;
  182812. #endif
  182813. #if defined(PNG_1_0_X)
  182814. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182815. png_uint_32 row_buf_size;
  182816. #endif
  182817. /* New members added in libpng-1.2.0 */
  182818. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182819. # if !defined(PNG_1_0_X)
  182820. # if defined(PNG_MMX_CODE_SUPPORTED)
  182821. png_byte mmx_bitdepth_threshold;
  182822. png_uint_32 mmx_rowbytes_threshold;
  182823. # endif
  182824. png_uint_32 asm_flags;
  182825. # endif
  182826. #endif
  182827. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182828. #ifdef PNG_USER_MEM_SUPPORTED
  182829. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182830. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182831. png_free_ptr free_fn; /* function for freeing memory */
  182832. #endif
  182833. /* New member added in libpng-1.0.13 and 1.2.0 */
  182834. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182835. #if defined(PNG_READ_DITHER_SUPPORTED)
  182836. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182837. png_bytep dither_sort; /* working sort array */
  182838. png_bytep index_to_palette; /* where the original index currently is */
  182839. /* in the palette */
  182840. png_bytep palette_to_index; /* which original index points to this */
  182841. /* palette color */
  182842. #endif
  182843. /* New members added in libpng-1.0.16 and 1.2.6 */
  182844. png_byte compression_type;
  182845. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182846. png_uint_32 user_width_max;
  182847. png_uint_32 user_height_max;
  182848. #endif
  182849. /* New member added in libpng-1.0.25 and 1.2.17 */
  182850. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182851. /* storage for unknown chunk that the library doesn't recognize. */
  182852. png_unknown_chunk unknown_chunk;
  182853. #endif
  182854. };
  182855. /* This triggers a compiler error in png.c, if png.c and png.h
  182856. * do not agree upon the version number.
  182857. */
  182858. typedef png_structp version_1_2_21;
  182859. typedef png_struct FAR * FAR * png_structpp;
  182860. /* Here are the function definitions most commonly used. This is not
  182861. * the place to find out how to use libpng. See libpng.txt for the
  182862. * full explanation, see example.c for the summary. This just provides
  182863. * a simple one line description of the use of each function.
  182864. */
  182865. /* Returns the version number of the library */
  182866. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182867. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182868. * Handling more than 8 bytes from the beginning of the file is an error.
  182869. */
  182870. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182871. int num_bytes));
  182872. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182873. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182874. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182875. * start > 7 will always fail (ie return non-zero).
  182876. */
  182877. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182878. png_size_t num_to_check));
  182879. /* Simple signature checking function. This is the same as calling
  182880. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182881. */
  182882. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182883. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182884. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182885. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182886. png_error_ptr error_fn, png_error_ptr warn_fn));
  182887. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182888. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182889. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182890. png_error_ptr error_fn, png_error_ptr warn_fn));
  182891. #ifdef PNG_WRITE_SUPPORTED
  182892. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182893. PNGARG((png_structp png_ptr));
  182894. #endif
  182895. #ifdef PNG_WRITE_SUPPORTED
  182896. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182897. PNGARG((png_structp png_ptr, png_uint_32 size));
  182898. #endif
  182899. /* Reset the compression stream */
  182900. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182901. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182902. #ifdef PNG_USER_MEM_SUPPORTED
  182903. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182904. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182905. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182906. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182907. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182908. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182909. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182910. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182911. #endif
  182912. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182913. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182914. png_bytep chunk_name, png_bytep data, png_size_t length));
  182915. /* Write the start of a PNG chunk - length and chunk name. */
  182916. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182917. png_bytep chunk_name, png_uint_32 length));
  182918. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182919. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182920. png_bytep data, png_size_t length));
  182921. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182922. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182923. /* Allocate and initialize the info structure */
  182924. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182925. PNGARG((png_structp png_ptr));
  182926. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182927. /* Initialize the info structure (old interface - DEPRECATED) */
  182928. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182929. #undef png_info_init
  182930. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182931. png_sizeof(png_info));
  182932. #endif
  182933. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182934. png_size_t png_info_struct_size));
  182935. /* Writes all the PNG information before the image. */
  182936. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182937. png_infop info_ptr));
  182938. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182939. png_infop info_ptr));
  182940. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182941. /* read the information before the actual image data. */
  182942. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182943. png_infop info_ptr));
  182944. #endif
  182945. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182946. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182947. PNGARG((png_structp png_ptr, png_timep ptime));
  182948. #endif
  182949. #if !defined(_WIN32_WCE)
  182950. /* "time.h" functions are not supported on WindowsCE */
  182951. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182952. /* convert from a struct tm to png_time */
  182953. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182954. struct tm FAR * ttime));
  182955. /* convert from time_t to png_time. Uses gmtime() */
  182956. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182957. time_t ttime));
  182958. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182959. #endif /* _WIN32_WCE */
  182960. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182961. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182962. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182963. #if !defined(PNG_1_0_X)
  182964. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182965. png_ptr));
  182966. #endif
  182967. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182968. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182969. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182970. /* Deprecated */
  182971. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182972. #endif
  182973. #endif
  182974. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182975. /* Use blue, green, red order for pixels. */
  182976. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182977. #endif
  182978. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182979. /* Expand the grayscale to 24-bit RGB if necessary. */
  182980. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182981. #endif
  182982. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182983. /* Reduce RGB to grayscale. */
  182984. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182985. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182986. int error_action, double red, double green ));
  182987. #endif
  182988. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182989. int error_action, png_fixed_point red, png_fixed_point green ));
  182990. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182991. png_ptr));
  182992. #endif
  182993. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182994. png_colorp palette));
  182995. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182996. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182997. #endif
  182998. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182999. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183000. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  183001. #endif
  183002. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  183003. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183004. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  183005. #endif
  183006. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  183007. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  183008. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  183009. png_uint_32 filler, int flags));
  183010. /* The values of the PNG_FILLER_ defines should NOT be changed */
  183011. #define PNG_FILLER_BEFORE 0
  183012. #define PNG_FILLER_AFTER 1
  183013. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  183014. #if !defined(PNG_1_0_X)
  183015. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  183016. png_uint_32 filler, int flags));
  183017. #endif
  183018. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  183019. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183020. /* Swap bytes in 16-bit depth files. */
  183021. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  183022. #endif
  183023. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  183024. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  183025. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  183026. #endif
  183027. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183028. /* Swap packing order of pixels in bytes. */
  183029. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  183030. #endif
  183031. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183032. /* Converts files to legal bit depths. */
  183033. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  183034. png_color_8p true_bits));
  183035. #endif
  183036. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  183037. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183038. /* Have the code handle the interlacing. Returns the number of passes. */
  183039. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  183040. #endif
  183041. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183042. /* Invert monochrome files */
  183043. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183044. #endif
  183045. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183046. /* Handle alpha and tRNS by replacing with a background color. */
  183047. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183048. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  183049. png_color_16p background_color, int background_gamma_code,
  183050. int need_expand, double background_gamma));
  183051. #endif
  183052. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  183053. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  183054. #define PNG_BACKGROUND_GAMMA_FILE 2
  183055. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  183056. #endif
  183057. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183058. /* strip the second byte of information from a 16-bit depth file. */
  183059. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  183060. #endif
  183061. #if defined(PNG_READ_DITHER_SUPPORTED)
  183062. /* Turn on dithering, and reduce the palette to the number of colors available. */
  183063. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  183064. png_colorp palette, int num_palette, int maximum_colors,
  183065. png_uint_16p histogram, int full_dither));
  183066. #endif
  183067. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183068. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183069. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183070. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183071. double screen_gamma, double default_file_gamma));
  183072. #endif
  183073. #endif
  183074. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183075. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183076. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183077. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183078. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183079. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183080. int empty_plte_permitted));
  183081. #endif
  183082. #endif
  183083. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183084. /* Set how many lines between output flushes - 0 for no flushing */
  183085. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183086. /* Flush the current PNG output buffer */
  183087. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183088. #endif
  183089. /* optional update palette with requested transformations */
  183090. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183091. /* optional call to update the users info structure */
  183092. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183093. png_infop info_ptr));
  183094. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183095. /* read one or more rows of image data. */
  183096. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183097. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183098. #endif
  183099. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183100. /* read a row of data. */
  183101. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183102. png_bytep row,
  183103. png_bytep display_row));
  183104. #endif
  183105. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183106. /* read the whole image into memory at once. */
  183107. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183108. png_bytepp image));
  183109. #endif
  183110. /* write a row of image data */
  183111. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183112. png_bytep row));
  183113. /* write a few rows of image data */
  183114. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183115. png_bytepp row, png_uint_32 num_rows));
  183116. /* write the image data */
  183117. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183118. png_bytepp image));
  183119. /* writes the end of the PNG file. */
  183120. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183121. png_infop info_ptr));
  183122. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183123. /* read the end of the PNG file. */
  183124. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183125. png_infop info_ptr));
  183126. #endif
  183127. /* free any memory associated with the png_info_struct */
  183128. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183129. png_infopp info_ptr_ptr));
  183130. /* free any memory associated with the png_struct and the png_info_structs */
  183131. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183132. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183133. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183134. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183135. png_infop end_info_ptr));
  183136. /* free any memory associated with the png_struct and the png_info_structs */
  183137. extern PNG_EXPORT(void,png_destroy_write_struct)
  183138. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183139. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183140. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183141. /* set the libpng method of handling chunk CRC errors */
  183142. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183143. int crit_action, int ancil_action));
  183144. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183145. * ancillary and critical chunks, and whether to use the data contained
  183146. * therein. Note that it is impossible to "discard" data in a critical
  183147. * chunk. For versions prior to 0.90, the action was always error/quit,
  183148. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183149. * chunks is warn/discard. These values should NOT be changed.
  183150. *
  183151. * value action:critical action:ancillary
  183152. */
  183153. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183154. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183155. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183156. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183157. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183158. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183159. /* These functions give the user control over the scan-line filtering in
  183160. * libpng and the compression methods used by zlib. These functions are
  183161. * mainly useful for testing, as the defaults should work with most users.
  183162. * Those users who are tight on memory or want faster performance at the
  183163. * expense of compression can modify them. See the compression library
  183164. * header file (zlib.h) for an explination of the compression functions.
  183165. */
  183166. /* set the filtering method(s) used by libpng. Currently, the only valid
  183167. * value for "method" is 0.
  183168. */
  183169. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183170. int filters));
  183171. /* Flags for png_set_filter() to say which filters to use. The flags
  183172. * are chosen so that they don't conflict with real filter types
  183173. * below, in case they are supplied instead of the #defined constants.
  183174. * These values should NOT be changed.
  183175. */
  183176. #define PNG_NO_FILTERS 0x00
  183177. #define PNG_FILTER_NONE 0x08
  183178. #define PNG_FILTER_SUB 0x10
  183179. #define PNG_FILTER_UP 0x20
  183180. #define PNG_FILTER_AVG 0x40
  183181. #define PNG_FILTER_PAETH 0x80
  183182. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183183. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183184. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183185. * These defines should NOT be changed.
  183186. */
  183187. #define PNG_FILTER_VALUE_NONE 0
  183188. #define PNG_FILTER_VALUE_SUB 1
  183189. #define PNG_FILTER_VALUE_UP 2
  183190. #define PNG_FILTER_VALUE_AVG 3
  183191. #define PNG_FILTER_VALUE_PAETH 4
  183192. #define PNG_FILTER_VALUE_LAST 5
  183193. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183194. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183195. * defines, either the default (minimum-sum-of-absolute-differences), or
  183196. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183197. *
  183198. * Weights are factors >= 1.0, indicating how important it is to keep the
  183199. * filter type consistent between rows. Larger numbers mean the current
  183200. * filter is that many times as likely to be the same as the "num_weights"
  183201. * previous filters. This is cumulative for each previous row with a weight.
  183202. * There needs to be "num_weights" values in "filter_weights", or it can be
  183203. * NULL if the weights aren't being specified. Weights have no influence on
  183204. * the selection of the first row filter. Well chosen weights can (in theory)
  183205. * improve the compression for a given image.
  183206. *
  183207. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183208. * filter type. Higher costs indicate more decoding expense, and are
  183209. * therefore less likely to be selected over a filter with lower computational
  183210. * costs. There needs to be a value in "filter_costs" for each valid filter
  183211. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183212. * setting the costs. Costs try to improve the speed of decompression without
  183213. * unduly increasing the compressed image size.
  183214. *
  183215. * A negative weight or cost indicates the default value is to be used, and
  183216. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183217. * The default values for both weights and costs are currently 1.0, but may
  183218. * change if good general weighting/cost heuristics can be found. If both
  183219. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183220. * to the UNWEIGHTED method, but with added encoding time/computation.
  183221. */
  183222. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183223. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183224. int heuristic_method, int num_weights, png_doublep filter_weights,
  183225. png_doublep filter_costs));
  183226. #endif
  183227. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183228. /* Heuristic used for row filter selection. These defines should NOT be
  183229. * changed.
  183230. */
  183231. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183232. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183233. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183234. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183235. /* Set the library compression level. Currently, valid values range from
  183236. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183237. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183238. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183239. * for PNG images, and do considerably fewer caclulations. In the future,
  183240. * these values may not correspond directly to the zlib compression levels.
  183241. */
  183242. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183243. int level));
  183244. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183245. PNGARG((png_structp png_ptr, int mem_level));
  183246. extern PNG_EXPORT(void,png_set_compression_strategy)
  183247. PNGARG((png_structp png_ptr, int strategy));
  183248. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183249. PNGARG((png_structp png_ptr, int window_bits));
  183250. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183251. int method));
  183252. /* These next functions are called for input/output, memory, and error
  183253. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183254. * and call standard C I/O routines such as fread(), fwrite(), and
  183255. * fprintf(). These functions can be made to use other I/O routines
  183256. * at run time for those applications that need to handle I/O in a
  183257. * different manner by calling png_set_???_fn(). See libpng.txt for
  183258. * more information.
  183259. */
  183260. #if !defined(PNG_NO_STDIO)
  183261. /* Initialize the input/output for the PNG file to the default functions. */
  183262. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183263. #endif
  183264. /* Replace the (error and abort), and warning functions with user
  183265. * supplied functions. If no messages are to be printed you must still
  183266. * write and use replacement functions. The replacement error_fn should
  183267. * still do a longjmp to the last setjmp location if you are using this
  183268. * method of error handling. If error_fn or warning_fn is NULL, the
  183269. * default function will be used.
  183270. */
  183271. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183272. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183273. /* Return the user pointer associated with the error functions */
  183274. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183275. /* Replace the default data output functions with a user supplied one(s).
  183276. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183277. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183278. * output_flush_fn will be ignored (and thus can be NULL).
  183279. */
  183280. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183281. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183282. /* Replace the default data input function with a user supplied one. */
  183283. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183284. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183285. /* Return the user pointer associated with the I/O functions */
  183286. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183287. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183288. png_read_status_ptr read_row_fn));
  183289. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183290. png_write_status_ptr write_row_fn));
  183291. #ifdef PNG_USER_MEM_SUPPORTED
  183292. /* Replace the default memory allocation functions with user supplied one(s). */
  183293. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183294. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183295. /* Return the user pointer associated with the memory functions */
  183296. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183297. #endif
  183298. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183299. defined(PNG_LEGACY_SUPPORTED)
  183300. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183301. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183302. #endif
  183303. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183304. defined(PNG_LEGACY_SUPPORTED)
  183305. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183306. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183307. #endif
  183308. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183309. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183310. defined(PNG_LEGACY_SUPPORTED)
  183311. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183312. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183313. int user_transform_channels));
  183314. /* Return the user pointer associated with the user transform functions */
  183315. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183316. PNGARG((png_structp png_ptr));
  183317. #endif
  183318. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183319. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183320. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183321. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183322. png_ptr));
  183323. #endif
  183324. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183325. /* Sets the function callbacks for the push reader, and a pointer to a
  183326. * user-defined structure available to the callback functions.
  183327. */
  183328. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183329. png_voidp progressive_ptr,
  183330. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183331. png_progressive_end_ptr end_fn));
  183332. /* returns the user pointer associated with the push read functions */
  183333. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183334. PNGARG((png_structp png_ptr));
  183335. /* function to be called when data becomes available */
  183336. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183337. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183338. /* function that combines rows. Not very much different than the
  183339. * png_combine_row() call. Is this even used?????
  183340. */
  183341. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183342. png_bytep old_row, png_bytep new_row));
  183343. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183344. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183345. png_uint_32 size));
  183346. #if defined(PNG_1_0_X)
  183347. # define png_malloc_warn png_malloc
  183348. #else
  183349. /* Added at libpng version 1.2.4 */
  183350. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183351. png_uint_32 size));
  183352. #endif
  183353. /* frees a pointer allocated by png_malloc() */
  183354. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183355. #if defined(PNG_1_0_X)
  183356. /* Function to allocate memory for zlib. */
  183357. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183358. uInt size));
  183359. /* Function to free memory for zlib */
  183360. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183361. #endif
  183362. /* Free data that was allocated internally */
  183363. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183364. png_infop info_ptr, png_uint_32 free_me, int num));
  183365. #ifdef PNG_FREE_ME_SUPPORTED
  183366. /* Reassign responsibility for freeing existing data, whether allocated
  183367. * by libpng or by the application */
  183368. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183369. png_infop info_ptr, int freer, png_uint_32 mask));
  183370. #endif
  183371. /* assignments for png_data_freer */
  183372. #define PNG_DESTROY_WILL_FREE_DATA 1
  183373. #define PNG_SET_WILL_FREE_DATA 1
  183374. #define PNG_USER_WILL_FREE_DATA 2
  183375. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183376. #define PNG_FREE_HIST 0x0008
  183377. #define PNG_FREE_ICCP 0x0010
  183378. #define PNG_FREE_SPLT 0x0020
  183379. #define PNG_FREE_ROWS 0x0040
  183380. #define PNG_FREE_PCAL 0x0080
  183381. #define PNG_FREE_SCAL 0x0100
  183382. #define PNG_FREE_UNKN 0x0200
  183383. #define PNG_FREE_LIST 0x0400
  183384. #define PNG_FREE_PLTE 0x1000
  183385. #define PNG_FREE_TRNS 0x2000
  183386. #define PNG_FREE_TEXT 0x4000
  183387. #define PNG_FREE_ALL 0x7fff
  183388. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183389. #ifdef PNG_USER_MEM_SUPPORTED
  183390. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183391. png_uint_32 size));
  183392. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183393. png_voidp ptr));
  183394. #endif
  183395. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183396. png_voidp s1, png_voidp s2, png_uint_32 size));
  183397. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183398. png_voidp s1, int value, png_uint_32 size));
  183399. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183400. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183401. int check));
  183402. #endif /* USE_FAR_KEYWORD */
  183403. #ifndef PNG_NO_ERROR_TEXT
  183404. /* Fatal error in PNG image of libpng - can't continue */
  183405. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183406. png_const_charp error_message));
  183407. /* The same, but the chunk name is prepended to the error string. */
  183408. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183409. png_const_charp error_message));
  183410. #else
  183411. /* Fatal error in PNG image of libpng - can't continue */
  183412. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183413. #endif
  183414. #ifndef PNG_NO_WARNINGS
  183415. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183416. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183417. png_const_charp warning_message));
  183418. #ifdef PNG_READ_SUPPORTED
  183419. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183420. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183421. png_const_charp warning_message));
  183422. #endif /* PNG_READ_SUPPORTED */
  183423. #endif /* PNG_NO_WARNINGS */
  183424. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183425. * Similarly, the png_get_<chunk> calls are used to read values from the
  183426. * png_info_struct, either storing the parameters in the passed variables, or
  183427. * setting pointers into the png_info_struct where the data is stored. The
  183428. * png_get_<chunk> functions return a non-zero value if the data was available
  183429. * in info_ptr, or return zero and do not change any of the parameters if the
  183430. * data was not available.
  183431. *
  183432. * These functions should be used instead of directly accessing png_info
  183433. * to avoid problems with future changes in the size and internal layout of
  183434. * png_info_struct.
  183435. */
  183436. /* Returns "flag" if chunk data is valid in info_ptr. */
  183437. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183438. png_infop info_ptr, png_uint_32 flag));
  183439. /* Returns number of bytes needed to hold a transformed row. */
  183440. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183441. png_infop info_ptr));
  183442. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183443. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183444. returned from png_read_png(). */
  183445. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183446. png_infop info_ptr));
  183447. /* Set row_pointers, which is an array of pointers to scanlines for use
  183448. by png_write_png(). */
  183449. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183450. png_infop info_ptr, png_bytepp row_pointers));
  183451. #endif
  183452. /* Returns number of color channels in image. */
  183453. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183454. png_infop info_ptr));
  183455. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183456. /* Returns image width in pixels. */
  183457. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183458. png_ptr, png_infop info_ptr));
  183459. /* Returns image height in pixels. */
  183460. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183461. png_ptr, png_infop info_ptr));
  183462. /* Returns image bit_depth. */
  183463. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183464. png_ptr, png_infop info_ptr));
  183465. /* Returns image color_type. */
  183466. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183467. png_ptr, png_infop info_ptr));
  183468. /* Returns image filter_type. */
  183469. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183470. png_ptr, png_infop info_ptr));
  183471. /* Returns image interlace_type. */
  183472. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183473. png_ptr, png_infop info_ptr));
  183474. /* Returns image compression_type. */
  183475. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183476. png_ptr, png_infop info_ptr));
  183477. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183478. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183479. png_ptr, png_infop info_ptr));
  183480. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183481. png_ptr, png_infop info_ptr));
  183482. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183483. png_ptr, png_infop info_ptr));
  183484. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183485. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183486. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183487. png_ptr, png_infop info_ptr));
  183488. #endif
  183489. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183490. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183491. png_ptr, png_infop info_ptr));
  183492. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183493. png_ptr, png_infop info_ptr));
  183494. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183495. png_ptr, png_infop info_ptr));
  183496. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183497. png_ptr, png_infop info_ptr));
  183498. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183499. /* Returns pointer to signature string read from PNG header */
  183500. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183501. png_infop info_ptr));
  183502. #if defined(PNG_bKGD_SUPPORTED)
  183503. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183504. png_infop info_ptr, png_color_16p *background));
  183505. #endif
  183506. #if defined(PNG_bKGD_SUPPORTED)
  183507. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183508. png_infop info_ptr, png_color_16p background));
  183509. #endif
  183510. #if defined(PNG_cHRM_SUPPORTED)
  183511. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183512. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183513. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183514. double *red_y, double *green_x, double *green_y, double *blue_x,
  183515. double *blue_y));
  183516. #endif
  183517. #ifdef PNG_FIXED_POINT_SUPPORTED
  183518. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183519. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183520. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183521. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183522. *int_blue_x, png_fixed_point *int_blue_y));
  183523. #endif
  183524. #endif
  183525. #if defined(PNG_cHRM_SUPPORTED)
  183526. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183527. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183528. png_infop info_ptr, double white_x, double white_y, double red_x,
  183529. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183530. #endif
  183531. #ifdef PNG_FIXED_POINT_SUPPORTED
  183532. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183533. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183534. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183535. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183536. png_fixed_point int_blue_y));
  183537. #endif
  183538. #endif
  183539. #if defined(PNG_gAMA_SUPPORTED)
  183540. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183541. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183542. png_infop info_ptr, double *file_gamma));
  183543. #endif
  183544. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183545. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183546. #endif
  183547. #if defined(PNG_gAMA_SUPPORTED)
  183548. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183549. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183550. png_infop info_ptr, double file_gamma));
  183551. #endif
  183552. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183553. png_infop info_ptr, png_fixed_point int_file_gamma));
  183554. #endif
  183555. #if defined(PNG_hIST_SUPPORTED)
  183556. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183557. png_infop info_ptr, png_uint_16p *hist));
  183558. #endif
  183559. #if defined(PNG_hIST_SUPPORTED)
  183560. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183561. png_infop info_ptr, png_uint_16p hist));
  183562. #endif
  183563. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183564. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183565. int *bit_depth, int *color_type, int *interlace_method,
  183566. int *compression_method, int *filter_method));
  183567. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183568. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183569. int color_type, int interlace_method, int compression_method,
  183570. int filter_method));
  183571. #if defined(PNG_oFFs_SUPPORTED)
  183572. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183573. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183574. int *unit_type));
  183575. #endif
  183576. #if defined(PNG_oFFs_SUPPORTED)
  183577. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183578. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183579. int unit_type));
  183580. #endif
  183581. #if defined(PNG_pCAL_SUPPORTED)
  183582. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183583. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183584. int *type, int *nparams, png_charp *units, png_charpp *params));
  183585. #endif
  183586. #if defined(PNG_pCAL_SUPPORTED)
  183587. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183588. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183589. int type, int nparams, png_charp units, png_charpp params));
  183590. #endif
  183591. #if defined(PNG_pHYs_SUPPORTED)
  183592. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183593. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183594. #endif
  183595. #if defined(PNG_pHYs_SUPPORTED)
  183596. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183597. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183598. #endif
  183599. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183600. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183601. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183602. png_infop info_ptr, png_colorp palette, int num_palette));
  183603. #if defined(PNG_sBIT_SUPPORTED)
  183604. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183605. png_infop info_ptr, png_color_8p *sig_bit));
  183606. #endif
  183607. #if defined(PNG_sBIT_SUPPORTED)
  183608. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183609. png_infop info_ptr, png_color_8p sig_bit));
  183610. #endif
  183611. #if defined(PNG_sRGB_SUPPORTED)
  183612. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183613. png_infop info_ptr, int *intent));
  183614. #endif
  183615. #if defined(PNG_sRGB_SUPPORTED)
  183616. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183617. png_infop info_ptr, int intent));
  183618. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183619. png_infop info_ptr, int intent));
  183620. #endif
  183621. #if defined(PNG_iCCP_SUPPORTED)
  183622. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183623. png_infop info_ptr, png_charpp name, int *compression_type,
  183624. png_charpp profile, png_uint_32 *proflen));
  183625. /* Note to maintainer: profile should be png_bytepp */
  183626. #endif
  183627. #if defined(PNG_iCCP_SUPPORTED)
  183628. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183629. png_infop info_ptr, png_charp name, int compression_type,
  183630. png_charp profile, png_uint_32 proflen));
  183631. /* Note to maintainer: profile should be png_bytep */
  183632. #endif
  183633. #if defined(PNG_sPLT_SUPPORTED)
  183634. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183635. png_infop info_ptr, png_sPLT_tpp entries));
  183636. #endif
  183637. #if defined(PNG_sPLT_SUPPORTED)
  183638. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183639. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183640. #endif
  183641. #if defined(PNG_TEXT_SUPPORTED)
  183642. /* png_get_text also returns the number of text chunks in *num_text */
  183643. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183644. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183645. #endif
  183646. /*
  183647. * Note while png_set_text() will accept a structure whose text,
  183648. * language, and translated keywords are NULL pointers, the structure
  183649. * returned by png_get_text will always contain regular
  183650. * zero-terminated C strings. They might be empty strings but
  183651. * they will never be NULL pointers.
  183652. */
  183653. #if defined(PNG_TEXT_SUPPORTED)
  183654. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183655. png_infop info_ptr, png_textp text_ptr, int num_text));
  183656. #endif
  183657. #if defined(PNG_tIME_SUPPORTED)
  183658. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183659. png_infop info_ptr, png_timep *mod_time));
  183660. #endif
  183661. #if defined(PNG_tIME_SUPPORTED)
  183662. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183663. png_infop info_ptr, png_timep mod_time));
  183664. #endif
  183665. #if defined(PNG_tRNS_SUPPORTED)
  183666. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183667. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183668. png_color_16p *trans_values));
  183669. #endif
  183670. #if defined(PNG_tRNS_SUPPORTED)
  183671. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183672. png_infop info_ptr, png_bytep trans, int num_trans,
  183673. png_color_16p trans_values));
  183674. #endif
  183675. #if defined(PNG_tRNS_SUPPORTED)
  183676. #endif
  183677. #if defined(PNG_sCAL_SUPPORTED)
  183678. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183679. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183680. png_infop info_ptr, int *unit, double *width, double *height));
  183681. #else
  183682. #ifdef PNG_FIXED_POINT_SUPPORTED
  183683. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183684. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183685. #endif
  183686. #endif
  183687. #endif /* PNG_sCAL_SUPPORTED */
  183688. #if defined(PNG_sCAL_SUPPORTED)
  183689. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183690. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183691. png_infop info_ptr, int unit, double width, double height));
  183692. #else
  183693. #ifdef PNG_FIXED_POINT_SUPPORTED
  183694. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183695. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183696. #endif
  183697. #endif
  183698. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183699. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183700. /* provide a list of chunks and how they are to be handled, if the built-in
  183701. handling or default unknown chunk handling is not desired. Any chunks not
  183702. listed will be handled in the default manner. The IHDR and IEND chunks
  183703. must not be listed.
  183704. keep = 0: follow default behaviour
  183705. = 1: do not keep
  183706. = 2: keep only if safe-to-copy
  183707. = 3: keep even if unsafe-to-copy
  183708. */
  183709. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183710. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183711. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183712. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183713. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183714. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183715. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183716. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183717. #endif
  183718. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183719. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183720. chunk_name));
  183721. #endif
  183722. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183723. If you need to turn it off for a chunk that your application has freed,
  183724. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183725. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183726. png_infop info_ptr, int mask));
  183727. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183728. /* The "params" pointer is currently not used and is for future expansion. */
  183729. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183730. png_infop info_ptr,
  183731. int transforms,
  183732. png_voidp params));
  183733. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183734. png_infop info_ptr,
  183735. int transforms,
  183736. png_voidp params));
  183737. #endif
  183738. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183739. * numbers for PNG_DEBUG mean more debugging information. This has
  183740. * only been added since version 0.95 so it is not implemented throughout
  183741. * libpng yet, but more support will be added as needed.
  183742. */
  183743. #ifdef PNG_DEBUG
  183744. #if (PNG_DEBUG > 0)
  183745. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183746. #include <crtdbg.h>
  183747. #if (PNG_DEBUG > 1)
  183748. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183749. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183750. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183751. #endif
  183752. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183753. #ifndef PNG_DEBUG_FILE
  183754. #define PNG_DEBUG_FILE stderr
  183755. #endif /* PNG_DEBUG_FILE */
  183756. #if (PNG_DEBUG > 1)
  183757. #define png_debug(l,m) \
  183758. { \
  183759. int num_tabs=l; \
  183760. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183761. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183762. }
  183763. #define png_debug1(l,m,p1) \
  183764. { \
  183765. int num_tabs=l; \
  183766. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183767. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183768. }
  183769. #define png_debug2(l,m,p1,p2) \
  183770. { \
  183771. int num_tabs=l; \
  183772. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183773. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183774. }
  183775. #endif /* (PNG_DEBUG > 1) */
  183776. #endif /* _MSC_VER */
  183777. #endif /* (PNG_DEBUG > 0) */
  183778. #endif /* PNG_DEBUG */
  183779. #ifndef png_debug
  183780. #define png_debug(l, m)
  183781. #endif
  183782. #ifndef png_debug1
  183783. #define png_debug1(l, m, p1)
  183784. #endif
  183785. #ifndef png_debug2
  183786. #define png_debug2(l, m, p1, p2)
  183787. #endif
  183788. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183789. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183790. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183791. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183792. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183793. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183794. png_ptr, png_uint_32 mng_features_permitted));
  183795. #endif
  183796. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183797. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183798. #define PNG_HANDLE_CHUNK_NEVER 1
  183799. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183800. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183801. /* Added to version 1.2.0 */
  183802. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183803. #if defined(PNG_MMX_CODE_SUPPORTED)
  183804. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183805. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183806. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183807. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183808. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183809. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183810. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183811. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183812. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183813. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183814. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183815. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183816. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183817. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183818. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183819. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183820. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183821. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183822. | PNG_MMX_READ_FLAGS \
  183823. | PNG_MMX_WRITE_FLAGS )
  183824. #define PNG_SELECT_READ 1
  183825. #define PNG_SELECT_WRITE 2
  183826. #endif /* PNG_MMX_CODE_SUPPORTED */
  183827. #if !defined(PNG_1_0_X)
  183828. /* pngget.c */
  183829. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183830. PNGARG((int flag_select, int *compilerID));
  183831. /* pngget.c */
  183832. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183833. PNGARG((int flag_select));
  183834. /* pngget.c */
  183835. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183836. PNGARG((png_structp png_ptr));
  183837. /* pngget.c */
  183838. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183839. PNGARG((png_structp png_ptr));
  183840. /* pngget.c */
  183841. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183842. PNGARG((png_structp png_ptr));
  183843. /* pngset.c */
  183844. extern PNG_EXPORT(void,png_set_asm_flags)
  183845. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183846. /* pngset.c */
  183847. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183848. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183849. png_uint_32 mmx_rowbytes_threshold));
  183850. #endif /* PNG_1_0_X */
  183851. #if !defined(PNG_1_0_X)
  183852. /* png.c, pnggccrd.c, or pngvcrd.c */
  183853. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183854. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183855. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183856. * messages before passing them to the error or warning handler. */
  183857. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183858. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183859. png_ptr, png_uint_32 strip_mode));
  183860. #endif
  183861. #endif /* PNG_1_0_X */
  183862. /* Added at libpng-1.2.6 */
  183863. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183864. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183865. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183866. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183867. png_ptr));
  183868. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183869. png_ptr));
  183870. #endif
  183871. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183872. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183873. /* With these routines we avoid an integer divide, which will be slower on
  183874. * most machines. However, it does take more operations than the corresponding
  183875. * divide method, so it may be slower on a few RISC systems. There are two
  183876. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183877. *
  183878. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183879. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183880. * standard method.
  183881. *
  183882. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183883. */
  183884. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183885. # define png_composite(composite, fg, alpha, bg) \
  183886. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183887. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183888. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183889. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183890. # define png_composite_16(composite, fg, alpha, bg) \
  183891. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183892. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183893. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183894. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183895. #else /* standard method using integer division */
  183896. # define png_composite(composite, fg, alpha, bg) \
  183897. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183898. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183899. (png_uint_16)127) / 255)
  183900. # define png_composite_16(composite, fg, alpha, bg) \
  183901. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183902. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183903. (png_uint_32)32767) / (png_uint_32)65535L)
  183904. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183905. /* Inline macros to do direct reads of bytes from the input buffer. These
  183906. * require that you are using an architecture that uses PNG byte ordering
  183907. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183908. * in big-endian mode and 680x0 are the only ones that will support this.
  183909. * The x86 line of processors definitely do not. The png_get_int_32()
  183910. * routine also assumes we are using two's complement format for negative
  183911. * values, which is almost certainly true.
  183912. */
  183913. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183914. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183915. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183916. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183917. #else
  183918. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183919. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183920. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183921. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183922. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183923. PNGARG((png_structp png_ptr, png_bytep buf));
  183924. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183925. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183926. */
  183927. extern PNG_EXPORT(void,png_save_uint_32)
  183928. PNGARG((png_bytep buf, png_uint_32 i));
  183929. extern PNG_EXPORT(void,png_save_int_32)
  183930. PNGARG((png_bytep buf, png_int_32 i));
  183931. /* Place a 16-bit number into a buffer in PNG byte order.
  183932. * The parameter is declared unsigned int, not png_uint_16,
  183933. * just to avoid potential problems on pre-ANSI C compilers.
  183934. */
  183935. extern PNG_EXPORT(void,png_save_uint_16)
  183936. PNGARG((png_bytep buf, unsigned int i));
  183937. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183938. /* ************************************************************************* */
  183939. /* These next functions are used internally in the code. They generally
  183940. * shouldn't be used unless you are writing code to add or replace some
  183941. * functionality in libpng. More information about most functions can
  183942. * be found in the files where the functions are located.
  183943. */
  183944. /* Various modes of operation, that are visible to applications because
  183945. * they are used for unknown chunk location.
  183946. */
  183947. #define PNG_HAVE_IHDR 0x01
  183948. #define PNG_HAVE_PLTE 0x02
  183949. #define PNG_HAVE_IDAT 0x04
  183950. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183951. #define PNG_HAVE_IEND 0x10
  183952. #if defined(PNG_INTERNAL)
  183953. /* More modes of operation. Note that after an init, mode is set to
  183954. * zero automatically when the structure is created.
  183955. */
  183956. #define PNG_HAVE_gAMA 0x20
  183957. #define PNG_HAVE_cHRM 0x40
  183958. #define PNG_HAVE_sRGB 0x80
  183959. #define PNG_HAVE_CHUNK_HEADER 0x100
  183960. #define PNG_WROTE_tIME 0x200
  183961. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183962. #define PNG_BACKGROUND_IS_GRAY 0x800
  183963. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183964. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183965. /* flags for the transformations the PNG library does on the image data */
  183966. #define PNG_BGR 0x0001
  183967. #define PNG_INTERLACE 0x0002
  183968. #define PNG_PACK 0x0004
  183969. #define PNG_SHIFT 0x0008
  183970. #define PNG_SWAP_BYTES 0x0010
  183971. #define PNG_INVERT_MONO 0x0020
  183972. #define PNG_DITHER 0x0040
  183973. #define PNG_BACKGROUND 0x0080
  183974. #define PNG_BACKGROUND_EXPAND 0x0100
  183975. /* 0x0200 unused */
  183976. #define PNG_16_TO_8 0x0400
  183977. #define PNG_RGBA 0x0800
  183978. #define PNG_EXPAND 0x1000
  183979. #define PNG_GAMMA 0x2000
  183980. #define PNG_GRAY_TO_RGB 0x4000
  183981. #define PNG_FILLER 0x8000L
  183982. #define PNG_PACKSWAP 0x10000L
  183983. #define PNG_SWAP_ALPHA 0x20000L
  183984. #define PNG_STRIP_ALPHA 0x40000L
  183985. #define PNG_INVERT_ALPHA 0x80000L
  183986. #define PNG_USER_TRANSFORM 0x100000L
  183987. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183988. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183989. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183990. /* 0x800000L Unused */
  183991. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183992. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183993. /* 0x4000000L unused */
  183994. /* 0x8000000L unused */
  183995. /* 0x10000000L unused */
  183996. /* 0x20000000L unused */
  183997. /* 0x40000000L unused */
  183998. /* flags for png_create_struct */
  183999. #define PNG_STRUCT_PNG 0x0001
  184000. #define PNG_STRUCT_INFO 0x0002
  184001. /* Scaling factor for filter heuristic weighting calculations */
  184002. #define PNG_WEIGHT_SHIFT 8
  184003. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  184004. #define PNG_COST_SHIFT 3
  184005. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  184006. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  184007. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  184008. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  184009. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  184010. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  184011. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  184012. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  184013. #define PNG_FLAG_ROW_INIT 0x0040
  184014. #define PNG_FLAG_FILLER_AFTER 0x0080
  184015. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  184016. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  184017. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  184018. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  184019. #define PNG_FLAG_FREE_PLTE 0x1000
  184020. #define PNG_FLAG_FREE_TRNS 0x2000
  184021. #define PNG_FLAG_FREE_HIST 0x4000
  184022. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  184023. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  184024. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  184025. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  184026. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  184027. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  184028. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  184029. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  184030. /* 0x800000L unused */
  184031. /* 0x1000000L unused */
  184032. /* 0x2000000L unused */
  184033. /* 0x4000000L unused */
  184034. /* 0x8000000L unused */
  184035. /* 0x10000000L unused */
  184036. /* 0x20000000L unused */
  184037. /* 0x40000000L unused */
  184038. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  184039. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  184040. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  184041. PNG_FLAG_CRC_CRITICAL_IGNORE)
  184042. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184043. PNG_FLAG_CRC_CRITICAL_MASK)
  184044. /* save typing and make code easier to understand */
  184045. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184046. abs((int)((c1).green) - (int)((c2).green)) + \
  184047. abs((int)((c1).blue) - (int)((c2).blue)))
  184048. /* Added to libpng-1.2.6 JB */
  184049. #define PNG_ROWBYTES(pixel_bits, width) \
  184050. ((pixel_bits) >= 8 ? \
  184051. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  184052. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  184053. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  184054. ideal-delta..ideal+delta. Each argument is evaluated twice.
  184055. "ideal" and "delta" should be constants, normally simple
  184056. integers, "value" a variable. Added to libpng-1.2.6 JB */
  184057. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  184058. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  184059. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  184060. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  184061. /* place to hold the signature string for a PNG file. */
  184062. #ifdef PNG_USE_GLOBAL_ARRAYS
  184063. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  184064. #else
  184065. #endif
  184066. #endif /* PNG_NO_EXTERN */
  184067. /* Constant strings for known chunk types. If you need to add a chunk,
  184068. * define the name here, and add an invocation of the macro in png.c and
  184069. * wherever it's needed.
  184070. */
  184071. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184072. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184073. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184074. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184075. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184076. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184077. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184078. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184079. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184080. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184081. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184082. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184083. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184084. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184085. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184086. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184087. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184088. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184089. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184090. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184091. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184092. #ifdef PNG_USE_GLOBAL_ARRAYS
  184093. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184094. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184095. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184096. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184097. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184098. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184099. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184100. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184101. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184102. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184103. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184104. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184105. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184106. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184107. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184108. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184109. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184110. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184111. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184112. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184113. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184114. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184115. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184116. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184117. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184118. */
  184119. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184120. #undef png_read_init
  184121. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184122. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184123. #endif
  184124. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184125. png_const_charp user_png_ver, png_size_t png_struct_size));
  184126. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184127. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184128. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184129. png_info_size));
  184130. #endif
  184131. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184132. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184133. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184134. */
  184135. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184136. #undef png_write_init
  184137. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184138. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184139. #endif
  184140. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184141. png_const_charp user_png_ver, png_size_t png_struct_size));
  184142. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184143. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184144. png_info_size));
  184145. /* Allocate memory for an internal libpng struct */
  184146. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184147. /* Free memory from internal libpng struct */
  184148. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184149. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184150. malloc_fn, png_voidp mem_ptr));
  184151. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184152. png_free_ptr free_fn, png_voidp mem_ptr));
  184153. /* Free any memory that info_ptr points to and reset struct. */
  184154. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184155. png_infop info_ptr));
  184156. #ifndef PNG_1_0_X
  184157. /* Function to allocate memory for zlib. */
  184158. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184159. /* Function to free memory for zlib */
  184160. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184161. #ifdef PNG_SIZE_T
  184162. /* Function to convert a sizeof an item to png_sizeof item */
  184163. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184164. #endif
  184165. /* Next four functions are used internally as callbacks. PNGAPI is required
  184166. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184167. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184168. png_bytep data, png_size_t length));
  184169. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184170. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184171. png_bytep buffer, png_size_t length));
  184172. #endif
  184173. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184174. png_bytep data, png_size_t length));
  184175. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184176. #if !defined(PNG_NO_STDIO)
  184177. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184178. #endif
  184179. #endif
  184180. #else /* PNG_1_0_X */
  184181. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184182. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184183. png_bytep buffer, png_size_t length));
  184184. #endif
  184185. #endif /* PNG_1_0_X */
  184186. /* Reset the CRC variable */
  184187. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184188. /* Write the "data" buffer to whatever output you are using. */
  184189. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184190. png_size_t length));
  184191. /* Read data from whatever input you are using into the "data" buffer */
  184192. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184193. png_size_t length));
  184194. /* Read bytes into buf, and update png_ptr->crc */
  184195. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184196. png_size_t length));
  184197. /* Decompress data in a chunk that uses compression */
  184198. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184199. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184200. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184201. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184202. png_size_t prefix_length, png_size_t *data_length));
  184203. #endif
  184204. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184205. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184206. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184207. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184208. /* Calculate the CRC over a section of data. Note that we are only
  184209. * passing a maximum of 64K on systems that have this as a memory limit,
  184210. * since this is the maximum buffer size we can specify.
  184211. */
  184212. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184213. png_size_t length));
  184214. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184215. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184216. #endif
  184217. /* simple function to write the signature */
  184218. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184219. /* write various chunks */
  184220. /* Write the IHDR chunk, and update the png_struct with the necessary
  184221. * information.
  184222. */
  184223. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184224. png_uint_32 height,
  184225. int bit_depth, int color_type, int compression_method, int filter_method,
  184226. int interlace_method));
  184227. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184228. png_uint_32 num_pal));
  184229. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184230. png_size_t length));
  184231. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184232. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184233. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184234. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184235. #endif
  184236. #ifdef PNG_FIXED_POINT_SUPPORTED
  184237. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184238. file_gamma));
  184239. #endif
  184240. #endif
  184241. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184242. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184243. int color_type));
  184244. #endif
  184245. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184246. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184247. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184248. double white_x, double white_y,
  184249. double red_x, double red_y, double green_x, double green_y,
  184250. double blue_x, double blue_y));
  184251. #endif
  184252. #ifdef PNG_FIXED_POINT_SUPPORTED
  184253. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184254. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184255. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184256. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184257. png_fixed_point int_blue_y));
  184258. #endif
  184259. #endif
  184260. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184261. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184262. int intent));
  184263. #endif
  184264. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184265. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184266. png_charp name, int compression_type,
  184267. png_charp profile, int proflen));
  184268. /* Note to maintainer: profile should be png_bytep */
  184269. #endif
  184270. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184271. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184272. png_sPLT_tp palette));
  184273. #endif
  184274. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184275. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184276. png_color_16p values, int number, int color_type));
  184277. #endif
  184278. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184279. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184280. png_color_16p values, int color_type));
  184281. #endif
  184282. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184283. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184284. int num_hist));
  184285. #endif
  184286. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184287. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184288. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184289. png_charp key, png_charpp new_key));
  184290. #endif
  184291. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184292. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184293. png_charp text, png_size_t text_len));
  184294. #endif
  184295. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184296. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184297. png_charp text, png_size_t text_len, int compression));
  184298. #endif
  184299. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184300. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184301. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184302. png_charp text));
  184303. #endif
  184304. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184305. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184306. png_infop info_ptr, png_textp text_ptr, int num_text));
  184307. #endif
  184308. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184309. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184310. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184311. #endif
  184312. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184313. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184314. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184315. png_charp units, png_charpp params));
  184316. #endif
  184317. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184318. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184319. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184320. int unit_type));
  184321. #endif
  184322. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184323. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184324. png_timep mod_time));
  184325. #endif
  184326. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184327. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184328. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184329. int unit, double width, double height));
  184330. #else
  184331. #ifdef PNG_FIXED_POINT_SUPPORTED
  184332. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184333. int unit, png_charp width, png_charp height));
  184334. #endif
  184335. #endif
  184336. #endif
  184337. /* Called when finished processing a row of data */
  184338. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184339. /* Internal use only. Called before first row of data */
  184340. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184341. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184342. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184343. #endif
  184344. /* combine a row of data, dealing with alpha, etc. if requested */
  184345. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184346. int mask));
  184347. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184348. /* expand an interlaced row */
  184349. /* OLD pre-1.0.9 interface:
  184350. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184351. png_bytep row, int pass, png_uint_32 transformations));
  184352. */
  184353. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184354. #endif
  184355. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184356. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184357. /* grab pixels out of a row for an interlaced pass */
  184358. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184359. png_bytep row, int pass));
  184360. #endif
  184361. /* unfilter a row */
  184362. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184363. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184364. /* Choose the best filter to use and filter the row data */
  184365. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184366. png_row_infop row_info));
  184367. /* Write out the filtered row. */
  184368. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184369. png_bytep filtered_row));
  184370. /* finish a row while reading, dealing with interlacing passes, etc. */
  184371. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184372. /* initialize the row buffers, etc. */
  184373. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184374. /* optional call to update the users info structure */
  184375. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184376. png_infop info_ptr));
  184377. /* these are the functions that do the transformations */
  184378. #if defined(PNG_READ_FILLER_SUPPORTED)
  184379. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184380. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184381. #endif
  184382. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184383. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184384. png_bytep row));
  184385. #endif
  184386. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184387. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184388. png_bytep row));
  184389. #endif
  184390. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184391. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184392. png_bytep row));
  184393. #endif
  184394. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184395. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184396. png_bytep row));
  184397. #endif
  184398. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184399. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184400. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184401. png_bytep row, png_uint_32 flags));
  184402. #endif
  184403. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184404. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184405. #endif
  184406. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184407. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184408. #endif
  184409. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184410. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184411. row_info, png_bytep row));
  184412. #endif
  184413. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184414. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184415. png_bytep row));
  184416. #endif
  184417. #if defined(PNG_READ_PACK_SUPPORTED)
  184418. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184419. #endif
  184420. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184421. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184422. png_color_8p sig_bits));
  184423. #endif
  184424. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184425. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184426. #endif
  184427. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184428. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184429. #endif
  184430. #if defined(PNG_READ_DITHER_SUPPORTED)
  184431. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184432. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184433. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184434. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184435. png_colorp palette, int num_palette));
  184436. # endif
  184437. #endif
  184438. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184439. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184440. #endif
  184441. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184442. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184443. png_bytep row, png_uint_32 bit_depth));
  184444. #endif
  184445. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184446. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184447. png_color_8p bit_depth));
  184448. #endif
  184449. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184450. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184451. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184452. png_color_16p trans_values, png_color_16p background,
  184453. png_color_16p background_1,
  184454. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184455. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184456. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184457. #else
  184458. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184459. png_color_16p trans_values, png_color_16p background));
  184460. #endif
  184461. #endif
  184462. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184463. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184464. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184465. int gamma_shift));
  184466. #endif
  184467. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184468. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184469. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184470. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184471. png_bytep row, png_color_16p trans_value));
  184472. #endif
  184473. /* The following decodes the appropriate chunks, and does error correction,
  184474. * then calls the appropriate callback for the chunk if it is valid.
  184475. */
  184476. /* decode the IHDR chunk */
  184477. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184478. png_uint_32 length));
  184479. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184480. png_uint_32 length));
  184481. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184482. png_uint_32 length));
  184483. #if defined(PNG_READ_bKGD_SUPPORTED)
  184484. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184485. png_uint_32 length));
  184486. #endif
  184487. #if defined(PNG_READ_cHRM_SUPPORTED)
  184488. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184489. png_uint_32 length));
  184490. #endif
  184491. #if defined(PNG_READ_gAMA_SUPPORTED)
  184492. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184493. png_uint_32 length));
  184494. #endif
  184495. #if defined(PNG_READ_hIST_SUPPORTED)
  184496. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184497. png_uint_32 length));
  184498. #endif
  184499. #if defined(PNG_READ_iCCP_SUPPORTED)
  184500. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184501. png_uint_32 length));
  184502. #endif /* PNG_READ_iCCP_SUPPORTED */
  184503. #if defined(PNG_READ_iTXt_SUPPORTED)
  184504. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184505. png_uint_32 length));
  184506. #endif
  184507. #if defined(PNG_READ_oFFs_SUPPORTED)
  184508. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184509. png_uint_32 length));
  184510. #endif
  184511. #if defined(PNG_READ_pCAL_SUPPORTED)
  184512. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184513. png_uint_32 length));
  184514. #endif
  184515. #if defined(PNG_READ_pHYs_SUPPORTED)
  184516. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184517. png_uint_32 length));
  184518. #endif
  184519. #if defined(PNG_READ_sBIT_SUPPORTED)
  184520. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184521. png_uint_32 length));
  184522. #endif
  184523. #if defined(PNG_READ_sCAL_SUPPORTED)
  184524. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184525. png_uint_32 length));
  184526. #endif
  184527. #if defined(PNG_READ_sPLT_SUPPORTED)
  184528. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184529. png_uint_32 length));
  184530. #endif /* PNG_READ_sPLT_SUPPORTED */
  184531. #if defined(PNG_READ_sRGB_SUPPORTED)
  184532. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184533. png_uint_32 length));
  184534. #endif
  184535. #if defined(PNG_READ_tEXt_SUPPORTED)
  184536. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184537. png_uint_32 length));
  184538. #endif
  184539. #if defined(PNG_READ_tIME_SUPPORTED)
  184540. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184541. png_uint_32 length));
  184542. #endif
  184543. #if defined(PNG_READ_tRNS_SUPPORTED)
  184544. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184545. png_uint_32 length));
  184546. #endif
  184547. #if defined(PNG_READ_zTXt_SUPPORTED)
  184548. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184549. png_uint_32 length));
  184550. #endif
  184551. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184552. png_infop info_ptr, png_uint_32 length));
  184553. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184554. png_bytep chunk_name));
  184555. /* handle the transformations for reading and writing */
  184556. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184557. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184558. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184559. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184560. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184561. png_infop info_ptr));
  184562. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184563. png_infop info_ptr));
  184564. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184565. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184566. png_uint_32 length));
  184567. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184568. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184569. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184570. png_bytep buffer, png_size_t buffer_length));
  184571. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184572. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184573. png_bytep buffer, png_size_t buffer_length));
  184574. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184575. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184576. png_infop info_ptr, png_uint_32 length));
  184577. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184578. png_infop info_ptr));
  184579. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184580. png_infop info_ptr));
  184581. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184582. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184583. png_infop info_ptr));
  184584. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184585. png_infop info_ptr));
  184586. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184587. #if defined(PNG_READ_tEXt_SUPPORTED)
  184588. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184589. png_infop info_ptr, png_uint_32 length));
  184590. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184591. png_infop info_ptr));
  184592. #endif
  184593. #if defined(PNG_READ_zTXt_SUPPORTED)
  184594. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184595. png_infop info_ptr, png_uint_32 length));
  184596. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184597. png_infop info_ptr));
  184598. #endif
  184599. #if defined(PNG_READ_iTXt_SUPPORTED)
  184600. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184601. png_infop info_ptr, png_uint_32 length));
  184602. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184603. png_infop info_ptr));
  184604. #endif
  184605. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184606. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184607. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184608. png_bytep row));
  184609. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184610. png_bytep row));
  184611. #endif
  184612. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184613. #if defined(PNG_MMX_CODE_SUPPORTED)
  184614. /* png.c */ /* PRIVATE */
  184615. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184616. #endif
  184617. #endif
  184618. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184619. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184620. png_infop info_ptr));
  184621. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184622. png_infop info_ptr));
  184623. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184624. png_infop info_ptr));
  184625. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184626. png_infop info_ptr));
  184627. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184628. png_infop info_ptr));
  184629. #if defined(PNG_pHYs_SUPPORTED)
  184630. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184631. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184632. #endif /* PNG_pHYs_SUPPORTED */
  184633. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184634. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184635. #endif /* PNG_INTERNAL */
  184636. #ifdef __cplusplus
  184637. //}
  184638. #endif
  184639. #endif /* PNG_VERSION_INFO_ONLY */
  184640. /* do not put anything past this line */
  184641. #endif /* PNG_H */
  184642. /*** End of inlined file: png.h ***/
  184643. #define PNG_NO_EXTERN
  184644. /*** Start of inlined file: png.c ***/
  184645. /* png.c - location for general purpose libpng functions
  184646. *
  184647. * Last changed in libpng 1.2.21 [October 4, 2007]
  184648. * For conditions of distribution and use, see copyright notice in png.h
  184649. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184650. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184651. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184652. */
  184653. #define PNG_INTERNAL
  184654. #define PNG_NO_EXTERN
  184655. /* Generate a compiler error if there is an old png.h in the search path. */
  184656. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184657. /* Version information for C files. This had better match the version
  184658. * string defined in png.h. */
  184659. #ifdef PNG_USE_GLOBAL_ARRAYS
  184660. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184661. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184662. #ifdef PNG_READ_SUPPORTED
  184663. /* png_sig was changed to a function in version 1.0.5c */
  184664. /* Place to hold the signature string for a PNG file. */
  184665. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184666. #endif /* PNG_READ_SUPPORTED */
  184667. /* Invoke global declarations for constant strings for known chunk types */
  184668. PNG_IHDR;
  184669. PNG_IDAT;
  184670. PNG_IEND;
  184671. PNG_PLTE;
  184672. PNG_bKGD;
  184673. PNG_cHRM;
  184674. PNG_gAMA;
  184675. PNG_hIST;
  184676. PNG_iCCP;
  184677. PNG_iTXt;
  184678. PNG_oFFs;
  184679. PNG_pCAL;
  184680. PNG_sCAL;
  184681. PNG_pHYs;
  184682. PNG_sBIT;
  184683. PNG_sPLT;
  184684. PNG_sRGB;
  184685. PNG_tEXt;
  184686. PNG_tIME;
  184687. PNG_tRNS;
  184688. PNG_zTXt;
  184689. #ifdef PNG_READ_SUPPORTED
  184690. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184691. /* start of interlace block */
  184692. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184693. /* offset to next interlace block */
  184694. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184695. /* start of interlace block in the y direction */
  184696. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184697. /* offset to next interlace block in the y direction */
  184698. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184699. /* Height of interlace block. This is not currently used - if you need
  184700. * it, uncomment it here and in png.h
  184701. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184702. */
  184703. /* Mask to determine which pixels are valid in a pass */
  184704. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184705. /* Mask to determine which pixels to overwrite while displaying */
  184706. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184707. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184708. #endif /* PNG_READ_SUPPORTED */
  184709. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184710. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184711. * of the PNG file signature. If the PNG data is embedded into another
  184712. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184713. * or write any of the magic bytes before it starts on the IHDR.
  184714. */
  184715. #ifdef PNG_READ_SUPPORTED
  184716. void PNGAPI
  184717. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184718. {
  184719. if(png_ptr == NULL) return;
  184720. png_debug(1, "in png_set_sig_bytes\n");
  184721. if (num_bytes > 8)
  184722. png_error(png_ptr, "Too many bytes for PNG signature.");
  184723. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184724. }
  184725. /* Checks whether the supplied bytes match the PNG signature. We allow
  184726. * checking less than the full 8-byte signature so that those apps that
  184727. * already read the first few bytes of a file to determine the file type
  184728. * can simply check the remaining bytes for extra assurance. Returns
  184729. * an integer less than, equal to, or greater than zero if sig is found,
  184730. * respectively, to be less than, to match, or be greater than the correct
  184731. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184732. */
  184733. int PNGAPI
  184734. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184735. {
  184736. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184737. if (num_to_check > 8)
  184738. num_to_check = 8;
  184739. else if (num_to_check < 1)
  184740. return (-1);
  184741. if (start > 7)
  184742. return (-1);
  184743. if (start + num_to_check > 8)
  184744. num_to_check = 8 - start;
  184745. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184746. }
  184747. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184748. /* (Obsolete) function to check signature bytes. It does not allow one
  184749. * to check a partial signature. This function might be removed in the
  184750. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184751. */
  184752. int PNGAPI
  184753. png_check_sig(png_bytep sig, int num)
  184754. {
  184755. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184756. }
  184757. #endif
  184758. #endif /* PNG_READ_SUPPORTED */
  184759. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184760. /* Function to allocate memory for zlib and clear it to 0. */
  184761. #ifdef PNG_1_0_X
  184762. voidpf PNGAPI
  184763. #else
  184764. voidpf /* private */
  184765. #endif
  184766. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184767. {
  184768. png_voidp ptr;
  184769. png_structp p=(png_structp)png_ptr;
  184770. png_uint_32 save_flags=p->flags;
  184771. png_uint_32 num_bytes;
  184772. if(png_ptr == NULL) return (NULL);
  184773. if (items > PNG_UINT_32_MAX/size)
  184774. {
  184775. png_warning (p, "Potential overflow in png_zalloc()");
  184776. return (NULL);
  184777. }
  184778. num_bytes = (png_uint_32)items * size;
  184779. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184780. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184781. p->flags=save_flags;
  184782. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184783. if (ptr == NULL)
  184784. return ((voidpf)ptr);
  184785. if (num_bytes > (png_uint_32)0x8000L)
  184786. {
  184787. png_memset(ptr, 0, (png_size_t)0x8000L);
  184788. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184789. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184790. }
  184791. else
  184792. {
  184793. png_memset(ptr, 0, (png_size_t)num_bytes);
  184794. }
  184795. #endif
  184796. return ((voidpf)ptr);
  184797. }
  184798. /* function to free memory for zlib */
  184799. #ifdef PNG_1_0_X
  184800. void PNGAPI
  184801. #else
  184802. void /* private */
  184803. #endif
  184804. png_zfree(voidpf png_ptr, voidpf ptr)
  184805. {
  184806. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184807. }
  184808. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184809. * in case CRC is > 32 bits to leave the top bits 0.
  184810. */
  184811. void /* PRIVATE */
  184812. png_reset_crc(png_structp png_ptr)
  184813. {
  184814. png_ptr->crc = crc32(0, Z_NULL, 0);
  184815. }
  184816. /* Calculate the CRC over a section of data. We can only pass as
  184817. * much data to this routine as the largest single buffer size. We
  184818. * also check that this data will actually be used before going to the
  184819. * trouble of calculating it.
  184820. */
  184821. void /* PRIVATE */
  184822. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184823. {
  184824. int need_crc = 1;
  184825. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184826. {
  184827. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184828. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184829. need_crc = 0;
  184830. }
  184831. else /* critical */
  184832. {
  184833. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184834. need_crc = 0;
  184835. }
  184836. if (need_crc)
  184837. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184838. }
  184839. /* Allocate the memory for an info_struct for the application. We don't
  184840. * really need the png_ptr, but it could potentially be useful in the
  184841. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184842. * and png_info_init() so that applications that want to use a shared
  184843. * libpng don't have to be recompiled if png_info changes size.
  184844. */
  184845. png_infop PNGAPI
  184846. png_create_info_struct(png_structp png_ptr)
  184847. {
  184848. png_infop info_ptr;
  184849. png_debug(1, "in png_create_info_struct\n");
  184850. if(png_ptr == NULL) return (NULL);
  184851. #ifdef PNG_USER_MEM_SUPPORTED
  184852. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184853. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184854. #else
  184855. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184856. #endif
  184857. if (info_ptr != NULL)
  184858. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184859. return (info_ptr);
  184860. }
  184861. /* This function frees the memory associated with a single info struct.
  184862. * Normally, one would use either png_destroy_read_struct() or
  184863. * png_destroy_write_struct() to free an info struct, but this may be
  184864. * useful for some applications.
  184865. */
  184866. void PNGAPI
  184867. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184868. {
  184869. png_infop info_ptr = NULL;
  184870. if(png_ptr == NULL) return;
  184871. png_debug(1, "in png_destroy_info_struct\n");
  184872. if (info_ptr_ptr != NULL)
  184873. info_ptr = *info_ptr_ptr;
  184874. if (info_ptr != NULL)
  184875. {
  184876. png_info_destroy(png_ptr, info_ptr);
  184877. #ifdef PNG_USER_MEM_SUPPORTED
  184878. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184879. png_ptr->mem_ptr);
  184880. #else
  184881. png_destroy_struct((png_voidp)info_ptr);
  184882. #endif
  184883. *info_ptr_ptr = NULL;
  184884. }
  184885. }
  184886. /* Initialize the info structure. This is now an internal function (0.89)
  184887. * and applications using it are urged to use png_create_info_struct()
  184888. * instead.
  184889. */
  184890. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184891. #undef png_info_init
  184892. void PNGAPI
  184893. png_info_init(png_infop info_ptr)
  184894. {
  184895. /* We only come here via pre-1.0.12-compiled applications */
  184896. png_info_init_3(&info_ptr, 0);
  184897. }
  184898. #endif
  184899. void PNGAPI
  184900. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184901. {
  184902. png_infop info_ptr = *ptr_ptr;
  184903. if(info_ptr == NULL) return;
  184904. png_debug(1, "in png_info_init_3\n");
  184905. if(png_sizeof(png_info) > png_info_struct_size)
  184906. {
  184907. png_destroy_struct(info_ptr);
  184908. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184909. *ptr_ptr = info_ptr;
  184910. }
  184911. /* set everything to 0 */
  184912. png_memset(info_ptr, 0, png_sizeof (png_info));
  184913. }
  184914. #ifdef PNG_FREE_ME_SUPPORTED
  184915. void PNGAPI
  184916. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184917. int freer, png_uint_32 mask)
  184918. {
  184919. png_debug(1, "in png_data_freer\n");
  184920. if (png_ptr == NULL || info_ptr == NULL)
  184921. return;
  184922. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184923. info_ptr->free_me |= mask;
  184924. else if(freer == PNG_USER_WILL_FREE_DATA)
  184925. info_ptr->free_me &= ~mask;
  184926. else
  184927. png_warning(png_ptr,
  184928. "Unknown freer parameter in png_data_freer.");
  184929. }
  184930. #endif
  184931. void PNGAPI
  184932. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184933. int num)
  184934. {
  184935. png_debug(1, "in png_free_data\n");
  184936. if (png_ptr == NULL || info_ptr == NULL)
  184937. return;
  184938. #if defined(PNG_TEXT_SUPPORTED)
  184939. /* free text item num or (if num == -1) all text items */
  184940. #ifdef PNG_FREE_ME_SUPPORTED
  184941. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184942. #else
  184943. if (mask & PNG_FREE_TEXT)
  184944. #endif
  184945. {
  184946. if (num != -1)
  184947. {
  184948. if (info_ptr->text && info_ptr->text[num].key)
  184949. {
  184950. png_free(png_ptr, info_ptr->text[num].key);
  184951. info_ptr->text[num].key = NULL;
  184952. }
  184953. }
  184954. else
  184955. {
  184956. int i;
  184957. for (i = 0; i < info_ptr->num_text; i++)
  184958. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184959. png_free(png_ptr, info_ptr->text);
  184960. info_ptr->text = NULL;
  184961. info_ptr->num_text=0;
  184962. }
  184963. }
  184964. #endif
  184965. #if defined(PNG_tRNS_SUPPORTED)
  184966. /* free any tRNS entry */
  184967. #ifdef PNG_FREE_ME_SUPPORTED
  184968. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184969. #else
  184970. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184971. #endif
  184972. {
  184973. png_free(png_ptr, info_ptr->trans);
  184974. info_ptr->valid &= ~PNG_INFO_tRNS;
  184975. #ifndef PNG_FREE_ME_SUPPORTED
  184976. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184977. #endif
  184978. info_ptr->trans = NULL;
  184979. }
  184980. #endif
  184981. #if defined(PNG_sCAL_SUPPORTED)
  184982. /* free any sCAL entry */
  184983. #ifdef PNG_FREE_ME_SUPPORTED
  184984. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184985. #else
  184986. if (mask & PNG_FREE_SCAL)
  184987. #endif
  184988. {
  184989. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184990. png_free(png_ptr, info_ptr->scal_s_width);
  184991. png_free(png_ptr, info_ptr->scal_s_height);
  184992. info_ptr->scal_s_width = NULL;
  184993. info_ptr->scal_s_height = NULL;
  184994. #endif
  184995. info_ptr->valid &= ~PNG_INFO_sCAL;
  184996. }
  184997. #endif
  184998. #if defined(PNG_pCAL_SUPPORTED)
  184999. /* free any pCAL entry */
  185000. #ifdef PNG_FREE_ME_SUPPORTED
  185001. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  185002. #else
  185003. if (mask & PNG_FREE_PCAL)
  185004. #endif
  185005. {
  185006. png_free(png_ptr, info_ptr->pcal_purpose);
  185007. png_free(png_ptr, info_ptr->pcal_units);
  185008. info_ptr->pcal_purpose = NULL;
  185009. info_ptr->pcal_units = NULL;
  185010. if (info_ptr->pcal_params != NULL)
  185011. {
  185012. int i;
  185013. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  185014. {
  185015. png_free(png_ptr, info_ptr->pcal_params[i]);
  185016. info_ptr->pcal_params[i]=NULL;
  185017. }
  185018. png_free(png_ptr, info_ptr->pcal_params);
  185019. info_ptr->pcal_params = NULL;
  185020. }
  185021. info_ptr->valid &= ~PNG_INFO_pCAL;
  185022. }
  185023. #endif
  185024. #if defined(PNG_iCCP_SUPPORTED)
  185025. /* free any iCCP entry */
  185026. #ifdef PNG_FREE_ME_SUPPORTED
  185027. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  185028. #else
  185029. if (mask & PNG_FREE_ICCP)
  185030. #endif
  185031. {
  185032. png_free(png_ptr, info_ptr->iccp_name);
  185033. png_free(png_ptr, info_ptr->iccp_profile);
  185034. info_ptr->iccp_name = NULL;
  185035. info_ptr->iccp_profile = NULL;
  185036. info_ptr->valid &= ~PNG_INFO_iCCP;
  185037. }
  185038. #endif
  185039. #if defined(PNG_sPLT_SUPPORTED)
  185040. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  185041. #ifdef PNG_FREE_ME_SUPPORTED
  185042. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185043. #else
  185044. if (mask & PNG_FREE_SPLT)
  185045. #endif
  185046. {
  185047. if (num != -1)
  185048. {
  185049. if(info_ptr->splt_palettes)
  185050. {
  185051. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  185052. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  185053. info_ptr->splt_palettes[num].name = NULL;
  185054. info_ptr->splt_palettes[num].entries = NULL;
  185055. }
  185056. }
  185057. else
  185058. {
  185059. if(info_ptr->splt_palettes_num)
  185060. {
  185061. int i;
  185062. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  185063. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  185064. png_free(png_ptr, info_ptr->splt_palettes);
  185065. info_ptr->splt_palettes = NULL;
  185066. info_ptr->splt_palettes_num = 0;
  185067. }
  185068. info_ptr->valid &= ~PNG_INFO_sPLT;
  185069. }
  185070. }
  185071. #endif
  185072. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185073. if(png_ptr->unknown_chunk.data)
  185074. {
  185075. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185076. png_ptr->unknown_chunk.data = NULL;
  185077. }
  185078. #ifdef PNG_FREE_ME_SUPPORTED
  185079. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185080. #else
  185081. if (mask & PNG_FREE_UNKN)
  185082. #endif
  185083. {
  185084. if (num != -1)
  185085. {
  185086. if(info_ptr->unknown_chunks)
  185087. {
  185088. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185089. info_ptr->unknown_chunks[num].data = NULL;
  185090. }
  185091. }
  185092. else
  185093. {
  185094. int i;
  185095. if(info_ptr->unknown_chunks_num)
  185096. {
  185097. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185098. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185099. png_free(png_ptr, info_ptr->unknown_chunks);
  185100. info_ptr->unknown_chunks = NULL;
  185101. info_ptr->unknown_chunks_num = 0;
  185102. }
  185103. }
  185104. }
  185105. #endif
  185106. #if defined(PNG_hIST_SUPPORTED)
  185107. /* free any hIST entry */
  185108. #ifdef PNG_FREE_ME_SUPPORTED
  185109. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185110. #else
  185111. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185112. #endif
  185113. {
  185114. png_free(png_ptr, info_ptr->hist);
  185115. info_ptr->hist = NULL;
  185116. info_ptr->valid &= ~PNG_INFO_hIST;
  185117. #ifndef PNG_FREE_ME_SUPPORTED
  185118. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185119. #endif
  185120. }
  185121. #endif
  185122. /* free any PLTE entry that was internally allocated */
  185123. #ifdef PNG_FREE_ME_SUPPORTED
  185124. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185125. #else
  185126. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185127. #endif
  185128. {
  185129. png_zfree(png_ptr, info_ptr->palette);
  185130. info_ptr->palette = NULL;
  185131. info_ptr->valid &= ~PNG_INFO_PLTE;
  185132. #ifndef PNG_FREE_ME_SUPPORTED
  185133. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185134. #endif
  185135. info_ptr->num_palette = 0;
  185136. }
  185137. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185138. /* free any image bits attached to the info structure */
  185139. #ifdef PNG_FREE_ME_SUPPORTED
  185140. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185141. #else
  185142. if (mask & PNG_FREE_ROWS)
  185143. #endif
  185144. {
  185145. if(info_ptr->row_pointers)
  185146. {
  185147. int row;
  185148. for (row = 0; row < (int)info_ptr->height; row++)
  185149. {
  185150. png_free(png_ptr, info_ptr->row_pointers[row]);
  185151. info_ptr->row_pointers[row]=NULL;
  185152. }
  185153. png_free(png_ptr, info_ptr->row_pointers);
  185154. info_ptr->row_pointers=NULL;
  185155. }
  185156. info_ptr->valid &= ~PNG_INFO_IDAT;
  185157. }
  185158. #endif
  185159. #ifdef PNG_FREE_ME_SUPPORTED
  185160. if(num == -1)
  185161. info_ptr->free_me &= ~mask;
  185162. else
  185163. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185164. #endif
  185165. }
  185166. /* This is an internal routine to free any memory that the info struct is
  185167. * pointing to before re-using it or freeing the struct itself. Recall
  185168. * that png_free() checks for NULL pointers for us.
  185169. */
  185170. void /* PRIVATE */
  185171. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185172. {
  185173. png_debug(1, "in png_info_destroy\n");
  185174. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185175. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185176. if (png_ptr->num_chunk_list)
  185177. {
  185178. png_free(png_ptr, png_ptr->chunk_list);
  185179. png_ptr->chunk_list=NULL;
  185180. png_ptr->num_chunk_list=0;
  185181. }
  185182. #endif
  185183. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185184. }
  185185. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185186. /* This function returns a pointer to the io_ptr associated with the user
  185187. * functions. The application should free any memory associated with this
  185188. * pointer before png_write_destroy() or png_read_destroy() are called.
  185189. */
  185190. png_voidp PNGAPI
  185191. png_get_io_ptr(png_structp png_ptr)
  185192. {
  185193. if(png_ptr == NULL) return (NULL);
  185194. return (png_ptr->io_ptr);
  185195. }
  185196. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185197. #if !defined(PNG_NO_STDIO)
  185198. /* Initialize the default input/output functions for the PNG file. If you
  185199. * use your own read or write routines, you can call either png_set_read_fn()
  185200. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185201. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185202. * necessarily available.
  185203. */
  185204. void PNGAPI
  185205. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185206. {
  185207. png_debug(1, "in png_init_io\n");
  185208. if(png_ptr == NULL) return;
  185209. png_ptr->io_ptr = (png_voidp)fp;
  185210. }
  185211. #endif
  185212. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185213. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185214. * a "Creation Time" or other text-based time string.
  185215. */
  185216. png_charp PNGAPI
  185217. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185218. {
  185219. static PNG_CONST char short_months[12][4] =
  185220. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185221. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185222. if(png_ptr == NULL) return (NULL);
  185223. if (png_ptr->time_buffer == NULL)
  185224. {
  185225. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185226. png_sizeof(char)));
  185227. }
  185228. #if defined(_WIN32_WCE)
  185229. {
  185230. wchar_t time_buf[29];
  185231. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185232. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185233. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185234. ptime->second % 61);
  185235. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185236. NULL, NULL);
  185237. }
  185238. #else
  185239. #ifdef USE_FAR_KEYWORD
  185240. {
  185241. char near_time_buf[29];
  185242. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185243. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185244. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185245. ptime->second % 61);
  185246. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185247. 29*png_sizeof(char));
  185248. }
  185249. #else
  185250. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185251. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185252. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185253. ptime->second % 61);
  185254. #endif
  185255. #endif /* _WIN32_WCE */
  185256. return ((png_charp)png_ptr->time_buffer);
  185257. }
  185258. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185259. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185260. png_charp PNGAPI
  185261. png_get_copyright(png_structp png_ptr)
  185262. {
  185263. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185264. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185265. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185266. Copyright (c) 1996-1997 Andreas Dilger\n\
  185267. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185268. }
  185269. /* The following return the library version as a short string in the
  185270. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185271. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185272. * is defined in png.h.
  185273. * Note: now there is no difference between png_get_libpng_ver() and
  185274. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185275. * it is guaranteed that png.c uses the correct version of png.h.
  185276. */
  185277. png_charp PNGAPI
  185278. png_get_libpng_ver(png_structp png_ptr)
  185279. {
  185280. /* Version of *.c files used when building libpng */
  185281. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185282. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185283. }
  185284. png_charp PNGAPI
  185285. png_get_header_ver(png_structp png_ptr)
  185286. {
  185287. /* Version of *.h files used when building libpng */
  185288. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185289. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185290. }
  185291. png_charp PNGAPI
  185292. png_get_header_version(png_structp png_ptr)
  185293. {
  185294. /* Returns longer string containing both version and date */
  185295. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185296. return ((png_charp) PNG_HEADER_VERSION_STRING
  185297. #ifndef PNG_READ_SUPPORTED
  185298. " (NO READ SUPPORT)"
  185299. #endif
  185300. "\n");
  185301. }
  185302. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185303. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185304. int PNGAPI
  185305. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185306. {
  185307. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185308. int i;
  185309. png_bytep p;
  185310. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185311. return 0;
  185312. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185313. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185314. if (!png_memcmp(chunk_name, p, 4))
  185315. return ((int)*(p+4));
  185316. return 0;
  185317. }
  185318. #endif
  185319. /* This function, added to libpng-1.0.6g, is untested. */
  185320. int PNGAPI
  185321. png_reset_zstream(png_structp png_ptr)
  185322. {
  185323. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185324. return (inflateReset(&png_ptr->zstream));
  185325. }
  185326. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185327. /* This function was added to libpng-1.0.7 */
  185328. png_uint_32 PNGAPI
  185329. png_access_version_number(void)
  185330. {
  185331. /* Version of *.c files used when building libpng */
  185332. return((png_uint_32) PNG_LIBPNG_VER);
  185333. }
  185334. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185335. #if !defined(PNG_1_0_X)
  185336. /* this function was added to libpng 1.2.0 */
  185337. int PNGAPI
  185338. png_mmx_support(void)
  185339. {
  185340. /* obsolete, to be removed from libpng-1.4.0 */
  185341. return -1;
  185342. }
  185343. #endif /* PNG_1_0_X */
  185344. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185345. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185346. #ifdef PNG_SIZE_T
  185347. /* Added at libpng version 1.2.6 */
  185348. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185349. png_size_t PNGAPI
  185350. png_convert_size(size_t size)
  185351. {
  185352. if (size > (png_size_t)-1)
  185353. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185354. return ((png_size_t)size);
  185355. }
  185356. #endif /* PNG_SIZE_T */
  185357. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185358. /*** End of inlined file: png.c ***/
  185359. /*** Start of inlined file: pngerror.c ***/
  185360. /* pngerror.c - stub functions for i/o and memory allocation
  185361. *
  185362. * Last changed in libpng 1.2.20 October 4, 2007
  185363. * For conditions of distribution and use, see copyright notice in png.h
  185364. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185365. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185366. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185367. *
  185368. * This file provides a location for all error handling. Users who
  185369. * need special error handling are expected to write replacement functions
  185370. * and use png_set_error_fn() to use those functions. See the instructions
  185371. * at each function.
  185372. */
  185373. #define PNG_INTERNAL
  185374. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185375. static void /* PRIVATE */
  185376. png_default_error PNGARG((png_structp png_ptr,
  185377. png_const_charp error_message));
  185378. #ifndef PNG_NO_WARNINGS
  185379. static void /* PRIVATE */
  185380. png_default_warning PNGARG((png_structp png_ptr,
  185381. png_const_charp warning_message));
  185382. #endif /* PNG_NO_WARNINGS */
  185383. /* This function is called whenever there is a fatal error. This function
  185384. * should not be changed. If there is a need to handle errors differently,
  185385. * you should supply a replacement error function and use png_set_error_fn()
  185386. * to replace the error function at run-time.
  185387. */
  185388. #ifndef PNG_NO_ERROR_TEXT
  185389. void PNGAPI
  185390. png_error(png_structp png_ptr, png_const_charp error_message)
  185391. {
  185392. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185393. char msg[16];
  185394. if (png_ptr != NULL)
  185395. {
  185396. if (png_ptr->flags&
  185397. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185398. {
  185399. if (*error_message == '#')
  185400. {
  185401. int offset;
  185402. for (offset=1; offset<15; offset++)
  185403. if (*(error_message+offset) == ' ')
  185404. break;
  185405. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185406. {
  185407. int i;
  185408. for (i=0; i<offset-1; i++)
  185409. msg[i]=error_message[i+1];
  185410. msg[i]='\0';
  185411. error_message=msg;
  185412. }
  185413. else
  185414. error_message+=offset;
  185415. }
  185416. else
  185417. {
  185418. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185419. {
  185420. msg[0]='0';
  185421. msg[1]='\0';
  185422. error_message=msg;
  185423. }
  185424. }
  185425. }
  185426. }
  185427. #endif
  185428. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185429. (*(png_ptr->error_fn))(png_ptr, error_message);
  185430. /* If the custom handler doesn't exist, or if it returns,
  185431. use the default handler, which will not return. */
  185432. png_default_error(png_ptr, error_message);
  185433. }
  185434. #else
  185435. void PNGAPI
  185436. png_err(png_structp png_ptr)
  185437. {
  185438. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185439. (*(png_ptr->error_fn))(png_ptr, '\0');
  185440. /* If the custom handler doesn't exist, or if it returns,
  185441. use the default handler, which will not return. */
  185442. png_default_error(png_ptr, '\0');
  185443. }
  185444. #endif /* PNG_NO_ERROR_TEXT */
  185445. #ifndef PNG_NO_WARNINGS
  185446. /* This function is called whenever there is a non-fatal error. This function
  185447. * should not be changed. If there is a need to handle warnings differently,
  185448. * you should supply a replacement warning function and use
  185449. * png_set_error_fn() to replace the warning function at run-time.
  185450. */
  185451. void PNGAPI
  185452. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185453. {
  185454. int offset = 0;
  185455. if (png_ptr != NULL)
  185456. {
  185457. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185458. if (png_ptr->flags&
  185459. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185460. #endif
  185461. {
  185462. if (*warning_message == '#')
  185463. {
  185464. for (offset=1; offset<15; offset++)
  185465. if (*(warning_message+offset) == ' ')
  185466. break;
  185467. }
  185468. }
  185469. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185470. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185471. }
  185472. else
  185473. png_default_warning(png_ptr, warning_message+offset);
  185474. }
  185475. #endif /* PNG_NO_WARNINGS */
  185476. /* These utilities are used internally to build an error message that relates
  185477. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185478. * this is used to prefix the message. The message is limited in length
  185479. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185480. * if the character is invalid.
  185481. */
  185482. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185483. /*static PNG_CONST char png_digit[16] = {
  185484. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185485. 'A', 'B', 'C', 'D', 'E', 'F'
  185486. };*/
  185487. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185488. static void /* PRIVATE */
  185489. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185490. error_message)
  185491. {
  185492. int iout = 0, iin = 0;
  185493. while (iin < 4)
  185494. {
  185495. int c = png_ptr->chunk_name[iin++];
  185496. if (isnonalpha(c))
  185497. {
  185498. buffer[iout++] = '[';
  185499. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185500. buffer[iout++] = png_digit[c & 0x0f];
  185501. buffer[iout++] = ']';
  185502. }
  185503. else
  185504. {
  185505. buffer[iout++] = (png_byte)c;
  185506. }
  185507. }
  185508. if (error_message == NULL)
  185509. buffer[iout] = 0;
  185510. else
  185511. {
  185512. buffer[iout++] = ':';
  185513. buffer[iout++] = ' ';
  185514. png_strncpy(buffer+iout, error_message, 63);
  185515. buffer[iout+63] = 0;
  185516. }
  185517. }
  185518. #ifdef PNG_READ_SUPPORTED
  185519. void PNGAPI
  185520. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185521. {
  185522. char msg[18+64];
  185523. if (png_ptr == NULL)
  185524. png_error(png_ptr, error_message);
  185525. else
  185526. {
  185527. png_format_buffer(png_ptr, msg, error_message);
  185528. png_error(png_ptr, msg);
  185529. }
  185530. }
  185531. #endif /* PNG_READ_SUPPORTED */
  185532. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185533. #ifndef PNG_NO_WARNINGS
  185534. void PNGAPI
  185535. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185536. {
  185537. char msg[18+64];
  185538. if (png_ptr == NULL)
  185539. png_warning(png_ptr, warning_message);
  185540. else
  185541. {
  185542. png_format_buffer(png_ptr, msg, warning_message);
  185543. png_warning(png_ptr, msg);
  185544. }
  185545. }
  185546. #endif /* PNG_NO_WARNINGS */
  185547. /* This is the default error handling function. Note that replacements for
  185548. * this function MUST NOT RETURN, or the program will likely crash. This
  185549. * function is used by default, or if the program supplies NULL for the
  185550. * error function pointer in png_set_error_fn().
  185551. */
  185552. static void /* PRIVATE */
  185553. png_default_error(png_structp, png_const_charp error_message)
  185554. {
  185555. #ifndef PNG_NO_CONSOLE_IO
  185556. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185557. if (*error_message == '#')
  185558. {
  185559. int offset;
  185560. char error_number[16];
  185561. for (offset=0; offset<15; offset++)
  185562. {
  185563. error_number[offset] = *(error_message+offset+1);
  185564. if (*(error_message+offset) == ' ')
  185565. break;
  185566. }
  185567. if((offset > 1) && (offset < 15))
  185568. {
  185569. error_number[offset-1]='\0';
  185570. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185571. error_message+offset);
  185572. }
  185573. else
  185574. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185575. }
  185576. else
  185577. #endif
  185578. fprintf(stderr, "libpng error: %s\n", error_message);
  185579. #endif
  185580. #ifdef PNG_SETJMP_SUPPORTED
  185581. if (png_ptr)
  185582. {
  185583. # ifdef USE_FAR_KEYWORD
  185584. {
  185585. jmp_buf jmpbuf;
  185586. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185587. longjmp(jmpbuf, 1);
  185588. }
  185589. # else
  185590. longjmp(png_ptr->jmpbuf, 1);
  185591. # endif
  185592. }
  185593. #else
  185594. PNG_ABORT();
  185595. #endif
  185596. #ifdef PNG_NO_CONSOLE_IO
  185597. error_message = error_message; /* make compiler happy */
  185598. #endif
  185599. }
  185600. #ifndef PNG_NO_WARNINGS
  185601. /* This function is called when there is a warning, but the library thinks
  185602. * it can continue anyway. Replacement functions don't have to do anything
  185603. * here if you don't want them to. In the default configuration, png_ptr is
  185604. * not used, but it is passed in case it may be useful.
  185605. */
  185606. static void /* PRIVATE */
  185607. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185608. {
  185609. #ifndef PNG_NO_CONSOLE_IO
  185610. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185611. if (*warning_message == '#')
  185612. {
  185613. int offset;
  185614. char warning_number[16];
  185615. for (offset=0; offset<15; offset++)
  185616. {
  185617. warning_number[offset]=*(warning_message+offset+1);
  185618. if (*(warning_message+offset) == ' ')
  185619. break;
  185620. }
  185621. if((offset > 1) && (offset < 15))
  185622. {
  185623. warning_number[offset-1]='\0';
  185624. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185625. warning_message+offset);
  185626. }
  185627. else
  185628. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185629. }
  185630. else
  185631. # endif
  185632. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185633. #else
  185634. warning_message = warning_message; /* make compiler happy */
  185635. #endif
  185636. png_ptr = png_ptr; /* make compiler happy */
  185637. }
  185638. #endif /* PNG_NO_WARNINGS */
  185639. /* This function is called when the application wants to use another method
  185640. * of handling errors and warnings. Note that the error function MUST NOT
  185641. * return to the calling routine or serious problems will occur. The return
  185642. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185643. */
  185644. void PNGAPI
  185645. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185646. png_error_ptr error_fn, png_error_ptr warning_fn)
  185647. {
  185648. if (png_ptr == NULL)
  185649. return;
  185650. png_ptr->error_ptr = error_ptr;
  185651. png_ptr->error_fn = error_fn;
  185652. png_ptr->warning_fn = warning_fn;
  185653. }
  185654. /* This function returns a pointer to the error_ptr associated with the user
  185655. * functions. The application should free any memory associated with this
  185656. * pointer before png_write_destroy and png_read_destroy are called.
  185657. */
  185658. png_voidp PNGAPI
  185659. png_get_error_ptr(png_structp png_ptr)
  185660. {
  185661. if (png_ptr == NULL)
  185662. return NULL;
  185663. return ((png_voidp)png_ptr->error_ptr);
  185664. }
  185665. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185666. void PNGAPI
  185667. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185668. {
  185669. if(png_ptr != NULL)
  185670. {
  185671. png_ptr->flags &=
  185672. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185673. }
  185674. }
  185675. #endif
  185676. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185677. /*** End of inlined file: pngerror.c ***/
  185678. /*** Start of inlined file: pngget.c ***/
  185679. /* pngget.c - retrieval of values from info struct
  185680. *
  185681. * Last changed in libpng 1.2.15 January 5, 2007
  185682. * For conditions of distribution and use, see copyright notice in png.h
  185683. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185684. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185685. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185686. */
  185687. #define PNG_INTERNAL
  185688. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185689. png_uint_32 PNGAPI
  185690. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185691. {
  185692. if (png_ptr != NULL && info_ptr != NULL)
  185693. return(info_ptr->valid & flag);
  185694. else
  185695. return(0);
  185696. }
  185697. png_uint_32 PNGAPI
  185698. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185699. {
  185700. if (png_ptr != NULL && info_ptr != NULL)
  185701. return(info_ptr->rowbytes);
  185702. else
  185703. return(0);
  185704. }
  185705. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185706. png_bytepp PNGAPI
  185707. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185708. {
  185709. if (png_ptr != NULL && info_ptr != NULL)
  185710. return(info_ptr->row_pointers);
  185711. else
  185712. return(0);
  185713. }
  185714. #endif
  185715. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185716. /* easy access to info, added in libpng-0.99 */
  185717. png_uint_32 PNGAPI
  185718. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185719. {
  185720. if (png_ptr != NULL && info_ptr != NULL)
  185721. {
  185722. return info_ptr->width;
  185723. }
  185724. return (0);
  185725. }
  185726. png_uint_32 PNGAPI
  185727. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185728. {
  185729. if (png_ptr != NULL && info_ptr != NULL)
  185730. {
  185731. return info_ptr->height;
  185732. }
  185733. return (0);
  185734. }
  185735. png_byte PNGAPI
  185736. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185737. {
  185738. if (png_ptr != NULL && info_ptr != NULL)
  185739. {
  185740. return info_ptr->bit_depth;
  185741. }
  185742. return (0);
  185743. }
  185744. png_byte PNGAPI
  185745. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185746. {
  185747. if (png_ptr != NULL && info_ptr != NULL)
  185748. {
  185749. return info_ptr->color_type;
  185750. }
  185751. return (0);
  185752. }
  185753. png_byte PNGAPI
  185754. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185755. {
  185756. if (png_ptr != NULL && info_ptr != NULL)
  185757. {
  185758. return info_ptr->filter_type;
  185759. }
  185760. return (0);
  185761. }
  185762. png_byte PNGAPI
  185763. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185764. {
  185765. if (png_ptr != NULL && info_ptr != NULL)
  185766. {
  185767. return info_ptr->interlace_type;
  185768. }
  185769. return (0);
  185770. }
  185771. png_byte PNGAPI
  185772. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185773. {
  185774. if (png_ptr != NULL && info_ptr != NULL)
  185775. {
  185776. return info_ptr->compression_type;
  185777. }
  185778. return (0);
  185779. }
  185780. png_uint_32 PNGAPI
  185781. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185782. {
  185783. if (png_ptr != NULL && info_ptr != NULL)
  185784. #if defined(PNG_pHYs_SUPPORTED)
  185785. if (info_ptr->valid & PNG_INFO_pHYs)
  185786. {
  185787. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185788. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185789. return (0);
  185790. else return (info_ptr->x_pixels_per_unit);
  185791. }
  185792. #else
  185793. return (0);
  185794. #endif
  185795. return (0);
  185796. }
  185797. png_uint_32 PNGAPI
  185798. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185799. {
  185800. if (png_ptr != NULL && info_ptr != NULL)
  185801. #if defined(PNG_pHYs_SUPPORTED)
  185802. if (info_ptr->valid & PNG_INFO_pHYs)
  185803. {
  185804. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185805. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185806. return (0);
  185807. else return (info_ptr->y_pixels_per_unit);
  185808. }
  185809. #else
  185810. return (0);
  185811. #endif
  185812. return (0);
  185813. }
  185814. png_uint_32 PNGAPI
  185815. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185816. {
  185817. if (png_ptr != NULL && info_ptr != NULL)
  185818. #if defined(PNG_pHYs_SUPPORTED)
  185819. if (info_ptr->valid & PNG_INFO_pHYs)
  185820. {
  185821. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185822. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185823. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185824. return (0);
  185825. else return (info_ptr->x_pixels_per_unit);
  185826. }
  185827. #else
  185828. return (0);
  185829. #endif
  185830. return (0);
  185831. }
  185832. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185833. float PNGAPI
  185834. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185835. {
  185836. if (png_ptr != NULL && info_ptr != NULL)
  185837. #if defined(PNG_pHYs_SUPPORTED)
  185838. if (info_ptr->valid & PNG_INFO_pHYs)
  185839. {
  185840. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185841. if (info_ptr->x_pixels_per_unit == 0)
  185842. return ((float)0.0);
  185843. else
  185844. return ((float)((float)info_ptr->y_pixels_per_unit
  185845. /(float)info_ptr->x_pixels_per_unit));
  185846. }
  185847. #else
  185848. return (0.0);
  185849. #endif
  185850. return ((float)0.0);
  185851. }
  185852. #endif
  185853. png_int_32 PNGAPI
  185854. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185855. {
  185856. if (png_ptr != NULL && info_ptr != NULL)
  185857. #if defined(PNG_oFFs_SUPPORTED)
  185858. if (info_ptr->valid & PNG_INFO_oFFs)
  185859. {
  185860. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185861. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185862. return (0);
  185863. else return (info_ptr->x_offset);
  185864. }
  185865. #else
  185866. return (0);
  185867. #endif
  185868. return (0);
  185869. }
  185870. png_int_32 PNGAPI
  185871. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185872. {
  185873. if (png_ptr != NULL && info_ptr != NULL)
  185874. #if defined(PNG_oFFs_SUPPORTED)
  185875. if (info_ptr->valid & PNG_INFO_oFFs)
  185876. {
  185877. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185878. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185879. return (0);
  185880. else return (info_ptr->y_offset);
  185881. }
  185882. #else
  185883. return (0);
  185884. #endif
  185885. return (0);
  185886. }
  185887. png_int_32 PNGAPI
  185888. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185889. {
  185890. if (png_ptr != NULL && info_ptr != NULL)
  185891. #if defined(PNG_oFFs_SUPPORTED)
  185892. if (info_ptr->valid & PNG_INFO_oFFs)
  185893. {
  185894. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185895. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185896. return (0);
  185897. else return (info_ptr->x_offset);
  185898. }
  185899. #else
  185900. return (0);
  185901. #endif
  185902. return (0);
  185903. }
  185904. png_int_32 PNGAPI
  185905. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185906. {
  185907. if (png_ptr != NULL && info_ptr != NULL)
  185908. #if defined(PNG_oFFs_SUPPORTED)
  185909. if (info_ptr->valid & PNG_INFO_oFFs)
  185910. {
  185911. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185912. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185913. return (0);
  185914. else return (info_ptr->y_offset);
  185915. }
  185916. #else
  185917. return (0);
  185918. #endif
  185919. return (0);
  185920. }
  185921. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185922. png_uint_32 PNGAPI
  185923. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185924. {
  185925. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185926. *.0254 +.5));
  185927. }
  185928. png_uint_32 PNGAPI
  185929. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185930. {
  185931. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185932. *.0254 +.5));
  185933. }
  185934. png_uint_32 PNGAPI
  185935. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185936. {
  185937. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185938. *.0254 +.5));
  185939. }
  185940. float PNGAPI
  185941. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185942. {
  185943. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185944. *.00003937);
  185945. }
  185946. float PNGAPI
  185947. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185948. {
  185949. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185950. *.00003937);
  185951. }
  185952. #if defined(PNG_pHYs_SUPPORTED)
  185953. png_uint_32 PNGAPI
  185954. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185955. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185956. {
  185957. png_uint_32 retval = 0;
  185958. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185959. {
  185960. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185961. if (res_x != NULL)
  185962. {
  185963. *res_x = info_ptr->x_pixels_per_unit;
  185964. retval |= PNG_INFO_pHYs;
  185965. }
  185966. if (res_y != NULL)
  185967. {
  185968. *res_y = info_ptr->y_pixels_per_unit;
  185969. retval |= PNG_INFO_pHYs;
  185970. }
  185971. if (unit_type != NULL)
  185972. {
  185973. *unit_type = (int)info_ptr->phys_unit_type;
  185974. retval |= PNG_INFO_pHYs;
  185975. if(*unit_type == 1)
  185976. {
  185977. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185978. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185979. }
  185980. }
  185981. }
  185982. return (retval);
  185983. }
  185984. #endif /* PNG_pHYs_SUPPORTED */
  185985. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185986. /* png_get_channels really belongs in here, too, but it's been around longer */
  185987. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185988. png_byte PNGAPI
  185989. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185990. {
  185991. if (png_ptr != NULL && info_ptr != NULL)
  185992. return(info_ptr->channels);
  185993. else
  185994. return (0);
  185995. }
  185996. png_bytep PNGAPI
  185997. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185998. {
  185999. if (png_ptr != NULL && info_ptr != NULL)
  186000. return(info_ptr->signature);
  186001. else
  186002. return (NULL);
  186003. }
  186004. #if defined(PNG_bKGD_SUPPORTED)
  186005. png_uint_32 PNGAPI
  186006. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  186007. png_color_16p *background)
  186008. {
  186009. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  186010. && background != NULL)
  186011. {
  186012. png_debug1(1, "in %s retrieval function\n", "bKGD");
  186013. *background = &(info_ptr->background);
  186014. return (PNG_INFO_bKGD);
  186015. }
  186016. return (0);
  186017. }
  186018. #endif
  186019. #if defined(PNG_cHRM_SUPPORTED)
  186020. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186021. png_uint_32 PNGAPI
  186022. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  186023. double *white_x, double *white_y, double *red_x, double *red_y,
  186024. double *green_x, double *green_y, double *blue_x, double *blue_y)
  186025. {
  186026. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186027. {
  186028. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186029. if (white_x != NULL)
  186030. *white_x = (double)info_ptr->x_white;
  186031. if (white_y != NULL)
  186032. *white_y = (double)info_ptr->y_white;
  186033. if (red_x != NULL)
  186034. *red_x = (double)info_ptr->x_red;
  186035. if (red_y != NULL)
  186036. *red_y = (double)info_ptr->y_red;
  186037. if (green_x != NULL)
  186038. *green_x = (double)info_ptr->x_green;
  186039. if (green_y != NULL)
  186040. *green_y = (double)info_ptr->y_green;
  186041. if (blue_x != NULL)
  186042. *blue_x = (double)info_ptr->x_blue;
  186043. if (blue_y != NULL)
  186044. *blue_y = (double)info_ptr->y_blue;
  186045. return (PNG_INFO_cHRM);
  186046. }
  186047. return (0);
  186048. }
  186049. #endif
  186050. #ifdef PNG_FIXED_POINT_SUPPORTED
  186051. png_uint_32 PNGAPI
  186052. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  186053. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  186054. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  186055. png_fixed_point *blue_x, png_fixed_point *blue_y)
  186056. {
  186057. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186058. {
  186059. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186060. if (white_x != NULL)
  186061. *white_x = info_ptr->int_x_white;
  186062. if (white_y != NULL)
  186063. *white_y = info_ptr->int_y_white;
  186064. if (red_x != NULL)
  186065. *red_x = info_ptr->int_x_red;
  186066. if (red_y != NULL)
  186067. *red_y = info_ptr->int_y_red;
  186068. if (green_x != NULL)
  186069. *green_x = info_ptr->int_x_green;
  186070. if (green_y != NULL)
  186071. *green_y = info_ptr->int_y_green;
  186072. if (blue_x != NULL)
  186073. *blue_x = info_ptr->int_x_blue;
  186074. if (blue_y != NULL)
  186075. *blue_y = info_ptr->int_y_blue;
  186076. return (PNG_INFO_cHRM);
  186077. }
  186078. return (0);
  186079. }
  186080. #endif
  186081. #endif
  186082. #if defined(PNG_gAMA_SUPPORTED)
  186083. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186084. png_uint_32 PNGAPI
  186085. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186086. {
  186087. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186088. && file_gamma != NULL)
  186089. {
  186090. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186091. *file_gamma = (double)info_ptr->gamma;
  186092. return (PNG_INFO_gAMA);
  186093. }
  186094. return (0);
  186095. }
  186096. #endif
  186097. #ifdef PNG_FIXED_POINT_SUPPORTED
  186098. png_uint_32 PNGAPI
  186099. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186100. png_fixed_point *int_file_gamma)
  186101. {
  186102. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186103. && int_file_gamma != NULL)
  186104. {
  186105. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186106. *int_file_gamma = info_ptr->int_gamma;
  186107. return (PNG_INFO_gAMA);
  186108. }
  186109. return (0);
  186110. }
  186111. #endif
  186112. #endif
  186113. #if defined(PNG_sRGB_SUPPORTED)
  186114. png_uint_32 PNGAPI
  186115. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186116. {
  186117. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186118. && file_srgb_intent != NULL)
  186119. {
  186120. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186121. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186122. return (PNG_INFO_sRGB);
  186123. }
  186124. return (0);
  186125. }
  186126. #endif
  186127. #if defined(PNG_iCCP_SUPPORTED)
  186128. png_uint_32 PNGAPI
  186129. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186130. png_charpp name, int *compression_type,
  186131. png_charpp profile, png_uint_32 *proflen)
  186132. {
  186133. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186134. && name != NULL && profile != NULL && proflen != NULL)
  186135. {
  186136. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186137. *name = info_ptr->iccp_name;
  186138. *profile = info_ptr->iccp_profile;
  186139. /* compression_type is a dummy so the API won't have to change
  186140. if we introduce multiple compression types later. */
  186141. *proflen = (int)info_ptr->iccp_proflen;
  186142. *compression_type = (int)info_ptr->iccp_compression;
  186143. return (PNG_INFO_iCCP);
  186144. }
  186145. return (0);
  186146. }
  186147. #endif
  186148. #if defined(PNG_sPLT_SUPPORTED)
  186149. png_uint_32 PNGAPI
  186150. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186151. png_sPLT_tpp spalettes)
  186152. {
  186153. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186154. {
  186155. *spalettes = info_ptr->splt_palettes;
  186156. return ((png_uint_32)info_ptr->splt_palettes_num);
  186157. }
  186158. return (0);
  186159. }
  186160. #endif
  186161. #if defined(PNG_hIST_SUPPORTED)
  186162. png_uint_32 PNGAPI
  186163. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186164. {
  186165. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186166. && hist != NULL)
  186167. {
  186168. png_debug1(1, "in %s retrieval function\n", "hIST");
  186169. *hist = info_ptr->hist;
  186170. return (PNG_INFO_hIST);
  186171. }
  186172. return (0);
  186173. }
  186174. #endif
  186175. png_uint_32 PNGAPI
  186176. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186177. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186178. int *color_type, int *interlace_type, int *compression_type,
  186179. int *filter_type)
  186180. {
  186181. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186182. bit_depth != NULL && color_type != NULL)
  186183. {
  186184. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186185. *width = info_ptr->width;
  186186. *height = info_ptr->height;
  186187. *bit_depth = info_ptr->bit_depth;
  186188. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186189. png_error(png_ptr, "Invalid bit depth");
  186190. *color_type = info_ptr->color_type;
  186191. if (info_ptr->color_type > 6)
  186192. png_error(png_ptr, "Invalid color type");
  186193. if (compression_type != NULL)
  186194. *compression_type = info_ptr->compression_type;
  186195. if (filter_type != NULL)
  186196. *filter_type = info_ptr->filter_type;
  186197. if (interlace_type != NULL)
  186198. *interlace_type = info_ptr->interlace_type;
  186199. /* check for potential overflow of rowbytes */
  186200. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186201. png_error(png_ptr, "Invalid image width");
  186202. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186203. png_error(png_ptr, "Invalid image height");
  186204. if (info_ptr->width > (PNG_UINT_32_MAX
  186205. >> 3) /* 8-byte RGBA pixels */
  186206. - 64 /* bigrowbuf hack */
  186207. - 1 /* filter byte */
  186208. - 7*8 /* rounding of width to multiple of 8 pixels */
  186209. - 8) /* extra max_pixel_depth pad */
  186210. {
  186211. png_warning(png_ptr,
  186212. "Width too large for libpng to process image data.");
  186213. }
  186214. return (1);
  186215. }
  186216. return (0);
  186217. }
  186218. #if defined(PNG_oFFs_SUPPORTED)
  186219. png_uint_32 PNGAPI
  186220. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186221. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186222. {
  186223. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186224. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186225. {
  186226. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186227. *offset_x = info_ptr->x_offset;
  186228. *offset_y = info_ptr->y_offset;
  186229. *unit_type = (int)info_ptr->offset_unit_type;
  186230. return (PNG_INFO_oFFs);
  186231. }
  186232. return (0);
  186233. }
  186234. #endif
  186235. #if defined(PNG_pCAL_SUPPORTED)
  186236. png_uint_32 PNGAPI
  186237. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186238. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186239. png_charp *units, png_charpp *params)
  186240. {
  186241. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186242. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186243. nparams != NULL && units != NULL && params != NULL)
  186244. {
  186245. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186246. *purpose = info_ptr->pcal_purpose;
  186247. *X0 = info_ptr->pcal_X0;
  186248. *X1 = info_ptr->pcal_X1;
  186249. *type = (int)info_ptr->pcal_type;
  186250. *nparams = (int)info_ptr->pcal_nparams;
  186251. *units = info_ptr->pcal_units;
  186252. *params = info_ptr->pcal_params;
  186253. return (PNG_INFO_pCAL);
  186254. }
  186255. return (0);
  186256. }
  186257. #endif
  186258. #if defined(PNG_sCAL_SUPPORTED)
  186259. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186260. png_uint_32 PNGAPI
  186261. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186262. int *unit, double *width, double *height)
  186263. {
  186264. if (png_ptr != NULL && info_ptr != NULL &&
  186265. (info_ptr->valid & PNG_INFO_sCAL))
  186266. {
  186267. *unit = info_ptr->scal_unit;
  186268. *width = info_ptr->scal_pixel_width;
  186269. *height = info_ptr->scal_pixel_height;
  186270. return (PNG_INFO_sCAL);
  186271. }
  186272. return(0);
  186273. }
  186274. #else
  186275. #ifdef PNG_FIXED_POINT_SUPPORTED
  186276. png_uint_32 PNGAPI
  186277. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186278. int *unit, png_charpp width, png_charpp height)
  186279. {
  186280. if (png_ptr != NULL && info_ptr != NULL &&
  186281. (info_ptr->valid & PNG_INFO_sCAL))
  186282. {
  186283. *unit = info_ptr->scal_unit;
  186284. *width = info_ptr->scal_s_width;
  186285. *height = info_ptr->scal_s_height;
  186286. return (PNG_INFO_sCAL);
  186287. }
  186288. return(0);
  186289. }
  186290. #endif
  186291. #endif
  186292. #endif
  186293. #if defined(PNG_pHYs_SUPPORTED)
  186294. png_uint_32 PNGAPI
  186295. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186296. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186297. {
  186298. png_uint_32 retval = 0;
  186299. if (png_ptr != NULL && info_ptr != NULL &&
  186300. (info_ptr->valid & PNG_INFO_pHYs))
  186301. {
  186302. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186303. if (res_x != NULL)
  186304. {
  186305. *res_x = info_ptr->x_pixels_per_unit;
  186306. retval |= PNG_INFO_pHYs;
  186307. }
  186308. if (res_y != NULL)
  186309. {
  186310. *res_y = info_ptr->y_pixels_per_unit;
  186311. retval |= PNG_INFO_pHYs;
  186312. }
  186313. if (unit_type != NULL)
  186314. {
  186315. *unit_type = (int)info_ptr->phys_unit_type;
  186316. retval |= PNG_INFO_pHYs;
  186317. }
  186318. }
  186319. return (retval);
  186320. }
  186321. #endif
  186322. png_uint_32 PNGAPI
  186323. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186324. int *num_palette)
  186325. {
  186326. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186327. && palette != NULL)
  186328. {
  186329. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186330. *palette = info_ptr->palette;
  186331. *num_palette = info_ptr->num_palette;
  186332. png_debug1(3, "num_palette = %d\n", *num_palette);
  186333. return (PNG_INFO_PLTE);
  186334. }
  186335. return (0);
  186336. }
  186337. #if defined(PNG_sBIT_SUPPORTED)
  186338. png_uint_32 PNGAPI
  186339. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186340. {
  186341. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186342. && sig_bit != NULL)
  186343. {
  186344. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186345. *sig_bit = &(info_ptr->sig_bit);
  186346. return (PNG_INFO_sBIT);
  186347. }
  186348. return (0);
  186349. }
  186350. #endif
  186351. #if defined(PNG_TEXT_SUPPORTED)
  186352. png_uint_32 PNGAPI
  186353. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186354. int *num_text)
  186355. {
  186356. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186357. {
  186358. png_debug1(1, "in %s retrieval function\n",
  186359. (png_ptr->chunk_name[0] == '\0' ? "text"
  186360. : (png_const_charp)png_ptr->chunk_name));
  186361. if (text_ptr != NULL)
  186362. *text_ptr = info_ptr->text;
  186363. if (num_text != NULL)
  186364. *num_text = info_ptr->num_text;
  186365. return ((png_uint_32)info_ptr->num_text);
  186366. }
  186367. if (num_text != NULL)
  186368. *num_text = 0;
  186369. return(0);
  186370. }
  186371. #endif
  186372. #if defined(PNG_tIME_SUPPORTED)
  186373. png_uint_32 PNGAPI
  186374. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186375. {
  186376. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186377. && mod_time != NULL)
  186378. {
  186379. png_debug1(1, "in %s retrieval function\n", "tIME");
  186380. *mod_time = &(info_ptr->mod_time);
  186381. return (PNG_INFO_tIME);
  186382. }
  186383. return (0);
  186384. }
  186385. #endif
  186386. #if defined(PNG_tRNS_SUPPORTED)
  186387. png_uint_32 PNGAPI
  186388. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186389. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186390. {
  186391. png_uint_32 retval = 0;
  186392. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186393. {
  186394. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186395. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186396. {
  186397. if (trans != NULL)
  186398. {
  186399. *trans = info_ptr->trans;
  186400. retval |= PNG_INFO_tRNS;
  186401. }
  186402. if (trans_values != NULL)
  186403. *trans_values = &(info_ptr->trans_values);
  186404. }
  186405. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186406. {
  186407. if (trans_values != NULL)
  186408. {
  186409. *trans_values = &(info_ptr->trans_values);
  186410. retval |= PNG_INFO_tRNS;
  186411. }
  186412. if(trans != NULL)
  186413. *trans = NULL;
  186414. }
  186415. if(num_trans != NULL)
  186416. {
  186417. *num_trans = info_ptr->num_trans;
  186418. retval |= PNG_INFO_tRNS;
  186419. }
  186420. }
  186421. return (retval);
  186422. }
  186423. #endif
  186424. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186425. png_uint_32 PNGAPI
  186426. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186427. png_unknown_chunkpp unknowns)
  186428. {
  186429. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186430. {
  186431. *unknowns = info_ptr->unknown_chunks;
  186432. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186433. }
  186434. return (0);
  186435. }
  186436. #endif
  186437. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186438. png_byte PNGAPI
  186439. png_get_rgb_to_gray_status (png_structp png_ptr)
  186440. {
  186441. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186442. }
  186443. #endif
  186444. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186445. png_voidp PNGAPI
  186446. png_get_user_chunk_ptr(png_structp png_ptr)
  186447. {
  186448. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186449. }
  186450. #endif
  186451. #ifdef PNG_WRITE_SUPPORTED
  186452. png_uint_32 PNGAPI
  186453. png_get_compression_buffer_size(png_structp png_ptr)
  186454. {
  186455. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186456. }
  186457. #endif
  186458. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186459. #ifndef PNG_1_0_X
  186460. /* this function was added to libpng 1.2.0 and should exist by default */
  186461. png_uint_32 PNGAPI
  186462. png_get_asm_flags (png_structp png_ptr)
  186463. {
  186464. /* obsolete, to be removed from libpng-1.4.0 */
  186465. return (png_ptr? 0L: 0L);
  186466. }
  186467. /* this function was added to libpng 1.2.0 and should exist by default */
  186468. png_uint_32 PNGAPI
  186469. png_get_asm_flagmask (int flag_select)
  186470. {
  186471. /* obsolete, to be removed from libpng-1.4.0 */
  186472. flag_select=flag_select;
  186473. return 0L;
  186474. }
  186475. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186476. /* this function was added to libpng 1.2.0 */
  186477. png_uint_32 PNGAPI
  186478. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186479. {
  186480. /* obsolete, to be removed from libpng-1.4.0 */
  186481. flag_select=flag_select;
  186482. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186483. return 0L;
  186484. }
  186485. /* this function was added to libpng 1.2.0 */
  186486. png_byte PNGAPI
  186487. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186488. {
  186489. /* obsolete, to be removed from libpng-1.4.0 */
  186490. return (png_ptr? 0: 0);
  186491. }
  186492. /* this function was added to libpng 1.2.0 */
  186493. png_uint_32 PNGAPI
  186494. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186495. {
  186496. /* obsolete, to be removed from libpng-1.4.0 */
  186497. return (png_ptr? 0L: 0L);
  186498. }
  186499. #endif /* ?PNG_1_0_X */
  186500. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186501. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186502. /* these functions were added to libpng 1.2.6 */
  186503. png_uint_32 PNGAPI
  186504. png_get_user_width_max (png_structp png_ptr)
  186505. {
  186506. return (png_ptr? png_ptr->user_width_max : 0);
  186507. }
  186508. png_uint_32 PNGAPI
  186509. png_get_user_height_max (png_structp png_ptr)
  186510. {
  186511. return (png_ptr? png_ptr->user_height_max : 0);
  186512. }
  186513. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186514. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186515. /*** End of inlined file: pngget.c ***/
  186516. /*** Start of inlined file: pngmem.c ***/
  186517. /* pngmem.c - stub functions for memory allocation
  186518. *
  186519. * Last changed in libpng 1.2.13 November 13, 2006
  186520. * For conditions of distribution and use, see copyright notice in png.h
  186521. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186522. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186523. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186524. *
  186525. * This file provides a location for all memory allocation. Users who
  186526. * need special memory handling are expected to supply replacement
  186527. * functions for png_malloc() and png_free(), and to use
  186528. * png_create_read_struct_2() and png_create_write_struct_2() to
  186529. * identify the replacement functions.
  186530. */
  186531. #define PNG_INTERNAL
  186532. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186533. /* Borland DOS special memory handler */
  186534. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186535. /* if you change this, be sure to change the one in png.h also */
  186536. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186537. by a single call to calloc() if this is thought to improve performance. */
  186538. png_voidp /* PRIVATE */
  186539. png_create_struct(int type)
  186540. {
  186541. #ifdef PNG_USER_MEM_SUPPORTED
  186542. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186543. }
  186544. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186545. png_voidp /* PRIVATE */
  186546. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186547. {
  186548. #endif /* PNG_USER_MEM_SUPPORTED */
  186549. png_size_t size;
  186550. png_voidp struct_ptr;
  186551. if (type == PNG_STRUCT_INFO)
  186552. size = png_sizeof(png_info);
  186553. else if (type == PNG_STRUCT_PNG)
  186554. size = png_sizeof(png_struct);
  186555. else
  186556. return (png_get_copyright(NULL));
  186557. #ifdef PNG_USER_MEM_SUPPORTED
  186558. if(malloc_fn != NULL)
  186559. {
  186560. png_struct dummy_struct;
  186561. png_structp png_ptr = &dummy_struct;
  186562. png_ptr->mem_ptr=mem_ptr;
  186563. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186564. }
  186565. else
  186566. #endif /* PNG_USER_MEM_SUPPORTED */
  186567. struct_ptr = (png_voidp)farmalloc(size);
  186568. if (struct_ptr != NULL)
  186569. png_memset(struct_ptr, 0, size);
  186570. return (struct_ptr);
  186571. }
  186572. /* Free memory allocated by a png_create_struct() call */
  186573. void /* PRIVATE */
  186574. png_destroy_struct(png_voidp struct_ptr)
  186575. {
  186576. #ifdef PNG_USER_MEM_SUPPORTED
  186577. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186578. }
  186579. /* Free memory allocated by a png_create_struct() call */
  186580. void /* PRIVATE */
  186581. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186582. png_voidp mem_ptr)
  186583. {
  186584. #endif
  186585. if (struct_ptr != NULL)
  186586. {
  186587. #ifdef PNG_USER_MEM_SUPPORTED
  186588. if(free_fn != NULL)
  186589. {
  186590. png_struct dummy_struct;
  186591. png_structp png_ptr = &dummy_struct;
  186592. png_ptr->mem_ptr=mem_ptr;
  186593. (*(free_fn))(png_ptr, struct_ptr);
  186594. return;
  186595. }
  186596. #endif /* PNG_USER_MEM_SUPPORTED */
  186597. farfree (struct_ptr);
  186598. }
  186599. }
  186600. /* Allocate memory. For reasonable files, size should never exceed
  186601. * 64K. However, zlib may allocate more then 64K if you don't tell
  186602. * it not to. See zconf.h and png.h for more information. zlib does
  186603. * need to allocate exactly 64K, so whatever you call here must
  186604. * have the ability to do that.
  186605. *
  186606. * Borland seems to have a problem in DOS mode for exactly 64K.
  186607. * It gives you a segment with an offset of 8 (perhaps to store its
  186608. * memory stuff). zlib doesn't like this at all, so we have to
  186609. * detect and deal with it. This code should not be needed in
  186610. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186611. * been updated by Alexander Lehmann for version 0.89 to waste less
  186612. * memory.
  186613. *
  186614. * Note that we can't use png_size_t for the "size" declaration,
  186615. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186616. * result, we would be truncating potentially larger memory requests
  186617. * (which should cause a fatal error) and introducing major problems.
  186618. */
  186619. png_voidp PNGAPI
  186620. png_malloc(png_structp png_ptr, png_uint_32 size)
  186621. {
  186622. png_voidp ret;
  186623. if (png_ptr == NULL || size == 0)
  186624. return (NULL);
  186625. #ifdef PNG_USER_MEM_SUPPORTED
  186626. if(png_ptr->malloc_fn != NULL)
  186627. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186628. else
  186629. ret = (png_malloc_default(png_ptr, size));
  186630. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186631. png_error(png_ptr, "Out of memory!");
  186632. return (ret);
  186633. }
  186634. png_voidp PNGAPI
  186635. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186636. {
  186637. png_voidp ret;
  186638. #endif /* PNG_USER_MEM_SUPPORTED */
  186639. if (png_ptr == NULL || size == 0)
  186640. return (NULL);
  186641. #ifdef PNG_MAX_MALLOC_64K
  186642. if (size > (png_uint_32)65536L)
  186643. {
  186644. png_warning(png_ptr, "Cannot Allocate > 64K");
  186645. ret = NULL;
  186646. }
  186647. else
  186648. #endif
  186649. if (size != (size_t)size)
  186650. ret = NULL;
  186651. else if (size == (png_uint_32)65536L)
  186652. {
  186653. if (png_ptr->offset_table == NULL)
  186654. {
  186655. /* try to see if we need to do any of this fancy stuff */
  186656. ret = farmalloc(size);
  186657. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186658. {
  186659. int num_blocks;
  186660. png_uint_32 total_size;
  186661. png_bytep table;
  186662. int i;
  186663. png_byte huge * hptr;
  186664. if (ret != NULL)
  186665. {
  186666. farfree(ret);
  186667. ret = NULL;
  186668. }
  186669. if(png_ptr->zlib_window_bits > 14)
  186670. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186671. else
  186672. num_blocks = 1;
  186673. if (png_ptr->zlib_mem_level >= 7)
  186674. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186675. else
  186676. num_blocks++;
  186677. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186678. table = farmalloc(total_size);
  186679. if (table == NULL)
  186680. {
  186681. #ifndef PNG_USER_MEM_SUPPORTED
  186682. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186683. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186684. else
  186685. png_warning(png_ptr, "Out Of Memory.");
  186686. #endif
  186687. return (NULL);
  186688. }
  186689. if ((png_size_t)table & 0xfff0)
  186690. {
  186691. #ifndef PNG_USER_MEM_SUPPORTED
  186692. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186693. png_error(png_ptr,
  186694. "Farmalloc didn't return normalized pointer");
  186695. else
  186696. png_warning(png_ptr,
  186697. "Farmalloc didn't return normalized pointer");
  186698. #endif
  186699. return (NULL);
  186700. }
  186701. png_ptr->offset_table = table;
  186702. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186703. png_sizeof (png_bytep));
  186704. if (png_ptr->offset_table_ptr == NULL)
  186705. {
  186706. #ifndef PNG_USER_MEM_SUPPORTED
  186707. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186708. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186709. else
  186710. png_warning(png_ptr, "Out Of memory.");
  186711. #endif
  186712. return (NULL);
  186713. }
  186714. hptr = (png_byte huge *)table;
  186715. if ((png_size_t)hptr & 0xf)
  186716. {
  186717. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186718. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186719. }
  186720. for (i = 0; i < num_blocks; i++)
  186721. {
  186722. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186723. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186724. }
  186725. png_ptr->offset_table_number = num_blocks;
  186726. png_ptr->offset_table_count = 0;
  186727. png_ptr->offset_table_count_free = 0;
  186728. }
  186729. }
  186730. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186731. {
  186732. #ifndef PNG_USER_MEM_SUPPORTED
  186733. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186734. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186735. else
  186736. png_warning(png_ptr, "Out of Memory.");
  186737. #endif
  186738. return (NULL);
  186739. }
  186740. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186741. }
  186742. else
  186743. ret = farmalloc(size);
  186744. #ifndef PNG_USER_MEM_SUPPORTED
  186745. if (ret == NULL)
  186746. {
  186747. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186748. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186749. else
  186750. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186751. }
  186752. #endif
  186753. return (ret);
  186754. }
  186755. /* free a pointer allocated by png_malloc(). In the default
  186756. configuration, png_ptr is not used, but is passed in case it
  186757. is needed. If ptr is NULL, return without taking any action. */
  186758. void PNGAPI
  186759. png_free(png_structp png_ptr, png_voidp ptr)
  186760. {
  186761. if (png_ptr == NULL || ptr == NULL)
  186762. return;
  186763. #ifdef PNG_USER_MEM_SUPPORTED
  186764. if (png_ptr->free_fn != NULL)
  186765. {
  186766. (*(png_ptr->free_fn))(png_ptr, ptr);
  186767. return;
  186768. }
  186769. else png_free_default(png_ptr, ptr);
  186770. }
  186771. void PNGAPI
  186772. png_free_default(png_structp png_ptr, png_voidp ptr)
  186773. {
  186774. #endif /* PNG_USER_MEM_SUPPORTED */
  186775. if(png_ptr == NULL) return;
  186776. if (png_ptr->offset_table != NULL)
  186777. {
  186778. int i;
  186779. for (i = 0; i < png_ptr->offset_table_count; i++)
  186780. {
  186781. if (ptr == png_ptr->offset_table_ptr[i])
  186782. {
  186783. ptr = NULL;
  186784. png_ptr->offset_table_count_free++;
  186785. break;
  186786. }
  186787. }
  186788. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186789. {
  186790. farfree(png_ptr->offset_table);
  186791. farfree(png_ptr->offset_table_ptr);
  186792. png_ptr->offset_table = NULL;
  186793. png_ptr->offset_table_ptr = NULL;
  186794. }
  186795. }
  186796. if (ptr != NULL)
  186797. {
  186798. farfree(ptr);
  186799. }
  186800. }
  186801. #else /* Not the Borland DOS special memory handler */
  186802. /* Allocate memory for a png_struct or a png_info. The malloc and
  186803. memset can be replaced by a single call to calloc() if this is thought
  186804. to improve performance noticably. */
  186805. png_voidp /* PRIVATE */
  186806. png_create_struct(int type)
  186807. {
  186808. #ifdef PNG_USER_MEM_SUPPORTED
  186809. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186810. }
  186811. /* Allocate memory for a png_struct or a png_info. The malloc and
  186812. memset can be replaced by a single call to calloc() if this is thought
  186813. to improve performance noticably. */
  186814. png_voidp /* PRIVATE */
  186815. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186816. {
  186817. #endif /* PNG_USER_MEM_SUPPORTED */
  186818. png_size_t size;
  186819. png_voidp struct_ptr;
  186820. if (type == PNG_STRUCT_INFO)
  186821. size = png_sizeof(png_info);
  186822. else if (type == PNG_STRUCT_PNG)
  186823. size = png_sizeof(png_struct);
  186824. else
  186825. return (NULL);
  186826. #ifdef PNG_USER_MEM_SUPPORTED
  186827. if(malloc_fn != NULL)
  186828. {
  186829. png_struct dummy_struct;
  186830. png_structp png_ptr = &dummy_struct;
  186831. png_ptr->mem_ptr=mem_ptr;
  186832. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186833. if (struct_ptr != NULL)
  186834. png_memset(struct_ptr, 0, size);
  186835. return (struct_ptr);
  186836. }
  186837. #endif /* PNG_USER_MEM_SUPPORTED */
  186838. #if defined(__TURBOC__) && !defined(__FLAT__)
  186839. struct_ptr = (png_voidp)farmalloc(size);
  186840. #else
  186841. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186842. struct_ptr = (png_voidp)halloc(size,1);
  186843. # else
  186844. struct_ptr = (png_voidp)malloc(size);
  186845. # endif
  186846. #endif
  186847. if (struct_ptr != NULL)
  186848. png_memset(struct_ptr, 0, size);
  186849. return (struct_ptr);
  186850. }
  186851. /* Free memory allocated by a png_create_struct() call */
  186852. void /* PRIVATE */
  186853. png_destroy_struct(png_voidp struct_ptr)
  186854. {
  186855. #ifdef PNG_USER_MEM_SUPPORTED
  186856. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186857. }
  186858. /* Free memory allocated by a png_create_struct() call */
  186859. void /* PRIVATE */
  186860. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186861. png_voidp mem_ptr)
  186862. {
  186863. #endif /* PNG_USER_MEM_SUPPORTED */
  186864. if (struct_ptr != NULL)
  186865. {
  186866. #ifdef PNG_USER_MEM_SUPPORTED
  186867. if(free_fn != NULL)
  186868. {
  186869. png_struct dummy_struct;
  186870. png_structp png_ptr = &dummy_struct;
  186871. png_ptr->mem_ptr=mem_ptr;
  186872. (*(free_fn))(png_ptr, struct_ptr);
  186873. return;
  186874. }
  186875. #endif /* PNG_USER_MEM_SUPPORTED */
  186876. #if defined(__TURBOC__) && !defined(__FLAT__)
  186877. farfree(struct_ptr);
  186878. #else
  186879. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186880. hfree(struct_ptr);
  186881. # else
  186882. free(struct_ptr);
  186883. # endif
  186884. #endif
  186885. }
  186886. }
  186887. /* Allocate memory. For reasonable files, size should never exceed
  186888. 64K. However, zlib may allocate more then 64K if you don't tell
  186889. it not to. See zconf.h and png.h for more information. zlib does
  186890. need to allocate exactly 64K, so whatever you call here must
  186891. have the ability to do that. */
  186892. png_voidp PNGAPI
  186893. png_malloc(png_structp png_ptr, png_uint_32 size)
  186894. {
  186895. png_voidp ret;
  186896. #ifdef PNG_USER_MEM_SUPPORTED
  186897. if (png_ptr == NULL || size == 0)
  186898. return (NULL);
  186899. if(png_ptr->malloc_fn != NULL)
  186900. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186901. else
  186902. ret = (png_malloc_default(png_ptr, size));
  186903. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186904. png_error(png_ptr, "Out of Memory!");
  186905. return (ret);
  186906. }
  186907. png_voidp PNGAPI
  186908. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186909. {
  186910. png_voidp ret;
  186911. #endif /* PNG_USER_MEM_SUPPORTED */
  186912. if (png_ptr == NULL || size == 0)
  186913. return (NULL);
  186914. #ifdef PNG_MAX_MALLOC_64K
  186915. if (size > (png_uint_32)65536L)
  186916. {
  186917. #ifndef PNG_USER_MEM_SUPPORTED
  186918. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186919. png_error(png_ptr, "Cannot Allocate > 64K");
  186920. else
  186921. #endif
  186922. return NULL;
  186923. }
  186924. #endif
  186925. /* Check for overflow */
  186926. #if defined(__TURBOC__) && !defined(__FLAT__)
  186927. if (size != (unsigned long)size)
  186928. ret = NULL;
  186929. else
  186930. ret = farmalloc(size);
  186931. #else
  186932. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186933. if (size != (unsigned long)size)
  186934. ret = NULL;
  186935. else
  186936. ret = halloc(size, 1);
  186937. # else
  186938. if (size != (size_t)size)
  186939. ret = NULL;
  186940. else
  186941. ret = malloc((size_t)size);
  186942. # endif
  186943. #endif
  186944. #ifndef PNG_USER_MEM_SUPPORTED
  186945. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186946. png_error(png_ptr, "Out of Memory");
  186947. #endif
  186948. return (ret);
  186949. }
  186950. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186951. without taking any action. */
  186952. void PNGAPI
  186953. png_free(png_structp png_ptr, png_voidp ptr)
  186954. {
  186955. if (png_ptr == NULL || ptr == NULL)
  186956. return;
  186957. #ifdef PNG_USER_MEM_SUPPORTED
  186958. if (png_ptr->free_fn != NULL)
  186959. {
  186960. (*(png_ptr->free_fn))(png_ptr, ptr);
  186961. return;
  186962. }
  186963. else png_free_default(png_ptr, ptr);
  186964. }
  186965. void PNGAPI
  186966. png_free_default(png_structp png_ptr, png_voidp ptr)
  186967. {
  186968. if (png_ptr == NULL || ptr == NULL)
  186969. return;
  186970. #endif /* PNG_USER_MEM_SUPPORTED */
  186971. #if defined(__TURBOC__) && !defined(__FLAT__)
  186972. farfree(ptr);
  186973. #else
  186974. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186975. hfree(ptr);
  186976. # else
  186977. free(ptr);
  186978. # endif
  186979. #endif
  186980. }
  186981. #endif /* Not Borland DOS special memory handler */
  186982. #if defined(PNG_1_0_X)
  186983. # define png_malloc_warn png_malloc
  186984. #else
  186985. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186986. * function will set up png_malloc() to issue a png_warning and return NULL
  186987. * instead of issuing a png_error, if it fails to allocate the requested
  186988. * memory.
  186989. */
  186990. png_voidp PNGAPI
  186991. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186992. {
  186993. png_voidp ptr;
  186994. png_uint_32 save_flags;
  186995. if(png_ptr == NULL) return (NULL);
  186996. save_flags=png_ptr->flags;
  186997. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186998. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186999. png_ptr->flags=save_flags;
  187000. return(ptr);
  187001. }
  187002. #endif
  187003. png_voidp PNGAPI
  187004. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  187005. png_uint_32 length)
  187006. {
  187007. png_size_t size;
  187008. size = (png_size_t)length;
  187009. if ((png_uint_32)size != length)
  187010. png_error(png_ptr,"Overflow in png_memcpy_check.");
  187011. return(png_memcpy (s1, s2, size));
  187012. }
  187013. png_voidp PNGAPI
  187014. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  187015. png_uint_32 length)
  187016. {
  187017. png_size_t size;
  187018. size = (png_size_t)length;
  187019. if ((png_uint_32)size != length)
  187020. png_error(png_ptr,"Overflow in png_memset_check.");
  187021. return (png_memset (s1, value, size));
  187022. }
  187023. #ifdef PNG_USER_MEM_SUPPORTED
  187024. /* This function is called when the application wants to use another method
  187025. * of allocating and freeing memory.
  187026. */
  187027. void PNGAPI
  187028. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  187029. malloc_fn, png_free_ptr free_fn)
  187030. {
  187031. if(png_ptr != NULL) {
  187032. png_ptr->mem_ptr = mem_ptr;
  187033. png_ptr->malloc_fn = malloc_fn;
  187034. png_ptr->free_fn = free_fn;
  187035. }
  187036. }
  187037. /* This function returns a pointer to the mem_ptr associated with the user
  187038. * functions. The application should free any memory associated with this
  187039. * pointer before png_write_destroy and png_read_destroy are called.
  187040. */
  187041. png_voidp PNGAPI
  187042. png_get_mem_ptr(png_structp png_ptr)
  187043. {
  187044. if(png_ptr == NULL) return (NULL);
  187045. return ((png_voidp)png_ptr->mem_ptr);
  187046. }
  187047. #endif /* PNG_USER_MEM_SUPPORTED */
  187048. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187049. /*** End of inlined file: pngmem.c ***/
  187050. /*** Start of inlined file: pngread.c ***/
  187051. /* pngread.c - read a PNG file
  187052. *
  187053. * Last changed in libpng 1.2.20 September 7, 2007
  187054. * For conditions of distribution and use, see copyright notice in png.h
  187055. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187056. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187057. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187058. *
  187059. * This file contains routines that an application calls directly to
  187060. * read a PNG file or stream.
  187061. */
  187062. #define PNG_INTERNAL
  187063. #if defined(PNG_READ_SUPPORTED)
  187064. /* Create a PNG structure for reading, and allocate any memory needed. */
  187065. png_structp PNGAPI
  187066. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187067. png_error_ptr error_fn, png_error_ptr warn_fn)
  187068. {
  187069. #ifdef PNG_USER_MEM_SUPPORTED
  187070. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187071. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187072. }
  187073. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187074. png_structp PNGAPI
  187075. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187076. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187077. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187078. {
  187079. #endif /* PNG_USER_MEM_SUPPORTED */
  187080. png_structp png_ptr;
  187081. #ifdef PNG_SETJMP_SUPPORTED
  187082. #ifdef USE_FAR_KEYWORD
  187083. jmp_buf jmpbuf;
  187084. #endif
  187085. #endif
  187086. int i;
  187087. png_debug(1, "in png_create_read_struct\n");
  187088. #ifdef PNG_USER_MEM_SUPPORTED
  187089. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187090. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187091. #else
  187092. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187093. #endif
  187094. if (png_ptr == NULL)
  187095. return (NULL);
  187096. /* added at libpng-1.2.6 */
  187097. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187098. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187099. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187100. #endif
  187101. #ifdef PNG_SETJMP_SUPPORTED
  187102. #ifdef USE_FAR_KEYWORD
  187103. if (setjmp(jmpbuf))
  187104. #else
  187105. if (setjmp(png_ptr->jmpbuf))
  187106. #endif
  187107. {
  187108. png_free(png_ptr, png_ptr->zbuf);
  187109. png_ptr->zbuf=NULL;
  187110. #ifdef PNG_USER_MEM_SUPPORTED
  187111. png_destroy_struct_2((png_voidp)png_ptr,
  187112. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187113. #else
  187114. png_destroy_struct((png_voidp)png_ptr);
  187115. #endif
  187116. return (NULL);
  187117. }
  187118. #ifdef USE_FAR_KEYWORD
  187119. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187120. #endif
  187121. #endif
  187122. #ifdef PNG_USER_MEM_SUPPORTED
  187123. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187124. #endif
  187125. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187126. i=0;
  187127. do
  187128. {
  187129. if(user_png_ver[i] != png_libpng_ver[i])
  187130. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187131. } while (png_libpng_ver[i++]);
  187132. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187133. {
  187134. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187135. * we must recompile any applications that use any older library version.
  187136. * For versions after libpng 1.0, we will be compatible, so we need
  187137. * only check the first digit.
  187138. */
  187139. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187140. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187141. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187142. {
  187143. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187144. char msg[80];
  187145. if (user_png_ver)
  187146. {
  187147. png_snprintf(msg, 80,
  187148. "Application was compiled with png.h from libpng-%.20s",
  187149. user_png_ver);
  187150. png_warning(png_ptr, msg);
  187151. }
  187152. png_snprintf(msg, 80,
  187153. "Application is running with png.c from libpng-%.20s",
  187154. png_libpng_ver);
  187155. png_warning(png_ptr, msg);
  187156. #endif
  187157. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187158. png_ptr->flags=0;
  187159. #endif
  187160. png_error(png_ptr,
  187161. "Incompatible libpng version in application and library");
  187162. }
  187163. }
  187164. /* initialize zbuf - compression buffer */
  187165. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187166. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187167. (png_uint_32)png_ptr->zbuf_size);
  187168. png_ptr->zstream.zalloc = png_zalloc;
  187169. png_ptr->zstream.zfree = png_zfree;
  187170. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187171. switch (inflateInit(&png_ptr->zstream))
  187172. {
  187173. case Z_OK: /* Do nothing */ break;
  187174. case Z_MEM_ERROR:
  187175. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187176. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187177. default: png_error(png_ptr, "Unknown zlib error");
  187178. }
  187179. png_ptr->zstream.next_out = png_ptr->zbuf;
  187180. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187181. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187182. #ifdef PNG_SETJMP_SUPPORTED
  187183. /* Applications that neglect to set up their own setjmp() and then encounter
  187184. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187185. abort instead of returning. */
  187186. #ifdef USE_FAR_KEYWORD
  187187. if (setjmp(jmpbuf))
  187188. PNG_ABORT();
  187189. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187190. #else
  187191. if (setjmp(png_ptr->jmpbuf))
  187192. PNG_ABORT();
  187193. #endif
  187194. #endif
  187195. return (png_ptr);
  187196. }
  187197. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187198. /* Initialize PNG structure for reading, and allocate any memory needed.
  187199. This interface is deprecated in favour of the png_create_read_struct(),
  187200. and it will disappear as of libpng-1.3.0. */
  187201. #undef png_read_init
  187202. void PNGAPI
  187203. png_read_init(png_structp png_ptr)
  187204. {
  187205. /* We only come here via pre-1.0.7-compiled applications */
  187206. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187207. }
  187208. void PNGAPI
  187209. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187210. png_size_t png_struct_size, png_size_t png_info_size)
  187211. {
  187212. /* We only come here via pre-1.0.12-compiled applications */
  187213. if(png_ptr == NULL) return;
  187214. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187215. if(png_sizeof(png_struct) > png_struct_size ||
  187216. png_sizeof(png_info) > png_info_size)
  187217. {
  187218. char msg[80];
  187219. png_ptr->warning_fn=NULL;
  187220. if (user_png_ver)
  187221. {
  187222. png_snprintf(msg, 80,
  187223. "Application was compiled with png.h from libpng-%.20s",
  187224. user_png_ver);
  187225. png_warning(png_ptr, msg);
  187226. }
  187227. png_snprintf(msg, 80,
  187228. "Application is running with png.c from libpng-%.20s",
  187229. png_libpng_ver);
  187230. png_warning(png_ptr, msg);
  187231. }
  187232. #endif
  187233. if(png_sizeof(png_struct) > png_struct_size)
  187234. {
  187235. png_ptr->error_fn=NULL;
  187236. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187237. png_ptr->flags=0;
  187238. #endif
  187239. png_error(png_ptr,
  187240. "The png struct allocated by the application for reading is too small.");
  187241. }
  187242. if(png_sizeof(png_info) > png_info_size)
  187243. {
  187244. png_ptr->error_fn=NULL;
  187245. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187246. png_ptr->flags=0;
  187247. #endif
  187248. png_error(png_ptr,
  187249. "The info struct allocated by application for reading is too small.");
  187250. }
  187251. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187252. }
  187253. #endif /* PNG_1_0_X || PNG_1_2_X */
  187254. void PNGAPI
  187255. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187256. png_size_t png_struct_size)
  187257. {
  187258. #ifdef PNG_SETJMP_SUPPORTED
  187259. jmp_buf tmp_jmp; /* to save current jump buffer */
  187260. #endif
  187261. int i=0;
  187262. png_structp png_ptr=*ptr_ptr;
  187263. if(png_ptr == NULL) return;
  187264. do
  187265. {
  187266. if(user_png_ver[i] != png_libpng_ver[i])
  187267. {
  187268. #ifdef PNG_LEGACY_SUPPORTED
  187269. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187270. #else
  187271. png_ptr->warning_fn=NULL;
  187272. png_warning(png_ptr,
  187273. "Application uses deprecated png_read_init() and should be recompiled.");
  187274. break;
  187275. #endif
  187276. }
  187277. } while (png_libpng_ver[i++]);
  187278. png_debug(1, "in png_read_init_3\n");
  187279. #ifdef PNG_SETJMP_SUPPORTED
  187280. /* save jump buffer and error functions */
  187281. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187282. #endif
  187283. if(png_sizeof(png_struct) > png_struct_size)
  187284. {
  187285. png_destroy_struct(png_ptr);
  187286. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187287. png_ptr = *ptr_ptr;
  187288. }
  187289. /* reset all variables to 0 */
  187290. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187291. #ifdef PNG_SETJMP_SUPPORTED
  187292. /* restore jump buffer */
  187293. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187294. #endif
  187295. /* added at libpng-1.2.6 */
  187296. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187297. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187298. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187299. #endif
  187300. /* initialize zbuf - compression buffer */
  187301. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187302. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187303. (png_uint_32)png_ptr->zbuf_size);
  187304. png_ptr->zstream.zalloc = png_zalloc;
  187305. png_ptr->zstream.zfree = png_zfree;
  187306. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187307. switch (inflateInit(&png_ptr->zstream))
  187308. {
  187309. case Z_OK: /* Do nothing */ break;
  187310. case Z_MEM_ERROR:
  187311. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187312. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187313. default: png_error(png_ptr, "Unknown zlib error");
  187314. }
  187315. png_ptr->zstream.next_out = png_ptr->zbuf;
  187316. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187317. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187318. }
  187319. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187320. /* Read the information before the actual image data. This has been
  187321. * changed in v0.90 to allow reading a file that already has the magic
  187322. * bytes read from the stream. You can tell libpng how many bytes have
  187323. * been read from the beginning of the stream (up to the maximum of 8)
  187324. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187325. * here. The application can then have access to the signature bytes we
  187326. * read if it is determined that this isn't a valid PNG file.
  187327. */
  187328. void PNGAPI
  187329. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187330. {
  187331. if(png_ptr == NULL) return;
  187332. png_debug(1, "in png_read_info\n");
  187333. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187334. if (png_ptr->sig_bytes < 8)
  187335. {
  187336. png_size_t num_checked = png_ptr->sig_bytes,
  187337. num_to_check = 8 - num_checked;
  187338. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187339. png_ptr->sig_bytes = 8;
  187340. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187341. {
  187342. if (num_checked < 4 &&
  187343. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187344. png_error(png_ptr, "Not a PNG file");
  187345. else
  187346. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187347. }
  187348. if (num_checked < 3)
  187349. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187350. }
  187351. for(;;)
  187352. {
  187353. #ifdef PNG_USE_LOCAL_ARRAYS
  187354. PNG_CONST PNG_IHDR;
  187355. PNG_CONST PNG_IDAT;
  187356. PNG_CONST PNG_IEND;
  187357. PNG_CONST PNG_PLTE;
  187358. #if defined(PNG_READ_bKGD_SUPPORTED)
  187359. PNG_CONST PNG_bKGD;
  187360. #endif
  187361. #if defined(PNG_READ_cHRM_SUPPORTED)
  187362. PNG_CONST PNG_cHRM;
  187363. #endif
  187364. #if defined(PNG_READ_gAMA_SUPPORTED)
  187365. PNG_CONST PNG_gAMA;
  187366. #endif
  187367. #if defined(PNG_READ_hIST_SUPPORTED)
  187368. PNG_CONST PNG_hIST;
  187369. #endif
  187370. #if defined(PNG_READ_iCCP_SUPPORTED)
  187371. PNG_CONST PNG_iCCP;
  187372. #endif
  187373. #if defined(PNG_READ_iTXt_SUPPORTED)
  187374. PNG_CONST PNG_iTXt;
  187375. #endif
  187376. #if defined(PNG_READ_oFFs_SUPPORTED)
  187377. PNG_CONST PNG_oFFs;
  187378. #endif
  187379. #if defined(PNG_READ_pCAL_SUPPORTED)
  187380. PNG_CONST PNG_pCAL;
  187381. #endif
  187382. #if defined(PNG_READ_pHYs_SUPPORTED)
  187383. PNG_CONST PNG_pHYs;
  187384. #endif
  187385. #if defined(PNG_READ_sBIT_SUPPORTED)
  187386. PNG_CONST PNG_sBIT;
  187387. #endif
  187388. #if defined(PNG_READ_sCAL_SUPPORTED)
  187389. PNG_CONST PNG_sCAL;
  187390. #endif
  187391. #if defined(PNG_READ_sPLT_SUPPORTED)
  187392. PNG_CONST PNG_sPLT;
  187393. #endif
  187394. #if defined(PNG_READ_sRGB_SUPPORTED)
  187395. PNG_CONST PNG_sRGB;
  187396. #endif
  187397. #if defined(PNG_READ_tEXt_SUPPORTED)
  187398. PNG_CONST PNG_tEXt;
  187399. #endif
  187400. #if defined(PNG_READ_tIME_SUPPORTED)
  187401. PNG_CONST PNG_tIME;
  187402. #endif
  187403. #if defined(PNG_READ_tRNS_SUPPORTED)
  187404. PNG_CONST PNG_tRNS;
  187405. #endif
  187406. #if defined(PNG_READ_zTXt_SUPPORTED)
  187407. PNG_CONST PNG_zTXt;
  187408. #endif
  187409. #endif /* PNG_USE_LOCAL_ARRAYS */
  187410. png_byte chunk_length[4];
  187411. png_uint_32 length;
  187412. png_read_data(png_ptr, chunk_length, 4);
  187413. length = png_get_uint_31(png_ptr,chunk_length);
  187414. png_reset_crc(png_ptr);
  187415. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187416. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187417. length);
  187418. /* This should be a binary subdivision search or a hash for
  187419. * matching the chunk name rather than a linear search.
  187420. */
  187421. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187422. if(png_ptr->mode & PNG_AFTER_IDAT)
  187423. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187424. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187425. png_handle_IHDR(png_ptr, info_ptr, length);
  187426. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187427. png_handle_IEND(png_ptr, info_ptr, length);
  187428. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187429. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187430. {
  187431. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187432. png_ptr->mode |= PNG_HAVE_IDAT;
  187433. png_handle_unknown(png_ptr, info_ptr, length);
  187434. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187435. png_ptr->mode |= PNG_HAVE_PLTE;
  187436. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187437. {
  187438. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187439. png_error(png_ptr, "Missing IHDR before IDAT");
  187440. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187441. !(png_ptr->mode & PNG_HAVE_PLTE))
  187442. png_error(png_ptr, "Missing PLTE before IDAT");
  187443. break;
  187444. }
  187445. }
  187446. #endif
  187447. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187448. png_handle_PLTE(png_ptr, info_ptr, length);
  187449. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187450. {
  187451. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187452. png_error(png_ptr, "Missing IHDR before IDAT");
  187453. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187454. !(png_ptr->mode & PNG_HAVE_PLTE))
  187455. png_error(png_ptr, "Missing PLTE before IDAT");
  187456. png_ptr->idat_size = length;
  187457. png_ptr->mode |= PNG_HAVE_IDAT;
  187458. break;
  187459. }
  187460. #if defined(PNG_READ_bKGD_SUPPORTED)
  187461. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187462. png_handle_bKGD(png_ptr, info_ptr, length);
  187463. #endif
  187464. #if defined(PNG_READ_cHRM_SUPPORTED)
  187465. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187466. png_handle_cHRM(png_ptr, info_ptr, length);
  187467. #endif
  187468. #if defined(PNG_READ_gAMA_SUPPORTED)
  187469. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187470. png_handle_gAMA(png_ptr, info_ptr, length);
  187471. #endif
  187472. #if defined(PNG_READ_hIST_SUPPORTED)
  187473. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187474. png_handle_hIST(png_ptr, info_ptr, length);
  187475. #endif
  187476. #if defined(PNG_READ_oFFs_SUPPORTED)
  187477. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187478. png_handle_oFFs(png_ptr, info_ptr, length);
  187479. #endif
  187480. #if defined(PNG_READ_pCAL_SUPPORTED)
  187481. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187482. png_handle_pCAL(png_ptr, info_ptr, length);
  187483. #endif
  187484. #if defined(PNG_READ_sCAL_SUPPORTED)
  187485. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187486. png_handle_sCAL(png_ptr, info_ptr, length);
  187487. #endif
  187488. #if defined(PNG_READ_pHYs_SUPPORTED)
  187489. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187490. png_handle_pHYs(png_ptr, info_ptr, length);
  187491. #endif
  187492. #if defined(PNG_READ_sBIT_SUPPORTED)
  187493. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187494. png_handle_sBIT(png_ptr, info_ptr, length);
  187495. #endif
  187496. #if defined(PNG_READ_sRGB_SUPPORTED)
  187497. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187498. png_handle_sRGB(png_ptr, info_ptr, length);
  187499. #endif
  187500. #if defined(PNG_READ_iCCP_SUPPORTED)
  187501. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187502. png_handle_iCCP(png_ptr, info_ptr, length);
  187503. #endif
  187504. #if defined(PNG_READ_sPLT_SUPPORTED)
  187505. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187506. png_handle_sPLT(png_ptr, info_ptr, length);
  187507. #endif
  187508. #if defined(PNG_READ_tEXt_SUPPORTED)
  187509. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187510. png_handle_tEXt(png_ptr, info_ptr, length);
  187511. #endif
  187512. #if defined(PNG_READ_tIME_SUPPORTED)
  187513. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187514. png_handle_tIME(png_ptr, info_ptr, length);
  187515. #endif
  187516. #if defined(PNG_READ_tRNS_SUPPORTED)
  187517. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187518. png_handle_tRNS(png_ptr, info_ptr, length);
  187519. #endif
  187520. #if defined(PNG_READ_zTXt_SUPPORTED)
  187521. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187522. png_handle_zTXt(png_ptr, info_ptr, length);
  187523. #endif
  187524. #if defined(PNG_READ_iTXt_SUPPORTED)
  187525. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187526. png_handle_iTXt(png_ptr, info_ptr, length);
  187527. #endif
  187528. else
  187529. png_handle_unknown(png_ptr, info_ptr, length);
  187530. }
  187531. }
  187532. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187533. /* optional call to update the users info_ptr structure */
  187534. void PNGAPI
  187535. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187536. {
  187537. png_debug(1, "in png_read_update_info\n");
  187538. if(png_ptr == NULL) return;
  187539. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187540. png_read_start_row(png_ptr);
  187541. else
  187542. png_warning(png_ptr,
  187543. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187544. png_read_transform_info(png_ptr, info_ptr);
  187545. }
  187546. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187547. /* Initialize palette, background, etc, after transformations
  187548. * are set, but before any reading takes place. This allows
  187549. * the user to obtain a gamma-corrected palette, for example.
  187550. * If the user doesn't call this, we will do it ourselves.
  187551. */
  187552. void PNGAPI
  187553. png_start_read_image(png_structp png_ptr)
  187554. {
  187555. png_debug(1, "in png_start_read_image\n");
  187556. if(png_ptr == NULL) return;
  187557. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187558. png_read_start_row(png_ptr);
  187559. }
  187560. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187561. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187562. void PNGAPI
  187563. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187564. {
  187565. #ifdef PNG_USE_LOCAL_ARRAYS
  187566. PNG_CONST PNG_IDAT;
  187567. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187568. 0xff};
  187569. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187570. #endif
  187571. int ret;
  187572. if(png_ptr == NULL) return;
  187573. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187574. png_ptr->row_number, png_ptr->pass);
  187575. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187576. png_read_start_row(png_ptr);
  187577. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187578. {
  187579. /* check for transforms that have been set but were defined out */
  187580. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187581. if (png_ptr->transformations & PNG_INVERT_MONO)
  187582. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187583. #endif
  187584. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187585. if (png_ptr->transformations & PNG_FILLER)
  187586. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187587. #endif
  187588. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187589. if (png_ptr->transformations & PNG_PACKSWAP)
  187590. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187591. #endif
  187592. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187593. if (png_ptr->transformations & PNG_PACK)
  187594. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187595. #endif
  187596. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187597. if (png_ptr->transformations & PNG_SHIFT)
  187598. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187599. #endif
  187600. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187601. if (png_ptr->transformations & PNG_BGR)
  187602. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187603. #endif
  187604. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187605. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187606. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187607. #endif
  187608. }
  187609. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187610. /* if interlaced and we do not need a new row, combine row and return */
  187611. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187612. {
  187613. switch (png_ptr->pass)
  187614. {
  187615. case 0:
  187616. if (png_ptr->row_number & 0x07)
  187617. {
  187618. if (dsp_row != NULL)
  187619. png_combine_row(png_ptr, dsp_row,
  187620. png_pass_dsp_mask[png_ptr->pass]);
  187621. png_read_finish_row(png_ptr);
  187622. return;
  187623. }
  187624. break;
  187625. case 1:
  187626. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187627. {
  187628. if (dsp_row != NULL)
  187629. png_combine_row(png_ptr, dsp_row,
  187630. png_pass_dsp_mask[png_ptr->pass]);
  187631. png_read_finish_row(png_ptr);
  187632. return;
  187633. }
  187634. break;
  187635. case 2:
  187636. if ((png_ptr->row_number & 0x07) != 4)
  187637. {
  187638. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187639. png_combine_row(png_ptr, dsp_row,
  187640. png_pass_dsp_mask[png_ptr->pass]);
  187641. png_read_finish_row(png_ptr);
  187642. return;
  187643. }
  187644. break;
  187645. case 3:
  187646. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187647. {
  187648. if (dsp_row != NULL)
  187649. png_combine_row(png_ptr, dsp_row,
  187650. png_pass_dsp_mask[png_ptr->pass]);
  187651. png_read_finish_row(png_ptr);
  187652. return;
  187653. }
  187654. break;
  187655. case 4:
  187656. if ((png_ptr->row_number & 3) != 2)
  187657. {
  187658. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187659. png_combine_row(png_ptr, dsp_row,
  187660. png_pass_dsp_mask[png_ptr->pass]);
  187661. png_read_finish_row(png_ptr);
  187662. return;
  187663. }
  187664. break;
  187665. case 5:
  187666. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187667. {
  187668. if (dsp_row != NULL)
  187669. png_combine_row(png_ptr, dsp_row,
  187670. png_pass_dsp_mask[png_ptr->pass]);
  187671. png_read_finish_row(png_ptr);
  187672. return;
  187673. }
  187674. break;
  187675. case 6:
  187676. if (!(png_ptr->row_number & 1))
  187677. {
  187678. png_read_finish_row(png_ptr);
  187679. return;
  187680. }
  187681. break;
  187682. }
  187683. }
  187684. #endif
  187685. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187686. png_error(png_ptr, "Invalid attempt to read row data");
  187687. png_ptr->zstream.next_out = png_ptr->row_buf;
  187688. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187689. do
  187690. {
  187691. if (!(png_ptr->zstream.avail_in))
  187692. {
  187693. while (!png_ptr->idat_size)
  187694. {
  187695. png_byte chunk_length[4];
  187696. png_crc_finish(png_ptr, 0);
  187697. png_read_data(png_ptr, chunk_length, 4);
  187698. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187699. png_reset_crc(png_ptr);
  187700. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187701. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187702. png_error(png_ptr, "Not enough image data");
  187703. }
  187704. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187705. png_ptr->zstream.next_in = png_ptr->zbuf;
  187706. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187707. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187708. png_crc_read(png_ptr, png_ptr->zbuf,
  187709. (png_size_t)png_ptr->zstream.avail_in);
  187710. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187711. }
  187712. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187713. if (ret == Z_STREAM_END)
  187714. {
  187715. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187716. png_ptr->idat_size)
  187717. png_error(png_ptr, "Extra compressed data");
  187718. png_ptr->mode |= PNG_AFTER_IDAT;
  187719. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187720. break;
  187721. }
  187722. if (ret != Z_OK)
  187723. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187724. "Decompression error");
  187725. } while (png_ptr->zstream.avail_out);
  187726. png_ptr->row_info.color_type = png_ptr->color_type;
  187727. png_ptr->row_info.width = png_ptr->iwidth;
  187728. png_ptr->row_info.channels = png_ptr->channels;
  187729. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187730. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187731. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187732. png_ptr->row_info.width);
  187733. if(png_ptr->row_buf[0])
  187734. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187735. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187736. (int)(png_ptr->row_buf[0]));
  187737. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187738. png_ptr->rowbytes + 1);
  187739. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187740. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187741. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187742. {
  187743. /* Intrapixel differencing */
  187744. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187745. }
  187746. #endif
  187747. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187748. png_do_read_transformations(png_ptr);
  187749. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187750. /* blow up interlaced rows to full size */
  187751. if (png_ptr->interlaced &&
  187752. (png_ptr->transformations & PNG_INTERLACE))
  187753. {
  187754. if (png_ptr->pass < 6)
  187755. /* old interface (pre-1.0.9):
  187756. png_do_read_interlace(&(png_ptr->row_info),
  187757. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187758. */
  187759. png_do_read_interlace(png_ptr);
  187760. if (dsp_row != NULL)
  187761. png_combine_row(png_ptr, dsp_row,
  187762. png_pass_dsp_mask[png_ptr->pass]);
  187763. if (row != NULL)
  187764. png_combine_row(png_ptr, row,
  187765. png_pass_mask[png_ptr->pass]);
  187766. }
  187767. else
  187768. #endif
  187769. {
  187770. if (row != NULL)
  187771. png_combine_row(png_ptr, row, 0xff);
  187772. if (dsp_row != NULL)
  187773. png_combine_row(png_ptr, dsp_row, 0xff);
  187774. }
  187775. png_read_finish_row(png_ptr);
  187776. if (png_ptr->read_row_fn != NULL)
  187777. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187778. }
  187779. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187780. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187781. /* Read one or more rows of image data. If the image is interlaced,
  187782. * and png_set_interlace_handling() has been called, the rows need to
  187783. * contain the contents of the rows from the previous pass. If the
  187784. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187785. * called, the rows contents must be initialized to the contents of the
  187786. * screen.
  187787. *
  187788. * "row" holds the actual image, and pixels are placed in it
  187789. * as they arrive. If the image is displayed after each pass, it will
  187790. * appear to "sparkle" in. "display_row" can be used to display a
  187791. * "chunky" progressive image, with finer detail added as it becomes
  187792. * available. If you do not want this "chunky" display, you may pass
  187793. * NULL for display_row. If you do not want the sparkle display, and
  187794. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187795. * If you have called png_handle_alpha(), and the image has either an
  187796. * alpha channel or a transparency chunk, you must provide a buffer for
  187797. * rows. In this case, you do not have to provide a display_row buffer
  187798. * also, but you may. If the image is not interlaced, or if you have
  187799. * not called png_set_interlace_handling(), the display_row buffer will
  187800. * be ignored, so pass NULL to it.
  187801. *
  187802. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187803. */
  187804. void PNGAPI
  187805. png_read_rows(png_structp png_ptr, png_bytepp row,
  187806. png_bytepp display_row, png_uint_32 num_rows)
  187807. {
  187808. png_uint_32 i;
  187809. png_bytepp rp;
  187810. png_bytepp dp;
  187811. png_debug(1, "in png_read_rows\n");
  187812. if(png_ptr == NULL) return;
  187813. rp = row;
  187814. dp = display_row;
  187815. if (rp != NULL && dp != NULL)
  187816. for (i = 0; i < num_rows; i++)
  187817. {
  187818. png_bytep rptr = *rp++;
  187819. png_bytep dptr = *dp++;
  187820. png_read_row(png_ptr, rptr, dptr);
  187821. }
  187822. else if(rp != NULL)
  187823. for (i = 0; i < num_rows; i++)
  187824. {
  187825. png_bytep rptr = *rp;
  187826. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187827. rp++;
  187828. }
  187829. else if(dp != NULL)
  187830. for (i = 0; i < num_rows; i++)
  187831. {
  187832. png_bytep dptr = *dp;
  187833. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187834. dp++;
  187835. }
  187836. }
  187837. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187838. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187839. /* Read the entire image. If the image has an alpha channel or a tRNS
  187840. * chunk, and you have called png_handle_alpha()[*], you will need to
  187841. * initialize the image to the current image that PNG will be overlaying.
  187842. * We set the num_rows again here, in case it was incorrectly set in
  187843. * png_read_start_row() by a call to png_read_update_info() or
  187844. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187845. * prior to either of these functions like it should have been. You can
  187846. * only call this function once. If you desire to have an image for
  187847. * each pass of a interlaced image, use png_read_rows() instead.
  187848. *
  187849. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187850. */
  187851. void PNGAPI
  187852. png_read_image(png_structp png_ptr, png_bytepp image)
  187853. {
  187854. png_uint_32 i,image_height;
  187855. int pass, j;
  187856. png_bytepp rp;
  187857. png_debug(1, "in png_read_image\n");
  187858. if(png_ptr == NULL) return;
  187859. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187860. pass = png_set_interlace_handling(png_ptr);
  187861. #else
  187862. if (png_ptr->interlaced)
  187863. png_error(png_ptr,
  187864. "Cannot read interlaced image -- interlace handler disabled.");
  187865. pass = 1;
  187866. #endif
  187867. image_height=png_ptr->height;
  187868. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187869. for (j = 0; j < pass; j++)
  187870. {
  187871. rp = image;
  187872. for (i = 0; i < image_height; i++)
  187873. {
  187874. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187875. rp++;
  187876. }
  187877. }
  187878. }
  187879. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187880. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187881. /* Read the end of the PNG file. Will not read past the end of the
  187882. * file, will verify the end is accurate, and will read any comments
  187883. * or time information at the end of the file, if info is not NULL.
  187884. */
  187885. void PNGAPI
  187886. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187887. {
  187888. png_byte chunk_length[4];
  187889. png_uint_32 length;
  187890. png_debug(1, "in png_read_end\n");
  187891. if(png_ptr == NULL) return;
  187892. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187893. do
  187894. {
  187895. #ifdef PNG_USE_LOCAL_ARRAYS
  187896. PNG_CONST PNG_IHDR;
  187897. PNG_CONST PNG_IDAT;
  187898. PNG_CONST PNG_IEND;
  187899. PNG_CONST PNG_PLTE;
  187900. #if defined(PNG_READ_bKGD_SUPPORTED)
  187901. PNG_CONST PNG_bKGD;
  187902. #endif
  187903. #if defined(PNG_READ_cHRM_SUPPORTED)
  187904. PNG_CONST PNG_cHRM;
  187905. #endif
  187906. #if defined(PNG_READ_gAMA_SUPPORTED)
  187907. PNG_CONST PNG_gAMA;
  187908. #endif
  187909. #if defined(PNG_READ_hIST_SUPPORTED)
  187910. PNG_CONST PNG_hIST;
  187911. #endif
  187912. #if defined(PNG_READ_iCCP_SUPPORTED)
  187913. PNG_CONST PNG_iCCP;
  187914. #endif
  187915. #if defined(PNG_READ_iTXt_SUPPORTED)
  187916. PNG_CONST PNG_iTXt;
  187917. #endif
  187918. #if defined(PNG_READ_oFFs_SUPPORTED)
  187919. PNG_CONST PNG_oFFs;
  187920. #endif
  187921. #if defined(PNG_READ_pCAL_SUPPORTED)
  187922. PNG_CONST PNG_pCAL;
  187923. #endif
  187924. #if defined(PNG_READ_pHYs_SUPPORTED)
  187925. PNG_CONST PNG_pHYs;
  187926. #endif
  187927. #if defined(PNG_READ_sBIT_SUPPORTED)
  187928. PNG_CONST PNG_sBIT;
  187929. #endif
  187930. #if defined(PNG_READ_sCAL_SUPPORTED)
  187931. PNG_CONST PNG_sCAL;
  187932. #endif
  187933. #if defined(PNG_READ_sPLT_SUPPORTED)
  187934. PNG_CONST PNG_sPLT;
  187935. #endif
  187936. #if defined(PNG_READ_sRGB_SUPPORTED)
  187937. PNG_CONST PNG_sRGB;
  187938. #endif
  187939. #if defined(PNG_READ_tEXt_SUPPORTED)
  187940. PNG_CONST PNG_tEXt;
  187941. #endif
  187942. #if defined(PNG_READ_tIME_SUPPORTED)
  187943. PNG_CONST PNG_tIME;
  187944. #endif
  187945. #if defined(PNG_READ_tRNS_SUPPORTED)
  187946. PNG_CONST PNG_tRNS;
  187947. #endif
  187948. #if defined(PNG_READ_zTXt_SUPPORTED)
  187949. PNG_CONST PNG_zTXt;
  187950. #endif
  187951. #endif /* PNG_USE_LOCAL_ARRAYS */
  187952. png_read_data(png_ptr, chunk_length, 4);
  187953. length = png_get_uint_31(png_ptr,chunk_length);
  187954. png_reset_crc(png_ptr);
  187955. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187956. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187957. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187958. png_handle_IHDR(png_ptr, info_ptr, length);
  187959. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187960. png_handle_IEND(png_ptr, info_ptr, length);
  187961. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187962. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187963. {
  187964. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187965. {
  187966. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187967. png_error(png_ptr, "Too many IDAT's found");
  187968. }
  187969. png_handle_unknown(png_ptr, info_ptr, length);
  187970. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187971. png_ptr->mode |= PNG_HAVE_PLTE;
  187972. }
  187973. #endif
  187974. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187975. {
  187976. /* Zero length IDATs are legal after the last IDAT has been
  187977. * read, but not after other chunks have been read.
  187978. */
  187979. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187980. png_error(png_ptr, "Too many IDAT's found");
  187981. png_crc_finish(png_ptr, length);
  187982. }
  187983. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187984. png_handle_PLTE(png_ptr, info_ptr, length);
  187985. #if defined(PNG_READ_bKGD_SUPPORTED)
  187986. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187987. png_handle_bKGD(png_ptr, info_ptr, length);
  187988. #endif
  187989. #if defined(PNG_READ_cHRM_SUPPORTED)
  187990. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187991. png_handle_cHRM(png_ptr, info_ptr, length);
  187992. #endif
  187993. #if defined(PNG_READ_gAMA_SUPPORTED)
  187994. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187995. png_handle_gAMA(png_ptr, info_ptr, length);
  187996. #endif
  187997. #if defined(PNG_READ_hIST_SUPPORTED)
  187998. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187999. png_handle_hIST(png_ptr, info_ptr, length);
  188000. #endif
  188001. #if defined(PNG_READ_oFFs_SUPPORTED)
  188002. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188003. png_handle_oFFs(png_ptr, info_ptr, length);
  188004. #endif
  188005. #if defined(PNG_READ_pCAL_SUPPORTED)
  188006. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188007. png_handle_pCAL(png_ptr, info_ptr, length);
  188008. #endif
  188009. #if defined(PNG_READ_sCAL_SUPPORTED)
  188010. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188011. png_handle_sCAL(png_ptr, info_ptr, length);
  188012. #endif
  188013. #if defined(PNG_READ_pHYs_SUPPORTED)
  188014. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188015. png_handle_pHYs(png_ptr, info_ptr, length);
  188016. #endif
  188017. #if defined(PNG_READ_sBIT_SUPPORTED)
  188018. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188019. png_handle_sBIT(png_ptr, info_ptr, length);
  188020. #endif
  188021. #if defined(PNG_READ_sRGB_SUPPORTED)
  188022. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188023. png_handle_sRGB(png_ptr, info_ptr, length);
  188024. #endif
  188025. #if defined(PNG_READ_iCCP_SUPPORTED)
  188026. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188027. png_handle_iCCP(png_ptr, info_ptr, length);
  188028. #endif
  188029. #if defined(PNG_READ_sPLT_SUPPORTED)
  188030. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188031. png_handle_sPLT(png_ptr, info_ptr, length);
  188032. #endif
  188033. #if defined(PNG_READ_tEXt_SUPPORTED)
  188034. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188035. png_handle_tEXt(png_ptr, info_ptr, length);
  188036. #endif
  188037. #if defined(PNG_READ_tIME_SUPPORTED)
  188038. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188039. png_handle_tIME(png_ptr, info_ptr, length);
  188040. #endif
  188041. #if defined(PNG_READ_tRNS_SUPPORTED)
  188042. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188043. png_handle_tRNS(png_ptr, info_ptr, length);
  188044. #endif
  188045. #if defined(PNG_READ_zTXt_SUPPORTED)
  188046. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188047. png_handle_zTXt(png_ptr, info_ptr, length);
  188048. #endif
  188049. #if defined(PNG_READ_iTXt_SUPPORTED)
  188050. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188051. png_handle_iTXt(png_ptr, info_ptr, length);
  188052. #endif
  188053. else
  188054. png_handle_unknown(png_ptr, info_ptr, length);
  188055. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  188056. }
  188057. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188058. /* free all memory used by the read */
  188059. void PNGAPI
  188060. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  188061. png_infopp end_info_ptr_ptr)
  188062. {
  188063. png_structp png_ptr = NULL;
  188064. png_infop info_ptr = NULL, end_info_ptr = NULL;
  188065. #ifdef PNG_USER_MEM_SUPPORTED
  188066. png_free_ptr free_fn;
  188067. png_voidp mem_ptr;
  188068. #endif
  188069. png_debug(1, "in png_destroy_read_struct\n");
  188070. if (png_ptr_ptr != NULL)
  188071. png_ptr = *png_ptr_ptr;
  188072. if (info_ptr_ptr != NULL)
  188073. info_ptr = *info_ptr_ptr;
  188074. if (end_info_ptr_ptr != NULL)
  188075. end_info_ptr = *end_info_ptr_ptr;
  188076. #ifdef PNG_USER_MEM_SUPPORTED
  188077. free_fn = png_ptr->free_fn;
  188078. mem_ptr = png_ptr->mem_ptr;
  188079. #endif
  188080. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188081. if (info_ptr != NULL)
  188082. {
  188083. #if defined(PNG_TEXT_SUPPORTED)
  188084. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188085. #endif
  188086. #ifdef PNG_USER_MEM_SUPPORTED
  188087. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188088. (png_voidp)mem_ptr);
  188089. #else
  188090. png_destroy_struct((png_voidp)info_ptr);
  188091. #endif
  188092. *info_ptr_ptr = NULL;
  188093. }
  188094. if (end_info_ptr != NULL)
  188095. {
  188096. #if defined(PNG_READ_TEXT_SUPPORTED)
  188097. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188098. #endif
  188099. #ifdef PNG_USER_MEM_SUPPORTED
  188100. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188101. (png_voidp)mem_ptr);
  188102. #else
  188103. png_destroy_struct((png_voidp)end_info_ptr);
  188104. #endif
  188105. *end_info_ptr_ptr = NULL;
  188106. }
  188107. if (png_ptr != NULL)
  188108. {
  188109. #ifdef PNG_USER_MEM_SUPPORTED
  188110. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188111. (png_voidp)mem_ptr);
  188112. #else
  188113. png_destroy_struct((png_voidp)png_ptr);
  188114. #endif
  188115. *png_ptr_ptr = NULL;
  188116. }
  188117. }
  188118. /* free all memory used by the read (old method) */
  188119. void /* PRIVATE */
  188120. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188121. {
  188122. #ifdef PNG_SETJMP_SUPPORTED
  188123. jmp_buf tmp_jmp;
  188124. #endif
  188125. png_error_ptr error_fn;
  188126. png_error_ptr warning_fn;
  188127. png_voidp error_ptr;
  188128. #ifdef PNG_USER_MEM_SUPPORTED
  188129. png_free_ptr free_fn;
  188130. #endif
  188131. png_debug(1, "in png_read_destroy\n");
  188132. if (info_ptr != NULL)
  188133. png_info_destroy(png_ptr, info_ptr);
  188134. if (end_info_ptr != NULL)
  188135. png_info_destroy(png_ptr, end_info_ptr);
  188136. png_free(png_ptr, png_ptr->zbuf);
  188137. png_free(png_ptr, png_ptr->big_row_buf);
  188138. png_free(png_ptr, png_ptr->prev_row);
  188139. #if defined(PNG_READ_DITHER_SUPPORTED)
  188140. png_free(png_ptr, png_ptr->palette_lookup);
  188141. png_free(png_ptr, png_ptr->dither_index);
  188142. #endif
  188143. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188144. png_free(png_ptr, png_ptr->gamma_table);
  188145. #endif
  188146. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188147. png_free(png_ptr, png_ptr->gamma_from_1);
  188148. png_free(png_ptr, png_ptr->gamma_to_1);
  188149. #endif
  188150. #ifdef PNG_FREE_ME_SUPPORTED
  188151. if (png_ptr->free_me & PNG_FREE_PLTE)
  188152. png_zfree(png_ptr, png_ptr->palette);
  188153. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188154. #else
  188155. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188156. png_zfree(png_ptr, png_ptr->palette);
  188157. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188158. #endif
  188159. #if defined(PNG_tRNS_SUPPORTED) || \
  188160. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188161. #ifdef PNG_FREE_ME_SUPPORTED
  188162. if (png_ptr->free_me & PNG_FREE_TRNS)
  188163. png_free(png_ptr, png_ptr->trans);
  188164. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188165. #else
  188166. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188167. png_free(png_ptr, png_ptr->trans);
  188168. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188169. #endif
  188170. #endif
  188171. #if defined(PNG_READ_hIST_SUPPORTED)
  188172. #ifdef PNG_FREE_ME_SUPPORTED
  188173. if (png_ptr->free_me & PNG_FREE_HIST)
  188174. png_free(png_ptr, png_ptr->hist);
  188175. png_ptr->free_me &= ~PNG_FREE_HIST;
  188176. #else
  188177. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188178. png_free(png_ptr, png_ptr->hist);
  188179. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188180. #endif
  188181. #endif
  188182. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188183. if (png_ptr->gamma_16_table != NULL)
  188184. {
  188185. int i;
  188186. int istop = (1 << (8 - png_ptr->gamma_shift));
  188187. for (i = 0; i < istop; i++)
  188188. {
  188189. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188190. }
  188191. png_free(png_ptr, png_ptr->gamma_16_table);
  188192. }
  188193. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188194. if (png_ptr->gamma_16_from_1 != NULL)
  188195. {
  188196. int i;
  188197. int istop = (1 << (8 - png_ptr->gamma_shift));
  188198. for (i = 0; i < istop; i++)
  188199. {
  188200. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188201. }
  188202. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188203. }
  188204. if (png_ptr->gamma_16_to_1 != NULL)
  188205. {
  188206. int i;
  188207. int istop = (1 << (8 - png_ptr->gamma_shift));
  188208. for (i = 0; i < istop; i++)
  188209. {
  188210. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188211. }
  188212. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188213. }
  188214. #endif
  188215. #endif
  188216. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188217. png_free(png_ptr, png_ptr->time_buffer);
  188218. #endif
  188219. inflateEnd(&png_ptr->zstream);
  188220. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188221. png_free(png_ptr, png_ptr->save_buffer);
  188222. #endif
  188223. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188224. #ifdef PNG_TEXT_SUPPORTED
  188225. png_free(png_ptr, png_ptr->current_text);
  188226. #endif /* PNG_TEXT_SUPPORTED */
  188227. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188228. /* Save the important info out of the png_struct, in case it is
  188229. * being used again.
  188230. */
  188231. #ifdef PNG_SETJMP_SUPPORTED
  188232. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188233. #endif
  188234. error_fn = png_ptr->error_fn;
  188235. warning_fn = png_ptr->warning_fn;
  188236. error_ptr = png_ptr->error_ptr;
  188237. #ifdef PNG_USER_MEM_SUPPORTED
  188238. free_fn = png_ptr->free_fn;
  188239. #endif
  188240. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188241. png_ptr->error_fn = error_fn;
  188242. png_ptr->warning_fn = warning_fn;
  188243. png_ptr->error_ptr = error_ptr;
  188244. #ifdef PNG_USER_MEM_SUPPORTED
  188245. png_ptr->free_fn = free_fn;
  188246. #endif
  188247. #ifdef PNG_SETJMP_SUPPORTED
  188248. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188249. #endif
  188250. }
  188251. void PNGAPI
  188252. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188253. {
  188254. if(png_ptr == NULL) return;
  188255. png_ptr->read_row_fn = read_row_fn;
  188256. }
  188257. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188258. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188259. void PNGAPI
  188260. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188261. int transforms,
  188262. voidp params)
  188263. {
  188264. int row;
  188265. if(png_ptr == NULL) return;
  188266. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188267. /* invert the alpha channel from opacity to transparency
  188268. */
  188269. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188270. png_set_invert_alpha(png_ptr);
  188271. #endif
  188272. /* png_read_info() gives us all of the information from the
  188273. * PNG file before the first IDAT (image data chunk).
  188274. */
  188275. png_read_info(png_ptr, info_ptr);
  188276. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188277. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188278. /* -------------- image transformations start here ------------------- */
  188279. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188280. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188281. */
  188282. if (transforms & PNG_TRANSFORM_STRIP_16)
  188283. png_set_strip_16(png_ptr);
  188284. #endif
  188285. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188286. /* Strip alpha bytes from the input data without combining with
  188287. * the background (not recommended).
  188288. */
  188289. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188290. png_set_strip_alpha(png_ptr);
  188291. #endif
  188292. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188293. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188294. * byte into separate bytes (useful for paletted and grayscale images).
  188295. */
  188296. if (transforms & PNG_TRANSFORM_PACKING)
  188297. png_set_packing(png_ptr);
  188298. #endif
  188299. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188300. /* Change the order of packed pixels to least significant bit first
  188301. * (not useful if you are using png_set_packing).
  188302. */
  188303. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188304. png_set_packswap(png_ptr);
  188305. #endif
  188306. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188307. /* Expand paletted colors into true RGB triplets
  188308. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188309. * Expand paletted or RGB images with transparency to full alpha
  188310. * channels so the data will be available as RGBA quartets.
  188311. */
  188312. if (transforms & PNG_TRANSFORM_EXPAND)
  188313. if ((png_ptr->bit_depth < 8) ||
  188314. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188315. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188316. png_set_expand(png_ptr);
  188317. #endif
  188318. /* We don't handle background color or gamma transformation or dithering.
  188319. */
  188320. #if defined(PNG_READ_INVERT_SUPPORTED)
  188321. /* invert monochrome files to have 0 as white and 1 as black
  188322. */
  188323. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188324. png_set_invert_mono(png_ptr);
  188325. #endif
  188326. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188327. /* If you want to shift the pixel values from the range [0,255] or
  188328. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188329. * colors were originally in:
  188330. */
  188331. if ((transforms & PNG_TRANSFORM_SHIFT)
  188332. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188333. {
  188334. png_color_8p sig_bit;
  188335. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188336. png_set_shift(png_ptr, sig_bit);
  188337. }
  188338. #endif
  188339. #if defined(PNG_READ_BGR_SUPPORTED)
  188340. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188341. */
  188342. if (transforms & PNG_TRANSFORM_BGR)
  188343. png_set_bgr(png_ptr);
  188344. #endif
  188345. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188346. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188347. */
  188348. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188349. png_set_swap_alpha(png_ptr);
  188350. #endif
  188351. #if defined(PNG_READ_SWAP_SUPPORTED)
  188352. /* swap bytes of 16 bit files to least significant byte first
  188353. */
  188354. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188355. png_set_swap(png_ptr);
  188356. #endif
  188357. /* We don't handle adding filler bytes */
  188358. /* Optional call to gamma correct and add the background to the palette
  188359. * and update info structure. REQUIRED if you are expecting libpng to
  188360. * update the palette for you (i.e., you selected such a transform above).
  188361. */
  188362. png_read_update_info(png_ptr, info_ptr);
  188363. /* -------------- image transformations end here ------------------- */
  188364. #ifdef PNG_FREE_ME_SUPPORTED
  188365. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188366. #endif
  188367. if(info_ptr->row_pointers == NULL)
  188368. {
  188369. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188370. info_ptr->height * png_sizeof(png_bytep));
  188371. #ifdef PNG_FREE_ME_SUPPORTED
  188372. info_ptr->free_me |= PNG_FREE_ROWS;
  188373. #endif
  188374. for (row = 0; row < (int)info_ptr->height; row++)
  188375. {
  188376. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188377. png_get_rowbytes(png_ptr, info_ptr));
  188378. }
  188379. }
  188380. png_read_image(png_ptr, info_ptr->row_pointers);
  188381. info_ptr->valid |= PNG_INFO_IDAT;
  188382. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188383. png_read_end(png_ptr, info_ptr);
  188384. transforms = transforms; /* quiet compiler warnings */
  188385. params = params;
  188386. }
  188387. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188388. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188389. #endif /* PNG_READ_SUPPORTED */
  188390. /*** End of inlined file: pngread.c ***/
  188391. /*** Start of inlined file: pngpread.c ***/
  188392. /* pngpread.c - read a png file in push mode
  188393. *
  188394. * Last changed in libpng 1.2.21 October 4, 2007
  188395. * For conditions of distribution and use, see copyright notice in png.h
  188396. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188397. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188398. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188399. */
  188400. #define PNG_INTERNAL
  188401. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188402. /* push model modes */
  188403. #define PNG_READ_SIG_MODE 0
  188404. #define PNG_READ_CHUNK_MODE 1
  188405. #define PNG_READ_IDAT_MODE 2
  188406. #define PNG_SKIP_MODE 3
  188407. #define PNG_READ_tEXt_MODE 4
  188408. #define PNG_READ_zTXt_MODE 5
  188409. #define PNG_READ_DONE_MODE 6
  188410. #define PNG_READ_iTXt_MODE 7
  188411. #define PNG_ERROR_MODE 8
  188412. void PNGAPI
  188413. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188414. png_bytep buffer, png_size_t buffer_size)
  188415. {
  188416. if(png_ptr == NULL) return;
  188417. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188418. while (png_ptr->buffer_size)
  188419. {
  188420. png_process_some_data(png_ptr, info_ptr);
  188421. }
  188422. }
  188423. /* What we do with the incoming data depends on what we were previously
  188424. * doing before we ran out of data...
  188425. */
  188426. void /* PRIVATE */
  188427. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188428. {
  188429. if(png_ptr == NULL) return;
  188430. switch (png_ptr->process_mode)
  188431. {
  188432. case PNG_READ_SIG_MODE:
  188433. {
  188434. png_push_read_sig(png_ptr, info_ptr);
  188435. break;
  188436. }
  188437. case PNG_READ_CHUNK_MODE:
  188438. {
  188439. png_push_read_chunk(png_ptr, info_ptr);
  188440. break;
  188441. }
  188442. case PNG_READ_IDAT_MODE:
  188443. {
  188444. png_push_read_IDAT(png_ptr);
  188445. break;
  188446. }
  188447. #if defined(PNG_READ_tEXt_SUPPORTED)
  188448. case PNG_READ_tEXt_MODE:
  188449. {
  188450. png_push_read_tEXt(png_ptr, info_ptr);
  188451. break;
  188452. }
  188453. #endif
  188454. #if defined(PNG_READ_zTXt_SUPPORTED)
  188455. case PNG_READ_zTXt_MODE:
  188456. {
  188457. png_push_read_zTXt(png_ptr, info_ptr);
  188458. break;
  188459. }
  188460. #endif
  188461. #if defined(PNG_READ_iTXt_SUPPORTED)
  188462. case PNG_READ_iTXt_MODE:
  188463. {
  188464. png_push_read_iTXt(png_ptr, info_ptr);
  188465. break;
  188466. }
  188467. #endif
  188468. case PNG_SKIP_MODE:
  188469. {
  188470. png_push_crc_finish(png_ptr);
  188471. break;
  188472. }
  188473. default:
  188474. {
  188475. png_ptr->buffer_size = 0;
  188476. break;
  188477. }
  188478. }
  188479. }
  188480. /* Read any remaining signature bytes from the stream and compare them with
  188481. * the correct PNG signature. It is possible that this routine is called
  188482. * with bytes already read from the signature, either because they have been
  188483. * checked by the calling application, or because of multiple calls to this
  188484. * routine.
  188485. */
  188486. void /* PRIVATE */
  188487. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188488. {
  188489. png_size_t num_checked = png_ptr->sig_bytes,
  188490. num_to_check = 8 - num_checked;
  188491. if (png_ptr->buffer_size < num_to_check)
  188492. {
  188493. num_to_check = png_ptr->buffer_size;
  188494. }
  188495. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188496. num_to_check);
  188497. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188498. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188499. {
  188500. if (num_checked < 4 &&
  188501. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188502. png_error(png_ptr, "Not a PNG file");
  188503. else
  188504. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188505. }
  188506. else
  188507. {
  188508. if (png_ptr->sig_bytes >= 8)
  188509. {
  188510. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188511. }
  188512. }
  188513. }
  188514. void /* PRIVATE */
  188515. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188516. {
  188517. #ifdef PNG_USE_LOCAL_ARRAYS
  188518. PNG_CONST PNG_IHDR;
  188519. PNG_CONST PNG_IDAT;
  188520. PNG_CONST PNG_IEND;
  188521. PNG_CONST PNG_PLTE;
  188522. #if defined(PNG_READ_bKGD_SUPPORTED)
  188523. PNG_CONST PNG_bKGD;
  188524. #endif
  188525. #if defined(PNG_READ_cHRM_SUPPORTED)
  188526. PNG_CONST PNG_cHRM;
  188527. #endif
  188528. #if defined(PNG_READ_gAMA_SUPPORTED)
  188529. PNG_CONST PNG_gAMA;
  188530. #endif
  188531. #if defined(PNG_READ_hIST_SUPPORTED)
  188532. PNG_CONST PNG_hIST;
  188533. #endif
  188534. #if defined(PNG_READ_iCCP_SUPPORTED)
  188535. PNG_CONST PNG_iCCP;
  188536. #endif
  188537. #if defined(PNG_READ_iTXt_SUPPORTED)
  188538. PNG_CONST PNG_iTXt;
  188539. #endif
  188540. #if defined(PNG_READ_oFFs_SUPPORTED)
  188541. PNG_CONST PNG_oFFs;
  188542. #endif
  188543. #if defined(PNG_READ_pCAL_SUPPORTED)
  188544. PNG_CONST PNG_pCAL;
  188545. #endif
  188546. #if defined(PNG_READ_pHYs_SUPPORTED)
  188547. PNG_CONST PNG_pHYs;
  188548. #endif
  188549. #if defined(PNG_READ_sBIT_SUPPORTED)
  188550. PNG_CONST PNG_sBIT;
  188551. #endif
  188552. #if defined(PNG_READ_sCAL_SUPPORTED)
  188553. PNG_CONST PNG_sCAL;
  188554. #endif
  188555. #if defined(PNG_READ_sRGB_SUPPORTED)
  188556. PNG_CONST PNG_sRGB;
  188557. #endif
  188558. #if defined(PNG_READ_sPLT_SUPPORTED)
  188559. PNG_CONST PNG_sPLT;
  188560. #endif
  188561. #if defined(PNG_READ_tEXt_SUPPORTED)
  188562. PNG_CONST PNG_tEXt;
  188563. #endif
  188564. #if defined(PNG_READ_tIME_SUPPORTED)
  188565. PNG_CONST PNG_tIME;
  188566. #endif
  188567. #if defined(PNG_READ_tRNS_SUPPORTED)
  188568. PNG_CONST PNG_tRNS;
  188569. #endif
  188570. #if defined(PNG_READ_zTXt_SUPPORTED)
  188571. PNG_CONST PNG_zTXt;
  188572. #endif
  188573. #endif /* PNG_USE_LOCAL_ARRAYS */
  188574. /* First we make sure we have enough data for the 4 byte chunk name
  188575. * and the 4 byte chunk length before proceeding with decoding the
  188576. * chunk data. To fully decode each of these chunks, we also make
  188577. * sure we have enough data in the buffer for the 4 byte CRC at the
  188578. * end of every chunk (except IDAT, which is handled separately).
  188579. */
  188580. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188581. {
  188582. png_byte chunk_length[4];
  188583. if (png_ptr->buffer_size < 8)
  188584. {
  188585. png_push_save_buffer(png_ptr);
  188586. return;
  188587. }
  188588. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188589. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188590. png_reset_crc(png_ptr);
  188591. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188592. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188593. }
  188594. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188595. if(png_ptr->mode & PNG_AFTER_IDAT)
  188596. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188597. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188598. {
  188599. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188600. {
  188601. png_push_save_buffer(png_ptr);
  188602. return;
  188603. }
  188604. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188605. }
  188606. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188607. {
  188608. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188609. {
  188610. png_push_save_buffer(png_ptr);
  188611. return;
  188612. }
  188613. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188614. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188615. png_push_have_end(png_ptr, info_ptr);
  188616. }
  188617. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188618. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188619. {
  188620. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188621. {
  188622. png_push_save_buffer(png_ptr);
  188623. return;
  188624. }
  188625. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188626. png_ptr->mode |= PNG_HAVE_IDAT;
  188627. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188628. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188629. png_ptr->mode |= PNG_HAVE_PLTE;
  188630. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188631. {
  188632. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188633. png_error(png_ptr, "Missing IHDR before IDAT");
  188634. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188635. !(png_ptr->mode & PNG_HAVE_PLTE))
  188636. png_error(png_ptr, "Missing PLTE before IDAT");
  188637. }
  188638. }
  188639. #endif
  188640. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188641. {
  188642. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188643. {
  188644. png_push_save_buffer(png_ptr);
  188645. return;
  188646. }
  188647. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188648. }
  188649. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188650. {
  188651. /* If we reach an IDAT chunk, this means we have read all of the
  188652. * header chunks, and we can start reading the image (or if this
  188653. * is called after the image has been read - we have an error).
  188654. */
  188655. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188656. png_error(png_ptr, "Missing IHDR before IDAT");
  188657. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188658. !(png_ptr->mode & PNG_HAVE_PLTE))
  188659. png_error(png_ptr, "Missing PLTE before IDAT");
  188660. if (png_ptr->mode & PNG_HAVE_IDAT)
  188661. {
  188662. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188663. if (png_ptr->push_length == 0)
  188664. return;
  188665. if (png_ptr->mode & PNG_AFTER_IDAT)
  188666. png_error(png_ptr, "Too many IDAT's found");
  188667. }
  188668. png_ptr->idat_size = png_ptr->push_length;
  188669. png_ptr->mode |= PNG_HAVE_IDAT;
  188670. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188671. png_push_have_info(png_ptr, info_ptr);
  188672. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188673. png_ptr->zstream.next_out = png_ptr->row_buf;
  188674. return;
  188675. }
  188676. #if defined(PNG_READ_gAMA_SUPPORTED)
  188677. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188678. {
  188679. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188680. {
  188681. png_push_save_buffer(png_ptr);
  188682. return;
  188683. }
  188684. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188685. }
  188686. #endif
  188687. #if defined(PNG_READ_sBIT_SUPPORTED)
  188688. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 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_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188696. }
  188697. #endif
  188698. #if defined(PNG_READ_cHRM_SUPPORTED)
  188699. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188700. {
  188701. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188702. {
  188703. png_push_save_buffer(png_ptr);
  188704. return;
  188705. }
  188706. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188707. }
  188708. #endif
  188709. #if defined(PNG_READ_sRGB_SUPPORTED)
  188710. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188711. {
  188712. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188713. {
  188714. png_push_save_buffer(png_ptr);
  188715. return;
  188716. }
  188717. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188718. }
  188719. #endif
  188720. #if defined(PNG_READ_iCCP_SUPPORTED)
  188721. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188722. {
  188723. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188724. {
  188725. png_push_save_buffer(png_ptr);
  188726. return;
  188727. }
  188728. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188729. }
  188730. #endif
  188731. #if defined(PNG_READ_sPLT_SUPPORTED)
  188732. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188733. {
  188734. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188735. {
  188736. png_push_save_buffer(png_ptr);
  188737. return;
  188738. }
  188739. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188740. }
  188741. #endif
  188742. #if defined(PNG_READ_tRNS_SUPPORTED)
  188743. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188744. {
  188745. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188746. {
  188747. png_push_save_buffer(png_ptr);
  188748. return;
  188749. }
  188750. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188751. }
  188752. #endif
  188753. #if defined(PNG_READ_bKGD_SUPPORTED)
  188754. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188755. {
  188756. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188757. {
  188758. png_push_save_buffer(png_ptr);
  188759. return;
  188760. }
  188761. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188762. }
  188763. #endif
  188764. #if defined(PNG_READ_hIST_SUPPORTED)
  188765. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188766. {
  188767. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188768. {
  188769. png_push_save_buffer(png_ptr);
  188770. return;
  188771. }
  188772. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188773. }
  188774. #endif
  188775. #if defined(PNG_READ_pHYs_SUPPORTED)
  188776. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188777. {
  188778. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188779. {
  188780. png_push_save_buffer(png_ptr);
  188781. return;
  188782. }
  188783. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188784. }
  188785. #endif
  188786. #if defined(PNG_READ_oFFs_SUPPORTED)
  188787. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188788. {
  188789. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188790. {
  188791. png_push_save_buffer(png_ptr);
  188792. return;
  188793. }
  188794. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188795. }
  188796. #endif
  188797. #if defined(PNG_READ_pCAL_SUPPORTED)
  188798. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188799. {
  188800. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188801. {
  188802. png_push_save_buffer(png_ptr);
  188803. return;
  188804. }
  188805. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188806. }
  188807. #endif
  188808. #if defined(PNG_READ_sCAL_SUPPORTED)
  188809. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188810. {
  188811. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188812. {
  188813. png_push_save_buffer(png_ptr);
  188814. return;
  188815. }
  188816. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188817. }
  188818. #endif
  188819. #if defined(PNG_READ_tIME_SUPPORTED)
  188820. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188821. {
  188822. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188823. {
  188824. png_push_save_buffer(png_ptr);
  188825. return;
  188826. }
  188827. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188828. }
  188829. #endif
  188830. #if defined(PNG_READ_tEXt_SUPPORTED)
  188831. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188832. {
  188833. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188834. {
  188835. png_push_save_buffer(png_ptr);
  188836. return;
  188837. }
  188838. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188839. }
  188840. #endif
  188841. #if defined(PNG_READ_zTXt_SUPPORTED)
  188842. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188843. {
  188844. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188845. {
  188846. png_push_save_buffer(png_ptr);
  188847. return;
  188848. }
  188849. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188850. }
  188851. #endif
  188852. #if defined(PNG_READ_iTXt_SUPPORTED)
  188853. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188854. {
  188855. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188856. {
  188857. png_push_save_buffer(png_ptr);
  188858. return;
  188859. }
  188860. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188861. }
  188862. #endif
  188863. else
  188864. {
  188865. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188866. {
  188867. png_push_save_buffer(png_ptr);
  188868. return;
  188869. }
  188870. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188871. }
  188872. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188873. }
  188874. void /* PRIVATE */
  188875. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188876. {
  188877. png_ptr->process_mode = PNG_SKIP_MODE;
  188878. png_ptr->skip_length = skip;
  188879. }
  188880. void /* PRIVATE */
  188881. png_push_crc_finish(png_structp png_ptr)
  188882. {
  188883. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188884. {
  188885. png_size_t save_size;
  188886. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188887. save_size = (png_size_t)png_ptr->skip_length;
  188888. else
  188889. save_size = png_ptr->save_buffer_size;
  188890. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188891. png_ptr->skip_length -= save_size;
  188892. png_ptr->buffer_size -= save_size;
  188893. png_ptr->save_buffer_size -= save_size;
  188894. png_ptr->save_buffer_ptr += save_size;
  188895. }
  188896. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188897. {
  188898. png_size_t save_size;
  188899. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188900. save_size = (png_size_t)png_ptr->skip_length;
  188901. else
  188902. save_size = png_ptr->current_buffer_size;
  188903. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188904. png_ptr->skip_length -= save_size;
  188905. png_ptr->buffer_size -= save_size;
  188906. png_ptr->current_buffer_size -= save_size;
  188907. png_ptr->current_buffer_ptr += save_size;
  188908. }
  188909. if (!png_ptr->skip_length)
  188910. {
  188911. if (png_ptr->buffer_size < 4)
  188912. {
  188913. png_push_save_buffer(png_ptr);
  188914. return;
  188915. }
  188916. png_crc_finish(png_ptr, 0);
  188917. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188918. }
  188919. }
  188920. void PNGAPI
  188921. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188922. {
  188923. png_bytep ptr;
  188924. if(png_ptr == NULL) return;
  188925. ptr = buffer;
  188926. if (png_ptr->save_buffer_size)
  188927. {
  188928. png_size_t save_size;
  188929. if (length < png_ptr->save_buffer_size)
  188930. save_size = length;
  188931. else
  188932. save_size = png_ptr->save_buffer_size;
  188933. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188934. length -= save_size;
  188935. ptr += save_size;
  188936. png_ptr->buffer_size -= save_size;
  188937. png_ptr->save_buffer_size -= save_size;
  188938. png_ptr->save_buffer_ptr += save_size;
  188939. }
  188940. if (length && png_ptr->current_buffer_size)
  188941. {
  188942. png_size_t save_size;
  188943. if (length < png_ptr->current_buffer_size)
  188944. save_size = length;
  188945. else
  188946. save_size = png_ptr->current_buffer_size;
  188947. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188948. png_ptr->buffer_size -= save_size;
  188949. png_ptr->current_buffer_size -= save_size;
  188950. png_ptr->current_buffer_ptr += save_size;
  188951. }
  188952. }
  188953. void /* PRIVATE */
  188954. png_push_save_buffer(png_structp png_ptr)
  188955. {
  188956. if (png_ptr->save_buffer_size)
  188957. {
  188958. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188959. {
  188960. png_size_t i,istop;
  188961. png_bytep sp;
  188962. png_bytep dp;
  188963. istop = png_ptr->save_buffer_size;
  188964. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188965. i < istop; i++, sp++, dp++)
  188966. {
  188967. *dp = *sp;
  188968. }
  188969. }
  188970. }
  188971. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188972. png_ptr->save_buffer_max)
  188973. {
  188974. png_size_t new_max;
  188975. png_bytep old_buffer;
  188976. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188977. (png_ptr->current_buffer_size + 256))
  188978. {
  188979. png_error(png_ptr, "Potential overflow of save_buffer");
  188980. }
  188981. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188982. old_buffer = png_ptr->save_buffer;
  188983. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188984. (png_uint_32)new_max);
  188985. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188986. png_free(png_ptr, old_buffer);
  188987. png_ptr->save_buffer_max = new_max;
  188988. }
  188989. if (png_ptr->current_buffer_size)
  188990. {
  188991. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188992. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188993. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188994. png_ptr->current_buffer_size = 0;
  188995. }
  188996. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188997. png_ptr->buffer_size = 0;
  188998. }
  188999. void /* PRIVATE */
  189000. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  189001. png_size_t buffer_length)
  189002. {
  189003. png_ptr->current_buffer = buffer;
  189004. png_ptr->current_buffer_size = buffer_length;
  189005. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  189006. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  189007. }
  189008. void /* PRIVATE */
  189009. png_push_read_IDAT(png_structp png_ptr)
  189010. {
  189011. #ifdef PNG_USE_LOCAL_ARRAYS
  189012. PNG_CONST PNG_IDAT;
  189013. #endif
  189014. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  189015. {
  189016. png_byte chunk_length[4];
  189017. if (png_ptr->buffer_size < 8)
  189018. {
  189019. png_push_save_buffer(png_ptr);
  189020. return;
  189021. }
  189022. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189023. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189024. png_reset_crc(png_ptr);
  189025. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189026. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189027. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189028. {
  189029. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189030. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189031. png_error(png_ptr, "Not enough compressed data");
  189032. return;
  189033. }
  189034. png_ptr->idat_size = png_ptr->push_length;
  189035. }
  189036. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  189037. {
  189038. png_size_t save_size;
  189039. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  189040. {
  189041. save_size = (png_size_t)png_ptr->idat_size;
  189042. /* check for overflow */
  189043. if((png_uint_32)save_size != png_ptr->idat_size)
  189044. png_error(png_ptr, "save_size overflowed in pngpread");
  189045. }
  189046. else
  189047. save_size = png_ptr->save_buffer_size;
  189048. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189049. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189050. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189051. png_ptr->idat_size -= save_size;
  189052. png_ptr->buffer_size -= save_size;
  189053. png_ptr->save_buffer_size -= save_size;
  189054. png_ptr->save_buffer_ptr += save_size;
  189055. }
  189056. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  189057. {
  189058. png_size_t save_size;
  189059. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  189060. {
  189061. save_size = (png_size_t)png_ptr->idat_size;
  189062. /* check for overflow */
  189063. if((png_uint_32)save_size != png_ptr->idat_size)
  189064. png_error(png_ptr, "save_size overflowed in pngpread");
  189065. }
  189066. else
  189067. save_size = png_ptr->current_buffer_size;
  189068. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189069. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189070. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189071. png_ptr->idat_size -= save_size;
  189072. png_ptr->buffer_size -= save_size;
  189073. png_ptr->current_buffer_size -= save_size;
  189074. png_ptr->current_buffer_ptr += save_size;
  189075. }
  189076. if (!png_ptr->idat_size)
  189077. {
  189078. if (png_ptr->buffer_size < 4)
  189079. {
  189080. png_push_save_buffer(png_ptr);
  189081. return;
  189082. }
  189083. png_crc_finish(png_ptr, 0);
  189084. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189085. png_ptr->mode |= PNG_AFTER_IDAT;
  189086. }
  189087. }
  189088. void /* PRIVATE */
  189089. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189090. png_size_t buffer_length)
  189091. {
  189092. int ret;
  189093. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189094. png_error(png_ptr, "Extra compression data");
  189095. png_ptr->zstream.next_in = buffer;
  189096. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189097. for(;;)
  189098. {
  189099. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189100. if (ret != Z_OK)
  189101. {
  189102. if (ret == Z_STREAM_END)
  189103. {
  189104. if (png_ptr->zstream.avail_in)
  189105. png_error(png_ptr, "Extra compressed data");
  189106. if (!(png_ptr->zstream.avail_out))
  189107. {
  189108. png_push_process_row(png_ptr);
  189109. }
  189110. png_ptr->mode |= PNG_AFTER_IDAT;
  189111. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189112. break;
  189113. }
  189114. else if (ret == Z_BUF_ERROR)
  189115. break;
  189116. else
  189117. png_error(png_ptr, "Decompression Error");
  189118. }
  189119. if (!(png_ptr->zstream.avail_out))
  189120. {
  189121. if ((
  189122. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189123. png_ptr->interlaced && png_ptr->pass > 6) ||
  189124. (!png_ptr->interlaced &&
  189125. #endif
  189126. png_ptr->row_number == png_ptr->num_rows))
  189127. {
  189128. if (png_ptr->zstream.avail_in)
  189129. {
  189130. png_warning(png_ptr, "Too much data in IDAT chunks");
  189131. }
  189132. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189133. break;
  189134. }
  189135. png_push_process_row(png_ptr);
  189136. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189137. png_ptr->zstream.next_out = png_ptr->row_buf;
  189138. }
  189139. else
  189140. break;
  189141. }
  189142. }
  189143. void /* PRIVATE */
  189144. png_push_process_row(png_structp png_ptr)
  189145. {
  189146. png_ptr->row_info.color_type = png_ptr->color_type;
  189147. png_ptr->row_info.width = png_ptr->iwidth;
  189148. png_ptr->row_info.channels = png_ptr->channels;
  189149. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189150. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189151. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189152. png_ptr->row_info.width);
  189153. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189154. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189155. (int)(png_ptr->row_buf[0]));
  189156. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189157. png_ptr->rowbytes + 1);
  189158. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189159. png_do_read_transformations(png_ptr);
  189160. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189161. /* blow up interlaced rows to full size */
  189162. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189163. {
  189164. if (png_ptr->pass < 6)
  189165. /* old interface (pre-1.0.9):
  189166. png_do_read_interlace(&(png_ptr->row_info),
  189167. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189168. */
  189169. png_do_read_interlace(png_ptr);
  189170. switch (png_ptr->pass)
  189171. {
  189172. case 0:
  189173. {
  189174. int i;
  189175. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189176. {
  189177. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189178. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189179. }
  189180. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189181. {
  189182. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189183. {
  189184. png_push_have_row(png_ptr, png_bytep_NULL);
  189185. png_read_push_finish_row(png_ptr);
  189186. }
  189187. }
  189188. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189189. {
  189190. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189191. {
  189192. png_push_have_row(png_ptr, png_bytep_NULL);
  189193. png_read_push_finish_row(png_ptr);
  189194. }
  189195. }
  189196. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189197. {
  189198. png_push_have_row(png_ptr, png_bytep_NULL);
  189199. png_read_push_finish_row(png_ptr);
  189200. }
  189201. break;
  189202. }
  189203. case 1:
  189204. {
  189205. int i;
  189206. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189207. {
  189208. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189209. png_read_push_finish_row(png_ptr);
  189210. }
  189211. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189212. {
  189213. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189214. {
  189215. png_push_have_row(png_ptr, png_bytep_NULL);
  189216. png_read_push_finish_row(png_ptr);
  189217. }
  189218. }
  189219. break;
  189220. }
  189221. case 2:
  189222. {
  189223. int i;
  189224. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189225. {
  189226. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189227. png_read_push_finish_row(png_ptr);
  189228. }
  189229. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189230. {
  189231. png_push_have_row(png_ptr, png_bytep_NULL);
  189232. png_read_push_finish_row(png_ptr);
  189233. }
  189234. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189235. {
  189236. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189237. {
  189238. png_push_have_row(png_ptr, png_bytep_NULL);
  189239. png_read_push_finish_row(png_ptr);
  189240. }
  189241. }
  189242. break;
  189243. }
  189244. case 3:
  189245. {
  189246. int i;
  189247. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189248. {
  189249. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189250. png_read_push_finish_row(png_ptr);
  189251. }
  189252. if (png_ptr->pass == 4) /* skip top two generated rows */
  189253. {
  189254. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189255. {
  189256. png_push_have_row(png_ptr, png_bytep_NULL);
  189257. png_read_push_finish_row(png_ptr);
  189258. }
  189259. }
  189260. break;
  189261. }
  189262. case 4:
  189263. {
  189264. int i;
  189265. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189266. {
  189267. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189268. png_read_push_finish_row(png_ptr);
  189269. }
  189270. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189271. {
  189272. png_push_have_row(png_ptr, png_bytep_NULL);
  189273. png_read_push_finish_row(png_ptr);
  189274. }
  189275. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189276. {
  189277. png_push_have_row(png_ptr, png_bytep_NULL);
  189278. png_read_push_finish_row(png_ptr);
  189279. }
  189280. break;
  189281. }
  189282. case 5:
  189283. {
  189284. int i;
  189285. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189286. {
  189287. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189288. png_read_push_finish_row(png_ptr);
  189289. }
  189290. if (png_ptr->pass == 6) /* skip top generated row */
  189291. {
  189292. png_push_have_row(png_ptr, png_bytep_NULL);
  189293. png_read_push_finish_row(png_ptr);
  189294. }
  189295. break;
  189296. }
  189297. case 6:
  189298. {
  189299. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189300. png_read_push_finish_row(png_ptr);
  189301. if (png_ptr->pass != 6)
  189302. break;
  189303. png_push_have_row(png_ptr, png_bytep_NULL);
  189304. png_read_push_finish_row(png_ptr);
  189305. }
  189306. }
  189307. }
  189308. else
  189309. #endif
  189310. {
  189311. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189312. png_read_push_finish_row(png_ptr);
  189313. }
  189314. }
  189315. void /* PRIVATE */
  189316. png_read_push_finish_row(png_structp png_ptr)
  189317. {
  189318. #ifdef PNG_USE_LOCAL_ARRAYS
  189319. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189320. /* start of interlace block */
  189321. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189322. /* offset to next interlace block */
  189323. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189324. /* start of interlace block in the y direction */
  189325. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189326. /* offset to next interlace block in the y direction */
  189327. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189328. /* Height of interlace block. This is not currently used - if you need
  189329. * it, uncomment it here and in png.h
  189330. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189331. */
  189332. #endif
  189333. png_ptr->row_number++;
  189334. if (png_ptr->row_number < png_ptr->num_rows)
  189335. return;
  189336. if (png_ptr->interlaced)
  189337. {
  189338. png_ptr->row_number = 0;
  189339. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189340. png_ptr->rowbytes + 1);
  189341. do
  189342. {
  189343. png_ptr->pass++;
  189344. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189345. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189346. (png_ptr->pass == 5 && png_ptr->width < 2))
  189347. png_ptr->pass++;
  189348. if (png_ptr->pass > 7)
  189349. png_ptr->pass--;
  189350. if (png_ptr->pass >= 7)
  189351. break;
  189352. png_ptr->iwidth = (png_ptr->width +
  189353. png_pass_inc[png_ptr->pass] - 1 -
  189354. png_pass_start[png_ptr->pass]) /
  189355. png_pass_inc[png_ptr->pass];
  189356. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189357. png_ptr->iwidth) + 1;
  189358. if (png_ptr->transformations & PNG_INTERLACE)
  189359. break;
  189360. png_ptr->num_rows = (png_ptr->height +
  189361. png_pass_yinc[png_ptr->pass] - 1 -
  189362. png_pass_ystart[png_ptr->pass]) /
  189363. png_pass_yinc[png_ptr->pass];
  189364. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189365. }
  189366. }
  189367. #if defined(PNG_READ_tEXt_SUPPORTED)
  189368. void /* PRIVATE */
  189369. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189370. length)
  189371. {
  189372. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189373. {
  189374. png_error(png_ptr, "Out of place tEXt");
  189375. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189376. }
  189377. #ifdef PNG_MAX_MALLOC_64K
  189378. png_ptr->skip_length = 0; /* This may not be necessary */
  189379. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189380. {
  189381. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189382. png_ptr->skip_length = length - (png_uint_32)65535L;
  189383. length = (png_uint_32)65535L;
  189384. }
  189385. #endif
  189386. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189387. (png_uint_32)(length+1));
  189388. png_ptr->current_text[length] = '\0';
  189389. png_ptr->current_text_ptr = png_ptr->current_text;
  189390. png_ptr->current_text_size = (png_size_t)length;
  189391. png_ptr->current_text_left = (png_size_t)length;
  189392. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189393. }
  189394. void /* PRIVATE */
  189395. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189396. {
  189397. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189398. {
  189399. png_size_t text_size;
  189400. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189401. text_size = png_ptr->buffer_size;
  189402. else
  189403. text_size = png_ptr->current_text_left;
  189404. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189405. png_ptr->current_text_left -= text_size;
  189406. png_ptr->current_text_ptr += text_size;
  189407. }
  189408. if (!(png_ptr->current_text_left))
  189409. {
  189410. png_textp text_ptr;
  189411. png_charp text;
  189412. png_charp key;
  189413. int ret;
  189414. if (png_ptr->buffer_size < 4)
  189415. {
  189416. png_push_save_buffer(png_ptr);
  189417. return;
  189418. }
  189419. png_push_crc_finish(png_ptr);
  189420. #if defined(PNG_MAX_MALLOC_64K)
  189421. if (png_ptr->skip_length)
  189422. return;
  189423. #endif
  189424. key = png_ptr->current_text;
  189425. for (text = key; *text; text++)
  189426. /* empty loop */ ;
  189427. if (text < key + png_ptr->current_text_size)
  189428. text++;
  189429. text_ptr = (png_textp)png_malloc(png_ptr,
  189430. (png_uint_32)png_sizeof(png_text));
  189431. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189432. text_ptr->key = key;
  189433. #ifdef PNG_iTXt_SUPPORTED
  189434. text_ptr->lang = NULL;
  189435. text_ptr->lang_key = NULL;
  189436. #endif
  189437. text_ptr->text = text;
  189438. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189439. png_free(png_ptr, key);
  189440. png_free(png_ptr, text_ptr);
  189441. png_ptr->current_text = NULL;
  189442. if (ret)
  189443. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189444. }
  189445. }
  189446. #endif
  189447. #if defined(PNG_READ_zTXt_SUPPORTED)
  189448. void /* PRIVATE */
  189449. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189450. length)
  189451. {
  189452. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189453. {
  189454. png_error(png_ptr, "Out of place zTXt");
  189455. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189456. }
  189457. #ifdef PNG_MAX_MALLOC_64K
  189458. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189459. * to be able to store the uncompressed data. Actually, the threshold
  189460. * is probably around 32K, but it isn't as definite as 64K is.
  189461. */
  189462. if (length > (png_uint_32)65535L)
  189463. {
  189464. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189465. png_push_crc_skip(png_ptr, length);
  189466. return;
  189467. }
  189468. #endif
  189469. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189470. (png_uint_32)(length+1));
  189471. png_ptr->current_text[length] = '\0';
  189472. png_ptr->current_text_ptr = png_ptr->current_text;
  189473. png_ptr->current_text_size = (png_size_t)length;
  189474. png_ptr->current_text_left = (png_size_t)length;
  189475. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189476. }
  189477. void /* PRIVATE */
  189478. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189479. {
  189480. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189481. {
  189482. png_size_t text_size;
  189483. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189484. text_size = png_ptr->buffer_size;
  189485. else
  189486. text_size = png_ptr->current_text_left;
  189487. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189488. png_ptr->current_text_left -= text_size;
  189489. png_ptr->current_text_ptr += text_size;
  189490. }
  189491. if (!(png_ptr->current_text_left))
  189492. {
  189493. png_textp text_ptr;
  189494. png_charp text;
  189495. png_charp key;
  189496. int ret;
  189497. png_size_t text_size, key_size;
  189498. if (png_ptr->buffer_size < 4)
  189499. {
  189500. png_push_save_buffer(png_ptr);
  189501. return;
  189502. }
  189503. png_push_crc_finish(png_ptr);
  189504. key = png_ptr->current_text;
  189505. for (text = key; *text; text++)
  189506. /* empty loop */ ;
  189507. /* zTXt can't have zero text */
  189508. if (text >= key + png_ptr->current_text_size)
  189509. {
  189510. png_ptr->current_text = NULL;
  189511. png_free(png_ptr, key);
  189512. return;
  189513. }
  189514. text++;
  189515. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189516. {
  189517. png_ptr->current_text = NULL;
  189518. png_free(png_ptr, key);
  189519. return;
  189520. }
  189521. text++;
  189522. png_ptr->zstream.next_in = (png_bytep )text;
  189523. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189524. (text - key));
  189525. png_ptr->zstream.next_out = png_ptr->zbuf;
  189526. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189527. key_size = text - key;
  189528. text_size = 0;
  189529. text = NULL;
  189530. ret = Z_STREAM_END;
  189531. while (png_ptr->zstream.avail_in)
  189532. {
  189533. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189534. if (ret != Z_OK && ret != Z_STREAM_END)
  189535. {
  189536. inflateReset(&png_ptr->zstream);
  189537. png_ptr->zstream.avail_in = 0;
  189538. png_ptr->current_text = NULL;
  189539. png_free(png_ptr, key);
  189540. png_free(png_ptr, text);
  189541. return;
  189542. }
  189543. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189544. {
  189545. if (text == NULL)
  189546. {
  189547. text = (png_charp)png_malloc(png_ptr,
  189548. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189549. + key_size + 1));
  189550. png_memcpy(text + key_size, png_ptr->zbuf,
  189551. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189552. png_memcpy(text, key, key_size);
  189553. text_size = key_size + png_ptr->zbuf_size -
  189554. png_ptr->zstream.avail_out;
  189555. *(text + text_size) = '\0';
  189556. }
  189557. else
  189558. {
  189559. png_charp tmp;
  189560. tmp = text;
  189561. text = (png_charp)png_malloc(png_ptr, text_size +
  189562. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189563. + 1));
  189564. png_memcpy(text, tmp, text_size);
  189565. png_free(png_ptr, tmp);
  189566. png_memcpy(text + text_size, png_ptr->zbuf,
  189567. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189568. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189569. *(text + text_size) = '\0';
  189570. }
  189571. if (ret != Z_STREAM_END)
  189572. {
  189573. png_ptr->zstream.next_out = png_ptr->zbuf;
  189574. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189575. }
  189576. }
  189577. else
  189578. {
  189579. break;
  189580. }
  189581. if (ret == Z_STREAM_END)
  189582. break;
  189583. }
  189584. inflateReset(&png_ptr->zstream);
  189585. png_ptr->zstream.avail_in = 0;
  189586. if (ret != Z_STREAM_END)
  189587. {
  189588. png_ptr->current_text = NULL;
  189589. png_free(png_ptr, key);
  189590. png_free(png_ptr, text);
  189591. return;
  189592. }
  189593. png_ptr->current_text = NULL;
  189594. png_free(png_ptr, key);
  189595. key = text;
  189596. text += key_size;
  189597. text_ptr = (png_textp)png_malloc(png_ptr,
  189598. (png_uint_32)png_sizeof(png_text));
  189599. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189600. text_ptr->key = key;
  189601. #ifdef PNG_iTXt_SUPPORTED
  189602. text_ptr->lang = NULL;
  189603. text_ptr->lang_key = NULL;
  189604. #endif
  189605. text_ptr->text = text;
  189606. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189607. png_free(png_ptr, key);
  189608. png_free(png_ptr, text_ptr);
  189609. if (ret)
  189610. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189611. }
  189612. }
  189613. #endif
  189614. #if defined(PNG_READ_iTXt_SUPPORTED)
  189615. void /* PRIVATE */
  189616. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189617. length)
  189618. {
  189619. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189620. {
  189621. png_error(png_ptr, "Out of place iTXt");
  189622. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189623. }
  189624. #ifdef PNG_MAX_MALLOC_64K
  189625. png_ptr->skip_length = 0; /* This may not be necessary */
  189626. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189627. {
  189628. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189629. png_ptr->skip_length = length - (png_uint_32)65535L;
  189630. length = (png_uint_32)65535L;
  189631. }
  189632. #endif
  189633. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189634. (png_uint_32)(length+1));
  189635. png_ptr->current_text[length] = '\0';
  189636. png_ptr->current_text_ptr = png_ptr->current_text;
  189637. png_ptr->current_text_size = (png_size_t)length;
  189638. png_ptr->current_text_left = (png_size_t)length;
  189639. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189640. }
  189641. void /* PRIVATE */
  189642. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189643. {
  189644. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189645. {
  189646. png_size_t text_size;
  189647. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189648. text_size = png_ptr->buffer_size;
  189649. else
  189650. text_size = png_ptr->current_text_left;
  189651. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189652. png_ptr->current_text_left -= text_size;
  189653. png_ptr->current_text_ptr += text_size;
  189654. }
  189655. if (!(png_ptr->current_text_left))
  189656. {
  189657. png_textp text_ptr;
  189658. png_charp key;
  189659. int comp_flag;
  189660. png_charp lang;
  189661. png_charp lang_key;
  189662. png_charp text;
  189663. int ret;
  189664. if (png_ptr->buffer_size < 4)
  189665. {
  189666. png_push_save_buffer(png_ptr);
  189667. return;
  189668. }
  189669. png_push_crc_finish(png_ptr);
  189670. #if defined(PNG_MAX_MALLOC_64K)
  189671. if (png_ptr->skip_length)
  189672. return;
  189673. #endif
  189674. key = png_ptr->current_text;
  189675. for (lang = key; *lang; lang++)
  189676. /* empty loop */ ;
  189677. if (lang < key + png_ptr->current_text_size - 3)
  189678. lang++;
  189679. comp_flag = *lang++;
  189680. lang++; /* skip comp_type, always zero */
  189681. for (lang_key = lang; *lang_key; lang_key++)
  189682. /* empty loop */ ;
  189683. lang_key++; /* skip NUL separator */
  189684. text=lang_key;
  189685. if (lang_key < key + png_ptr->current_text_size - 1)
  189686. {
  189687. for (; *text; text++)
  189688. /* empty loop */ ;
  189689. }
  189690. if (text < key + png_ptr->current_text_size)
  189691. text++;
  189692. text_ptr = (png_textp)png_malloc(png_ptr,
  189693. (png_uint_32)png_sizeof(png_text));
  189694. text_ptr->compression = comp_flag + 2;
  189695. text_ptr->key = key;
  189696. text_ptr->lang = lang;
  189697. text_ptr->lang_key = lang_key;
  189698. text_ptr->text = text;
  189699. text_ptr->text_length = 0;
  189700. text_ptr->itxt_length = png_strlen(text);
  189701. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189702. png_ptr->current_text = NULL;
  189703. png_free(png_ptr, text_ptr);
  189704. if (ret)
  189705. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189706. }
  189707. }
  189708. #endif
  189709. /* This function is called when we haven't found a handler for this
  189710. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189711. * name or a critical chunk), the chunk is (currently) silently ignored.
  189712. */
  189713. void /* PRIVATE */
  189714. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189715. length)
  189716. {
  189717. png_uint_32 skip=0;
  189718. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189719. if (!(png_ptr->chunk_name[0] & 0x20))
  189720. {
  189721. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189722. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189723. PNG_HANDLE_CHUNK_ALWAYS
  189724. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189725. && png_ptr->read_user_chunk_fn == NULL
  189726. #endif
  189727. )
  189728. #endif
  189729. png_chunk_error(png_ptr, "unknown critical chunk");
  189730. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189731. }
  189732. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189733. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189734. {
  189735. #ifdef PNG_MAX_MALLOC_64K
  189736. if (length > (png_uint_32)65535L)
  189737. {
  189738. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189739. skip = length - (png_uint_32)65535L;
  189740. length = (png_uint_32)65535L;
  189741. }
  189742. #endif
  189743. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189744. (png_charp)png_ptr->chunk_name, 5);
  189745. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189746. png_ptr->unknown_chunk.size = (png_size_t)length;
  189747. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189748. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189749. if(png_ptr->read_user_chunk_fn != NULL)
  189750. {
  189751. /* callback to user unknown chunk handler */
  189752. int ret;
  189753. ret = (*(png_ptr->read_user_chunk_fn))
  189754. (png_ptr, &png_ptr->unknown_chunk);
  189755. if (ret < 0)
  189756. png_chunk_error(png_ptr, "error in user chunk");
  189757. if (ret == 0)
  189758. {
  189759. if (!(png_ptr->chunk_name[0] & 0x20))
  189760. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189761. PNG_HANDLE_CHUNK_ALWAYS)
  189762. png_chunk_error(png_ptr, "unknown critical chunk");
  189763. png_set_unknown_chunks(png_ptr, info_ptr,
  189764. &png_ptr->unknown_chunk, 1);
  189765. }
  189766. }
  189767. #else
  189768. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189769. #endif
  189770. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189771. png_ptr->unknown_chunk.data = NULL;
  189772. }
  189773. else
  189774. #endif
  189775. skip=length;
  189776. png_push_crc_skip(png_ptr, skip);
  189777. }
  189778. void /* PRIVATE */
  189779. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189780. {
  189781. if (png_ptr->info_fn != NULL)
  189782. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189783. }
  189784. void /* PRIVATE */
  189785. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189786. {
  189787. if (png_ptr->end_fn != NULL)
  189788. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189789. }
  189790. void /* PRIVATE */
  189791. png_push_have_row(png_structp png_ptr, png_bytep row)
  189792. {
  189793. if (png_ptr->row_fn != NULL)
  189794. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189795. (int)png_ptr->pass);
  189796. }
  189797. void PNGAPI
  189798. png_progressive_combine_row (png_structp png_ptr,
  189799. png_bytep old_row, png_bytep new_row)
  189800. {
  189801. #ifdef PNG_USE_LOCAL_ARRAYS
  189802. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189803. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189804. #endif
  189805. if(png_ptr == NULL) return;
  189806. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189807. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189808. }
  189809. void PNGAPI
  189810. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189811. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189812. png_progressive_end_ptr end_fn)
  189813. {
  189814. if(png_ptr == NULL) return;
  189815. png_ptr->info_fn = info_fn;
  189816. png_ptr->row_fn = row_fn;
  189817. png_ptr->end_fn = end_fn;
  189818. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189819. }
  189820. png_voidp PNGAPI
  189821. png_get_progressive_ptr(png_structp png_ptr)
  189822. {
  189823. if(png_ptr == NULL) return (NULL);
  189824. return png_ptr->io_ptr;
  189825. }
  189826. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189827. /*** End of inlined file: pngpread.c ***/
  189828. /*** Start of inlined file: pngrio.c ***/
  189829. /* pngrio.c - functions for data input
  189830. *
  189831. * Last changed in libpng 1.2.13 November 13, 2006
  189832. * For conditions of distribution and use, see copyright notice in png.h
  189833. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189834. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189835. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189836. *
  189837. * This file provides a location for all input. Users who need
  189838. * special handling are expected to write a function that has the same
  189839. * arguments as this and performs a similar function, but that possibly
  189840. * has a different input method. Note that you shouldn't change this
  189841. * function, but rather write a replacement function and then make
  189842. * libpng use it at run time with png_set_read_fn(...).
  189843. */
  189844. #define PNG_INTERNAL
  189845. #if defined(PNG_READ_SUPPORTED)
  189846. /* Read the data from whatever input you are using. The default routine
  189847. reads from a file pointer. Note that this routine sometimes gets called
  189848. with very small lengths, so you should implement some kind of simple
  189849. buffering if you are using unbuffered reads. This should never be asked
  189850. to read more then 64K on a 16 bit machine. */
  189851. void /* PRIVATE */
  189852. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189853. {
  189854. png_debug1(4,"reading %d bytes\n", (int)length);
  189855. if (png_ptr->read_data_fn != NULL)
  189856. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189857. else
  189858. png_error(png_ptr, "Call to NULL read function");
  189859. }
  189860. #if !defined(PNG_NO_STDIO)
  189861. /* This is the function that does the actual reading of data. If you are
  189862. not reading from a standard C stream, you should create a replacement
  189863. read_data function and use it at run time with png_set_read_fn(), rather
  189864. than changing the library. */
  189865. #ifndef USE_FAR_KEYWORD
  189866. void PNGAPI
  189867. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189868. {
  189869. png_size_t check;
  189870. if(png_ptr == NULL) return;
  189871. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189872. * instead of an int, which is what fread() actually returns.
  189873. */
  189874. #if defined(_WIN32_WCE)
  189875. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189876. check = 0;
  189877. #else
  189878. check = (png_size_t)fread(data, (png_size_t)1, length,
  189879. (png_FILE_p)png_ptr->io_ptr);
  189880. #endif
  189881. if (check != length)
  189882. png_error(png_ptr, "Read Error");
  189883. }
  189884. #else
  189885. /* this is the model-independent version. Since the standard I/O library
  189886. can't handle far buffers in the medium and small models, we have to copy
  189887. the data.
  189888. */
  189889. #define NEAR_BUF_SIZE 1024
  189890. #define MIN(a,b) (a <= b ? a : b)
  189891. static void PNGAPI
  189892. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189893. {
  189894. int check;
  189895. png_byte *n_data;
  189896. png_FILE_p io_ptr;
  189897. if(png_ptr == NULL) return;
  189898. /* Check if data really is near. If so, use usual code. */
  189899. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189900. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189901. if ((png_bytep)n_data == data)
  189902. {
  189903. #if defined(_WIN32_WCE)
  189904. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189905. check = 0;
  189906. #else
  189907. check = fread(n_data, 1, length, io_ptr);
  189908. #endif
  189909. }
  189910. else
  189911. {
  189912. png_byte buf[NEAR_BUF_SIZE];
  189913. png_size_t read, remaining, err;
  189914. check = 0;
  189915. remaining = length;
  189916. do
  189917. {
  189918. read = MIN(NEAR_BUF_SIZE, remaining);
  189919. #if defined(_WIN32_WCE)
  189920. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189921. err = 0;
  189922. #else
  189923. err = fread(buf, (png_size_t)1, read, io_ptr);
  189924. #endif
  189925. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189926. if(err != read)
  189927. break;
  189928. else
  189929. check += err;
  189930. data += read;
  189931. remaining -= read;
  189932. }
  189933. while (remaining != 0);
  189934. }
  189935. if ((png_uint_32)check != (png_uint_32)length)
  189936. png_error(png_ptr, "read Error");
  189937. }
  189938. #endif
  189939. #endif
  189940. /* This function allows the application to supply a new input function
  189941. for libpng if standard C streams aren't being used.
  189942. This function takes as its arguments:
  189943. png_ptr - pointer to a png input data structure
  189944. io_ptr - pointer to user supplied structure containing info about
  189945. the input functions. May be NULL.
  189946. read_data_fn - pointer to a new input function that takes as its
  189947. arguments a pointer to a png_struct, a pointer to
  189948. a location where input data can be stored, and a 32-bit
  189949. unsigned int that is the number of bytes to be read.
  189950. To exit and output any fatal error messages the new write
  189951. function should call png_error(png_ptr, "Error msg"). */
  189952. void PNGAPI
  189953. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189954. png_rw_ptr read_data_fn)
  189955. {
  189956. if(png_ptr == NULL) return;
  189957. png_ptr->io_ptr = io_ptr;
  189958. #if !defined(PNG_NO_STDIO)
  189959. if (read_data_fn != NULL)
  189960. png_ptr->read_data_fn = read_data_fn;
  189961. else
  189962. png_ptr->read_data_fn = png_default_read_data;
  189963. #else
  189964. png_ptr->read_data_fn = read_data_fn;
  189965. #endif
  189966. /* It is an error to write to a read device */
  189967. if (png_ptr->write_data_fn != NULL)
  189968. {
  189969. png_ptr->write_data_fn = NULL;
  189970. png_warning(png_ptr,
  189971. "It's an error to set both read_data_fn and write_data_fn in the ");
  189972. png_warning(png_ptr,
  189973. "same structure. Resetting write_data_fn to NULL.");
  189974. }
  189975. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189976. png_ptr->output_flush_fn = NULL;
  189977. #endif
  189978. }
  189979. #endif /* PNG_READ_SUPPORTED */
  189980. /*** End of inlined file: pngrio.c ***/
  189981. /*** Start of inlined file: pngrtran.c ***/
  189982. /* pngrtran.c - transforms the data in a row for PNG readers
  189983. *
  189984. * Last changed in libpng 1.2.21 [October 4, 2007]
  189985. * For conditions of distribution and use, see copyright notice in png.h
  189986. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189987. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189988. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189989. *
  189990. * This file contains functions optionally called by an application
  189991. * in order to tell libpng how to handle data when reading a PNG.
  189992. * Transformations that are used in both reading and writing are
  189993. * in pngtrans.c.
  189994. */
  189995. #define PNG_INTERNAL
  189996. #if defined(PNG_READ_SUPPORTED)
  189997. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189998. void PNGAPI
  189999. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  190000. {
  190001. png_debug(1, "in png_set_crc_action\n");
  190002. /* Tell libpng how we react to CRC errors in critical chunks */
  190003. if(png_ptr == NULL) return;
  190004. switch (crit_action)
  190005. {
  190006. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190007. break;
  190008. case PNG_CRC_WARN_USE: /* warn/use data */
  190009. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190010. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  190011. break;
  190012. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190013. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190014. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  190015. PNG_FLAG_CRC_CRITICAL_IGNORE;
  190016. break;
  190017. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  190018. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  190019. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190020. case PNG_CRC_DEFAULT:
  190021. default:
  190022. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190023. break;
  190024. }
  190025. switch (ancil_action)
  190026. {
  190027. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190028. break;
  190029. case PNG_CRC_WARN_USE: /* warn/use data */
  190030. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190031. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  190032. break;
  190033. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190034. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190035. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  190036. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190037. break;
  190038. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190039. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190040. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190041. break;
  190042. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190043. case PNG_CRC_DEFAULT:
  190044. default:
  190045. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190046. break;
  190047. }
  190048. }
  190049. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  190050. defined(PNG_FLOATING_POINT_SUPPORTED)
  190051. /* handle alpha and tRNS via a background color */
  190052. void PNGAPI
  190053. png_set_background(png_structp png_ptr,
  190054. png_color_16p background_color, int background_gamma_code,
  190055. int need_expand, double background_gamma)
  190056. {
  190057. png_debug(1, "in png_set_background\n");
  190058. if(png_ptr == NULL) return;
  190059. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  190060. {
  190061. png_warning(png_ptr, "Application must supply a known background gamma");
  190062. return;
  190063. }
  190064. png_ptr->transformations |= PNG_BACKGROUND;
  190065. png_memcpy(&(png_ptr->background), background_color,
  190066. png_sizeof(png_color_16));
  190067. png_ptr->background_gamma = (float)background_gamma;
  190068. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190069. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190070. }
  190071. #endif
  190072. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190073. /* strip 16 bit depth files to 8 bit depth */
  190074. void PNGAPI
  190075. png_set_strip_16(png_structp png_ptr)
  190076. {
  190077. png_debug(1, "in png_set_strip_16\n");
  190078. if(png_ptr == NULL) return;
  190079. png_ptr->transformations |= PNG_16_TO_8;
  190080. }
  190081. #endif
  190082. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190083. void PNGAPI
  190084. png_set_strip_alpha(png_structp png_ptr)
  190085. {
  190086. png_debug(1, "in png_set_strip_alpha\n");
  190087. if(png_ptr == NULL) return;
  190088. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190089. }
  190090. #endif
  190091. #if defined(PNG_READ_DITHER_SUPPORTED)
  190092. /* Dither file to 8 bit. Supply a palette, the current number
  190093. * of elements in the palette, the maximum number of elements
  190094. * allowed, and a histogram if possible. If the current number
  190095. * of colors is greater then the maximum number, the palette will be
  190096. * modified to fit in the maximum number. "full_dither" indicates
  190097. * whether we need a dithering cube set up for RGB images, or if we
  190098. * simply are reducing the number of colors in a paletted image.
  190099. */
  190100. typedef struct png_dsort_struct
  190101. {
  190102. struct png_dsort_struct FAR * next;
  190103. png_byte left;
  190104. png_byte right;
  190105. } png_dsort;
  190106. typedef png_dsort FAR * png_dsortp;
  190107. typedef png_dsort FAR * FAR * png_dsortpp;
  190108. void PNGAPI
  190109. png_set_dither(png_structp png_ptr, png_colorp palette,
  190110. int num_palette, int maximum_colors, png_uint_16p histogram,
  190111. int full_dither)
  190112. {
  190113. png_debug(1, "in png_set_dither\n");
  190114. if(png_ptr == NULL) return;
  190115. png_ptr->transformations |= PNG_DITHER;
  190116. if (!full_dither)
  190117. {
  190118. int i;
  190119. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190120. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190121. for (i = 0; i < num_palette; i++)
  190122. png_ptr->dither_index[i] = (png_byte)i;
  190123. }
  190124. if (num_palette > maximum_colors)
  190125. {
  190126. if (histogram != NULL)
  190127. {
  190128. /* This is easy enough, just throw out the least used colors.
  190129. Perhaps not the best solution, but good enough. */
  190130. int i;
  190131. /* initialize an array to sort colors */
  190132. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190133. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190134. /* initialize the dither_sort array */
  190135. for (i = 0; i < num_palette; i++)
  190136. png_ptr->dither_sort[i] = (png_byte)i;
  190137. /* Find the least used palette entries by starting a
  190138. bubble sort, and running it until we have sorted
  190139. out enough colors. Note that we don't care about
  190140. sorting all the colors, just finding which are
  190141. least used. */
  190142. for (i = num_palette - 1; i >= maximum_colors; i--)
  190143. {
  190144. int done; /* to stop early if the list is pre-sorted */
  190145. int j;
  190146. done = 1;
  190147. for (j = 0; j < i; j++)
  190148. {
  190149. if (histogram[png_ptr->dither_sort[j]]
  190150. < histogram[png_ptr->dither_sort[j + 1]])
  190151. {
  190152. png_byte t;
  190153. t = png_ptr->dither_sort[j];
  190154. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190155. png_ptr->dither_sort[j + 1] = t;
  190156. done = 0;
  190157. }
  190158. }
  190159. if (done)
  190160. break;
  190161. }
  190162. /* swap the palette around, and set up a table, if necessary */
  190163. if (full_dither)
  190164. {
  190165. int j = num_palette;
  190166. /* put all the useful colors within the max, but don't
  190167. move the others */
  190168. for (i = 0; i < maximum_colors; i++)
  190169. {
  190170. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190171. {
  190172. do
  190173. j--;
  190174. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190175. palette[i] = palette[j];
  190176. }
  190177. }
  190178. }
  190179. else
  190180. {
  190181. int j = num_palette;
  190182. /* move all the used colors inside the max limit, and
  190183. develop a translation table */
  190184. for (i = 0; i < maximum_colors; i++)
  190185. {
  190186. /* only move the colors we need to */
  190187. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190188. {
  190189. png_color tmp_color;
  190190. do
  190191. j--;
  190192. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190193. tmp_color = palette[j];
  190194. palette[j] = palette[i];
  190195. palette[i] = tmp_color;
  190196. /* indicate where the color went */
  190197. png_ptr->dither_index[j] = (png_byte)i;
  190198. png_ptr->dither_index[i] = (png_byte)j;
  190199. }
  190200. }
  190201. /* find closest color for those colors we are not using */
  190202. for (i = 0; i < num_palette; i++)
  190203. {
  190204. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190205. {
  190206. int min_d, k, min_k, d_index;
  190207. /* find the closest color to one we threw out */
  190208. d_index = png_ptr->dither_index[i];
  190209. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190210. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190211. {
  190212. int d;
  190213. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190214. if (d < min_d)
  190215. {
  190216. min_d = d;
  190217. min_k = k;
  190218. }
  190219. }
  190220. /* point to closest color */
  190221. png_ptr->dither_index[i] = (png_byte)min_k;
  190222. }
  190223. }
  190224. }
  190225. png_free(png_ptr, png_ptr->dither_sort);
  190226. png_ptr->dither_sort=NULL;
  190227. }
  190228. else
  190229. {
  190230. /* This is much harder to do simply (and quickly). Perhaps
  190231. we need to go through a median cut routine, but those
  190232. don't always behave themselves with only a few colors
  190233. as input. So we will just find the closest two colors,
  190234. and throw out one of them (chosen somewhat randomly).
  190235. [We don't understand this at all, so if someone wants to
  190236. work on improving it, be our guest - AED, GRP]
  190237. */
  190238. int i;
  190239. int max_d;
  190240. int num_new_palette;
  190241. png_dsortp t;
  190242. png_dsortpp hash;
  190243. t=NULL;
  190244. /* initialize palette index arrays */
  190245. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190246. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190247. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190248. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190249. /* initialize the sort array */
  190250. for (i = 0; i < num_palette; i++)
  190251. {
  190252. png_ptr->index_to_palette[i] = (png_byte)i;
  190253. png_ptr->palette_to_index[i] = (png_byte)i;
  190254. }
  190255. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190256. png_sizeof (png_dsortp)));
  190257. for (i = 0; i < 769; i++)
  190258. hash[i] = NULL;
  190259. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190260. num_new_palette = num_palette;
  190261. /* initial wild guess at how far apart the farthest pixel
  190262. pair we will be eliminating will be. Larger
  190263. numbers mean more areas will be allocated, Smaller
  190264. numbers run the risk of not saving enough data, and
  190265. having to do this all over again.
  190266. I have not done extensive checking on this number.
  190267. */
  190268. max_d = 96;
  190269. while (num_new_palette > maximum_colors)
  190270. {
  190271. for (i = 0; i < num_new_palette - 1; i++)
  190272. {
  190273. int j;
  190274. for (j = i + 1; j < num_new_palette; j++)
  190275. {
  190276. int d;
  190277. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190278. if (d <= max_d)
  190279. {
  190280. t = (png_dsortp)png_malloc_warn(png_ptr,
  190281. (png_uint_32)(png_sizeof(png_dsort)));
  190282. if (t == NULL)
  190283. break;
  190284. t->next = hash[d];
  190285. t->left = (png_byte)i;
  190286. t->right = (png_byte)j;
  190287. hash[d] = t;
  190288. }
  190289. }
  190290. if (t == NULL)
  190291. break;
  190292. }
  190293. if (t != NULL)
  190294. for (i = 0; i <= max_d; i++)
  190295. {
  190296. if (hash[i] != NULL)
  190297. {
  190298. png_dsortp p;
  190299. for (p = hash[i]; p; p = p->next)
  190300. {
  190301. if ((int)png_ptr->index_to_palette[p->left]
  190302. < num_new_palette &&
  190303. (int)png_ptr->index_to_palette[p->right]
  190304. < num_new_palette)
  190305. {
  190306. int j, next_j;
  190307. if (num_new_palette & 0x01)
  190308. {
  190309. j = p->left;
  190310. next_j = p->right;
  190311. }
  190312. else
  190313. {
  190314. j = p->right;
  190315. next_j = p->left;
  190316. }
  190317. num_new_palette--;
  190318. palette[png_ptr->index_to_palette[j]]
  190319. = palette[num_new_palette];
  190320. if (!full_dither)
  190321. {
  190322. int k;
  190323. for (k = 0; k < num_palette; k++)
  190324. {
  190325. if (png_ptr->dither_index[k] ==
  190326. png_ptr->index_to_palette[j])
  190327. png_ptr->dither_index[k] =
  190328. png_ptr->index_to_palette[next_j];
  190329. if ((int)png_ptr->dither_index[k] ==
  190330. num_new_palette)
  190331. png_ptr->dither_index[k] =
  190332. png_ptr->index_to_palette[j];
  190333. }
  190334. }
  190335. png_ptr->index_to_palette[png_ptr->palette_to_index
  190336. [num_new_palette]] = png_ptr->index_to_palette[j];
  190337. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190338. = png_ptr->palette_to_index[num_new_palette];
  190339. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190340. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190341. }
  190342. if (num_new_palette <= maximum_colors)
  190343. break;
  190344. }
  190345. if (num_new_palette <= maximum_colors)
  190346. break;
  190347. }
  190348. }
  190349. for (i = 0; i < 769; i++)
  190350. {
  190351. if (hash[i] != NULL)
  190352. {
  190353. png_dsortp p = hash[i];
  190354. while (p)
  190355. {
  190356. t = p->next;
  190357. png_free(png_ptr, p);
  190358. p = t;
  190359. }
  190360. }
  190361. hash[i] = 0;
  190362. }
  190363. max_d += 96;
  190364. }
  190365. png_free(png_ptr, hash);
  190366. png_free(png_ptr, png_ptr->palette_to_index);
  190367. png_free(png_ptr, png_ptr->index_to_palette);
  190368. png_ptr->palette_to_index=NULL;
  190369. png_ptr->index_to_palette=NULL;
  190370. }
  190371. num_palette = maximum_colors;
  190372. }
  190373. if (png_ptr->palette == NULL)
  190374. {
  190375. png_ptr->palette = palette;
  190376. }
  190377. png_ptr->num_palette = (png_uint_16)num_palette;
  190378. if (full_dither)
  190379. {
  190380. int i;
  190381. png_bytep distance;
  190382. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190383. PNG_DITHER_BLUE_BITS;
  190384. int num_red = (1 << PNG_DITHER_RED_BITS);
  190385. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190386. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190387. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190388. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190389. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190390. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190391. png_sizeof (png_byte));
  190392. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190393. png_sizeof(png_byte)));
  190394. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190395. for (i = 0; i < num_palette; i++)
  190396. {
  190397. int ir, ig, ib;
  190398. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190399. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190400. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190401. for (ir = 0; ir < num_red; ir++)
  190402. {
  190403. /* int dr = abs(ir - r); */
  190404. int dr = ((ir > r) ? ir - r : r - ir);
  190405. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190406. for (ig = 0; ig < num_green; ig++)
  190407. {
  190408. /* int dg = abs(ig - g); */
  190409. int dg = ((ig > g) ? ig - g : g - ig);
  190410. int dt = dr + dg;
  190411. int dm = ((dr > dg) ? dr : dg);
  190412. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190413. for (ib = 0; ib < num_blue; ib++)
  190414. {
  190415. int d_index = index_g | ib;
  190416. /* int db = abs(ib - b); */
  190417. int db = ((ib > b) ? ib - b : b - ib);
  190418. int dmax = ((dm > db) ? dm : db);
  190419. int d = dmax + dt + db;
  190420. if (d < (int)distance[d_index])
  190421. {
  190422. distance[d_index] = (png_byte)d;
  190423. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190424. }
  190425. }
  190426. }
  190427. }
  190428. }
  190429. png_free(png_ptr, distance);
  190430. }
  190431. }
  190432. #endif
  190433. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190434. /* Transform the image from the file_gamma to the screen_gamma. We
  190435. * only do transformations on images where the file_gamma and screen_gamma
  190436. * are not close reciprocals, otherwise it slows things down slightly, and
  190437. * also needlessly introduces small errors.
  190438. *
  190439. * We will turn off gamma transformation later if no semitransparent entries
  190440. * are present in the tRNS array for palette images. We can't do it here
  190441. * because we don't necessarily have the tRNS chunk yet.
  190442. */
  190443. void PNGAPI
  190444. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190445. {
  190446. png_debug(1, "in png_set_gamma\n");
  190447. if(png_ptr == NULL) return;
  190448. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190449. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190450. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190451. png_ptr->transformations |= PNG_GAMMA;
  190452. png_ptr->gamma = (float)file_gamma;
  190453. png_ptr->screen_gamma = (float)scrn_gamma;
  190454. }
  190455. #endif
  190456. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190457. /* Expand paletted images to RGB, expand grayscale images of
  190458. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190459. * to alpha channels.
  190460. */
  190461. void PNGAPI
  190462. png_set_expand(png_structp png_ptr)
  190463. {
  190464. png_debug(1, "in png_set_expand\n");
  190465. if(png_ptr == NULL) return;
  190466. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190467. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190468. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190469. #endif
  190470. }
  190471. /* GRR 19990627: the following three functions currently are identical
  190472. * to png_set_expand(). However, it is entirely reasonable that someone
  190473. * might wish to expand an indexed image to RGB but *not* expand a single,
  190474. * fully transparent palette entry to a full alpha channel--perhaps instead
  190475. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190476. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190477. * IOW, a future version of the library may make the transformations flag
  190478. * a bit more fine-grained, with separate bits for each of these three
  190479. * functions.
  190480. *
  190481. * More to the point, these functions make it obvious what libpng will be
  190482. * doing, whereas "expand" can (and does) mean any number of things.
  190483. *
  190484. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190485. * to expand only the sample depth but not to expand the tRNS to alpha.
  190486. */
  190487. /* Expand paletted images to RGB. */
  190488. void PNGAPI
  190489. png_set_palette_to_rgb(png_structp png_ptr)
  190490. {
  190491. png_debug(1, "in png_set_palette_to_rgb\n");
  190492. if(png_ptr == NULL) return;
  190493. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190494. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190495. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190496. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190497. #endif
  190498. }
  190499. #if !defined(PNG_1_0_X)
  190500. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190501. void PNGAPI
  190502. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190503. {
  190504. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190505. if(png_ptr == NULL) return;
  190506. png_ptr->transformations |= PNG_EXPAND;
  190507. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190508. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190509. #endif
  190510. }
  190511. #endif
  190512. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190513. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190514. /* Deprecated as of libpng-1.2.9 */
  190515. void PNGAPI
  190516. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190517. {
  190518. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190519. if(png_ptr == NULL) return;
  190520. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190521. }
  190522. #endif
  190523. /* Expand tRNS chunks to alpha channels. */
  190524. void PNGAPI
  190525. png_set_tRNS_to_alpha(png_structp png_ptr)
  190526. {
  190527. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190528. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190529. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190530. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190531. #endif
  190532. }
  190533. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190534. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190535. void PNGAPI
  190536. png_set_gray_to_rgb(png_structp png_ptr)
  190537. {
  190538. png_debug(1, "in png_set_gray_to_rgb\n");
  190539. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190540. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190541. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190542. #endif
  190543. }
  190544. #endif
  190545. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190546. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190547. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190548. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190549. */
  190550. void PNGAPI
  190551. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190552. double green)
  190553. {
  190554. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190555. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190556. if(png_ptr == NULL) return;
  190557. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190558. }
  190559. #endif
  190560. void PNGAPI
  190561. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190562. png_fixed_point red, png_fixed_point green)
  190563. {
  190564. png_debug(1, "in png_set_rgb_to_gray\n");
  190565. if(png_ptr == NULL) return;
  190566. switch(error_action)
  190567. {
  190568. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190569. break;
  190570. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190571. break;
  190572. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190573. }
  190574. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190575. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190576. png_ptr->transformations |= PNG_EXPAND;
  190577. #else
  190578. {
  190579. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190580. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190581. }
  190582. #endif
  190583. {
  190584. png_uint_16 red_int, green_int;
  190585. if(red < 0 || green < 0)
  190586. {
  190587. red_int = 6968; /* .212671 * 32768 + .5 */
  190588. green_int = 23434; /* .715160 * 32768 + .5 */
  190589. }
  190590. else if(red + green < 100000L)
  190591. {
  190592. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190593. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190594. }
  190595. else
  190596. {
  190597. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190598. red_int = 6968;
  190599. green_int = 23434;
  190600. }
  190601. png_ptr->rgb_to_gray_red_coeff = red_int;
  190602. png_ptr->rgb_to_gray_green_coeff = green_int;
  190603. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190604. }
  190605. }
  190606. #endif
  190607. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190608. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190609. defined(PNG_LEGACY_SUPPORTED)
  190610. void PNGAPI
  190611. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190612. read_user_transform_fn)
  190613. {
  190614. png_debug(1, "in png_set_read_user_transform_fn\n");
  190615. if(png_ptr == NULL) return;
  190616. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190617. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190618. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190619. #endif
  190620. #ifdef PNG_LEGACY_SUPPORTED
  190621. if(read_user_transform_fn)
  190622. png_warning(png_ptr,
  190623. "This version of libpng does not support user transforms");
  190624. #endif
  190625. }
  190626. #endif
  190627. /* Initialize everything needed for the read. This includes modifying
  190628. * the palette.
  190629. */
  190630. void /* PRIVATE */
  190631. png_init_read_transformations(png_structp png_ptr)
  190632. {
  190633. png_debug(1, "in png_init_read_transformations\n");
  190634. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190635. if(png_ptr != NULL)
  190636. #endif
  190637. {
  190638. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190639. || defined(PNG_READ_GAMMA_SUPPORTED)
  190640. int color_type = png_ptr->color_type;
  190641. #endif
  190642. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190643. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190644. /* Detect gray background and attempt to enable optimization
  190645. * for gray --> RGB case */
  190646. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190647. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190648. * background color might actually be gray yet not be flagged as such.
  190649. * This is not a problem for the current code, which uses
  190650. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190651. * png_do_gray_to_rgb() transformation.
  190652. */
  190653. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190654. !(color_type & PNG_COLOR_MASK_COLOR))
  190655. {
  190656. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190657. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190658. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190659. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190660. png_ptr->background.red == png_ptr->background.green &&
  190661. png_ptr->background.red == png_ptr->background.blue)
  190662. {
  190663. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190664. png_ptr->background.gray = png_ptr->background.red;
  190665. }
  190666. #endif
  190667. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190668. (png_ptr->transformations & PNG_EXPAND))
  190669. {
  190670. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190671. {
  190672. /* expand background and tRNS chunks */
  190673. switch (png_ptr->bit_depth)
  190674. {
  190675. case 1:
  190676. png_ptr->background.gray *= (png_uint_16)0xff;
  190677. png_ptr->background.red = png_ptr->background.green
  190678. = png_ptr->background.blue = png_ptr->background.gray;
  190679. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190680. {
  190681. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190682. png_ptr->trans_values.red = png_ptr->trans_values.green
  190683. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190684. }
  190685. break;
  190686. case 2:
  190687. png_ptr->background.gray *= (png_uint_16)0x55;
  190688. png_ptr->background.red = png_ptr->background.green
  190689. = png_ptr->background.blue = png_ptr->background.gray;
  190690. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190691. {
  190692. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190693. png_ptr->trans_values.red = png_ptr->trans_values.green
  190694. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190695. }
  190696. break;
  190697. case 4:
  190698. png_ptr->background.gray *= (png_uint_16)0x11;
  190699. png_ptr->background.red = png_ptr->background.green
  190700. = png_ptr->background.blue = png_ptr->background.gray;
  190701. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190702. {
  190703. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190704. png_ptr->trans_values.red = png_ptr->trans_values.green
  190705. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190706. }
  190707. break;
  190708. case 8:
  190709. case 16:
  190710. png_ptr->background.red = png_ptr->background.green
  190711. = png_ptr->background.blue = png_ptr->background.gray;
  190712. break;
  190713. }
  190714. }
  190715. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190716. {
  190717. png_ptr->background.red =
  190718. png_ptr->palette[png_ptr->background.index].red;
  190719. png_ptr->background.green =
  190720. png_ptr->palette[png_ptr->background.index].green;
  190721. png_ptr->background.blue =
  190722. png_ptr->palette[png_ptr->background.index].blue;
  190723. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190724. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190725. {
  190726. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190727. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190728. #endif
  190729. {
  190730. /* invert the alpha channel (in tRNS) unless the pixels are
  190731. going to be expanded, in which case leave it for later */
  190732. int i,istop;
  190733. istop=(int)png_ptr->num_trans;
  190734. for (i=0; i<istop; i++)
  190735. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190736. }
  190737. }
  190738. #endif
  190739. }
  190740. }
  190741. #endif
  190742. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190743. png_ptr->background_1 = png_ptr->background;
  190744. #endif
  190745. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190746. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190747. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190748. < PNG_GAMMA_THRESHOLD))
  190749. {
  190750. int i,k;
  190751. k=0;
  190752. for (i=0; i<png_ptr->num_trans; i++)
  190753. {
  190754. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190755. k=1; /* partial transparency is present */
  190756. }
  190757. if (k == 0)
  190758. png_ptr->transformations &= (~PNG_GAMMA);
  190759. }
  190760. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190761. png_ptr->gamma != 0.0)
  190762. {
  190763. png_build_gamma_table(png_ptr);
  190764. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190765. if (png_ptr->transformations & PNG_BACKGROUND)
  190766. {
  190767. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190768. {
  190769. /* could skip if no transparency and
  190770. */
  190771. png_color back, back_1;
  190772. png_colorp palette = png_ptr->palette;
  190773. int num_palette = png_ptr->num_palette;
  190774. int i;
  190775. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190776. {
  190777. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190778. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190779. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190780. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190781. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190782. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190783. }
  190784. else
  190785. {
  190786. double g, gs;
  190787. switch (png_ptr->background_gamma_type)
  190788. {
  190789. case PNG_BACKGROUND_GAMMA_SCREEN:
  190790. g = (png_ptr->screen_gamma);
  190791. gs = 1.0;
  190792. break;
  190793. case PNG_BACKGROUND_GAMMA_FILE:
  190794. g = 1.0 / (png_ptr->gamma);
  190795. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190796. break;
  190797. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190798. g = 1.0 / (png_ptr->background_gamma);
  190799. gs = 1.0 / (png_ptr->background_gamma *
  190800. png_ptr->screen_gamma);
  190801. break;
  190802. default:
  190803. g = 1.0; /* back_1 */
  190804. gs = 1.0; /* back */
  190805. }
  190806. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190807. {
  190808. back.red = (png_byte)png_ptr->background.red;
  190809. back.green = (png_byte)png_ptr->background.green;
  190810. back.blue = (png_byte)png_ptr->background.blue;
  190811. }
  190812. else
  190813. {
  190814. back.red = (png_byte)(pow(
  190815. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190816. back.green = (png_byte)(pow(
  190817. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190818. back.blue = (png_byte)(pow(
  190819. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190820. }
  190821. back_1.red = (png_byte)(pow(
  190822. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190823. back_1.green = (png_byte)(pow(
  190824. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190825. back_1.blue = (png_byte)(pow(
  190826. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190827. }
  190828. for (i = 0; i < num_palette; i++)
  190829. {
  190830. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190831. {
  190832. if (png_ptr->trans[i] == 0)
  190833. {
  190834. palette[i] = back;
  190835. }
  190836. else /* if (png_ptr->trans[i] != 0xff) */
  190837. {
  190838. png_byte v, w;
  190839. v = png_ptr->gamma_to_1[palette[i].red];
  190840. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190841. palette[i].red = png_ptr->gamma_from_1[w];
  190842. v = png_ptr->gamma_to_1[palette[i].green];
  190843. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190844. palette[i].green = png_ptr->gamma_from_1[w];
  190845. v = png_ptr->gamma_to_1[palette[i].blue];
  190846. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190847. palette[i].blue = png_ptr->gamma_from_1[w];
  190848. }
  190849. }
  190850. else
  190851. {
  190852. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190853. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190854. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190855. }
  190856. }
  190857. }
  190858. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190859. else
  190860. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190861. {
  190862. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190863. double g = 1.0;
  190864. double gs = 1.0;
  190865. switch (png_ptr->background_gamma_type)
  190866. {
  190867. case PNG_BACKGROUND_GAMMA_SCREEN:
  190868. g = (png_ptr->screen_gamma);
  190869. gs = 1.0;
  190870. break;
  190871. case PNG_BACKGROUND_GAMMA_FILE:
  190872. g = 1.0 / (png_ptr->gamma);
  190873. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190874. break;
  190875. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190876. g = 1.0 / (png_ptr->background_gamma);
  190877. gs = 1.0 / (png_ptr->background_gamma *
  190878. png_ptr->screen_gamma);
  190879. break;
  190880. }
  190881. png_ptr->background_1.gray = (png_uint_16)(pow(
  190882. (double)png_ptr->background.gray / m, g) * m + .5);
  190883. png_ptr->background.gray = (png_uint_16)(pow(
  190884. (double)png_ptr->background.gray / m, gs) * m + .5);
  190885. if ((png_ptr->background.red != png_ptr->background.green) ||
  190886. (png_ptr->background.red != png_ptr->background.blue) ||
  190887. (png_ptr->background.red != png_ptr->background.gray))
  190888. {
  190889. /* RGB or RGBA with color background */
  190890. png_ptr->background_1.red = (png_uint_16)(pow(
  190891. (double)png_ptr->background.red / m, g) * m + .5);
  190892. png_ptr->background_1.green = (png_uint_16)(pow(
  190893. (double)png_ptr->background.green / m, g) * m + .5);
  190894. png_ptr->background_1.blue = (png_uint_16)(pow(
  190895. (double)png_ptr->background.blue / m, g) * m + .5);
  190896. png_ptr->background.red = (png_uint_16)(pow(
  190897. (double)png_ptr->background.red / m, gs) * m + .5);
  190898. png_ptr->background.green = (png_uint_16)(pow(
  190899. (double)png_ptr->background.green / m, gs) * m + .5);
  190900. png_ptr->background.blue = (png_uint_16)(pow(
  190901. (double)png_ptr->background.blue / m, gs) * m + .5);
  190902. }
  190903. else
  190904. {
  190905. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190906. png_ptr->background_1.red = png_ptr->background_1.green
  190907. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190908. png_ptr->background.red = png_ptr->background.green
  190909. = png_ptr->background.blue = png_ptr->background.gray;
  190910. }
  190911. }
  190912. }
  190913. else
  190914. /* transformation does not include PNG_BACKGROUND */
  190915. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190916. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190917. {
  190918. png_colorp palette = png_ptr->palette;
  190919. int num_palette = png_ptr->num_palette;
  190920. int i;
  190921. for (i = 0; i < num_palette; i++)
  190922. {
  190923. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190924. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190925. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190926. }
  190927. }
  190928. }
  190929. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190930. else
  190931. #endif
  190932. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190933. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190934. /* No GAMMA transformation */
  190935. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190936. (color_type == PNG_COLOR_TYPE_PALETTE))
  190937. {
  190938. int i;
  190939. int istop = (int)png_ptr->num_trans;
  190940. png_color back;
  190941. png_colorp palette = png_ptr->palette;
  190942. back.red = (png_byte)png_ptr->background.red;
  190943. back.green = (png_byte)png_ptr->background.green;
  190944. back.blue = (png_byte)png_ptr->background.blue;
  190945. for (i = 0; i < istop; i++)
  190946. {
  190947. if (png_ptr->trans[i] == 0)
  190948. {
  190949. palette[i] = back;
  190950. }
  190951. else if (png_ptr->trans[i] != 0xff)
  190952. {
  190953. /* The png_composite() macro is defined in png.h */
  190954. png_composite(palette[i].red, palette[i].red,
  190955. png_ptr->trans[i], back.red);
  190956. png_composite(palette[i].green, palette[i].green,
  190957. png_ptr->trans[i], back.green);
  190958. png_composite(palette[i].blue, palette[i].blue,
  190959. png_ptr->trans[i], back.blue);
  190960. }
  190961. }
  190962. }
  190963. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190964. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190965. if ((png_ptr->transformations & PNG_SHIFT) &&
  190966. (color_type == PNG_COLOR_TYPE_PALETTE))
  190967. {
  190968. png_uint_16 i;
  190969. png_uint_16 istop = png_ptr->num_palette;
  190970. int sr = 8 - png_ptr->sig_bit.red;
  190971. int sg = 8 - png_ptr->sig_bit.green;
  190972. int sb = 8 - png_ptr->sig_bit.blue;
  190973. if (sr < 0 || sr > 8)
  190974. sr = 0;
  190975. if (sg < 0 || sg > 8)
  190976. sg = 0;
  190977. if (sb < 0 || sb > 8)
  190978. sb = 0;
  190979. for (i = 0; i < istop; i++)
  190980. {
  190981. png_ptr->palette[i].red >>= sr;
  190982. png_ptr->palette[i].green >>= sg;
  190983. png_ptr->palette[i].blue >>= sb;
  190984. }
  190985. }
  190986. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190987. }
  190988. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190989. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190990. if(png_ptr)
  190991. return;
  190992. #endif
  190993. }
  190994. /* Modify the info structure to reflect the transformations. The
  190995. * info should be updated so a PNG file could be written with it,
  190996. * assuming the transformations result in valid PNG data.
  190997. */
  190998. void /* PRIVATE */
  190999. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  191000. {
  191001. png_debug(1, "in png_read_transform_info\n");
  191002. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191003. if (png_ptr->transformations & PNG_EXPAND)
  191004. {
  191005. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191006. {
  191007. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  191008. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  191009. else
  191010. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  191011. info_ptr->bit_depth = 8;
  191012. info_ptr->num_trans = 0;
  191013. }
  191014. else
  191015. {
  191016. if (png_ptr->num_trans)
  191017. {
  191018. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  191019. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191020. else
  191021. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191022. }
  191023. if (info_ptr->bit_depth < 8)
  191024. info_ptr->bit_depth = 8;
  191025. info_ptr->num_trans = 0;
  191026. }
  191027. }
  191028. #endif
  191029. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191030. if (png_ptr->transformations & PNG_BACKGROUND)
  191031. {
  191032. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191033. info_ptr->num_trans = 0;
  191034. info_ptr->background = png_ptr->background;
  191035. }
  191036. #endif
  191037. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191038. if (png_ptr->transformations & PNG_GAMMA)
  191039. {
  191040. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191041. info_ptr->gamma = png_ptr->gamma;
  191042. #endif
  191043. #ifdef PNG_FIXED_POINT_SUPPORTED
  191044. info_ptr->int_gamma = png_ptr->int_gamma;
  191045. #endif
  191046. }
  191047. #endif
  191048. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191049. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  191050. info_ptr->bit_depth = 8;
  191051. #endif
  191052. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191053. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191054. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191055. #endif
  191056. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191057. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191058. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  191059. #endif
  191060. #if defined(PNG_READ_DITHER_SUPPORTED)
  191061. if (png_ptr->transformations & PNG_DITHER)
  191062. {
  191063. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191064. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  191065. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  191066. {
  191067. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191068. }
  191069. }
  191070. #endif
  191071. #if defined(PNG_READ_PACK_SUPPORTED)
  191072. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191073. info_ptr->bit_depth = 8;
  191074. #endif
  191075. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191076. info_ptr->channels = 1;
  191077. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191078. info_ptr->channels = 3;
  191079. else
  191080. info_ptr->channels = 1;
  191081. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191082. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191083. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191084. #endif
  191085. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191086. info_ptr->channels++;
  191087. #if defined(PNG_READ_FILLER_SUPPORTED)
  191088. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191089. if ((png_ptr->transformations & PNG_FILLER) &&
  191090. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191091. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191092. {
  191093. info_ptr->channels++;
  191094. /* if adding a true alpha channel not just filler */
  191095. #if !defined(PNG_1_0_X)
  191096. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191097. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191098. #endif
  191099. }
  191100. #endif
  191101. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191102. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191103. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191104. {
  191105. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191106. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191107. if(info_ptr->channels < png_ptr->user_transform_channels)
  191108. info_ptr->channels = png_ptr->user_transform_channels;
  191109. }
  191110. #endif
  191111. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191112. info_ptr->bit_depth);
  191113. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191114. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191115. if(png_ptr)
  191116. return;
  191117. #endif
  191118. }
  191119. /* Transform the row. The order of transformations is significant,
  191120. * and is very touchy. If you add a transformation, take care to
  191121. * decide how it fits in with the other transformations here.
  191122. */
  191123. void /* PRIVATE */
  191124. png_do_read_transformations(png_structp png_ptr)
  191125. {
  191126. png_debug(1, "in png_do_read_transformations\n");
  191127. if (png_ptr->row_buf == NULL)
  191128. {
  191129. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191130. char msg[50];
  191131. png_snprintf2(msg, 50,
  191132. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191133. png_ptr->pass);
  191134. png_error(png_ptr, msg);
  191135. #else
  191136. png_error(png_ptr, "NULL row buffer");
  191137. #endif
  191138. }
  191139. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191140. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191141. /* Application has failed to call either png_read_start_image()
  191142. * or png_read_update_info() after setting transforms that expand
  191143. * pixels. This check added to libpng-1.2.19 */
  191144. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191145. png_error(png_ptr, "Uninitialized row");
  191146. #else
  191147. png_warning(png_ptr, "Uninitialized row");
  191148. #endif
  191149. #endif
  191150. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191151. if (png_ptr->transformations & PNG_EXPAND)
  191152. {
  191153. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191154. {
  191155. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191156. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191157. }
  191158. else
  191159. {
  191160. if (png_ptr->num_trans &&
  191161. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191162. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191163. &(png_ptr->trans_values));
  191164. else
  191165. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191166. NULL);
  191167. }
  191168. }
  191169. #endif
  191170. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191171. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191172. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191173. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191174. #endif
  191175. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191176. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191177. {
  191178. int rgb_error =
  191179. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191180. if(rgb_error)
  191181. {
  191182. png_ptr->rgb_to_gray_status=1;
  191183. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191184. PNG_RGB_TO_GRAY_WARN)
  191185. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191186. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191187. PNG_RGB_TO_GRAY_ERR)
  191188. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191189. }
  191190. }
  191191. #endif
  191192. /*
  191193. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191194. In most cases, the "simple transparency" should be done prior to doing
  191195. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191196. pixel is transparent. You would also need to make sure that the
  191197. transparency information is upgraded to RGB.
  191198. To summarize, the current flow is:
  191199. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191200. with background "in place" if transparent,
  191201. convert to RGB if necessary
  191202. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191203. convert to RGB if necessary
  191204. To support RGB backgrounds for gray images we need:
  191205. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191206. 3 or 6 bytes and composite with background
  191207. "in place" if transparent (3x compare/pixel
  191208. compared to doing composite with gray bkgrnd)
  191209. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191210. remove alpha bytes (3x float operations/pixel
  191211. compared with composite on gray background)
  191212. Greg's change will do this. The reason it wasn't done before is for
  191213. performance, as this increases the per-pixel operations. If we would check
  191214. in advance if the background was gray or RGB, and position the gray-to-RGB
  191215. transform appropriately, then it would save a lot of work/time.
  191216. */
  191217. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191218. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191219. * for performance reasons */
  191220. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191221. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191222. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191223. #endif
  191224. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191225. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191226. ((png_ptr->num_trans != 0 ) ||
  191227. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191228. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191229. &(png_ptr->trans_values), &(png_ptr->background)
  191230. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191231. , &(png_ptr->background_1),
  191232. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191233. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191234. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191235. png_ptr->gamma_shift
  191236. #endif
  191237. );
  191238. #endif
  191239. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191240. if ((png_ptr->transformations & PNG_GAMMA) &&
  191241. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191242. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191243. ((png_ptr->num_trans != 0) ||
  191244. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191245. #endif
  191246. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191247. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191248. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191249. png_ptr->gamma_shift);
  191250. #endif
  191251. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191252. if (png_ptr->transformations & PNG_16_TO_8)
  191253. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191254. #endif
  191255. #if defined(PNG_READ_DITHER_SUPPORTED)
  191256. if (png_ptr->transformations & PNG_DITHER)
  191257. {
  191258. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191259. png_ptr->palette_lookup, png_ptr->dither_index);
  191260. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191261. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191262. }
  191263. #endif
  191264. #if defined(PNG_READ_INVERT_SUPPORTED)
  191265. if (png_ptr->transformations & PNG_INVERT_MONO)
  191266. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191267. #endif
  191268. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191269. if (png_ptr->transformations & PNG_SHIFT)
  191270. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191271. &(png_ptr->shift));
  191272. #endif
  191273. #if defined(PNG_READ_PACK_SUPPORTED)
  191274. if (png_ptr->transformations & PNG_PACK)
  191275. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191276. #endif
  191277. #if defined(PNG_READ_BGR_SUPPORTED)
  191278. if (png_ptr->transformations & PNG_BGR)
  191279. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191280. #endif
  191281. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191282. if (png_ptr->transformations & PNG_PACKSWAP)
  191283. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191284. #endif
  191285. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191286. /* if gray -> RGB, do so now only if we did not do so above */
  191287. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191288. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191289. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191290. #endif
  191291. #if defined(PNG_READ_FILLER_SUPPORTED)
  191292. if (png_ptr->transformations & PNG_FILLER)
  191293. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191294. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191295. #endif
  191296. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191297. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191298. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191299. #endif
  191300. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191301. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191302. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191303. #endif
  191304. #if defined(PNG_READ_SWAP_SUPPORTED)
  191305. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191306. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191307. #endif
  191308. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191309. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191310. {
  191311. if(png_ptr->read_user_transform_fn != NULL)
  191312. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191313. (png_ptr, /* png_ptr */
  191314. &(png_ptr->row_info), /* row_info: */
  191315. /* png_uint_32 width; width of row */
  191316. /* png_uint_32 rowbytes; number of bytes in row */
  191317. /* png_byte color_type; color type of pixels */
  191318. /* png_byte bit_depth; bit depth of samples */
  191319. /* png_byte channels; number of channels (1-4) */
  191320. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191321. png_ptr->row_buf + 1); /* start of pixel data for row */
  191322. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191323. if(png_ptr->user_transform_depth)
  191324. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191325. if(png_ptr->user_transform_channels)
  191326. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191327. #endif
  191328. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191329. png_ptr->row_info.channels);
  191330. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191331. png_ptr->row_info.width);
  191332. }
  191333. #endif
  191334. }
  191335. #if defined(PNG_READ_PACK_SUPPORTED)
  191336. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191337. * without changing the actual values. Thus, if you had a row with
  191338. * a bit depth of 1, you would end up with bytes that only contained
  191339. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191340. * png_do_shift() after this.
  191341. */
  191342. void /* PRIVATE */
  191343. png_do_unpack(png_row_infop row_info, png_bytep row)
  191344. {
  191345. png_debug(1, "in png_do_unpack\n");
  191346. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191347. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191348. #else
  191349. if (row_info->bit_depth < 8)
  191350. #endif
  191351. {
  191352. png_uint_32 i;
  191353. png_uint_32 row_width=row_info->width;
  191354. switch (row_info->bit_depth)
  191355. {
  191356. case 1:
  191357. {
  191358. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191359. png_bytep dp = row + (png_size_t)row_width - 1;
  191360. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191361. for (i = 0; i < row_width; i++)
  191362. {
  191363. *dp = (png_byte)((*sp >> shift) & 0x01);
  191364. if (shift == 7)
  191365. {
  191366. shift = 0;
  191367. sp--;
  191368. }
  191369. else
  191370. shift++;
  191371. dp--;
  191372. }
  191373. break;
  191374. }
  191375. case 2:
  191376. {
  191377. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191378. png_bytep dp = row + (png_size_t)row_width - 1;
  191379. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191380. for (i = 0; i < row_width; i++)
  191381. {
  191382. *dp = (png_byte)((*sp >> shift) & 0x03);
  191383. if (shift == 6)
  191384. {
  191385. shift = 0;
  191386. sp--;
  191387. }
  191388. else
  191389. shift += 2;
  191390. dp--;
  191391. }
  191392. break;
  191393. }
  191394. case 4:
  191395. {
  191396. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191397. png_bytep dp = row + (png_size_t)row_width - 1;
  191398. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191399. for (i = 0; i < row_width; i++)
  191400. {
  191401. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191402. if (shift == 4)
  191403. {
  191404. shift = 0;
  191405. sp--;
  191406. }
  191407. else
  191408. shift = 4;
  191409. dp--;
  191410. }
  191411. break;
  191412. }
  191413. }
  191414. row_info->bit_depth = 8;
  191415. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191416. row_info->rowbytes = row_width * row_info->channels;
  191417. }
  191418. }
  191419. #endif
  191420. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191421. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191422. * pixels back to their significant bits values. Thus, if you have
  191423. * a row of bit depth 8, but only 5 are significant, this will shift
  191424. * the values back to 0 through 31.
  191425. */
  191426. void /* PRIVATE */
  191427. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191428. {
  191429. png_debug(1, "in png_do_unshift\n");
  191430. if (
  191431. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191432. row != NULL && row_info != NULL && sig_bits != NULL &&
  191433. #endif
  191434. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191435. {
  191436. int shift[4];
  191437. int channels = 0;
  191438. int c;
  191439. png_uint_16 value = 0;
  191440. png_uint_32 row_width = row_info->width;
  191441. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191442. {
  191443. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191444. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191445. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191446. }
  191447. else
  191448. {
  191449. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191450. }
  191451. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191452. {
  191453. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191454. }
  191455. for (c = 0; c < channels; c++)
  191456. {
  191457. if (shift[c] <= 0)
  191458. shift[c] = 0;
  191459. else
  191460. value = 1;
  191461. }
  191462. if (!value)
  191463. return;
  191464. switch (row_info->bit_depth)
  191465. {
  191466. case 2:
  191467. {
  191468. png_bytep bp;
  191469. png_uint_32 i;
  191470. png_uint_32 istop = row_info->rowbytes;
  191471. for (bp = row, i = 0; i < istop; i++)
  191472. {
  191473. *bp >>= 1;
  191474. *bp++ &= 0x55;
  191475. }
  191476. break;
  191477. }
  191478. case 4:
  191479. {
  191480. png_bytep bp = row;
  191481. png_uint_32 i;
  191482. png_uint_32 istop = row_info->rowbytes;
  191483. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191484. (png_byte)((int)0xf >> shift[0]));
  191485. for (i = 0; i < istop; i++)
  191486. {
  191487. *bp >>= shift[0];
  191488. *bp++ &= mask;
  191489. }
  191490. break;
  191491. }
  191492. case 8:
  191493. {
  191494. png_bytep bp = row;
  191495. png_uint_32 i;
  191496. png_uint_32 istop = row_width * channels;
  191497. for (i = 0; i < istop; i++)
  191498. {
  191499. *bp++ >>= shift[i%channels];
  191500. }
  191501. break;
  191502. }
  191503. case 16:
  191504. {
  191505. png_bytep bp = row;
  191506. png_uint_32 i;
  191507. png_uint_32 istop = channels * row_width;
  191508. for (i = 0; i < istop; i++)
  191509. {
  191510. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191511. value >>= shift[i%channels];
  191512. *bp++ = (png_byte)(value >> 8);
  191513. *bp++ = (png_byte)(value & 0xff);
  191514. }
  191515. break;
  191516. }
  191517. }
  191518. }
  191519. }
  191520. #endif
  191521. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191522. /* chop rows of bit depth 16 down to 8 */
  191523. void /* PRIVATE */
  191524. png_do_chop(png_row_infop row_info, png_bytep row)
  191525. {
  191526. png_debug(1, "in png_do_chop\n");
  191527. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191528. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191529. #else
  191530. if (row_info->bit_depth == 16)
  191531. #endif
  191532. {
  191533. png_bytep sp = row;
  191534. png_bytep dp = row;
  191535. png_uint_32 i;
  191536. png_uint_32 istop = row_info->width * row_info->channels;
  191537. for (i = 0; i<istop; i++, sp += 2, dp++)
  191538. {
  191539. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191540. /* This does a more accurate scaling of the 16-bit color
  191541. * value, rather than a simple low-byte truncation.
  191542. *
  191543. * What the ideal calculation should be:
  191544. * *dp = (((((png_uint_32)(*sp) << 8) |
  191545. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191546. *
  191547. * GRR: no, I think this is what it really should be:
  191548. * *dp = (((((png_uint_32)(*sp) << 8) |
  191549. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191550. *
  191551. * GRR: here's the exact calculation with shifts:
  191552. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191553. * *dp = (temp - (temp >> 8)) >> 8;
  191554. *
  191555. * Approximate calculation with shift/add instead of multiply/divide:
  191556. * *dp = ((((png_uint_32)(*sp) << 8) |
  191557. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191558. *
  191559. * What we actually do to avoid extra shifting and conversion:
  191560. */
  191561. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191562. #else
  191563. /* Simply discard the low order byte */
  191564. *dp = *sp;
  191565. #endif
  191566. }
  191567. row_info->bit_depth = 8;
  191568. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191569. row_info->rowbytes = row_info->width * row_info->channels;
  191570. }
  191571. }
  191572. #endif
  191573. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191574. void /* PRIVATE */
  191575. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191576. {
  191577. png_debug(1, "in png_do_read_swap_alpha\n");
  191578. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191579. if (row != NULL && row_info != NULL)
  191580. #endif
  191581. {
  191582. png_uint_32 row_width = row_info->width;
  191583. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191584. {
  191585. /* This converts from RGBA to ARGB */
  191586. if (row_info->bit_depth == 8)
  191587. {
  191588. png_bytep sp = row + row_info->rowbytes;
  191589. png_bytep dp = sp;
  191590. png_byte save;
  191591. png_uint_32 i;
  191592. for (i = 0; i < row_width; i++)
  191593. {
  191594. save = *(--sp);
  191595. *(--dp) = *(--sp);
  191596. *(--dp) = *(--sp);
  191597. *(--dp) = *(--sp);
  191598. *(--dp) = save;
  191599. }
  191600. }
  191601. /* This converts from RRGGBBAA to AARRGGBB */
  191602. else
  191603. {
  191604. png_bytep sp = row + row_info->rowbytes;
  191605. png_bytep dp = sp;
  191606. png_byte save[2];
  191607. png_uint_32 i;
  191608. for (i = 0; i < row_width; i++)
  191609. {
  191610. save[0] = *(--sp);
  191611. save[1] = *(--sp);
  191612. *(--dp) = *(--sp);
  191613. *(--dp) = *(--sp);
  191614. *(--dp) = *(--sp);
  191615. *(--dp) = *(--sp);
  191616. *(--dp) = *(--sp);
  191617. *(--dp) = *(--sp);
  191618. *(--dp) = save[0];
  191619. *(--dp) = save[1];
  191620. }
  191621. }
  191622. }
  191623. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191624. {
  191625. /* This converts from GA to AG */
  191626. if (row_info->bit_depth == 8)
  191627. {
  191628. png_bytep sp = row + row_info->rowbytes;
  191629. png_bytep dp = sp;
  191630. png_byte save;
  191631. png_uint_32 i;
  191632. for (i = 0; i < row_width; i++)
  191633. {
  191634. save = *(--sp);
  191635. *(--dp) = *(--sp);
  191636. *(--dp) = save;
  191637. }
  191638. }
  191639. /* This converts from GGAA to AAGG */
  191640. else
  191641. {
  191642. png_bytep sp = row + row_info->rowbytes;
  191643. png_bytep dp = sp;
  191644. png_byte save[2];
  191645. png_uint_32 i;
  191646. for (i = 0; i < row_width; i++)
  191647. {
  191648. save[0] = *(--sp);
  191649. save[1] = *(--sp);
  191650. *(--dp) = *(--sp);
  191651. *(--dp) = *(--sp);
  191652. *(--dp) = save[0];
  191653. *(--dp) = save[1];
  191654. }
  191655. }
  191656. }
  191657. }
  191658. }
  191659. #endif
  191660. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191661. void /* PRIVATE */
  191662. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191663. {
  191664. png_debug(1, "in png_do_read_invert_alpha\n");
  191665. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191666. if (row != NULL && row_info != NULL)
  191667. #endif
  191668. {
  191669. png_uint_32 row_width = row_info->width;
  191670. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191671. {
  191672. /* This inverts the alpha channel in RGBA */
  191673. if (row_info->bit_depth == 8)
  191674. {
  191675. png_bytep sp = row + row_info->rowbytes;
  191676. png_bytep dp = sp;
  191677. png_uint_32 i;
  191678. for (i = 0; i < row_width; i++)
  191679. {
  191680. *(--dp) = (png_byte)(255 - *(--sp));
  191681. /* This does nothing:
  191682. *(--dp) = *(--sp);
  191683. *(--dp) = *(--sp);
  191684. *(--dp) = *(--sp);
  191685. We can replace it with:
  191686. */
  191687. sp-=3;
  191688. dp=sp;
  191689. }
  191690. }
  191691. /* This inverts the alpha channel in RRGGBBAA */
  191692. else
  191693. {
  191694. png_bytep sp = row + row_info->rowbytes;
  191695. png_bytep dp = sp;
  191696. png_uint_32 i;
  191697. for (i = 0; i < row_width; i++)
  191698. {
  191699. *(--dp) = (png_byte)(255 - *(--sp));
  191700. *(--dp) = (png_byte)(255 - *(--sp));
  191701. /* This does nothing:
  191702. *(--dp) = *(--sp);
  191703. *(--dp) = *(--sp);
  191704. *(--dp) = *(--sp);
  191705. *(--dp) = *(--sp);
  191706. *(--dp) = *(--sp);
  191707. *(--dp) = *(--sp);
  191708. We can replace it with:
  191709. */
  191710. sp-=6;
  191711. dp=sp;
  191712. }
  191713. }
  191714. }
  191715. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191716. {
  191717. /* This inverts the alpha channel in GA */
  191718. if (row_info->bit_depth == 8)
  191719. {
  191720. png_bytep sp = row + row_info->rowbytes;
  191721. png_bytep dp = sp;
  191722. png_uint_32 i;
  191723. for (i = 0; i < row_width; i++)
  191724. {
  191725. *(--dp) = (png_byte)(255 - *(--sp));
  191726. *(--dp) = *(--sp);
  191727. }
  191728. }
  191729. /* This inverts the alpha channel in GGAA */
  191730. else
  191731. {
  191732. png_bytep sp = row + row_info->rowbytes;
  191733. png_bytep dp = sp;
  191734. png_uint_32 i;
  191735. for (i = 0; i < row_width; i++)
  191736. {
  191737. *(--dp) = (png_byte)(255 - *(--sp));
  191738. *(--dp) = (png_byte)(255 - *(--sp));
  191739. /*
  191740. *(--dp) = *(--sp);
  191741. *(--dp) = *(--sp);
  191742. */
  191743. sp-=2;
  191744. dp=sp;
  191745. }
  191746. }
  191747. }
  191748. }
  191749. }
  191750. #endif
  191751. #if defined(PNG_READ_FILLER_SUPPORTED)
  191752. /* Add filler channel if we have RGB color */
  191753. void /* PRIVATE */
  191754. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191755. png_uint_32 filler, png_uint_32 flags)
  191756. {
  191757. png_uint_32 i;
  191758. png_uint_32 row_width = row_info->width;
  191759. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191760. png_byte lo_filler = (png_byte)(filler & 0xff);
  191761. png_debug(1, "in png_do_read_filler\n");
  191762. if (
  191763. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191764. row != NULL && row_info != NULL &&
  191765. #endif
  191766. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191767. {
  191768. if(row_info->bit_depth == 8)
  191769. {
  191770. /* This changes the data from G to GX */
  191771. if (flags & PNG_FLAG_FILLER_AFTER)
  191772. {
  191773. png_bytep sp = row + (png_size_t)row_width;
  191774. png_bytep dp = sp + (png_size_t)row_width;
  191775. for (i = 1; i < row_width; i++)
  191776. {
  191777. *(--dp) = lo_filler;
  191778. *(--dp) = *(--sp);
  191779. }
  191780. *(--dp) = lo_filler;
  191781. row_info->channels = 2;
  191782. row_info->pixel_depth = 16;
  191783. row_info->rowbytes = row_width * 2;
  191784. }
  191785. /* This changes the data from G to XG */
  191786. else
  191787. {
  191788. png_bytep sp = row + (png_size_t)row_width;
  191789. png_bytep dp = sp + (png_size_t)row_width;
  191790. for (i = 0; i < row_width; i++)
  191791. {
  191792. *(--dp) = *(--sp);
  191793. *(--dp) = lo_filler;
  191794. }
  191795. row_info->channels = 2;
  191796. row_info->pixel_depth = 16;
  191797. row_info->rowbytes = row_width * 2;
  191798. }
  191799. }
  191800. else if(row_info->bit_depth == 16)
  191801. {
  191802. /* This changes the data from GG to GGXX */
  191803. if (flags & PNG_FLAG_FILLER_AFTER)
  191804. {
  191805. png_bytep sp = row + (png_size_t)row_width * 2;
  191806. png_bytep dp = sp + (png_size_t)row_width * 2;
  191807. for (i = 1; i < row_width; i++)
  191808. {
  191809. *(--dp) = hi_filler;
  191810. *(--dp) = lo_filler;
  191811. *(--dp) = *(--sp);
  191812. *(--dp) = *(--sp);
  191813. }
  191814. *(--dp) = hi_filler;
  191815. *(--dp) = lo_filler;
  191816. row_info->channels = 2;
  191817. row_info->pixel_depth = 32;
  191818. row_info->rowbytes = row_width * 4;
  191819. }
  191820. /* This changes the data from GG to XXGG */
  191821. else
  191822. {
  191823. png_bytep sp = row + (png_size_t)row_width * 2;
  191824. png_bytep dp = sp + (png_size_t)row_width * 2;
  191825. for (i = 0; i < row_width; i++)
  191826. {
  191827. *(--dp) = *(--sp);
  191828. *(--dp) = *(--sp);
  191829. *(--dp) = hi_filler;
  191830. *(--dp) = lo_filler;
  191831. }
  191832. row_info->channels = 2;
  191833. row_info->pixel_depth = 32;
  191834. row_info->rowbytes = row_width * 4;
  191835. }
  191836. }
  191837. } /* COLOR_TYPE == GRAY */
  191838. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191839. {
  191840. if(row_info->bit_depth == 8)
  191841. {
  191842. /* This changes the data from RGB to RGBX */
  191843. if (flags & PNG_FLAG_FILLER_AFTER)
  191844. {
  191845. png_bytep sp = row + (png_size_t)row_width * 3;
  191846. png_bytep dp = sp + (png_size_t)row_width;
  191847. for (i = 1; i < row_width; i++)
  191848. {
  191849. *(--dp) = lo_filler;
  191850. *(--dp) = *(--sp);
  191851. *(--dp) = *(--sp);
  191852. *(--dp) = *(--sp);
  191853. }
  191854. *(--dp) = lo_filler;
  191855. row_info->channels = 4;
  191856. row_info->pixel_depth = 32;
  191857. row_info->rowbytes = row_width * 4;
  191858. }
  191859. /* This changes the data from RGB to XRGB */
  191860. else
  191861. {
  191862. png_bytep sp = row + (png_size_t)row_width * 3;
  191863. png_bytep dp = sp + (png_size_t)row_width;
  191864. for (i = 0; i < row_width; i++)
  191865. {
  191866. *(--dp) = *(--sp);
  191867. *(--dp) = *(--sp);
  191868. *(--dp) = *(--sp);
  191869. *(--dp) = lo_filler;
  191870. }
  191871. row_info->channels = 4;
  191872. row_info->pixel_depth = 32;
  191873. row_info->rowbytes = row_width * 4;
  191874. }
  191875. }
  191876. else if(row_info->bit_depth == 16)
  191877. {
  191878. /* This changes the data from RRGGBB to RRGGBBXX */
  191879. if (flags & PNG_FLAG_FILLER_AFTER)
  191880. {
  191881. png_bytep sp = row + (png_size_t)row_width * 6;
  191882. png_bytep dp = sp + (png_size_t)row_width * 2;
  191883. for (i = 1; i < row_width; i++)
  191884. {
  191885. *(--dp) = hi_filler;
  191886. *(--dp) = lo_filler;
  191887. *(--dp) = *(--sp);
  191888. *(--dp) = *(--sp);
  191889. *(--dp) = *(--sp);
  191890. *(--dp) = *(--sp);
  191891. *(--dp) = *(--sp);
  191892. *(--dp) = *(--sp);
  191893. }
  191894. *(--dp) = hi_filler;
  191895. *(--dp) = lo_filler;
  191896. row_info->channels = 4;
  191897. row_info->pixel_depth = 64;
  191898. row_info->rowbytes = row_width * 8;
  191899. }
  191900. /* This changes the data from RRGGBB to XXRRGGBB */
  191901. else
  191902. {
  191903. png_bytep sp = row + (png_size_t)row_width * 6;
  191904. png_bytep dp = sp + (png_size_t)row_width * 2;
  191905. for (i = 0; i < row_width; i++)
  191906. {
  191907. *(--dp) = *(--sp);
  191908. *(--dp) = *(--sp);
  191909. *(--dp) = *(--sp);
  191910. *(--dp) = *(--sp);
  191911. *(--dp) = *(--sp);
  191912. *(--dp) = *(--sp);
  191913. *(--dp) = hi_filler;
  191914. *(--dp) = lo_filler;
  191915. }
  191916. row_info->channels = 4;
  191917. row_info->pixel_depth = 64;
  191918. row_info->rowbytes = row_width * 8;
  191919. }
  191920. }
  191921. } /* COLOR_TYPE == RGB */
  191922. }
  191923. #endif
  191924. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191925. /* expand grayscale files to RGB, with or without alpha */
  191926. void /* PRIVATE */
  191927. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191928. {
  191929. png_uint_32 i;
  191930. png_uint_32 row_width = row_info->width;
  191931. png_debug(1, "in png_do_gray_to_rgb\n");
  191932. if (row_info->bit_depth >= 8 &&
  191933. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191934. row != NULL && row_info != NULL &&
  191935. #endif
  191936. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191937. {
  191938. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191939. {
  191940. if (row_info->bit_depth == 8)
  191941. {
  191942. png_bytep sp = row + (png_size_t)row_width - 1;
  191943. png_bytep dp = sp + (png_size_t)row_width * 2;
  191944. for (i = 0; i < row_width; i++)
  191945. {
  191946. *(dp--) = *sp;
  191947. *(dp--) = *sp;
  191948. *(dp--) = *(sp--);
  191949. }
  191950. }
  191951. else
  191952. {
  191953. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191954. png_bytep dp = sp + (png_size_t)row_width * 4;
  191955. for (i = 0; i < row_width; i++)
  191956. {
  191957. *(dp--) = *sp;
  191958. *(dp--) = *(sp - 1);
  191959. *(dp--) = *sp;
  191960. *(dp--) = *(sp - 1);
  191961. *(dp--) = *(sp--);
  191962. *(dp--) = *(sp--);
  191963. }
  191964. }
  191965. }
  191966. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191967. {
  191968. if (row_info->bit_depth == 8)
  191969. {
  191970. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191971. png_bytep dp = sp + (png_size_t)row_width * 2;
  191972. for (i = 0; i < row_width; i++)
  191973. {
  191974. *(dp--) = *(sp--);
  191975. *(dp--) = *sp;
  191976. *(dp--) = *sp;
  191977. *(dp--) = *(sp--);
  191978. }
  191979. }
  191980. else
  191981. {
  191982. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191983. png_bytep dp = sp + (png_size_t)row_width * 4;
  191984. for (i = 0; i < row_width; i++)
  191985. {
  191986. *(dp--) = *(sp--);
  191987. *(dp--) = *(sp--);
  191988. *(dp--) = *sp;
  191989. *(dp--) = *(sp - 1);
  191990. *(dp--) = *sp;
  191991. *(dp--) = *(sp - 1);
  191992. *(dp--) = *(sp--);
  191993. *(dp--) = *(sp--);
  191994. }
  191995. }
  191996. }
  191997. row_info->channels += (png_byte)2;
  191998. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191999. row_info->pixel_depth = (png_byte)(row_info->channels *
  192000. row_info->bit_depth);
  192001. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192002. }
  192003. }
  192004. #endif
  192005. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192006. /* reduce RGB files to grayscale, with or without alpha
  192007. * using the equation given in Poynton's ColorFAQ at
  192008. * <http://www.inforamp.net/~poynton/>
  192009. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  192010. *
  192011. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  192012. *
  192013. * We approximate this with
  192014. *
  192015. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  192016. *
  192017. * which can be expressed with integers as
  192018. *
  192019. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  192020. *
  192021. * The calculation is to be done in a linear colorspace.
  192022. *
  192023. * Other integer coefficents can be used via png_set_rgb_to_gray().
  192024. */
  192025. int /* PRIVATE */
  192026. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  192027. {
  192028. png_uint_32 i;
  192029. png_uint_32 row_width = row_info->width;
  192030. int rgb_error = 0;
  192031. png_debug(1, "in png_do_rgb_to_gray\n");
  192032. if (
  192033. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192034. row != NULL && row_info != NULL &&
  192035. #endif
  192036. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192037. {
  192038. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  192039. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  192040. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  192041. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192042. {
  192043. if (row_info->bit_depth == 8)
  192044. {
  192045. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192046. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192047. {
  192048. png_bytep sp = row;
  192049. png_bytep dp = row;
  192050. for (i = 0; i < row_width; i++)
  192051. {
  192052. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192053. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192054. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192055. if(red != green || red != blue)
  192056. {
  192057. rgb_error |= 1;
  192058. *(dp++) = png_ptr->gamma_from_1[
  192059. (rc*red+gc*green+bc*blue)>>15];
  192060. }
  192061. else
  192062. *(dp++) = *(sp-1);
  192063. }
  192064. }
  192065. else
  192066. #endif
  192067. {
  192068. png_bytep sp = row;
  192069. png_bytep dp = row;
  192070. for (i = 0; i < row_width; i++)
  192071. {
  192072. png_byte red = *(sp++);
  192073. png_byte green = *(sp++);
  192074. png_byte blue = *(sp++);
  192075. if(red != green || red != blue)
  192076. {
  192077. rgb_error |= 1;
  192078. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192079. }
  192080. else
  192081. *(dp++) = *(sp-1);
  192082. }
  192083. }
  192084. }
  192085. else /* RGB bit_depth == 16 */
  192086. {
  192087. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192088. if (png_ptr->gamma_16_to_1 != NULL &&
  192089. png_ptr->gamma_16_from_1 != NULL)
  192090. {
  192091. png_bytep sp = row;
  192092. png_bytep dp = row;
  192093. for (i = 0; i < row_width; i++)
  192094. {
  192095. png_uint_16 red, green, blue, w;
  192096. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192097. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192098. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192099. if(red == green && red == blue)
  192100. w = red;
  192101. else
  192102. {
  192103. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192104. png_ptr->gamma_shift][red>>8];
  192105. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192106. png_ptr->gamma_shift][green>>8];
  192107. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192108. png_ptr->gamma_shift][blue>>8];
  192109. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192110. + bc*blue_1)>>15);
  192111. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192112. png_ptr->gamma_shift][gray16 >> 8];
  192113. rgb_error |= 1;
  192114. }
  192115. *(dp++) = (png_byte)((w>>8) & 0xff);
  192116. *(dp++) = (png_byte)(w & 0xff);
  192117. }
  192118. }
  192119. else
  192120. #endif
  192121. {
  192122. png_bytep sp = row;
  192123. png_bytep dp = row;
  192124. for (i = 0; i < row_width; i++)
  192125. {
  192126. png_uint_16 red, green, blue, gray16;
  192127. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192128. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192129. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192130. if(red != green || red != blue)
  192131. rgb_error |= 1;
  192132. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192133. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192134. *(dp++) = (png_byte)(gray16 & 0xff);
  192135. }
  192136. }
  192137. }
  192138. }
  192139. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192140. {
  192141. if (row_info->bit_depth == 8)
  192142. {
  192143. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192144. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192145. {
  192146. png_bytep sp = row;
  192147. png_bytep dp = row;
  192148. for (i = 0; i < row_width; i++)
  192149. {
  192150. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192151. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192152. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192153. if(red != green || red != blue)
  192154. rgb_error |= 1;
  192155. *(dp++) = png_ptr->gamma_from_1
  192156. [(rc*red + gc*green + bc*blue)>>15];
  192157. *(dp++) = *(sp++); /* alpha */
  192158. }
  192159. }
  192160. else
  192161. #endif
  192162. {
  192163. png_bytep sp = row;
  192164. png_bytep dp = row;
  192165. for (i = 0; i < row_width; i++)
  192166. {
  192167. png_byte red = *(sp++);
  192168. png_byte green = *(sp++);
  192169. png_byte blue = *(sp++);
  192170. if(red != green || red != blue)
  192171. rgb_error |= 1;
  192172. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192173. *(dp++) = *(sp++); /* alpha */
  192174. }
  192175. }
  192176. }
  192177. else /* RGBA bit_depth == 16 */
  192178. {
  192179. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192180. if (png_ptr->gamma_16_to_1 != NULL &&
  192181. png_ptr->gamma_16_from_1 != NULL)
  192182. {
  192183. png_bytep sp = row;
  192184. png_bytep dp = row;
  192185. for (i = 0; i < row_width; i++)
  192186. {
  192187. png_uint_16 red, green, blue, w;
  192188. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192189. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192190. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192191. if(red == green && red == blue)
  192192. w = red;
  192193. else
  192194. {
  192195. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192196. png_ptr->gamma_shift][red>>8];
  192197. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192198. png_ptr->gamma_shift][green>>8];
  192199. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192200. png_ptr->gamma_shift][blue>>8];
  192201. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192202. + gc * green_1 + bc * blue_1)>>15);
  192203. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192204. png_ptr->gamma_shift][gray16 >> 8];
  192205. rgb_error |= 1;
  192206. }
  192207. *(dp++) = (png_byte)((w>>8) & 0xff);
  192208. *(dp++) = (png_byte)(w & 0xff);
  192209. *(dp++) = *(sp++); /* alpha */
  192210. *(dp++) = *(sp++);
  192211. }
  192212. }
  192213. else
  192214. #endif
  192215. {
  192216. png_bytep sp = row;
  192217. png_bytep dp = row;
  192218. for (i = 0; i < row_width; i++)
  192219. {
  192220. png_uint_16 red, green, blue, gray16;
  192221. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192222. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192223. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192224. if(red != green || red != blue)
  192225. rgb_error |= 1;
  192226. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192227. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192228. *(dp++) = (png_byte)(gray16 & 0xff);
  192229. *(dp++) = *(sp++); /* alpha */
  192230. *(dp++) = *(sp++);
  192231. }
  192232. }
  192233. }
  192234. }
  192235. row_info->channels -= (png_byte)2;
  192236. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192237. row_info->pixel_depth = (png_byte)(row_info->channels *
  192238. row_info->bit_depth);
  192239. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192240. }
  192241. return rgb_error;
  192242. }
  192243. #endif
  192244. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192245. * large of png_color. This lets grayscale images be treated as
  192246. * paletted. Most useful for gamma correction and simplification
  192247. * of code.
  192248. */
  192249. void PNGAPI
  192250. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192251. {
  192252. int num_palette;
  192253. int color_inc;
  192254. int i;
  192255. int v;
  192256. png_debug(1, "in png_do_build_grayscale_palette\n");
  192257. if (palette == NULL)
  192258. return;
  192259. switch (bit_depth)
  192260. {
  192261. case 1:
  192262. num_palette = 2;
  192263. color_inc = 0xff;
  192264. break;
  192265. case 2:
  192266. num_palette = 4;
  192267. color_inc = 0x55;
  192268. break;
  192269. case 4:
  192270. num_palette = 16;
  192271. color_inc = 0x11;
  192272. break;
  192273. case 8:
  192274. num_palette = 256;
  192275. color_inc = 1;
  192276. break;
  192277. default:
  192278. num_palette = 0;
  192279. color_inc = 0;
  192280. break;
  192281. }
  192282. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192283. {
  192284. palette[i].red = (png_byte)v;
  192285. palette[i].green = (png_byte)v;
  192286. palette[i].blue = (png_byte)v;
  192287. }
  192288. }
  192289. /* This function is currently unused. Do we really need it? */
  192290. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192291. void /* PRIVATE */
  192292. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192293. int num_palette)
  192294. {
  192295. png_debug(1, "in png_correct_palette\n");
  192296. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192297. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192298. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192299. {
  192300. png_color back, back_1;
  192301. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192302. {
  192303. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192304. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192305. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192306. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192307. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192308. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192309. }
  192310. else
  192311. {
  192312. double g;
  192313. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192314. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192315. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192316. {
  192317. back.red = png_ptr->background.red;
  192318. back.green = png_ptr->background.green;
  192319. back.blue = png_ptr->background.blue;
  192320. }
  192321. else
  192322. {
  192323. back.red =
  192324. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192325. 255.0 + 0.5);
  192326. back.green =
  192327. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192328. 255.0 + 0.5);
  192329. back.blue =
  192330. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192331. 255.0 + 0.5);
  192332. }
  192333. g = 1.0 / png_ptr->background_gamma;
  192334. back_1.red =
  192335. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192336. 255.0 + 0.5);
  192337. back_1.green =
  192338. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192339. 255.0 + 0.5);
  192340. back_1.blue =
  192341. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192342. 255.0 + 0.5);
  192343. }
  192344. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192345. {
  192346. png_uint_32 i;
  192347. for (i = 0; i < (png_uint_32)num_palette; i++)
  192348. {
  192349. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192350. {
  192351. palette[i] = back;
  192352. }
  192353. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192354. {
  192355. png_byte v, w;
  192356. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192357. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192358. palette[i].red = png_ptr->gamma_from_1[w];
  192359. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192360. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192361. palette[i].green = png_ptr->gamma_from_1[w];
  192362. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192363. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192364. palette[i].blue = png_ptr->gamma_from_1[w];
  192365. }
  192366. else
  192367. {
  192368. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192369. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192370. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192371. }
  192372. }
  192373. }
  192374. else
  192375. {
  192376. int i;
  192377. for (i = 0; i < num_palette; i++)
  192378. {
  192379. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192380. {
  192381. palette[i] = back;
  192382. }
  192383. else
  192384. {
  192385. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192386. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192387. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192388. }
  192389. }
  192390. }
  192391. }
  192392. else
  192393. #endif
  192394. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192395. if (png_ptr->transformations & PNG_GAMMA)
  192396. {
  192397. int i;
  192398. for (i = 0; i < num_palette; i++)
  192399. {
  192400. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192401. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192402. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192403. }
  192404. }
  192405. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192406. else
  192407. #endif
  192408. #endif
  192409. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192410. if (png_ptr->transformations & PNG_BACKGROUND)
  192411. {
  192412. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192413. {
  192414. png_color back;
  192415. back.red = (png_byte)png_ptr->background.red;
  192416. back.green = (png_byte)png_ptr->background.green;
  192417. back.blue = (png_byte)png_ptr->background.blue;
  192418. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192419. {
  192420. if (png_ptr->trans[i] == 0)
  192421. {
  192422. palette[i].red = back.red;
  192423. palette[i].green = back.green;
  192424. palette[i].blue = back.blue;
  192425. }
  192426. else if (png_ptr->trans[i] != 0xff)
  192427. {
  192428. png_composite(palette[i].red, png_ptr->palette[i].red,
  192429. png_ptr->trans[i], back.red);
  192430. png_composite(palette[i].green, png_ptr->palette[i].green,
  192431. png_ptr->trans[i], back.green);
  192432. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192433. png_ptr->trans[i], back.blue);
  192434. }
  192435. }
  192436. }
  192437. else /* assume grayscale palette (what else could it be?) */
  192438. {
  192439. int i;
  192440. for (i = 0; i < num_palette; i++)
  192441. {
  192442. if (i == (png_byte)png_ptr->trans_values.gray)
  192443. {
  192444. palette[i].red = (png_byte)png_ptr->background.red;
  192445. palette[i].green = (png_byte)png_ptr->background.green;
  192446. palette[i].blue = (png_byte)png_ptr->background.blue;
  192447. }
  192448. }
  192449. }
  192450. }
  192451. #endif
  192452. }
  192453. #endif
  192454. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192455. /* Replace any alpha or transparency with the supplied background color.
  192456. * "background" is already in the screen gamma, while "background_1" is
  192457. * at a gamma of 1.0. Paletted files have already been taken care of.
  192458. */
  192459. void /* PRIVATE */
  192460. png_do_background(png_row_infop row_info, png_bytep row,
  192461. png_color_16p trans_values, png_color_16p background
  192462. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192463. , png_color_16p background_1,
  192464. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192465. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192466. png_uint_16pp gamma_16_to_1, int gamma_shift
  192467. #endif
  192468. )
  192469. {
  192470. png_bytep sp, dp;
  192471. png_uint_32 i;
  192472. png_uint_32 row_width=row_info->width;
  192473. int shift;
  192474. png_debug(1, "in png_do_background\n");
  192475. if (background != NULL &&
  192476. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192477. row != NULL && row_info != NULL &&
  192478. #endif
  192479. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192480. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192481. {
  192482. switch (row_info->color_type)
  192483. {
  192484. case PNG_COLOR_TYPE_GRAY:
  192485. {
  192486. switch (row_info->bit_depth)
  192487. {
  192488. case 1:
  192489. {
  192490. sp = row;
  192491. shift = 7;
  192492. for (i = 0; i < row_width; i++)
  192493. {
  192494. if ((png_uint_16)((*sp >> shift) & 0x01)
  192495. == trans_values->gray)
  192496. {
  192497. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192498. *sp |= (png_byte)(background->gray << shift);
  192499. }
  192500. if (!shift)
  192501. {
  192502. shift = 7;
  192503. sp++;
  192504. }
  192505. else
  192506. shift--;
  192507. }
  192508. break;
  192509. }
  192510. case 2:
  192511. {
  192512. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192513. if (gamma_table != NULL)
  192514. {
  192515. sp = row;
  192516. shift = 6;
  192517. for (i = 0; i < row_width; i++)
  192518. {
  192519. if ((png_uint_16)((*sp >> shift) & 0x03)
  192520. == trans_values->gray)
  192521. {
  192522. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192523. *sp |= (png_byte)(background->gray << shift);
  192524. }
  192525. else
  192526. {
  192527. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192528. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192529. (p << 4) | (p << 6)] >> 6) & 0x03);
  192530. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192531. *sp |= (png_byte)(g << shift);
  192532. }
  192533. if (!shift)
  192534. {
  192535. shift = 6;
  192536. sp++;
  192537. }
  192538. else
  192539. shift -= 2;
  192540. }
  192541. }
  192542. else
  192543. #endif
  192544. {
  192545. sp = row;
  192546. shift = 6;
  192547. for (i = 0; i < row_width; i++)
  192548. {
  192549. if ((png_uint_16)((*sp >> shift) & 0x03)
  192550. == trans_values->gray)
  192551. {
  192552. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192553. *sp |= (png_byte)(background->gray << shift);
  192554. }
  192555. if (!shift)
  192556. {
  192557. shift = 6;
  192558. sp++;
  192559. }
  192560. else
  192561. shift -= 2;
  192562. }
  192563. }
  192564. break;
  192565. }
  192566. case 4:
  192567. {
  192568. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192569. if (gamma_table != NULL)
  192570. {
  192571. sp = row;
  192572. shift = 4;
  192573. for (i = 0; i < row_width; i++)
  192574. {
  192575. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192576. == trans_values->gray)
  192577. {
  192578. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192579. *sp |= (png_byte)(background->gray << shift);
  192580. }
  192581. else
  192582. {
  192583. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192584. png_byte g = (png_byte)((gamma_table[p |
  192585. (p << 4)] >> 4) & 0x0f);
  192586. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192587. *sp |= (png_byte)(g << shift);
  192588. }
  192589. if (!shift)
  192590. {
  192591. shift = 4;
  192592. sp++;
  192593. }
  192594. else
  192595. shift -= 4;
  192596. }
  192597. }
  192598. else
  192599. #endif
  192600. {
  192601. sp = row;
  192602. shift = 4;
  192603. for (i = 0; i < row_width; i++)
  192604. {
  192605. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192606. == trans_values->gray)
  192607. {
  192608. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192609. *sp |= (png_byte)(background->gray << shift);
  192610. }
  192611. if (!shift)
  192612. {
  192613. shift = 4;
  192614. sp++;
  192615. }
  192616. else
  192617. shift -= 4;
  192618. }
  192619. }
  192620. break;
  192621. }
  192622. case 8:
  192623. {
  192624. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192625. if (gamma_table != NULL)
  192626. {
  192627. sp = row;
  192628. for (i = 0; i < row_width; i++, sp++)
  192629. {
  192630. if (*sp == trans_values->gray)
  192631. {
  192632. *sp = (png_byte)background->gray;
  192633. }
  192634. else
  192635. {
  192636. *sp = gamma_table[*sp];
  192637. }
  192638. }
  192639. }
  192640. else
  192641. #endif
  192642. {
  192643. sp = row;
  192644. for (i = 0; i < row_width; i++, sp++)
  192645. {
  192646. if (*sp == trans_values->gray)
  192647. {
  192648. *sp = (png_byte)background->gray;
  192649. }
  192650. }
  192651. }
  192652. break;
  192653. }
  192654. case 16:
  192655. {
  192656. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192657. if (gamma_16 != NULL)
  192658. {
  192659. sp = row;
  192660. for (i = 0; i < row_width; i++, sp += 2)
  192661. {
  192662. png_uint_16 v;
  192663. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192664. if (v == trans_values->gray)
  192665. {
  192666. /* background is already in screen gamma */
  192667. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192668. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192669. }
  192670. else
  192671. {
  192672. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192673. *sp = (png_byte)((v >> 8) & 0xff);
  192674. *(sp + 1) = (png_byte)(v & 0xff);
  192675. }
  192676. }
  192677. }
  192678. else
  192679. #endif
  192680. {
  192681. sp = row;
  192682. for (i = 0; i < row_width; i++, sp += 2)
  192683. {
  192684. png_uint_16 v;
  192685. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192686. if (v == trans_values->gray)
  192687. {
  192688. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192689. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192690. }
  192691. }
  192692. }
  192693. break;
  192694. }
  192695. }
  192696. break;
  192697. }
  192698. case PNG_COLOR_TYPE_RGB:
  192699. {
  192700. if (row_info->bit_depth == 8)
  192701. {
  192702. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192703. if (gamma_table != NULL)
  192704. {
  192705. sp = row;
  192706. for (i = 0; i < row_width; i++, sp += 3)
  192707. {
  192708. if (*sp == trans_values->red &&
  192709. *(sp + 1) == trans_values->green &&
  192710. *(sp + 2) == trans_values->blue)
  192711. {
  192712. *sp = (png_byte)background->red;
  192713. *(sp + 1) = (png_byte)background->green;
  192714. *(sp + 2) = (png_byte)background->blue;
  192715. }
  192716. else
  192717. {
  192718. *sp = gamma_table[*sp];
  192719. *(sp + 1) = gamma_table[*(sp + 1)];
  192720. *(sp + 2) = gamma_table[*(sp + 2)];
  192721. }
  192722. }
  192723. }
  192724. else
  192725. #endif
  192726. {
  192727. sp = row;
  192728. for (i = 0; i < row_width; i++, sp += 3)
  192729. {
  192730. if (*sp == trans_values->red &&
  192731. *(sp + 1) == trans_values->green &&
  192732. *(sp + 2) == trans_values->blue)
  192733. {
  192734. *sp = (png_byte)background->red;
  192735. *(sp + 1) = (png_byte)background->green;
  192736. *(sp + 2) = (png_byte)background->blue;
  192737. }
  192738. }
  192739. }
  192740. }
  192741. else /* if (row_info->bit_depth == 16) */
  192742. {
  192743. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192744. if (gamma_16 != NULL)
  192745. {
  192746. sp = row;
  192747. for (i = 0; i < row_width; i++, sp += 6)
  192748. {
  192749. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192750. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192751. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192752. if (r == trans_values->red && g == trans_values->green &&
  192753. b == trans_values->blue)
  192754. {
  192755. /* background is already in screen gamma */
  192756. *sp = (png_byte)((background->red >> 8) & 0xff);
  192757. *(sp + 1) = (png_byte)(background->red & 0xff);
  192758. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192759. *(sp + 3) = (png_byte)(background->green & 0xff);
  192760. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192761. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192762. }
  192763. else
  192764. {
  192765. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192766. *sp = (png_byte)((v >> 8) & 0xff);
  192767. *(sp + 1) = (png_byte)(v & 0xff);
  192768. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192769. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192770. *(sp + 3) = (png_byte)(v & 0xff);
  192771. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192772. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192773. *(sp + 5) = (png_byte)(v & 0xff);
  192774. }
  192775. }
  192776. }
  192777. else
  192778. #endif
  192779. {
  192780. sp = row;
  192781. for (i = 0; i < row_width; i++, sp += 6)
  192782. {
  192783. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192784. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192785. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192786. if (r == trans_values->red && g == trans_values->green &&
  192787. b == trans_values->blue)
  192788. {
  192789. *sp = (png_byte)((background->red >> 8) & 0xff);
  192790. *(sp + 1) = (png_byte)(background->red & 0xff);
  192791. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192792. *(sp + 3) = (png_byte)(background->green & 0xff);
  192793. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192794. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192795. }
  192796. }
  192797. }
  192798. }
  192799. break;
  192800. }
  192801. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192802. {
  192803. if (row_info->bit_depth == 8)
  192804. {
  192805. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192806. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192807. gamma_table != NULL)
  192808. {
  192809. sp = row;
  192810. dp = row;
  192811. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192812. {
  192813. png_uint_16 a = *(sp + 1);
  192814. if (a == 0xff)
  192815. {
  192816. *dp = gamma_table[*sp];
  192817. }
  192818. else if (a == 0)
  192819. {
  192820. /* background is already in screen gamma */
  192821. *dp = (png_byte)background->gray;
  192822. }
  192823. else
  192824. {
  192825. png_byte v, w;
  192826. v = gamma_to_1[*sp];
  192827. png_composite(w, v, a, background_1->gray);
  192828. *dp = gamma_from_1[w];
  192829. }
  192830. }
  192831. }
  192832. else
  192833. #endif
  192834. {
  192835. sp = row;
  192836. dp = row;
  192837. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192838. {
  192839. png_byte a = *(sp + 1);
  192840. if (a == 0xff)
  192841. {
  192842. *dp = *sp;
  192843. }
  192844. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192845. else if (a == 0)
  192846. {
  192847. *dp = (png_byte)background->gray;
  192848. }
  192849. else
  192850. {
  192851. png_composite(*dp, *sp, a, background_1->gray);
  192852. }
  192853. #else
  192854. *dp = (png_byte)background->gray;
  192855. #endif
  192856. }
  192857. }
  192858. }
  192859. else /* if (png_ptr->bit_depth == 16) */
  192860. {
  192861. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192862. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192863. gamma_16_to_1 != NULL)
  192864. {
  192865. sp = row;
  192866. dp = row;
  192867. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192868. {
  192869. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192870. if (a == (png_uint_16)0xffff)
  192871. {
  192872. png_uint_16 v;
  192873. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192874. *dp = (png_byte)((v >> 8) & 0xff);
  192875. *(dp + 1) = (png_byte)(v & 0xff);
  192876. }
  192877. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192878. else if (a == 0)
  192879. #else
  192880. else
  192881. #endif
  192882. {
  192883. /* background is already in screen gamma */
  192884. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192885. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192886. }
  192887. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192888. else
  192889. {
  192890. png_uint_16 g, v, w;
  192891. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192892. png_composite_16(v, g, a, background_1->gray);
  192893. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192894. *dp = (png_byte)((w >> 8) & 0xff);
  192895. *(dp + 1) = (png_byte)(w & 0xff);
  192896. }
  192897. #endif
  192898. }
  192899. }
  192900. else
  192901. #endif
  192902. {
  192903. sp = row;
  192904. dp = row;
  192905. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192906. {
  192907. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192908. if (a == (png_uint_16)0xffff)
  192909. {
  192910. png_memcpy(dp, sp, 2);
  192911. }
  192912. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192913. else if (a == 0)
  192914. #else
  192915. else
  192916. #endif
  192917. {
  192918. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192919. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192920. }
  192921. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192922. else
  192923. {
  192924. png_uint_16 g, v;
  192925. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192926. png_composite_16(v, g, a, background_1->gray);
  192927. *dp = (png_byte)((v >> 8) & 0xff);
  192928. *(dp + 1) = (png_byte)(v & 0xff);
  192929. }
  192930. #endif
  192931. }
  192932. }
  192933. }
  192934. break;
  192935. }
  192936. case PNG_COLOR_TYPE_RGB_ALPHA:
  192937. {
  192938. if (row_info->bit_depth == 8)
  192939. {
  192940. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192941. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192942. gamma_table != NULL)
  192943. {
  192944. sp = row;
  192945. dp = row;
  192946. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192947. {
  192948. png_byte a = *(sp + 3);
  192949. if (a == 0xff)
  192950. {
  192951. *dp = gamma_table[*sp];
  192952. *(dp + 1) = gamma_table[*(sp + 1)];
  192953. *(dp + 2) = gamma_table[*(sp + 2)];
  192954. }
  192955. else if (a == 0)
  192956. {
  192957. /* background is already in screen gamma */
  192958. *dp = (png_byte)background->red;
  192959. *(dp + 1) = (png_byte)background->green;
  192960. *(dp + 2) = (png_byte)background->blue;
  192961. }
  192962. else
  192963. {
  192964. png_byte v, w;
  192965. v = gamma_to_1[*sp];
  192966. png_composite(w, v, a, background_1->red);
  192967. *dp = gamma_from_1[w];
  192968. v = gamma_to_1[*(sp + 1)];
  192969. png_composite(w, v, a, background_1->green);
  192970. *(dp + 1) = gamma_from_1[w];
  192971. v = gamma_to_1[*(sp + 2)];
  192972. png_composite(w, v, a, background_1->blue);
  192973. *(dp + 2) = gamma_from_1[w];
  192974. }
  192975. }
  192976. }
  192977. else
  192978. #endif
  192979. {
  192980. sp = row;
  192981. dp = row;
  192982. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192983. {
  192984. png_byte a = *(sp + 3);
  192985. if (a == 0xff)
  192986. {
  192987. *dp = *sp;
  192988. *(dp + 1) = *(sp + 1);
  192989. *(dp + 2) = *(sp + 2);
  192990. }
  192991. else if (a == 0)
  192992. {
  192993. *dp = (png_byte)background->red;
  192994. *(dp + 1) = (png_byte)background->green;
  192995. *(dp + 2) = (png_byte)background->blue;
  192996. }
  192997. else
  192998. {
  192999. png_composite(*dp, *sp, a, background->red);
  193000. png_composite(*(dp + 1), *(sp + 1), a,
  193001. background->green);
  193002. png_composite(*(dp + 2), *(sp + 2), a,
  193003. background->blue);
  193004. }
  193005. }
  193006. }
  193007. }
  193008. else /* if (row_info->bit_depth == 16) */
  193009. {
  193010. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193011. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193012. gamma_16_to_1 != NULL)
  193013. {
  193014. sp = row;
  193015. dp = row;
  193016. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193017. {
  193018. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193019. << 8) + (png_uint_16)(*(sp + 7)));
  193020. if (a == (png_uint_16)0xffff)
  193021. {
  193022. png_uint_16 v;
  193023. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193024. *dp = (png_byte)((v >> 8) & 0xff);
  193025. *(dp + 1) = (png_byte)(v & 0xff);
  193026. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193027. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193028. *(dp + 3) = (png_byte)(v & 0xff);
  193029. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193030. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193031. *(dp + 5) = (png_byte)(v & 0xff);
  193032. }
  193033. else if (a == 0)
  193034. {
  193035. /* background is already in screen gamma */
  193036. *dp = (png_byte)((background->red >> 8) & 0xff);
  193037. *(dp + 1) = (png_byte)(background->red & 0xff);
  193038. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193039. *(dp + 3) = (png_byte)(background->green & 0xff);
  193040. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193041. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193042. }
  193043. else
  193044. {
  193045. png_uint_16 v, w, x;
  193046. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193047. png_composite_16(w, v, a, background_1->red);
  193048. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193049. *dp = (png_byte)((x >> 8) & 0xff);
  193050. *(dp + 1) = (png_byte)(x & 0xff);
  193051. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193052. png_composite_16(w, v, a, background_1->green);
  193053. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193054. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  193055. *(dp + 3) = (png_byte)(x & 0xff);
  193056. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193057. png_composite_16(w, v, a, background_1->blue);
  193058. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  193059. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  193060. *(dp + 5) = (png_byte)(x & 0xff);
  193061. }
  193062. }
  193063. }
  193064. else
  193065. #endif
  193066. {
  193067. sp = row;
  193068. dp = row;
  193069. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193070. {
  193071. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193072. << 8) + (png_uint_16)(*(sp + 7)));
  193073. if (a == (png_uint_16)0xffff)
  193074. {
  193075. png_memcpy(dp, sp, 6);
  193076. }
  193077. else if (a == 0)
  193078. {
  193079. *dp = (png_byte)((background->red >> 8) & 0xff);
  193080. *(dp + 1) = (png_byte)(background->red & 0xff);
  193081. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193082. *(dp + 3) = (png_byte)(background->green & 0xff);
  193083. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193084. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193085. }
  193086. else
  193087. {
  193088. png_uint_16 v;
  193089. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193090. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193091. + *(sp + 3));
  193092. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193093. + *(sp + 5));
  193094. png_composite_16(v, r, a, background->red);
  193095. *dp = (png_byte)((v >> 8) & 0xff);
  193096. *(dp + 1) = (png_byte)(v & 0xff);
  193097. png_composite_16(v, g, a, background->green);
  193098. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193099. *(dp + 3) = (png_byte)(v & 0xff);
  193100. png_composite_16(v, b, a, background->blue);
  193101. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193102. *(dp + 5) = (png_byte)(v & 0xff);
  193103. }
  193104. }
  193105. }
  193106. }
  193107. break;
  193108. }
  193109. }
  193110. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193111. {
  193112. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193113. row_info->channels--;
  193114. row_info->pixel_depth = (png_byte)(row_info->channels *
  193115. row_info->bit_depth);
  193116. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193117. }
  193118. }
  193119. }
  193120. #endif
  193121. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193122. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193123. * you do this after you deal with the transparency issue on grayscale
  193124. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193125. * is 16, use gamma_16_table and gamma_shift. Build these with
  193126. * build_gamma_table().
  193127. */
  193128. void /* PRIVATE */
  193129. png_do_gamma(png_row_infop row_info, png_bytep row,
  193130. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193131. int gamma_shift)
  193132. {
  193133. png_bytep sp;
  193134. png_uint_32 i;
  193135. png_uint_32 row_width=row_info->width;
  193136. png_debug(1, "in png_do_gamma\n");
  193137. if (
  193138. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193139. row != NULL && row_info != NULL &&
  193140. #endif
  193141. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193142. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193143. {
  193144. switch (row_info->color_type)
  193145. {
  193146. case PNG_COLOR_TYPE_RGB:
  193147. {
  193148. if (row_info->bit_depth == 8)
  193149. {
  193150. sp = row;
  193151. for (i = 0; i < row_width; i++)
  193152. {
  193153. *sp = gamma_table[*sp];
  193154. sp++;
  193155. *sp = gamma_table[*sp];
  193156. sp++;
  193157. *sp = gamma_table[*sp];
  193158. sp++;
  193159. }
  193160. }
  193161. else /* if (row_info->bit_depth == 16) */
  193162. {
  193163. sp = row;
  193164. for (i = 0; i < row_width; i++)
  193165. {
  193166. png_uint_16 v;
  193167. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193168. *sp = (png_byte)((v >> 8) & 0xff);
  193169. *(sp + 1) = (png_byte)(v & 0xff);
  193170. sp += 2;
  193171. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193172. *sp = (png_byte)((v >> 8) & 0xff);
  193173. *(sp + 1) = (png_byte)(v & 0xff);
  193174. sp += 2;
  193175. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193176. *sp = (png_byte)((v >> 8) & 0xff);
  193177. *(sp + 1) = (png_byte)(v & 0xff);
  193178. sp += 2;
  193179. }
  193180. }
  193181. break;
  193182. }
  193183. case PNG_COLOR_TYPE_RGB_ALPHA:
  193184. {
  193185. if (row_info->bit_depth == 8)
  193186. {
  193187. sp = row;
  193188. for (i = 0; i < row_width; i++)
  193189. {
  193190. *sp = gamma_table[*sp];
  193191. sp++;
  193192. *sp = gamma_table[*sp];
  193193. sp++;
  193194. *sp = gamma_table[*sp];
  193195. sp++;
  193196. sp++;
  193197. }
  193198. }
  193199. else /* if (row_info->bit_depth == 16) */
  193200. {
  193201. sp = row;
  193202. for (i = 0; i < row_width; i++)
  193203. {
  193204. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193205. *sp = (png_byte)((v >> 8) & 0xff);
  193206. *(sp + 1) = (png_byte)(v & 0xff);
  193207. sp += 2;
  193208. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193209. *sp = (png_byte)((v >> 8) & 0xff);
  193210. *(sp + 1) = (png_byte)(v & 0xff);
  193211. sp += 2;
  193212. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193213. *sp = (png_byte)((v >> 8) & 0xff);
  193214. *(sp + 1) = (png_byte)(v & 0xff);
  193215. sp += 4;
  193216. }
  193217. }
  193218. break;
  193219. }
  193220. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193221. {
  193222. if (row_info->bit_depth == 8)
  193223. {
  193224. sp = row;
  193225. for (i = 0; i < row_width; i++)
  193226. {
  193227. *sp = gamma_table[*sp];
  193228. sp += 2;
  193229. }
  193230. }
  193231. else /* if (row_info->bit_depth == 16) */
  193232. {
  193233. sp = row;
  193234. for (i = 0; i < row_width; i++)
  193235. {
  193236. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193237. *sp = (png_byte)((v >> 8) & 0xff);
  193238. *(sp + 1) = (png_byte)(v & 0xff);
  193239. sp += 4;
  193240. }
  193241. }
  193242. break;
  193243. }
  193244. case PNG_COLOR_TYPE_GRAY:
  193245. {
  193246. if (row_info->bit_depth == 2)
  193247. {
  193248. sp = row;
  193249. for (i = 0; i < row_width; i += 4)
  193250. {
  193251. int a = *sp & 0xc0;
  193252. int b = *sp & 0x30;
  193253. int c = *sp & 0x0c;
  193254. int d = *sp & 0x03;
  193255. *sp = (png_byte)(
  193256. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193257. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193258. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193259. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193260. sp++;
  193261. }
  193262. }
  193263. if (row_info->bit_depth == 4)
  193264. {
  193265. sp = row;
  193266. for (i = 0; i < row_width; i += 2)
  193267. {
  193268. int msb = *sp & 0xf0;
  193269. int lsb = *sp & 0x0f;
  193270. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193271. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193272. sp++;
  193273. }
  193274. }
  193275. else if (row_info->bit_depth == 8)
  193276. {
  193277. sp = row;
  193278. for (i = 0; i < row_width; i++)
  193279. {
  193280. *sp = gamma_table[*sp];
  193281. sp++;
  193282. }
  193283. }
  193284. else if (row_info->bit_depth == 16)
  193285. {
  193286. sp = row;
  193287. for (i = 0; i < row_width; i++)
  193288. {
  193289. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193290. *sp = (png_byte)((v >> 8) & 0xff);
  193291. *(sp + 1) = (png_byte)(v & 0xff);
  193292. sp += 2;
  193293. }
  193294. }
  193295. break;
  193296. }
  193297. }
  193298. }
  193299. }
  193300. #endif
  193301. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193302. /* Expands a palette row to an RGB or RGBA row depending
  193303. * upon whether you supply trans and num_trans.
  193304. */
  193305. void /* PRIVATE */
  193306. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193307. png_colorp palette, png_bytep trans, int num_trans)
  193308. {
  193309. int shift, value;
  193310. png_bytep sp, dp;
  193311. png_uint_32 i;
  193312. png_uint_32 row_width=row_info->width;
  193313. png_debug(1, "in png_do_expand_palette\n");
  193314. if (
  193315. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193316. row != NULL && row_info != NULL &&
  193317. #endif
  193318. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193319. {
  193320. if (row_info->bit_depth < 8)
  193321. {
  193322. switch (row_info->bit_depth)
  193323. {
  193324. case 1:
  193325. {
  193326. sp = row + (png_size_t)((row_width - 1) >> 3);
  193327. dp = row + (png_size_t)row_width - 1;
  193328. shift = 7 - (int)((row_width + 7) & 0x07);
  193329. for (i = 0; i < row_width; i++)
  193330. {
  193331. if ((*sp >> shift) & 0x01)
  193332. *dp = 1;
  193333. else
  193334. *dp = 0;
  193335. if (shift == 7)
  193336. {
  193337. shift = 0;
  193338. sp--;
  193339. }
  193340. else
  193341. shift++;
  193342. dp--;
  193343. }
  193344. break;
  193345. }
  193346. case 2:
  193347. {
  193348. sp = row + (png_size_t)((row_width - 1) >> 2);
  193349. dp = row + (png_size_t)row_width - 1;
  193350. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193351. for (i = 0; i < row_width; i++)
  193352. {
  193353. value = (*sp >> shift) & 0x03;
  193354. *dp = (png_byte)value;
  193355. if (shift == 6)
  193356. {
  193357. shift = 0;
  193358. sp--;
  193359. }
  193360. else
  193361. shift += 2;
  193362. dp--;
  193363. }
  193364. break;
  193365. }
  193366. case 4:
  193367. {
  193368. sp = row + (png_size_t)((row_width - 1) >> 1);
  193369. dp = row + (png_size_t)row_width - 1;
  193370. shift = (int)((row_width & 0x01) << 2);
  193371. for (i = 0; i < row_width; i++)
  193372. {
  193373. value = (*sp >> shift) & 0x0f;
  193374. *dp = (png_byte)value;
  193375. if (shift == 4)
  193376. {
  193377. shift = 0;
  193378. sp--;
  193379. }
  193380. else
  193381. shift += 4;
  193382. dp--;
  193383. }
  193384. break;
  193385. }
  193386. }
  193387. row_info->bit_depth = 8;
  193388. row_info->pixel_depth = 8;
  193389. row_info->rowbytes = row_width;
  193390. }
  193391. switch (row_info->bit_depth)
  193392. {
  193393. case 8:
  193394. {
  193395. if (trans != NULL)
  193396. {
  193397. sp = row + (png_size_t)row_width - 1;
  193398. dp = row + (png_size_t)(row_width << 2) - 1;
  193399. for (i = 0; i < row_width; i++)
  193400. {
  193401. if ((int)(*sp) >= num_trans)
  193402. *dp-- = 0xff;
  193403. else
  193404. *dp-- = trans[*sp];
  193405. *dp-- = palette[*sp].blue;
  193406. *dp-- = palette[*sp].green;
  193407. *dp-- = palette[*sp].red;
  193408. sp--;
  193409. }
  193410. row_info->bit_depth = 8;
  193411. row_info->pixel_depth = 32;
  193412. row_info->rowbytes = row_width * 4;
  193413. row_info->color_type = 6;
  193414. row_info->channels = 4;
  193415. }
  193416. else
  193417. {
  193418. sp = row + (png_size_t)row_width - 1;
  193419. dp = row + (png_size_t)(row_width * 3) - 1;
  193420. for (i = 0; i < row_width; i++)
  193421. {
  193422. *dp-- = palette[*sp].blue;
  193423. *dp-- = palette[*sp].green;
  193424. *dp-- = palette[*sp].red;
  193425. sp--;
  193426. }
  193427. row_info->bit_depth = 8;
  193428. row_info->pixel_depth = 24;
  193429. row_info->rowbytes = row_width * 3;
  193430. row_info->color_type = 2;
  193431. row_info->channels = 3;
  193432. }
  193433. break;
  193434. }
  193435. }
  193436. }
  193437. }
  193438. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193439. * expanded transparency value is supplied, an alpha channel is built.
  193440. */
  193441. void /* PRIVATE */
  193442. png_do_expand(png_row_infop row_info, png_bytep row,
  193443. png_color_16p trans_value)
  193444. {
  193445. int shift, value;
  193446. png_bytep sp, dp;
  193447. png_uint_32 i;
  193448. png_uint_32 row_width=row_info->width;
  193449. png_debug(1, "in png_do_expand\n");
  193450. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193451. if (row != NULL && row_info != NULL)
  193452. #endif
  193453. {
  193454. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193455. {
  193456. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193457. if (row_info->bit_depth < 8)
  193458. {
  193459. switch (row_info->bit_depth)
  193460. {
  193461. case 1:
  193462. {
  193463. gray = (png_uint_16)((gray&0x01)*0xff);
  193464. sp = row + (png_size_t)((row_width - 1) >> 3);
  193465. dp = row + (png_size_t)row_width - 1;
  193466. shift = 7 - (int)((row_width + 7) & 0x07);
  193467. for (i = 0; i < row_width; i++)
  193468. {
  193469. if ((*sp >> shift) & 0x01)
  193470. *dp = 0xff;
  193471. else
  193472. *dp = 0;
  193473. if (shift == 7)
  193474. {
  193475. shift = 0;
  193476. sp--;
  193477. }
  193478. else
  193479. shift++;
  193480. dp--;
  193481. }
  193482. break;
  193483. }
  193484. case 2:
  193485. {
  193486. gray = (png_uint_16)((gray&0x03)*0x55);
  193487. sp = row + (png_size_t)((row_width - 1) >> 2);
  193488. dp = row + (png_size_t)row_width - 1;
  193489. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193490. for (i = 0; i < row_width; i++)
  193491. {
  193492. value = (*sp >> shift) & 0x03;
  193493. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193494. (value << 6));
  193495. if (shift == 6)
  193496. {
  193497. shift = 0;
  193498. sp--;
  193499. }
  193500. else
  193501. shift += 2;
  193502. dp--;
  193503. }
  193504. break;
  193505. }
  193506. case 4:
  193507. {
  193508. gray = (png_uint_16)((gray&0x0f)*0x11);
  193509. sp = row + (png_size_t)((row_width - 1) >> 1);
  193510. dp = row + (png_size_t)row_width - 1;
  193511. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193512. for (i = 0; i < row_width; i++)
  193513. {
  193514. value = (*sp >> shift) & 0x0f;
  193515. *dp = (png_byte)(value | (value << 4));
  193516. if (shift == 4)
  193517. {
  193518. shift = 0;
  193519. sp--;
  193520. }
  193521. else
  193522. shift = 4;
  193523. dp--;
  193524. }
  193525. break;
  193526. }
  193527. }
  193528. row_info->bit_depth = 8;
  193529. row_info->pixel_depth = 8;
  193530. row_info->rowbytes = row_width;
  193531. }
  193532. if (trans_value != NULL)
  193533. {
  193534. if (row_info->bit_depth == 8)
  193535. {
  193536. gray = gray & 0xff;
  193537. sp = row + (png_size_t)row_width - 1;
  193538. dp = row + (png_size_t)(row_width << 1) - 1;
  193539. for (i = 0; i < row_width; i++)
  193540. {
  193541. if (*sp == gray)
  193542. *dp-- = 0;
  193543. else
  193544. *dp-- = 0xff;
  193545. *dp-- = *sp--;
  193546. }
  193547. }
  193548. else if (row_info->bit_depth == 16)
  193549. {
  193550. png_byte gray_high = (gray >> 8) & 0xff;
  193551. png_byte gray_low = gray & 0xff;
  193552. sp = row + row_info->rowbytes - 1;
  193553. dp = row + (row_info->rowbytes << 1) - 1;
  193554. for (i = 0; i < row_width; i++)
  193555. {
  193556. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193557. {
  193558. *dp-- = 0;
  193559. *dp-- = 0;
  193560. }
  193561. else
  193562. {
  193563. *dp-- = 0xff;
  193564. *dp-- = 0xff;
  193565. }
  193566. *dp-- = *sp--;
  193567. *dp-- = *sp--;
  193568. }
  193569. }
  193570. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193571. row_info->channels = 2;
  193572. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193573. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193574. row_width);
  193575. }
  193576. }
  193577. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193578. {
  193579. if (row_info->bit_depth == 8)
  193580. {
  193581. png_byte red = trans_value->red & 0xff;
  193582. png_byte green = trans_value->green & 0xff;
  193583. png_byte blue = trans_value->blue & 0xff;
  193584. sp = row + (png_size_t)row_info->rowbytes - 1;
  193585. dp = row + (png_size_t)(row_width << 2) - 1;
  193586. for (i = 0; i < row_width; i++)
  193587. {
  193588. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193589. *dp-- = 0;
  193590. else
  193591. *dp-- = 0xff;
  193592. *dp-- = *sp--;
  193593. *dp-- = *sp--;
  193594. *dp-- = *sp--;
  193595. }
  193596. }
  193597. else if (row_info->bit_depth == 16)
  193598. {
  193599. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193600. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193601. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193602. png_byte red_low = trans_value->red & 0xff;
  193603. png_byte green_low = trans_value->green & 0xff;
  193604. png_byte blue_low = trans_value->blue & 0xff;
  193605. sp = row + row_info->rowbytes - 1;
  193606. dp = row + (png_size_t)(row_width << 3) - 1;
  193607. for (i = 0; i < row_width; i++)
  193608. {
  193609. if (*(sp - 5) == red_high &&
  193610. *(sp - 4) == red_low &&
  193611. *(sp - 3) == green_high &&
  193612. *(sp - 2) == green_low &&
  193613. *(sp - 1) == blue_high &&
  193614. *(sp ) == blue_low)
  193615. {
  193616. *dp-- = 0;
  193617. *dp-- = 0;
  193618. }
  193619. else
  193620. {
  193621. *dp-- = 0xff;
  193622. *dp-- = 0xff;
  193623. }
  193624. *dp-- = *sp--;
  193625. *dp-- = *sp--;
  193626. *dp-- = *sp--;
  193627. *dp-- = *sp--;
  193628. *dp-- = *sp--;
  193629. *dp-- = *sp--;
  193630. }
  193631. }
  193632. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193633. row_info->channels = 4;
  193634. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193635. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193636. }
  193637. }
  193638. }
  193639. #endif
  193640. #if defined(PNG_READ_DITHER_SUPPORTED)
  193641. void /* PRIVATE */
  193642. png_do_dither(png_row_infop row_info, png_bytep row,
  193643. png_bytep palette_lookup, png_bytep dither_lookup)
  193644. {
  193645. png_bytep sp, dp;
  193646. png_uint_32 i;
  193647. png_uint_32 row_width=row_info->width;
  193648. png_debug(1, "in png_do_dither\n");
  193649. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193650. if (row != NULL && row_info != NULL)
  193651. #endif
  193652. {
  193653. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193654. palette_lookup && row_info->bit_depth == 8)
  193655. {
  193656. int r, g, b, p;
  193657. sp = row;
  193658. dp = row;
  193659. for (i = 0; i < row_width; i++)
  193660. {
  193661. r = *sp++;
  193662. g = *sp++;
  193663. b = *sp++;
  193664. /* this looks real messy, but the compiler will reduce
  193665. it down to a reasonable formula. For example, with
  193666. 5 bits per color, we get:
  193667. p = (((r >> 3) & 0x1f) << 10) |
  193668. (((g >> 3) & 0x1f) << 5) |
  193669. ((b >> 3) & 0x1f);
  193670. */
  193671. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193672. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193673. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193674. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193675. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193676. (PNG_DITHER_BLUE_BITS)) |
  193677. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193678. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193679. *dp++ = palette_lookup[p];
  193680. }
  193681. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193682. row_info->channels = 1;
  193683. row_info->pixel_depth = row_info->bit_depth;
  193684. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193685. }
  193686. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193687. palette_lookup != NULL && row_info->bit_depth == 8)
  193688. {
  193689. int r, g, b, p;
  193690. sp = row;
  193691. dp = row;
  193692. for (i = 0; i < row_width; i++)
  193693. {
  193694. r = *sp++;
  193695. g = *sp++;
  193696. b = *sp++;
  193697. sp++;
  193698. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193699. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193700. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193701. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193702. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193703. (PNG_DITHER_BLUE_BITS)) |
  193704. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193705. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193706. *dp++ = palette_lookup[p];
  193707. }
  193708. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193709. row_info->channels = 1;
  193710. row_info->pixel_depth = row_info->bit_depth;
  193711. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193712. }
  193713. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193714. dither_lookup && row_info->bit_depth == 8)
  193715. {
  193716. sp = row;
  193717. for (i = 0; i < row_width; i++, sp++)
  193718. {
  193719. *sp = dither_lookup[*sp];
  193720. }
  193721. }
  193722. }
  193723. }
  193724. #endif
  193725. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193726. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193727. static PNG_CONST int png_gamma_shift[] =
  193728. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193729. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193730. * tables, we don't make a full table if we are reducing to 8-bit in
  193731. * the future. Note also how the gamma_16 tables are segmented so that
  193732. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193733. */
  193734. void /* PRIVATE */
  193735. png_build_gamma_table(png_structp png_ptr)
  193736. {
  193737. png_debug(1, "in png_build_gamma_table\n");
  193738. if (png_ptr->bit_depth <= 8)
  193739. {
  193740. int i;
  193741. double g;
  193742. if (png_ptr->screen_gamma > .000001)
  193743. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193744. else
  193745. g = 1.0;
  193746. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193747. (png_uint_32)256);
  193748. for (i = 0; i < 256; i++)
  193749. {
  193750. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193751. g) * 255.0 + .5);
  193752. }
  193753. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193754. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193755. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193756. {
  193757. g = 1.0 / (png_ptr->gamma);
  193758. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193759. (png_uint_32)256);
  193760. for (i = 0; i < 256; i++)
  193761. {
  193762. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193763. g) * 255.0 + .5);
  193764. }
  193765. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193766. (png_uint_32)256);
  193767. if(png_ptr->screen_gamma > 0.000001)
  193768. g = 1.0 / png_ptr->screen_gamma;
  193769. else
  193770. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193771. for (i = 0; i < 256; i++)
  193772. {
  193773. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193774. g) * 255.0 + .5);
  193775. }
  193776. }
  193777. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193778. }
  193779. else
  193780. {
  193781. double g;
  193782. int i, j, shift, num;
  193783. int sig_bit;
  193784. png_uint_32 ig;
  193785. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193786. {
  193787. sig_bit = (int)png_ptr->sig_bit.red;
  193788. if ((int)png_ptr->sig_bit.green > sig_bit)
  193789. sig_bit = png_ptr->sig_bit.green;
  193790. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193791. sig_bit = png_ptr->sig_bit.blue;
  193792. }
  193793. else
  193794. {
  193795. sig_bit = (int)png_ptr->sig_bit.gray;
  193796. }
  193797. if (sig_bit > 0)
  193798. shift = 16 - sig_bit;
  193799. else
  193800. shift = 0;
  193801. if (png_ptr->transformations & PNG_16_TO_8)
  193802. {
  193803. if (shift < (16 - PNG_MAX_GAMMA_8))
  193804. shift = (16 - PNG_MAX_GAMMA_8);
  193805. }
  193806. if (shift > 8)
  193807. shift = 8;
  193808. if (shift < 0)
  193809. shift = 0;
  193810. png_ptr->gamma_shift = (png_byte)shift;
  193811. num = (1 << (8 - shift));
  193812. if (png_ptr->screen_gamma > .000001)
  193813. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193814. else
  193815. g = 1.0;
  193816. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193817. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193818. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193819. {
  193820. double fin, fout;
  193821. png_uint_32 last, max;
  193822. for (i = 0; i < num; i++)
  193823. {
  193824. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193825. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193826. }
  193827. g = 1.0 / g;
  193828. last = 0;
  193829. for (i = 0; i < 256; i++)
  193830. {
  193831. fout = ((double)i + 0.5) / 256.0;
  193832. fin = pow(fout, g);
  193833. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193834. while (last <= max)
  193835. {
  193836. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193837. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193838. (png_uint_16)i | ((png_uint_16)i << 8));
  193839. last++;
  193840. }
  193841. }
  193842. while (last < ((png_uint_32)num << 8))
  193843. {
  193844. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193845. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193846. last++;
  193847. }
  193848. }
  193849. else
  193850. {
  193851. for (i = 0; i < num; i++)
  193852. {
  193853. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193854. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193855. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193856. for (j = 0; j < 256; j++)
  193857. {
  193858. png_ptr->gamma_16_table[i][j] =
  193859. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193860. 65535.0, g) * 65535.0 + .5);
  193861. }
  193862. }
  193863. }
  193864. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193865. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193866. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193867. {
  193868. g = 1.0 / (png_ptr->gamma);
  193869. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193870. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193871. for (i = 0; i < num; i++)
  193872. {
  193873. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193874. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193875. ig = (((png_uint_32)i *
  193876. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193877. for (j = 0; j < 256; j++)
  193878. {
  193879. png_ptr->gamma_16_to_1[i][j] =
  193880. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193881. 65535.0, g) * 65535.0 + .5);
  193882. }
  193883. }
  193884. if(png_ptr->screen_gamma > 0.000001)
  193885. g = 1.0 / png_ptr->screen_gamma;
  193886. else
  193887. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193888. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193889. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193890. for (i = 0; i < num; i++)
  193891. {
  193892. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193893. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193894. ig = (((png_uint_32)i *
  193895. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193896. for (j = 0; j < 256; j++)
  193897. {
  193898. png_ptr->gamma_16_from_1[i][j] =
  193899. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193900. 65535.0, g) * 65535.0 + .5);
  193901. }
  193902. }
  193903. }
  193904. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193905. }
  193906. }
  193907. #endif
  193908. /* To do: install integer version of png_build_gamma_table here */
  193909. #endif
  193910. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193911. /* undoes intrapixel differencing */
  193912. void /* PRIVATE */
  193913. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193914. {
  193915. png_debug(1, "in png_do_read_intrapixel\n");
  193916. if (
  193917. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193918. row != NULL && row_info != NULL &&
  193919. #endif
  193920. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193921. {
  193922. int bytes_per_pixel;
  193923. png_uint_32 row_width = row_info->width;
  193924. if (row_info->bit_depth == 8)
  193925. {
  193926. png_bytep rp;
  193927. png_uint_32 i;
  193928. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193929. bytes_per_pixel = 3;
  193930. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193931. bytes_per_pixel = 4;
  193932. else
  193933. return;
  193934. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193935. {
  193936. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193937. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193938. }
  193939. }
  193940. else if (row_info->bit_depth == 16)
  193941. {
  193942. png_bytep rp;
  193943. png_uint_32 i;
  193944. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193945. bytes_per_pixel = 6;
  193946. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193947. bytes_per_pixel = 8;
  193948. else
  193949. return;
  193950. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193951. {
  193952. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193953. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193954. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193955. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193956. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193957. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193958. *(rp+1) = (png_byte)(red & 0xff);
  193959. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193960. *(rp+5) = (png_byte)(blue & 0xff);
  193961. }
  193962. }
  193963. }
  193964. }
  193965. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193966. #endif /* PNG_READ_SUPPORTED */
  193967. /*** End of inlined file: pngrtran.c ***/
  193968. /*** Start of inlined file: pngrutil.c ***/
  193969. /* pngrutil.c - utilities to read a PNG file
  193970. *
  193971. * Last changed in libpng 1.2.21 [October 4, 2007]
  193972. * For conditions of distribution and use, see copyright notice in png.h
  193973. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193974. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193975. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193976. *
  193977. * This file contains routines that are only called from within
  193978. * libpng itself during the course of reading an image.
  193979. */
  193980. #define PNG_INTERNAL
  193981. #if defined(PNG_READ_SUPPORTED)
  193982. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193983. # define WIN32_WCE_OLD
  193984. #endif
  193985. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193986. # if defined(WIN32_WCE_OLD)
  193987. /* strtod() function is not supported on WindowsCE */
  193988. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193989. {
  193990. double result = 0;
  193991. int len;
  193992. wchar_t *str, *end;
  193993. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193994. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193995. if ( NULL != str )
  193996. {
  193997. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193998. result = wcstod(str, &end);
  193999. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  194000. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  194001. png_free(png_ptr, str);
  194002. }
  194003. return result;
  194004. }
  194005. # else
  194006. # define png_strtod(p,a,b) strtod(a,b)
  194007. # endif
  194008. #endif
  194009. png_uint_32 PNGAPI
  194010. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  194011. {
  194012. png_uint_32 i = png_get_uint_32(buf);
  194013. if (i > PNG_UINT_31_MAX)
  194014. png_error(png_ptr, "PNG unsigned integer out of range.");
  194015. return (i);
  194016. }
  194017. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  194018. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  194019. png_uint_32 PNGAPI
  194020. png_get_uint_32(png_bytep buf)
  194021. {
  194022. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  194023. ((png_uint_32)(*(buf + 1)) << 16) +
  194024. ((png_uint_32)(*(buf + 2)) << 8) +
  194025. (png_uint_32)(*(buf + 3));
  194026. return (i);
  194027. }
  194028. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  194029. * data is stored in the PNG file in two's complement format, and it is
  194030. * assumed that the machine format for signed integers is the same. */
  194031. png_int_32 PNGAPI
  194032. png_get_int_32(png_bytep buf)
  194033. {
  194034. png_int_32 i = ((png_int_32)(*buf) << 24) +
  194035. ((png_int_32)(*(buf + 1)) << 16) +
  194036. ((png_int_32)(*(buf + 2)) << 8) +
  194037. (png_int_32)(*(buf + 3));
  194038. return (i);
  194039. }
  194040. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  194041. png_uint_16 PNGAPI
  194042. png_get_uint_16(png_bytep buf)
  194043. {
  194044. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194045. (png_uint_16)(*(buf + 1)));
  194046. return (i);
  194047. }
  194048. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  194049. /* Read data, and (optionally) run it through the CRC. */
  194050. void /* PRIVATE */
  194051. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  194052. {
  194053. if(png_ptr == NULL) return;
  194054. png_read_data(png_ptr, buf, length);
  194055. png_calculate_crc(png_ptr, buf, length);
  194056. }
  194057. /* Optionally skip data and then check the CRC. Depending on whether we
  194058. are reading a ancillary or critical chunk, and how the program has set
  194059. things up, we may calculate the CRC on the data and print a message.
  194060. Returns '1' if there was a CRC error, '0' otherwise. */
  194061. int /* PRIVATE */
  194062. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  194063. {
  194064. png_size_t i;
  194065. png_size_t istop = png_ptr->zbuf_size;
  194066. for (i = (png_size_t)skip; i > istop; i -= istop)
  194067. {
  194068. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194069. }
  194070. if (i)
  194071. {
  194072. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194073. }
  194074. if (png_crc_error(png_ptr))
  194075. {
  194076. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194077. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194078. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194079. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194080. {
  194081. png_chunk_warning(png_ptr, "CRC error");
  194082. }
  194083. else
  194084. {
  194085. png_chunk_error(png_ptr, "CRC error");
  194086. }
  194087. return (1);
  194088. }
  194089. return (0);
  194090. }
  194091. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194092. the data it has read thus far. */
  194093. int /* PRIVATE */
  194094. png_crc_error(png_structp png_ptr)
  194095. {
  194096. png_byte crc_bytes[4];
  194097. png_uint_32 crc;
  194098. int need_crc = 1;
  194099. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194100. {
  194101. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194102. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194103. need_crc = 0;
  194104. }
  194105. else /* critical */
  194106. {
  194107. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194108. need_crc = 0;
  194109. }
  194110. png_read_data(png_ptr, crc_bytes, 4);
  194111. if (need_crc)
  194112. {
  194113. crc = png_get_uint_32(crc_bytes);
  194114. return ((int)(crc != png_ptr->crc));
  194115. }
  194116. else
  194117. return (0);
  194118. }
  194119. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194120. defined(PNG_READ_iCCP_SUPPORTED)
  194121. /*
  194122. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194123. * points at an allocated area holding the contents of a chunk with a
  194124. * trailing compressed part. What we get back is an allocated area
  194125. * holding the original prefix part and an uncompressed version of the
  194126. * trailing part (the malloc area passed in is freed).
  194127. */
  194128. png_charp /* PRIVATE */
  194129. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194130. png_charp chunkdata, png_size_t chunklength,
  194131. png_size_t prefix_size, png_size_t *newlength)
  194132. {
  194133. static PNG_CONST char msg[] = "Error decoding compressed text";
  194134. png_charp text;
  194135. png_size_t text_size;
  194136. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194137. {
  194138. int ret = Z_OK;
  194139. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194140. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194141. png_ptr->zstream.next_out = png_ptr->zbuf;
  194142. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194143. text_size = 0;
  194144. text = NULL;
  194145. while (png_ptr->zstream.avail_in)
  194146. {
  194147. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194148. if (ret != Z_OK && ret != Z_STREAM_END)
  194149. {
  194150. if (png_ptr->zstream.msg != NULL)
  194151. png_warning(png_ptr, png_ptr->zstream.msg);
  194152. else
  194153. png_warning(png_ptr, msg);
  194154. inflateReset(&png_ptr->zstream);
  194155. png_ptr->zstream.avail_in = 0;
  194156. if (text == NULL)
  194157. {
  194158. text_size = prefix_size + png_sizeof(msg) + 1;
  194159. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194160. if (text == NULL)
  194161. {
  194162. png_free(png_ptr,chunkdata);
  194163. png_error(png_ptr,"Not enough memory to decompress chunk");
  194164. }
  194165. png_memcpy(text, chunkdata, prefix_size);
  194166. }
  194167. text[text_size - 1] = 0x00;
  194168. /* Copy what we can of the error message into the text chunk */
  194169. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194170. text_size = png_sizeof(msg) > text_size ? text_size :
  194171. png_sizeof(msg);
  194172. png_memcpy(text + prefix_size, msg, text_size + 1);
  194173. break;
  194174. }
  194175. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194176. {
  194177. if (text == NULL)
  194178. {
  194179. text_size = prefix_size +
  194180. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194181. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194182. if (text == NULL)
  194183. {
  194184. png_free(png_ptr,chunkdata);
  194185. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194186. }
  194187. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194188. text_size - prefix_size);
  194189. png_memcpy(text, chunkdata, prefix_size);
  194190. *(text + text_size) = 0x00;
  194191. }
  194192. else
  194193. {
  194194. png_charp tmp;
  194195. tmp = text;
  194196. text = (png_charp)png_malloc_warn(png_ptr,
  194197. (png_uint_32)(text_size +
  194198. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194199. if (text == NULL)
  194200. {
  194201. png_free(png_ptr, tmp);
  194202. png_free(png_ptr, chunkdata);
  194203. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194204. }
  194205. png_memcpy(text, tmp, text_size);
  194206. png_free(png_ptr, tmp);
  194207. png_memcpy(text + text_size, png_ptr->zbuf,
  194208. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194209. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194210. *(text + text_size) = 0x00;
  194211. }
  194212. if (ret == Z_STREAM_END)
  194213. break;
  194214. else
  194215. {
  194216. png_ptr->zstream.next_out = png_ptr->zbuf;
  194217. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194218. }
  194219. }
  194220. }
  194221. if (ret != Z_STREAM_END)
  194222. {
  194223. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194224. char umsg[52];
  194225. if (ret == Z_BUF_ERROR)
  194226. png_snprintf(umsg, 52,
  194227. "Buffer error in compressed datastream in %s chunk",
  194228. png_ptr->chunk_name);
  194229. else if (ret == Z_DATA_ERROR)
  194230. png_snprintf(umsg, 52,
  194231. "Data error in compressed datastream in %s chunk",
  194232. png_ptr->chunk_name);
  194233. else
  194234. png_snprintf(umsg, 52,
  194235. "Incomplete compressed datastream in %s chunk",
  194236. png_ptr->chunk_name);
  194237. png_warning(png_ptr, umsg);
  194238. #else
  194239. png_warning(png_ptr,
  194240. "Incomplete compressed datastream in chunk other than IDAT");
  194241. #endif
  194242. text_size=prefix_size;
  194243. if (text == NULL)
  194244. {
  194245. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194246. if (text == NULL)
  194247. {
  194248. png_free(png_ptr, chunkdata);
  194249. png_error(png_ptr,"Not enough memory for text.");
  194250. }
  194251. png_memcpy(text, chunkdata, prefix_size);
  194252. }
  194253. *(text + text_size) = 0x00;
  194254. }
  194255. inflateReset(&png_ptr->zstream);
  194256. png_ptr->zstream.avail_in = 0;
  194257. png_free(png_ptr, chunkdata);
  194258. chunkdata = text;
  194259. *newlength=text_size;
  194260. }
  194261. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194262. {
  194263. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194264. char umsg[50];
  194265. png_snprintf(umsg, 50,
  194266. "Unknown zTXt compression type %d", comp_type);
  194267. png_warning(png_ptr, umsg);
  194268. #else
  194269. png_warning(png_ptr, "Unknown zTXt compression type");
  194270. #endif
  194271. *(chunkdata + prefix_size) = 0x00;
  194272. *newlength=prefix_size;
  194273. }
  194274. return chunkdata;
  194275. }
  194276. #endif
  194277. /* read and check the IDHR chunk */
  194278. void /* PRIVATE */
  194279. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194280. {
  194281. png_byte buf[13];
  194282. png_uint_32 width, height;
  194283. int bit_depth, color_type, compression_type, filter_type;
  194284. int interlace_type;
  194285. png_debug(1, "in png_handle_IHDR\n");
  194286. if (png_ptr->mode & PNG_HAVE_IHDR)
  194287. png_error(png_ptr, "Out of place IHDR");
  194288. /* check the length */
  194289. if (length != 13)
  194290. png_error(png_ptr, "Invalid IHDR chunk");
  194291. png_ptr->mode |= PNG_HAVE_IHDR;
  194292. png_crc_read(png_ptr, buf, 13);
  194293. png_crc_finish(png_ptr, 0);
  194294. width = png_get_uint_31(png_ptr, buf);
  194295. height = png_get_uint_31(png_ptr, buf + 4);
  194296. bit_depth = buf[8];
  194297. color_type = buf[9];
  194298. compression_type = buf[10];
  194299. filter_type = buf[11];
  194300. interlace_type = buf[12];
  194301. /* set internal variables */
  194302. png_ptr->width = width;
  194303. png_ptr->height = height;
  194304. png_ptr->bit_depth = (png_byte)bit_depth;
  194305. png_ptr->interlaced = (png_byte)interlace_type;
  194306. png_ptr->color_type = (png_byte)color_type;
  194307. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194308. png_ptr->filter_type = (png_byte)filter_type;
  194309. #endif
  194310. png_ptr->compression_type = (png_byte)compression_type;
  194311. /* find number of channels */
  194312. switch (png_ptr->color_type)
  194313. {
  194314. case PNG_COLOR_TYPE_GRAY:
  194315. case PNG_COLOR_TYPE_PALETTE:
  194316. png_ptr->channels = 1;
  194317. break;
  194318. case PNG_COLOR_TYPE_RGB:
  194319. png_ptr->channels = 3;
  194320. break;
  194321. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194322. png_ptr->channels = 2;
  194323. break;
  194324. case PNG_COLOR_TYPE_RGB_ALPHA:
  194325. png_ptr->channels = 4;
  194326. break;
  194327. }
  194328. /* set up other useful info */
  194329. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194330. png_ptr->channels);
  194331. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194332. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194333. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194334. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194335. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194336. color_type, interlace_type, compression_type, filter_type);
  194337. }
  194338. /* read and check the palette */
  194339. void /* PRIVATE */
  194340. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194341. {
  194342. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194343. int num, i;
  194344. #ifndef PNG_NO_POINTER_INDEXING
  194345. png_colorp pal_ptr;
  194346. #endif
  194347. png_debug(1, "in png_handle_PLTE\n");
  194348. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194349. png_error(png_ptr, "Missing IHDR before PLTE");
  194350. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194351. {
  194352. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194353. png_crc_finish(png_ptr, length);
  194354. return;
  194355. }
  194356. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194357. png_error(png_ptr, "Duplicate PLTE chunk");
  194358. png_ptr->mode |= PNG_HAVE_PLTE;
  194359. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194360. {
  194361. png_warning(png_ptr,
  194362. "Ignoring PLTE chunk in grayscale PNG");
  194363. png_crc_finish(png_ptr, length);
  194364. return;
  194365. }
  194366. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194367. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194368. {
  194369. png_crc_finish(png_ptr, length);
  194370. return;
  194371. }
  194372. #endif
  194373. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194374. {
  194375. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194376. {
  194377. png_warning(png_ptr, "Invalid palette chunk");
  194378. png_crc_finish(png_ptr, length);
  194379. return;
  194380. }
  194381. else
  194382. {
  194383. png_error(png_ptr, "Invalid palette chunk");
  194384. }
  194385. }
  194386. num = (int)length / 3;
  194387. #ifndef PNG_NO_POINTER_INDEXING
  194388. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194389. {
  194390. png_byte buf[3];
  194391. png_crc_read(png_ptr, buf, 3);
  194392. pal_ptr->red = buf[0];
  194393. pal_ptr->green = buf[1];
  194394. pal_ptr->blue = buf[2];
  194395. }
  194396. #else
  194397. for (i = 0; i < num; i++)
  194398. {
  194399. png_byte buf[3];
  194400. png_crc_read(png_ptr, buf, 3);
  194401. /* don't depend upon png_color being any order */
  194402. palette[i].red = buf[0];
  194403. palette[i].green = buf[1];
  194404. palette[i].blue = buf[2];
  194405. }
  194406. #endif
  194407. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194408. whatever the normal CRC configuration tells us. However, if we
  194409. have an RGB image, the PLTE can be considered ancillary, so
  194410. we will act as though it is. */
  194411. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194412. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194413. #endif
  194414. {
  194415. png_crc_finish(png_ptr, 0);
  194416. }
  194417. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194418. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194419. {
  194420. /* If we don't want to use the data from an ancillary chunk,
  194421. we have two options: an error abort, or a warning and we
  194422. ignore the data in this chunk (which should be OK, since
  194423. it's considered ancillary for a RGB or RGBA image). */
  194424. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194425. {
  194426. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194427. {
  194428. png_chunk_error(png_ptr, "CRC error");
  194429. }
  194430. else
  194431. {
  194432. png_chunk_warning(png_ptr, "CRC error");
  194433. return;
  194434. }
  194435. }
  194436. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194437. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194438. {
  194439. png_chunk_warning(png_ptr, "CRC error");
  194440. }
  194441. }
  194442. #endif
  194443. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194444. #if defined(PNG_READ_tRNS_SUPPORTED)
  194445. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194446. {
  194447. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194448. {
  194449. if (png_ptr->num_trans > (png_uint_16)num)
  194450. {
  194451. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194452. png_ptr->num_trans = (png_uint_16)num;
  194453. }
  194454. if (info_ptr->num_trans > (png_uint_16)num)
  194455. {
  194456. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194457. info_ptr->num_trans = (png_uint_16)num;
  194458. }
  194459. }
  194460. }
  194461. #endif
  194462. }
  194463. void /* PRIVATE */
  194464. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194465. {
  194466. png_debug(1, "in png_handle_IEND\n");
  194467. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194468. {
  194469. png_error(png_ptr, "No image in file");
  194470. }
  194471. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194472. if (length != 0)
  194473. {
  194474. png_warning(png_ptr, "Incorrect IEND chunk length");
  194475. }
  194476. png_crc_finish(png_ptr, length);
  194477. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194478. }
  194479. #if defined(PNG_READ_gAMA_SUPPORTED)
  194480. void /* PRIVATE */
  194481. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194482. {
  194483. png_fixed_point igamma;
  194484. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194485. float file_gamma;
  194486. #endif
  194487. png_byte buf[4];
  194488. png_debug(1, "in png_handle_gAMA\n");
  194489. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194490. png_error(png_ptr, "Missing IHDR before gAMA");
  194491. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194492. {
  194493. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194494. png_crc_finish(png_ptr, length);
  194495. return;
  194496. }
  194497. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194498. /* Should be an error, but we can cope with it */
  194499. png_warning(png_ptr, "Out of place gAMA chunk");
  194500. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194501. #if defined(PNG_READ_sRGB_SUPPORTED)
  194502. && !(info_ptr->valid & PNG_INFO_sRGB)
  194503. #endif
  194504. )
  194505. {
  194506. png_warning(png_ptr, "Duplicate gAMA chunk");
  194507. png_crc_finish(png_ptr, length);
  194508. return;
  194509. }
  194510. if (length != 4)
  194511. {
  194512. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194513. png_crc_finish(png_ptr, length);
  194514. return;
  194515. }
  194516. png_crc_read(png_ptr, buf, 4);
  194517. if (png_crc_finish(png_ptr, 0))
  194518. return;
  194519. igamma = (png_fixed_point)png_get_uint_32(buf);
  194520. /* check for zero gamma */
  194521. if (igamma == 0)
  194522. {
  194523. png_warning(png_ptr,
  194524. "Ignoring gAMA chunk with gamma=0");
  194525. return;
  194526. }
  194527. #if defined(PNG_READ_sRGB_SUPPORTED)
  194528. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194529. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194530. {
  194531. png_warning(png_ptr,
  194532. "Ignoring incorrect gAMA value when sRGB is also present");
  194533. #ifndef PNG_NO_CONSOLE_IO
  194534. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194535. #endif
  194536. return;
  194537. }
  194538. #endif /* PNG_READ_sRGB_SUPPORTED */
  194539. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194540. file_gamma = (float)igamma / (float)100000.0;
  194541. # ifdef PNG_READ_GAMMA_SUPPORTED
  194542. png_ptr->gamma = file_gamma;
  194543. # endif
  194544. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194545. #endif
  194546. #ifdef PNG_FIXED_POINT_SUPPORTED
  194547. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194548. #endif
  194549. }
  194550. #endif
  194551. #if defined(PNG_READ_sBIT_SUPPORTED)
  194552. void /* PRIVATE */
  194553. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194554. {
  194555. png_size_t truelen;
  194556. png_byte buf[4];
  194557. png_debug(1, "in png_handle_sBIT\n");
  194558. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194559. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194560. png_error(png_ptr, "Missing IHDR before sBIT");
  194561. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194562. {
  194563. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194564. png_crc_finish(png_ptr, length);
  194565. return;
  194566. }
  194567. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194568. {
  194569. /* Should be an error, but we can cope with it */
  194570. png_warning(png_ptr, "Out of place sBIT chunk");
  194571. }
  194572. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194573. {
  194574. png_warning(png_ptr, "Duplicate sBIT chunk");
  194575. png_crc_finish(png_ptr, length);
  194576. return;
  194577. }
  194578. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194579. truelen = 3;
  194580. else
  194581. truelen = (png_size_t)png_ptr->channels;
  194582. if (length != truelen || length > 4)
  194583. {
  194584. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194585. png_crc_finish(png_ptr, length);
  194586. return;
  194587. }
  194588. png_crc_read(png_ptr, buf, truelen);
  194589. if (png_crc_finish(png_ptr, 0))
  194590. return;
  194591. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194592. {
  194593. png_ptr->sig_bit.red = buf[0];
  194594. png_ptr->sig_bit.green = buf[1];
  194595. png_ptr->sig_bit.blue = buf[2];
  194596. png_ptr->sig_bit.alpha = buf[3];
  194597. }
  194598. else
  194599. {
  194600. png_ptr->sig_bit.gray = buf[0];
  194601. png_ptr->sig_bit.red = buf[0];
  194602. png_ptr->sig_bit.green = buf[0];
  194603. png_ptr->sig_bit.blue = buf[0];
  194604. png_ptr->sig_bit.alpha = buf[1];
  194605. }
  194606. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194607. }
  194608. #endif
  194609. #if defined(PNG_READ_cHRM_SUPPORTED)
  194610. void /* PRIVATE */
  194611. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194612. {
  194613. png_byte buf[4];
  194614. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194615. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194616. #endif
  194617. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194618. int_y_green, int_x_blue, int_y_blue;
  194619. png_uint_32 uint_x, uint_y;
  194620. png_debug(1, "in png_handle_cHRM\n");
  194621. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194622. png_error(png_ptr, "Missing IHDR before cHRM");
  194623. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194624. {
  194625. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194626. png_crc_finish(png_ptr, length);
  194627. return;
  194628. }
  194629. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194630. /* Should be an error, but we can cope with it */
  194631. png_warning(png_ptr, "Missing PLTE before cHRM");
  194632. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194633. #if defined(PNG_READ_sRGB_SUPPORTED)
  194634. && !(info_ptr->valid & PNG_INFO_sRGB)
  194635. #endif
  194636. )
  194637. {
  194638. png_warning(png_ptr, "Duplicate cHRM chunk");
  194639. png_crc_finish(png_ptr, length);
  194640. return;
  194641. }
  194642. if (length != 32)
  194643. {
  194644. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194645. png_crc_finish(png_ptr, length);
  194646. return;
  194647. }
  194648. png_crc_read(png_ptr, buf, 4);
  194649. uint_x = png_get_uint_32(buf);
  194650. png_crc_read(png_ptr, buf, 4);
  194651. uint_y = png_get_uint_32(buf);
  194652. if (uint_x > 80000L || uint_y > 80000L ||
  194653. uint_x + uint_y > 100000L)
  194654. {
  194655. png_warning(png_ptr, "Invalid cHRM white point");
  194656. png_crc_finish(png_ptr, 24);
  194657. return;
  194658. }
  194659. int_x_white = (png_fixed_point)uint_x;
  194660. int_y_white = (png_fixed_point)uint_y;
  194661. png_crc_read(png_ptr, buf, 4);
  194662. uint_x = png_get_uint_32(buf);
  194663. png_crc_read(png_ptr, buf, 4);
  194664. uint_y = png_get_uint_32(buf);
  194665. if (uint_x + uint_y > 100000L)
  194666. {
  194667. png_warning(png_ptr, "Invalid cHRM red point");
  194668. png_crc_finish(png_ptr, 16);
  194669. return;
  194670. }
  194671. int_x_red = (png_fixed_point)uint_x;
  194672. int_y_red = (png_fixed_point)uint_y;
  194673. png_crc_read(png_ptr, buf, 4);
  194674. uint_x = png_get_uint_32(buf);
  194675. png_crc_read(png_ptr, buf, 4);
  194676. uint_y = png_get_uint_32(buf);
  194677. if (uint_x + uint_y > 100000L)
  194678. {
  194679. png_warning(png_ptr, "Invalid cHRM green point");
  194680. png_crc_finish(png_ptr, 8);
  194681. return;
  194682. }
  194683. int_x_green = (png_fixed_point)uint_x;
  194684. int_y_green = (png_fixed_point)uint_y;
  194685. png_crc_read(png_ptr, buf, 4);
  194686. uint_x = png_get_uint_32(buf);
  194687. png_crc_read(png_ptr, buf, 4);
  194688. uint_y = png_get_uint_32(buf);
  194689. if (uint_x + uint_y > 100000L)
  194690. {
  194691. png_warning(png_ptr, "Invalid cHRM blue point");
  194692. png_crc_finish(png_ptr, 0);
  194693. return;
  194694. }
  194695. int_x_blue = (png_fixed_point)uint_x;
  194696. int_y_blue = (png_fixed_point)uint_y;
  194697. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194698. white_x = (float)int_x_white / (float)100000.0;
  194699. white_y = (float)int_y_white / (float)100000.0;
  194700. red_x = (float)int_x_red / (float)100000.0;
  194701. red_y = (float)int_y_red / (float)100000.0;
  194702. green_x = (float)int_x_green / (float)100000.0;
  194703. green_y = (float)int_y_green / (float)100000.0;
  194704. blue_x = (float)int_x_blue / (float)100000.0;
  194705. blue_y = (float)int_y_blue / (float)100000.0;
  194706. #endif
  194707. #if defined(PNG_READ_sRGB_SUPPORTED)
  194708. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194709. {
  194710. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194711. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194712. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194713. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194714. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194715. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194716. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194717. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194718. {
  194719. png_warning(png_ptr,
  194720. "Ignoring incorrect cHRM value when sRGB is also present");
  194721. #ifndef PNG_NO_CONSOLE_IO
  194722. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194723. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194724. white_x, white_y, red_x, red_y);
  194725. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194726. green_x, green_y, blue_x, blue_y);
  194727. #else
  194728. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194729. int_x_white, int_y_white, int_x_red, int_y_red);
  194730. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194731. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194732. #endif
  194733. #endif /* PNG_NO_CONSOLE_IO */
  194734. }
  194735. png_crc_finish(png_ptr, 0);
  194736. return;
  194737. }
  194738. #endif /* PNG_READ_sRGB_SUPPORTED */
  194739. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194740. png_set_cHRM(png_ptr, info_ptr,
  194741. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194742. #endif
  194743. #ifdef PNG_FIXED_POINT_SUPPORTED
  194744. png_set_cHRM_fixed(png_ptr, info_ptr,
  194745. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194746. int_y_green, int_x_blue, int_y_blue);
  194747. #endif
  194748. if (png_crc_finish(png_ptr, 0))
  194749. return;
  194750. }
  194751. #endif
  194752. #if defined(PNG_READ_sRGB_SUPPORTED)
  194753. void /* PRIVATE */
  194754. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194755. {
  194756. int intent;
  194757. png_byte buf[1];
  194758. png_debug(1, "in png_handle_sRGB\n");
  194759. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194760. png_error(png_ptr, "Missing IHDR before sRGB");
  194761. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194762. {
  194763. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194764. png_crc_finish(png_ptr, length);
  194765. return;
  194766. }
  194767. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194768. /* Should be an error, but we can cope with it */
  194769. png_warning(png_ptr, "Out of place sRGB chunk");
  194770. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194771. {
  194772. png_warning(png_ptr, "Duplicate sRGB chunk");
  194773. png_crc_finish(png_ptr, length);
  194774. return;
  194775. }
  194776. if (length != 1)
  194777. {
  194778. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194779. png_crc_finish(png_ptr, length);
  194780. return;
  194781. }
  194782. png_crc_read(png_ptr, buf, 1);
  194783. if (png_crc_finish(png_ptr, 0))
  194784. return;
  194785. intent = buf[0];
  194786. /* check for bad intent */
  194787. if (intent >= PNG_sRGB_INTENT_LAST)
  194788. {
  194789. png_warning(png_ptr, "Unknown sRGB intent");
  194790. return;
  194791. }
  194792. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194793. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194794. {
  194795. png_fixed_point igamma;
  194796. #ifdef PNG_FIXED_POINT_SUPPORTED
  194797. igamma=info_ptr->int_gamma;
  194798. #else
  194799. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194800. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194801. # endif
  194802. #endif
  194803. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194804. {
  194805. png_warning(png_ptr,
  194806. "Ignoring incorrect gAMA value when sRGB is also present");
  194807. #ifndef PNG_NO_CONSOLE_IO
  194808. # ifdef PNG_FIXED_POINT_SUPPORTED
  194809. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194810. # else
  194811. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194812. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194813. # endif
  194814. # endif
  194815. #endif
  194816. }
  194817. }
  194818. #endif /* PNG_READ_gAMA_SUPPORTED */
  194819. #ifdef PNG_READ_cHRM_SUPPORTED
  194820. #ifdef PNG_FIXED_POINT_SUPPORTED
  194821. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194822. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194823. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194824. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194825. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194826. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194827. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194828. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194829. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194830. {
  194831. png_warning(png_ptr,
  194832. "Ignoring incorrect cHRM value when sRGB is also present");
  194833. }
  194834. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194835. #endif /* PNG_READ_cHRM_SUPPORTED */
  194836. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194837. }
  194838. #endif /* PNG_READ_sRGB_SUPPORTED */
  194839. #if defined(PNG_READ_iCCP_SUPPORTED)
  194840. void /* PRIVATE */
  194841. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194842. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194843. {
  194844. png_charp chunkdata;
  194845. png_byte compression_type;
  194846. png_bytep pC;
  194847. png_charp profile;
  194848. png_uint_32 skip = 0;
  194849. png_uint_32 profile_size, profile_length;
  194850. png_size_t slength, prefix_length, data_length;
  194851. png_debug(1, "in png_handle_iCCP\n");
  194852. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194853. png_error(png_ptr, "Missing IHDR before iCCP");
  194854. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194855. {
  194856. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194857. png_crc_finish(png_ptr, length);
  194858. return;
  194859. }
  194860. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194861. /* Should be an error, but we can cope with it */
  194862. png_warning(png_ptr, "Out of place iCCP chunk");
  194863. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194864. {
  194865. png_warning(png_ptr, "Duplicate iCCP chunk");
  194866. png_crc_finish(png_ptr, length);
  194867. return;
  194868. }
  194869. #ifdef PNG_MAX_MALLOC_64K
  194870. if (length > (png_uint_32)65535L)
  194871. {
  194872. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194873. skip = length - (png_uint_32)65535L;
  194874. length = (png_uint_32)65535L;
  194875. }
  194876. #endif
  194877. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194878. slength = (png_size_t)length;
  194879. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194880. if (png_crc_finish(png_ptr, skip))
  194881. {
  194882. png_free(png_ptr, chunkdata);
  194883. return;
  194884. }
  194885. chunkdata[slength] = 0x00;
  194886. for (profile = chunkdata; *profile; profile++)
  194887. /* empty loop to find end of name */ ;
  194888. ++profile;
  194889. /* there should be at least one zero (the compression type byte)
  194890. following the separator, and we should be on it */
  194891. if ( profile >= chunkdata + slength - 1)
  194892. {
  194893. png_free(png_ptr, chunkdata);
  194894. png_warning(png_ptr, "Malformed iCCP chunk");
  194895. return;
  194896. }
  194897. /* compression_type should always be zero */
  194898. compression_type = *profile++;
  194899. if (compression_type)
  194900. {
  194901. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194902. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194903. wrote nonzero) */
  194904. }
  194905. prefix_length = profile - chunkdata;
  194906. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194907. slength, prefix_length, &data_length);
  194908. profile_length = data_length - prefix_length;
  194909. if ( prefix_length > data_length || profile_length < 4)
  194910. {
  194911. png_free(png_ptr, chunkdata);
  194912. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194913. return;
  194914. }
  194915. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194916. pC = (png_bytep)(chunkdata+prefix_length);
  194917. profile_size = ((*(pC ))<<24) |
  194918. ((*(pC+1))<<16) |
  194919. ((*(pC+2))<< 8) |
  194920. ((*(pC+3)) );
  194921. if(profile_size < profile_length)
  194922. profile_length = profile_size;
  194923. if(profile_size > profile_length)
  194924. {
  194925. png_free(png_ptr, chunkdata);
  194926. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194927. return;
  194928. }
  194929. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194930. chunkdata + prefix_length, profile_length);
  194931. png_free(png_ptr, chunkdata);
  194932. }
  194933. #endif /* PNG_READ_iCCP_SUPPORTED */
  194934. #if defined(PNG_READ_sPLT_SUPPORTED)
  194935. void /* PRIVATE */
  194936. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194937. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194938. {
  194939. png_bytep chunkdata;
  194940. png_bytep entry_start;
  194941. png_sPLT_t new_palette;
  194942. #ifdef PNG_NO_POINTER_INDEXING
  194943. png_sPLT_entryp pp;
  194944. #endif
  194945. int data_length, entry_size, i;
  194946. png_uint_32 skip = 0;
  194947. png_size_t slength;
  194948. png_debug(1, "in png_handle_sPLT\n");
  194949. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194950. png_error(png_ptr, "Missing IHDR before sPLT");
  194951. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194952. {
  194953. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194954. png_crc_finish(png_ptr, length);
  194955. return;
  194956. }
  194957. #ifdef PNG_MAX_MALLOC_64K
  194958. if (length > (png_uint_32)65535L)
  194959. {
  194960. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194961. skip = length - (png_uint_32)65535L;
  194962. length = (png_uint_32)65535L;
  194963. }
  194964. #endif
  194965. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194966. slength = (png_size_t)length;
  194967. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194968. if (png_crc_finish(png_ptr, skip))
  194969. {
  194970. png_free(png_ptr, chunkdata);
  194971. return;
  194972. }
  194973. chunkdata[slength] = 0x00;
  194974. for (entry_start = chunkdata; *entry_start; entry_start++)
  194975. /* empty loop to find end of name */ ;
  194976. ++entry_start;
  194977. /* a sample depth should follow the separator, and we should be on it */
  194978. if (entry_start > chunkdata + slength - 2)
  194979. {
  194980. png_free(png_ptr, chunkdata);
  194981. png_warning(png_ptr, "malformed sPLT chunk");
  194982. return;
  194983. }
  194984. new_palette.depth = *entry_start++;
  194985. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194986. data_length = (slength - (entry_start - chunkdata));
  194987. /* integrity-check the data length */
  194988. if (data_length % entry_size)
  194989. {
  194990. png_free(png_ptr, chunkdata);
  194991. png_warning(png_ptr, "sPLT chunk has bad length");
  194992. return;
  194993. }
  194994. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194995. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194996. png_sizeof(png_sPLT_entry)))
  194997. {
  194998. png_warning(png_ptr, "sPLT chunk too long");
  194999. return;
  195000. }
  195001. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  195002. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  195003. if (new_palette.entries == NULL)
  195004. {
  195005. png_warning(png_ptr, "sPLT chunk requires too much memory");
  195006. return;
  195007. }
  195008. #ifndef PNG_NO_POINTER_INDEXING
  195009. for (i = 0; i < new_palette.nentries; i++)
  195010. {
  195011. png_sPLT_entryp pp = new_palette.entries + i;
  195012. if (new_palette.depth == 8)
  195013. {
  195014. pp->red = *entry_start++;
  195015. pp->green = *entry_start++;
  195016. pp->blue = *entry_start++;
  195017. pp->alpha = *entry_start++;
  195018. }
  195019. else
  195020. {
  195021. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  195022. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  195023. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  195024. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  195025. }
  195026. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195027. }
  195028. #else
  195029. pp = new_palette.entries;
  195030. for (i = 0; i < new_palette.nentries; i++)
  195031. {
  195032. if (new_palette.depth == 8)
  195033. {
  195034. pp[i].red = *entry_start++;
  195035. pp[i].green = *entry_start++;
  195036. pp[i].blue = *entry_start++;
  195037. pp[i].alpha = *entry_start++;
  195038. }
  195039. else
  195040. {
  195041. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  195042. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195043. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195044. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195045. }
  195046. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195047. }
  195048. #endif
  195049. /* discard all chunk data except the name and stash that */
  195050. new_palette.name = (png_charp)chunkdata;
  195051. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  195052. png_free(png_ptr, chunkdata);
  195053. png_free(png_ptr, new_palette.entries);
  195054. }
  195055. #endif /* PNG_READ_sPLT_SUPPORTED */
  195056. #if defined(PNG_READ_tRNS_SUPPORTED)
  195057. void /* PRIVATE */
  195058. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195059. {
  195060. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  195061. int bit_mask;
  195062. png_debug(1, "in png_handle_tRNS\n");
  195063. /* For non-indexed color, mask off any bits in the tRNS value that
  195064. * exceed the bit depth. Some creators were writing extra bits there.
  195065. * This is not needed for indexed color. */
  195066. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195067. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195068. png_error(png_ptr, "Missing IHDR before tRNS");
  195069. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195070. {
  195071. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195072. png_crc_finish(png_ptr, length);
  195073. return;
  195074. }
  195075. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195076. {
  195077. png_warning(png_ptr, "Duplicate tRNS chunk");
  195078. png_crc_finish(png_ptr, length);
  195079. return;
  195080. }
  195081. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195082. {
  195083. png_byte buf[2];
  195084. if (length != 2)
  195085. {
  195086. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195087. png_crc_finish(png_ptr, length);
  195088. return;
  195089. }
  195090. png_crc_read(png_ptr, buf, 2);
  195091. png_ptr->num_trans = 1;
  195092. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195093. }
  195094. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195095. {
  195096. png_byte buf[6];
  195097. if (length != 6)
  195098. {
  195099. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195100. png_crc_finish(png_ptr, length);
  195101. return;
  195102. }
  195103. png_crc_read(png_ptr, buf, (png_size_t)length);
  195104. png_ptr->num_trans = 1;
  195105. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195106. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195107. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195108. }
  195109. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195110. {
  195111. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195112. {
  195113. /* Should be an error, but we can cope with it. */
  195114. png_warning(png_ptr, "Missing PLTE before tRNS");
  195115. }
  195116. if (length > (png_uint_32)png_ptr->num_palette ||
  195117. length > PNG_MAX_PALETTE_LENGTH)
  195118. {
  195119. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195120. png_crc_finish(png_ptr, length);
  195121. return;
  195122. }
  195123. if (length == 0)
  195124. {
  195125. png_warning(png_ptr, "Zero length tRNS chunk");
  195126. png_crc_finish(png_ptr, length);
  195127. return;
  195128. }
  195129. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195130. png_ptr->num_trans = (png_uint_16)length;
  195131. }
  195132. else
  195133. {
  195134. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195135. png_crc_finish(png_ptr, length);
  195136. return;
  195137. }
  195138. if (png_crc_finish(png_ptr, 0))
  195139. {
  195140. png_ptr->num_trans = 0;
  195141. return;
  195142. }
  195143. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195144. &(png_ptr->trans_values));
  195145. }
  195146. #endif
  195147. #if defined(PNG_READ_bKGD_SUPPORTED)
  195148. void /* PRIVATE */
  195149. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195150. {
  195151. png_size_t truelen;
  195152. png_byte buf[6];
  195153. png_debug(1, "in png_handle_bKGD\n");
  195154. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195155. png_error(png_ptr, "Missing IHDR before bKGD");
  195156. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195157. {
  195158. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195159. png_crc_finish(png_ptr, length);
  195160. return;
  195161. }
  195162. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195163. !(png_ptr->mode & PNG_HAVE_PLTE))
  195164. {
  195165. png_warning(png_ptr, "Missing PLTE before bKGD");
  195166. png_crc_finish(png_ptr, length);
  195167. return;
  195168. }
  195169. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195170. {
  195171. png_warning(png_ptr, "Duplicate bKGD chunk");
  195172. png_crc_finish(png_ptr, length);
  195173. return;
  195174. }
  195175. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195176. truelen = 1;
  195177. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195178. truelen = 6;
  195179. else
  195180. truelen = 2;
  195181. if (length != truelen)
  195182. {
  195183. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195184. png_crc_finish(png_ptr, length);
  195185. return;
  195186. }
  195187. png_crc_read(png_ptr, buf, truelen);
  195188. if (png_crc_finish(png_ptr, 0))
  195189. return;
  195190. /* We convert the index value into RGB components so that we can allow
  195191. * arbitrary RGB values for background when we have transparency, and
  195192. * so it is easy to determine the RGB values of the background color
  195193. * from the info_ptr struct. */
  195194. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195195. {
  195196. png_ptr->background.index = buf[0];
  195197. if(info_ptr->num_palette)
  195198. {
  195199. if(buf[0] > info_ptr->num_palette)
  195200. {
  195201. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195202. return;
  195203. }
  195204. png_ptr->background.red =
  195205. (png_uint_16)png_ptr->palette[buf[0]].red;
  195206. png_ptr->background.green =
  195207. (png_uint_16)png_ptr->palette[buf[0]].green;
  195208. png_ptr->background.blue =
  195209. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195210. }
  195211. }
  195212. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195213. {
  195214. png_ptr->background.red =
  195215. png_ptr->background.green =
  195216. png_ptr->background.blue =
  195217. png_ptr->background.gray = png_get_uint_16(buf);
  195218. }
  195219. else
  195220. {
  195221. png_ptr->background.red = png_get_uint_16(buf);
  195222. png_ptr->background.green = png_get_uint_16(buf + 2);
  195223. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195224. }
  195225. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195226. }
  195227. #endif
  195228. #if defined(PNG_READ_hIST_SUPPORTED)
  195229. void /* PRIVATE */
  195230. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195231. {
  195232. unsigned int num, i;
  195233. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195234. png_debug(1, "in png_handle_hIST\n");
  195235. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195236. png_error(png_ptr, "Missing IHDR before hIST");
  195237. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195238. {
  195239. png_warning(png_ptr, "Invalid hIST after IDAT");
  195240. png_crc_finish(png_ptr, length);
  195241. return;
  195242. }
  195243. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195244. {
  195245. png_warning(png_ptr, "Missing PLTE before hIST");
  195246. png_crc_finish(png_ptr, length);
  195247. return;
  195248. }
  195249. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195250. {
  195251. png_warning(png_ptr, "Duplicate hIST chunk");
  195252. png_crc_finish(png_ptr, length);
  195253. return;
  195254. }
  195255. num = length / 2 ;
  195256. if (num != (unsigned int) png_ptr->num_palette || num >
  195257. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195258. {
  195259. png_warning(png_ptr, "Incorrect hIST chunk length");
  195260. png_crc_finish(png_ptr, length);
  195261. return;
  195262. }
  195263. for (i = 0; i < num; i++)
  195264. {
  195265. png_byte buf[2];
  195266. png_crc_read(png_ptr, buf, 2);
  195267. readbuf[i] = png_get_uint_16(buf);
  195268. }
  195269. if (png_crc_finish(png_ptr, 0))
  195270. return;
  195271. png_set_hIST(png_ptr, info_ptr, readbuf);
  195272. }
  195273. #endif
  195274. #if defined(PNG_READ_pHYs_SUPPORTED)
  195275. void /* PRIVATE */
  195276. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195277. {
  195278. png_byte buf[9];
  195279. png_uint_32 res_x, res_y;
  195280. int unit_type;
  195281. png_debug(1, "in png_handle_pHYs\n");
  195282. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195283. png_error(png_ptr, "Missing IHDR before pHYs");
  195284. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195285. {
  195286. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195287. png_crc_finish(png_ptr, length);
  195288. return;
  195289. }
  195290. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195291. {
  195292. png_warning(png_ptr, "Duplicate pHYs chunk");
  195293. png_crc_finish(png_ptr, length);
  195294. return;
  195295. }
  195296. if (length != 9)
  195297. {
  195298. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195299. png_crc_finish(png_ptr, length);
  195300. return;
  195301. }
  195302. png_crc_read(png_ptr, buf, 9);
  195303. if (png_crc_finish(png_ptr, 0))
  195304. return;
  195305. res_x = png_get_uint_32(buf);
  195306. res_y = png_get_uint_32(buf + 4);
  195307. unit_type = buf[8];
  195308. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195309. }
  195310. #endif
  195311. #if defined(PNG_READ_oFFs_SUPPORTED)
  195312. void /* PRIVATE */
  195313. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195314. {
  195315. png_byte buf[9];
  195316. png_int_32 offset_x, offset_y;
  195317. int unit_type;
  195318. png_debug(1, "in png_handle_oFFs\n");
  195319. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195320. png_error(png_ptr, "Missing IHDR before oFFs");
  195321. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195322. {
  195323. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195324. png_crc_finish(png_ptr, length);
  195325. return;
  195326. }
  195327. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195328. {
  195329. png_warning(png_ptr, "Duplicate oFFs chunk");
  195330. png_crc_finish(png_ptr, length);
  195331. return;
  195332. }
  195333. if (length != 9)
  195334. {
  195335. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195336. png_crc_finish(png_ptr, length);
  195337. return;
  195338. }
  195339. png_crc_read(png_ptr, buf, 9);
  195340. if (png_crc_finish(png_ptr, 0))
  195341. return;
  195342. offset_x = png_get_int_32(buf);
  195343. offset_y = png_get_int_32(buf + 4);
  195344. unit_type = buf[8];
  195345. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195346. }
  195347. #endif
  195348. #if defined(PNG_READ_pCAL_SUPPORTED)
  195349. /* read the pCAL chunk (described in the PNG Extensions document) */
  195350. void /* PRIVATE */
  195351. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195352. {
  195353. png_charp purpose;
  195354. png_int_32 X0, X1;
  195355. png_byte type, nparams;
  195356. png_charp buf, units, endptr;
  195357. png_charpp params;
  195358. png_size_t slength;
  195359. int i;
  195360. png_debug(1, "in png_handle_pCAL\n");
  195361. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195362. png_error(png_ptr, "Missing IHDR before pCAL");
  195363. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195364. {
  195365. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195366. png_crc_finish(png_ptr, length);
  195367. return;
  195368. }
  195369. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195370. {
  195371. png_warning(png_ptr, "Duplicate pCAL chunk");
  195372. png_crc_finish(png_ptr, length);
  195373. return;
  195374. }
  195375. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195376. length + 1);
  195377. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195378. if (purpose == NULL)
  195379. {
  195380. png_warning(png_ptr, "No memory for pCAL purpose.");
  195381. return;
  195382. }
  195383. slength = (png_size_t)length;
  195384. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195385. if (png_crc_finish(png_ptr, 0))
  195386. {
  195387. png_free(png_ptr, purpose);
  195388. return;
  195389. }
  195390. purpose[slength] = 0x00; /* null terminate the last string */
  195391. png_debug(3, "Finding end of pCAL purpose string\n");
  195392. for (buf = purpose; *buf; buf++)
  195393. /* empty loop */ ;
  195394. endptr = purpose + slength;
  195395. /* We need to have at least 12 bytes after the purpose string
  195396. in order to get the parameter information. */
  195397. if (endptr <= buf + 12)
  195398. {
  195399. png_warning(png_ptr, "Invalid pCAL data");
  195400. png_free(png_ptr, purpose);
  195401. return;
  195402. }
  195403. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195404. X0 = png_get_int_32((png_bytep)buf+1);
  195405. X1 = png_get_int_32((png_bytep)buf+5);
  195406. type = buf[9];
  195407. nparams = buf[10];
  195408. units = buf + 11;
  195409. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195410. /* Check that we have the right number of parameters for known
  195411. equation types. */
  195412. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195413. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195414. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195415. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195416. {
  195417. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195418. png_free(png_ptr, purpose);
  195419. return;
  195420. }
  195421. else if (type >= PNG_EQUATION_LAST)
  195422. {
  195423. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195424. }
  195425. for (buf = units; *buf; buf++)
  195426. /* Empty loop to move past the units string. */ ;
  195427. png_debug(3, "Allocating pCAL parameters array\n");
  195428. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195429. *png_sizeof(png_charp))) ;
  195430. if (params == NULL)
  195431. {
  195432. png_free(png_ptr, purpose);
  195433. png_warning(png_ptr, "No memory for pCAL params.");
  195434. return;
  195435. }
  195436. /* Get pointers to the start of each parameter string. */
  195437. for (i = 0; i < (int)nparams; i++)
  195438. {
  195439. buf++; /* Skip the null string terminator from previous parameter. */
  195440. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195441. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195442. /* Empty loop to move past each parameter string */ ;
  195443. /* Make sure we haven't run out of data yet */
  195444. if (buf > endptr)
  195445. {
  195446. png_warning(png_ptr, "Invalid pCAL data");
  195447. png_free(png_ptr, purpose);
  195448. png_free(png_ptr, params);
  195449. return;
  195450. }
  195451. }
  195452. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195453. units, params);
  195454. png_free(png_ptr, purpose);
  195455. png_free(png_ptr, params);
  195456. }
  195457. #endif
  195458. #if defined(PNG_READ_sCAL_SUPPORTED)
  195459. /* read the sCAL chunk */
  195460. void /* PRIVATE */
  195461. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195462. {
  195463. png_charp buffer, ep;
  195464. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195465. double width, height;
  195466. png_charp vp;
  195467. #else
  195468. #ifdef PNG_FIXED_POINT_SUPPORTED
  195469. png_charp swidth, sheight;
  195470. #endif
  195471. #endif
  195472. png_size_t slength;
  195473. png_debug(1, "in png_handle_sCAL\n");
  195474. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195475. png_error(png_ptr, "Missing IHDR before sCAL");
  195476. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195477. {
  195478. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195479. png_crc_finish(png_ptr, length);
  195480. return;
  195481. }
  195482. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195483. {
  195484. png_warning(png_ptr, "Duplicate sCAL chunk");
  195485. png_crc_finish(png_ptr, length);
  195486. return;
  195487. }
  195488. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195489. length + 1);
  195490. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195491. if (buffer == NULL)
  195492. {
  195493. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195494. return;
  195495. }
  195496. slength = (png_size_t)length;
  195497. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195498. if (png_crc_finish(png_ptr, 0))
  195499. {
  195500. png_free(png_ptr, buffer);
  195501. return;
  195502. }
  195503. buffer[slength] = 0x00; /* null terminate the last string */
  195504. ep = buffer + 1; /* skip unit byte */
  195505. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195506. width = png_strtod(png_ptr, ep, &vp);
  195507. if (*vp)
  195508. {
  195509. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195510. return;
  195511. }
  195512. #else
  195513. #ifdef PNG_FIXED_POINT_SUPPORTED
  195514. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195515. if (swidth == NULL)
  195516. {
  195517. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195518. return;
  195519. }
  195520. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195521. #endif
  195522. #endif
  195523. for (ep = buffer; *ep; ep++)
  195524. /* empty loop */ ;
  195525. ep++;
  195526. if (buffer + slength < ep)
  195527. {
  195528. png_warning(png_ptr, "Truncated sCAL chunk");
  195529. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195530. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195531. png_free(png_ptr, swidth);
  195532. #endif
  195533. png_free(png_ptr, buffer);
  195534. return;
  195535. }
  195536. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195537. height = png_strtod(png_ptr, ep, &vp);
  195538. if (*vp)
  195539. {
  195540. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195541. return;
  195542. }
  195543. #else
  195544. #ifdef PNG_FIXED_POINT_SUPPORTED
  195545. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195546. if (swidth == NULL)
  195547. {
  195548. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195549. return;
  195550. }
  195551. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195552. #endif
  195553. #endif
  195554. if (buffer + slength < ep
  195555. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195556. || width <= 0. || height <= 0.
  195557. #endif
  195558. )
  195559. {
  195560. png_warning(png_ptr, "Invalid sCAL data");
  195561. png_free(png_ptr, buffer);
  195562. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195563. png_free(png_ptr, swidth);
  195564. png_free(png_ptr, sheight);
  195565. #endif
  195566. return;
  195567. }
  195568. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195569. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195570. #else
  195571. #ifdef PNG_FIXED_POINT_SUPPORTED
  195572. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195573. #endif
  195574. #endif
  195575. png_free(png_ptr, buffer);
  195576. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195577. png_free(png_ptr, swidth);
  195578. png_free(png_ptr, sheight);
  195579. #endif
  195580. }
  195581. #endif
  195582. #if defined(PNG_READ_tIME_SUPPORTED)
  195583. void /* PRIVATE */
  195584. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195585. {
  195586. png_byte buf[7];
  195587. png_time mod_time;
  195588. png_debug(1, "in png_handle_tIME\n");
  195589. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195590. png_error(png_ptr, "Out of place tIME chunk");
  195591. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195592. {
  195593. png_warning(png_ptr, "Duplicate tIME chunk");
  195594. png_crc_finish(png_ptr, length);
  195595. return;
  195596. }
  195597. if (png_ptr->mode & PNG_HAVE_IDAT)
  195598. png_ptr->mode |= PNG_AFTER_IDAT;
  195599. if (length != 7)
  195600. {
  195601. png_warning(png_ptr, "Incorrect tIME chunk length");
  195602. png_crc_finish(png_ptr, length);
  195603. return;
  195604. }
  195605. png_crc_read(png_ptr, buf, 7);
  195606. if (png_crc_finish(png_ptr, 0))
  195607. return;
  195608. mod_time.second = buf[6];
  195609. mod_time.minute = buf[5];
  195610. mod_time.hour = buf[4];
  195611. mod_time.day = buf[3];
  195612. mod_time.month = buf[2];
  195613. mod_time.year = png_get_uint_16(buf);
  195614. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195615. }
  195616. #endif
  195617. #if defined(PNG_READ_tEXt_SUPPORTED)
  195618. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195619. void /* PRIVATE */
  195620. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195621. {
  195622. png_textp text_ptr;
  195623. png_charp key;
  195624. png_charp text;
  195625. png_uint_32 skip = 0;
  195626. png_size_t slength;
  195627. int ret;
  195628. png_debug(1, "in png_handle_tEXt\n");
  195629. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195630. png_error(png_ptr, "Missing IHDR before tEXt");
  195631. if (png_ptr->mode & PNG_HAVE_IDAT)
  195632. png_ptr->mode |= PNG_AFTER_IDAT;
  195633. #ifdef PNG_MAX_MALLOC_64K
  195634. if (length > (png_uint_32)65535L)
  195635. {
  195636. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195637. skip = length - (png_uint_32)65535L;
  195638. length = (png_uint_32)65535L;
  195639. }
  195640. #endif
  195641. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195642. if (key == NULL)
  195643. {
  195644. png_warning(png_ptr, "No memory to process text chunk.");
  195645. return;
  195646. }
  195647. slength = (png_size_t)length;
  195648. png_crc_read(png_ptr, (png_bytep)key, slength);
  195649. if (png_crc_finish(png_ptr, skip))
  195650. {
  195651. png_free(png_ptr, key);
  195652. return;
  195653. }
  195654. key[slength] = 0x00;
  195655. for (text = key; *text; text++)
  195656. /* empty loop to find end of key */ ;
  195657. if (text != key + slength)
  195658. text++;
  195659. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195660. (png_uint_32)png_sizeof(png_text));
  195661. if (text_ptr == NULL)
  195662. {
  195663. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195664. png_free(png_ptr, key);
  195665. return;
  195666. }
  195667. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195668. text_ptr->key = key;
  195669. #ifdef PNG_iTXt_SUPPORTED
  195670. text_ptr->lang = NULL;
  195671. text_ptr->lang_key = NULL;
  195672. text_ptr->itxt_length = 0;
  195673. #endif
  195674. text_ptr->text = text;
  195675. text_ptr->text_length = png_strlen(text);
  195676. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195677. png_free(png_ptr, key);
  195678. png_free(png_ptr, text_ptr);
  195679. if (ret)
  195680. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195681. }
  195682. #endif
  195683. #if defined(PNG_READ_zTXt_SUPPORTED)
  195684. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195685. void /* PRIVATE */
  195686. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195687. {
  195688. png_textp text_ptr;
  195689. png_charp chunkdata;
  195690. png_charp text;
  195691. int comp_type;
  195692. int ret;
  195693. png_size_t slength, prefix_len, data_len;
  195694. png_debug(1, "in png_handle_zTXt\n");
  195695. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195696. png_error(png_ptr, "Missing IHDR before zTXt");
  195697. if (png_ptr->mode & PNG_HAVE_IDAT)
  195698. png_ptr->mode |= PNG_AFTER_IDAT;
  195699. #ifdef PNG_MAX_MALLOC_64K
  195700. /* We will no doubt have problems with chunks even half this size, but
  195701. there is no hard and fast rule to tell us where to stop. */
  195702. if (length > (png_uint_32)65535L)
  195703. {
  195704. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195705. png_crc_finish(png_ptr, length);
  195706. return;
  195707. }
  195708. #endif
  195709. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195710. if (chunkdata == NULL)
  195711. {
  195712. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195713. return;
  195714. }
  195715. slength = (png_size_t)length;
  195716. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195717. if (png_crc_finish(png_ptr, 0))
  195718. {
  195719. png_free(png_ptr, chunkdata);
  195720. return;
  195721. }
  195722. chunkdata[slength] = 0x00;
  195723. for (text = chunkdata; *text; text++)
  195724. /* empty loop */ ;
  195725. /* zTXt must have some text after the chunkdataword */
  195726. if (text >= chunkdata + slength - 2)
  195727. {
  195728. png_warning(png_ptr, "Truncated zTXt chunk");
  195729. png_free(png_ptr, chunkdata);
  195730. return;
  195731. }
  195732. else
  195733. {
  195734. comp_type = *(++text);
  195735. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195736. {
  195737. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195738. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195739. }
  195740. text++; /* skip the compression_method byte */
  195741. }
  195742. prefix_len = text - chunkdata;
  195743. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195744. (png_size_t)length, prefix_len, &data_len);
  195745. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195746. (png_uint_32)png_sizeof(png_text));
  195747. if (text_ptr == NULL)
  195748. {
  195749. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195750. png_free(png_ptr, chunkdata);
  195751. return;
  195752. }
  195753. text_ptr->compression = comp_type;
  195754. text_ptr->key = chunkdata;
  195755. #ifdef PNG_iTXt_SUPPORTED
  195756. text_ptr->lang = NULL;
  195757. text_ptr->lang_key = NULL;
  195758. text_ptr->itxt_length = 0;
  195759. #endif
  195760. text_ptr->text = chunkdata + prefix_len;
  195761. text_ptr->text_length = data_len;
  195762. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195763. png_free(png_ptr, text_ptr);
  195764. png_free(png_ptr, chunkdata);
  195765. if (ret)
  195766. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195767. }
  195768. #endif
  195769. #if defined(PNG_READ_iTXt_SUPPORTED)
  195770. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195771. void /* PRIVATE */
  195772. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195773. {
  195774. png_textp text_ptr;
  195775. png_charp chunkdata;
  195776. png_charp key, lang, text, lang_key;
  195777. int comp_flag;
  195778. int comp_type = 0;
  195779. int ret;
  195780. png_size_t slength, prefix_len, data_len;
  195781. png_debug(1, "in png_handle_iTXt\n");
  195782. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195783. png_error(png_ptr, "Missing IHDR before iTXt");
  195784. if (png_ptr->mode & PNG_HAVE_IDAT)
  195785. png_ptr->mode |= PNG_AFTER_IDAT;
  195786. #ifdef PNG_MAX_MALLOC_64K
  195787. /* We will no doubt have problems with chunks even half this size, but
  195788. there is no hard and fast rule to tell us where to stop. */
  195789. if (length > (png_uint_32)65535L)
  195790. {
  195791. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195792. png_crc_finish(png_ptr, length);
  195793. return;
  195794. }
  195795. #endif
  195796. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195797. if (chunkdata == NULL)
  195798. {
  195799. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195800. return;
  195801. }
  195802. slength = (png_size_t)length;
  195803. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195804. if (png_crc_finish(png_ptr, 0))
  195805. {
  195806. png_free(png_ptr, chunkdata);
  195807. return;
  195808. }
  195809. chunkdata[slength] = 0x00;
  195810. for (lang = chunkdata; *lang; lang++)
  195811. /* empty loop */ ;
  195812. lang++; /* skip NUL separator */
  195813. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195814. translated keyword (possibly empty), and possibly some text after the
  195815. keyword */
  195816. if (lang >= chunkdata + slength - 3)
  195817. {
  195818. png_warning(png_ptr, "Truncated iTXt chunk");
  195819. png_free(png_ptr, chunkdata);
  195820. return;
  195821. }
  195822. else
  195823. {
  195824. comp_flag = *lang++;
  195825. comp_type = *lang++;
  195826. }
  195827. for (lang_key = lang; *lang_key; lang_key++)
  195828. /* empty loop */ ;
  195829. lang_key++; /* skip NUL separator */
  195830. if (lang_key >= chunkdata + slength)
  195831. {
  195832. png_warning(png_ptr, "Truncated iTXt chunk");
  195833. png_free(png_ptr, chunkdata);
  195834. return;
  195835. }
  195836. for (text = lang_key; *text; text++)
  195837. /* empty loop */ ;
  195838. text++; /* skip NUL separator */
  195839. if (text >= chunkdata + slength)
  195840. {
  195841. png_warning(png_ptr, "Malformed iTXt chunk");
  195842. png_free(png_ptr, chunkdata);
  195843. return;
  195844. }
  195845. prefix_len = text - chunkdata;
  195846. key=chunkdata;
  195847. if (comp_flag)
  195848. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195849. (size_t)length, prefix_len, &data_len);
  195850. else
  195851. data_len=png_strlen(chunkdata + prefix_len);
  195852. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195853. (png_uint_32)png_sizeof(png_text));
  195854. if (text_ptr == NULL)
  195855. {
  195856. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195857. png_free(png_ptr, chunkdata);
  195858. return;
  195859. }
  195860. text_ptr->compression = (int)comp_flag + 1;
  195861. text_ptr->lang_key = chunkdata+(lang_key-key);
  195862. text_ptr->lang = chunkdata+(lang-key);
  195863. text_ptr->itxt_length = data_len;
  195864. text_ptr->text_length = 0;
  195865. text_ptr->key = chunkdata;
  195866. text_ptr->text = chunkdata + prefix_len;
  195867. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195868. png_free(png_ptr, text_ptr);
  195869. png_free(png_ptr, chunkdata);
  195870. if (ret)
  195871. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195872. }
  195873. #endif
  195874. /* This function is called when we haven't found a handler for a
  195875. chunk. If there isn't a problem with the chunk itself (ie bad
  195876. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195877. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195878. case it will be saved away to be written out later. */
  195879. void /* PRIVATE */
  195880. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195881. {
  195882. png_uint_32 skip = 0;
  195883. png_debug(1, "in png_handle_unknown\n");
  195884. if (png_ptr->mode & PNG_HAVE_IDAT)
  195885. {
  195886. #ifdef PNG_USE_LOCAL_ARRAYS
  195887. PNG_CONST PNG_IDAT;
  195888. #endif
  195889. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195890. png_ptr->mode |= PNG_AFTER_IDAT;
  195891. }
  195892. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195893. if (!(png_ptr->chunk_name[0] & 0x20))
  195894. {
  195895. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195896. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195897. PNG_HANDLE_CHUNK_ALWAYS
  195898. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195899. && png_ptr->read_user_chunk_fn == NULL
  195900. #endif
  195901. )
  195902. #endif
  195903. png_chunk_error(png_ptr, "unknown critical chunk");
  195904. }
  195905. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195906. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195907. (png_ptr->read_user_chunk_fn != NULL))
  195908. {
  195909. #ifdef PNG_MAX_MALLOC_64K
  195910. if (length > (png_uint_32)65535L)
  195911. {
  195912. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195913. skip = length - (png_uint_32)65535L;
  195914. length = (png_uint_32)65535L;
  195915. }
  195916. #endif
  195917. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195918. (png_charp)png_ptr->chunk_name, 5);
  195919. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195920. png_ptr->unknown_chunk.size = (png_size_t)length;
  195921. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195922. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195923. if(png_ptr->read_user_chunk_fn != NULL)
  195924. {
  195925. /* callback to user unknown chunk handler */
  195926. int ret;
  195927. ret = (*(png_ptr->read_user_chunk_fn))
  195928. (png_ptr, &png_ptr->unknown_chunk);
  195929. if (ret < 0)
  195930. png_chunk_error(png_ptr, "error in user chunk");
  195931. if (ret == 0)
  195932. {
  195933. if (!(png_ptr->chunk_name[0] & 0x20))
  195934. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195935. PNG_HANDLE_CHUNK_ALWAYS)
  195936. png_chunk_error(png_ptr, "unknown critical chunk");
  195937. png_set_unknown_chunks(png_ptr, info_ptr,
  195938. &png_ptr->unknown_chunk, 1);
  195939. }
  195940. }
  195941. #else
  195942. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195943. #endif
  195944. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195945. png_ptr->unknown_chunk.data = NULL;
  195946. }
  195947. else
  195948. #endif
  195949. skip = length;
  195950. png_crc_finish(png_ptr, skip);
  195951. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195952. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195953. #endif
  195954. }
  195955. /* This function is called to verify that a chunk name is valid.
  195956. This function can't have the "critical chunk check" incorporated
  195957. into it, since in the future we will need to be able to call user
  195958. functions to handle unknown critical chunks after we check that
  195959. the chunk name itself is valid. */
  195960. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195961. void /* PRIVATE */
  195962. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195963. {
  195964. png_debug(1, "in png_check_chunk_name\n");
  195965. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195966. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195967. {
  195968. png_chunk_error(png_ptr, "invalid chunk type");
  195969. }
  195970. }
  195971. /* Combines the row recently read in with the existing pixels in the
  195972. row. This routine takes care of alpha and transparency if requested.
  195973. This routine also handles the two methods of progressive display
  195974. of interlaced images, depending on the mask value.
  195975. The mask value describes which pixels are to be combined with
  195976. the row. The pattern always repeats every 8 pixels, so just 8
  195977. bits are needed. A one indicates the pixel is to be combined,
  195978. a zero indicates the pixel is to be skipped. This is in addition
  195979. to any alpha or transparency value associated with the pixel. If
  195980. you want all pixels to be combined, pass 0xff (255) in mask. */
  195981. void /* PRIVATE */
  195982. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195983. {
  195984. png_debug(1,"in png_combine_row\n");
  195985. if (mask == 0xff)
  195986. {
  195987. png_memcpy(row, png_ptr->row_buf + 1,
  195988. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195989. }
  195990. else
  195991. {
  195992. switch (png_ptr->row_info.pixel_depth)
  195993. {
  195994. case 1:
  195995. {
  195996. png_bytep sp = png_ptr->row_buf + 1;
  195997. png_bytep dp = row;
  195998. int s_inc, s_start, s_end;
  195999. int m = 0x80;
  196000. int shift;
  196001. png_uint_32 i;
  196002. png_uint_32 row_width = png_ptr->width;
  196003. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196004. if (png_ptr->transformations & PNG_PACKSWAP)
  196005. {
  196006. s_start = 0;
  196007. s_end = 7;
  196008. s_inc = 1;
  196009. }
  196010. else
  196011. #endif
  196012. {
  196013. s_start = 7;
  196014. s_end = 0;
  196015. s_inc = -1;
  196016. }
  196017. shift = s_start;
  196018. for (i = 0; i < row_width; i++)
  196019. {
  196020. if (m & mask)
  196021. {
  196022. int value;
  196023. value = (*sp >> shift) & 0x01;
  196024. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  196025. *dp |= (png_byte)(value << shift);
  196026. }
  196027. if (shift == s_end)
  196028. {
  196029. shift = s_start;
  196030. sp++;
  196031. dp++;
  196032. }
  196033. else
  196034. shift += s_inc;
  196035. if (m == 1)
  196036. m = 0x80;
  196037. else
  196038. m >>= 1;
  196039. }
  196040. break;
  196041. }
  196042. case 2:
  196043. {
  196044. png_bytep sp = png_ptr->row_buf + 1;
  196045. png_bytep dp = row;
  196046. int s_start, s_end, s_inc;
  196047. int m = 0x80;
  196048. int shift;
  196049. png_uint_32 i;
  196050. png_uint_32 row_width = png_ptr->width;
  196051. int value;
  196052. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196053. if (png_ptr->transformations & PNG_PACKSWAP)
  196054. {
  196055. s_start = 0;
  196056. s_end = 6;
  196057. s_inc = 2;
  196058. }
  196059. else
  196060. #endif
  196061. {
  196062. s_start = 6;
  196063. s_end = 0;
  196064. s_inc = -2;
  196065. }
  196066. shift = s_start;
  196067. for (i = 0; i < row_width; i++)
  196068. {
  196069. if (m & mask)
  196070. {
  196071. value = (*sp >> shift) & 0x03;
  196072. *dp &= (png_byte)((0x3f3f >> (6 - 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 4:
  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 = 4;
  196105. s_inc = 4;
  196106. }
  196107. else
  196108. #endif
  196109. {
  196110. s_start = 4;
  196111. s_end = 0;
  196112. s_inc = -4;
  196113. }
  196114. shift = s_start;
  196115. for (i = 0; i < row_width; i++)
  196116. {
  196117. if (m & mask)
  196118. {
  196119. value = (*sp >> shift) & 0xf;
  196120. *dp &= (png_byte)((0xf0f >> (4 - 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. default:
  196139. {
  196140. png_bytep sp = png_ptr->row_buf + 1;
  196141. png_bytep dp = row;
  196142. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196143. png_uint_32 i;
  196144. png_uint_32 row_width = png_ptr->width;
  196145. png_byte m = 0x80;
  196146. for (i = 0; i < row_width; i++)
  196147. {
  196148. if (m & mask)
  196149. {
  196150. png_memcpy(dp, sp, pixel_bytes);
  196151. }
  196152. sp += pixel_bytes;
  196153. dp += pixel_bytes;
  196154. if (m == 1)
  196155. m = 0x80;
  196156. else
  196157. m >>= 1;
  196158. }
  196159. break;
  196160. }
  196161. }
  196162. }
  196163. }
  196164. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196165. /* OLD pre-1.0.9 interface:
  196166. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196167. png_uint_32 transformations)
  196168. */
  196169. void /* PRIVATE */
  196170. png_do_read_interlace(png_structp png_ptr)
  196171. {
  196172. png_row_infop row_info = &(png_ptr->row_info);
  196173. png_bytep row = png_ptr->row_buf + 1;
  196174. int pass = png_ptr->pass;
  196175. png_uint_32 transformations = png_ptr->transformations;
  196176. #ifdef PNG_USE_LOCAL_ARRAYS
  196177. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196178. /* offset to next interlace block */
  196179. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196180. #endif
  196181. png_debug(1,"in png_do_read_interlace\n");
  196182. if (row != NULL && row_info != NULL)
  196183. {
  196184. png_uint_32 final_width;
  196185. final_width = row_info->width * png_pass_inc[pass];
  196186. switch (row_info->pixel_depth)
  196187. {
  196188. case 1:
  196189. {
  196190. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196191. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196192. int sshift, dshift;
  196193. int s_start, s_end, s_inc;
  196194. int jstop = png_pass_inc[pass];
  196195. png_byte v;
  196196. png_uint_32 i;
  196197. int j;
  196198. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196199. if (transformations & PNG_PACKSWAP)
  196200. {
  196201. sshift = (int)((row_info->width + 7) & 0x07);
  196202. dshift = (int)((final_width + 7) & 0x07);
  196203. s_start = 7;
  196204. s_end = 0;
  196205. s_inc = -1;
  196206. }
  196207. else
  196208. #endif
  196209. {
  196210. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196211. dshift = 7 - (int)((final_width + 7) & 0x07);
  196212. s_start = 0;
  196213. s_end = 7;
  196214. s_inc = 1;
  196215. }
  196216. for (i = 0; i < row_info->width; i++)
  196217. {
  196218. v = (png_byte)((*sp >> sshift) & 0x01);
  196219. for (j = 0; j < jstop; j++)
  196220. {
  196221. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196222. *dp |= (png_byte)(v << dshift);
  196223. if (dshift == s_end)
  196224. {
  196225. dshift = s_start;
  196226. dp--;
  196227. }
  196228. else
  196229. dshift += s_inc;
  196230. }
  196231. if (sshift == s_end)
  196232. {
  196233. sshift = s_start;
  196234. sp--;
  196235. }
  196236. else
  196237. sshift += s_inc;
  196238. }
  196239. break;
  196240. }
  196241. case 2:
  196242. {
  196243. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196244. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196245. int sshift, dshift;
  196246. int s_start, s_end, s_inc;
  196247. int jstop = png_pass_inc[pass];
  196248. png_uint_32 i;
  196249. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196250. if (transformations & PNG_PACKSWAP)
  196251. {
  196252. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196253. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196254. s_start = 6;
  196255. s_end = 0;
  196256. s_inc = -2;
  196257. }
  196258. else
  196259. #endif
  196260. {
  196261. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196262. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196263. s_start = 0;
  196264. s_end = 6;
  196265. s_inc = 2;
  196266. }
  196267. for (i = 0; i < row_info->width; i++)
  196268. {
  196269. png_byte v;
  196270. int j;
  196271. v = (png_byte)((*sp >> sshift) & 0x03);
  196272. for (j = 0; j < jstop; j++)
  196273. {
  196274. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196275. *dp |= (png_byte)(v << dshift);
  196276. if (dshift == s_end)
  196277. {
  196278. dshift = s_start;
  196279. dp--;
  196280. }
  196281. else
  196282. dshift += s_inc;
  196283. }
  196284. if (sshift == s_end)
  196285. {
  196286. sshift = s_start;
  196287. sp--;
  196288. }
  196289. else
  196290. sshift += s_inc;
  196291. }
  196292. break;
  196293. }
  196294. case 4:
  196295. {
  196296. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196297. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196298. int sshift, dshift;
  196299. int s_start, s_end, s_inc;
  196300. png_uint_32 i;
  196301. int jstop = png_pass_inc[pass];
  196302. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196303. if (transformations & PNG_PACKSWAP)
  196304. {
  196305. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196306. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196307. s_start = 4;
  196308. s_end = 0;
  196309. s_inc = -4;
  196310. }
  196311. else
  196312. #endif
  196313. {
  196314. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196315. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196316. s_start = 0;
  196317. s_end = 4;
  196318. s_inc = 4;
  196319. }
  196320. for (i = 0; i < row_info->width; i++)
  196321. {
  196322. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196323. int j;
  196324. for (j = 0; j < jstop; j++)
  196325. {
  196326. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196327. *dp |= (png_byte)(v << dshift);
  196328. if (dshift == s_end)
  196329. {
  196330. dshift = s_start;
  196331. dp--;
  196332. }
  196333. else
  196334. dshift += s_inc;
  196335. }
  196336. if (sshift == s_end)
  196337. {
  196338. sshift = s_start;
  196339. sp--;
  196340. }
  196341. else
  196342. sshift += s_inc;
  196343. }
  196344. break;
  196345. }
  196346. default:
  196347. {
  196348. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196349. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196350. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196351. int jstop = png_pass_inc[pass];
  196352. png_uint_32 i;
  196353. for (i = 0; i < row_info->width; i++)
  196354. {
  196355. png_byte v[8];
  196356. int j;
  196357. png_memcpy(v, sp, pixel_bytes);
  196358. for (j = 0; j < jstop; j++)
  196359. {
  196360. png_memcpy(dp, v, pixel_bytes);
  196361. dp -= pixel_bytes;
  196362. }
  196363. sp -= pixel_bytes;
  196364. }
  196365. break;
  196366. }
  196367. }
  196368. row_info->width = final_width;
  196369. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196370. }
  196371. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196372. transformations = transformations; /* silence compiler warning */
  196373. #endif
  196374. }
  196375. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196376. void /* PRIVATE */
  196377. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196378. png_bytep prev_row, int filter)
  196379. {
  196380. png_debug(1, "in png_read_filter_row\n");
  196381. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196382. switch (filter)
  196383. {
  196384. case PNG_FILTER_VALUE_NONE:
  196385. break;
  196386. case PNG_FILTER_VALUE_SUB:
  196387. {
  196388. png_uint_32 i;
  196389. png_uint_32 istop = row_info->rowbytes;
  196390. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196391. png_bytep rp = row + bpp;
  196392. png_bytep lp = row;
  196393. for (i = bpp; i < istop; i++)
  196394. {
  196395. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196396. rp++;
  196397. }
  196398. break;
  196399. }
  196400. case PNG_FILTER_VALUE_UP:
  196401. {
  196402. png_uint_32 i;
  196403. png_uint_32 istop = row_info->rowbytes;
  196404. png_bytep rp = row;
  196405. png_bytep pp = prev_row;
  196406. for (i = 0; i < istop; i++)
  196407. {
  196408. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196409. rp++;
  196410. }
  196411. break;
  196412. }
  196413. case PNG_FILTER_VALUE_AVG:
  196414. {
  196415. png_uint_32 i;
  196416. png_bytep rp = row;
  196417. png_bytep pp = prev_row;
  196418. png_bytep lp = row;
  196419. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196420. png_uint_32 istop = row_info->rowbytes - bpp;
  196421. for (i = 0; i < bpp; i++)
  196422. {
  196423. *rp = (png_byte)(((int)(*rp) +
  196424. ((int)(*pp++) / 2 )) & 0xff);
  196425. rp++;
  196426. }
  196427. for (i = 0; i < istop; i++)
  196428. {
  196429. *rp = (png_byte)(((int)(*rp) +
  196430. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196431. rp++;
  196432. }
  196433. break;
  196434. }
  196435. case PNG_FILTER_VALUE_PAETH:
  196436. {
  196437. png_uint_32 i;
  196438. png_bytep rp = row;
  196439. png_bytep pp = prev_row;
  196440. png_bytep lp = row;
  196441. png_bytep cp = prev_row;
  196442. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196443. png_uint_32 istop=row_info->rowbytes - bpp;
  196444. for (i = 0; i < bpp; i++)
  196445. {
  196446. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196447. rp++;
  196448. }
  196449. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196450. {
  196451. int a, b, c, pa, pb, pc, p;
  196452. a = *lp++;
  196453. b = *pp++;
  196454. c = *cp++;
  196455. p = b - c;
  196456. pc = a - c;
  196457. #ifdef PNG_USE_ABS
  196458. pa = abs(p);
  196459. pb = abs(pc);
  196460. pc = abs(p + pc);
  196461. #else
  196462. pa = p < 0 ? -p : p;
  196463. pb = pc < 0 ? -pc : pc;
  196464. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196465. #endif
  196466. /*
  196467. if (pa <= pb && pa <= pc)
  196468. p = a;
  196469. else if (pb <= pc)
  196470. p = b;
  196471. else
  196472. p = c;
  196473. */
  196474. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196475. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196476. rp++;
  196477. }
  196478. break;
  196479. }
  196480. default:
  196481. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196482. *row=0;
  196483. break;
  196484. }
  196485. }
  196486. void /* PRIVATE */
  196487. png_read_finish_row(png_structp png_ptr)
  196488. {
  196489. #ifdef PNG_USE_LOCAL_ARRAYS
  196490. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196491. /* start of interlace block */
  196492. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196493. /* offset to next interlace block */
  196494. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196495. /* start of interlace block in the y direction */
  196496. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196497. /* offset to next interlace block in the y direction */
  196498. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196499. #endif
  196500. png_debug(1, "in png_read_finish_row\n");
  196501. png_ptr->row_number++;
  196502. if (png_ptr->row_number < png_ptr->num_rows)
  196503. return;
  196504. if (png_ptr->interlaced)
  196505. {
  196506. png_ptr->row_number = 0;
  196507. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196508. png_ptr->rowbytes + 1);
  196509. do
  196510. {
  196511. png_ptr->pass++;
  196512. if (png_ptr->pass >= 7)
  196513. break;
  196514. png_ptr->iwidth = (png_ptr->width +
  196515. png_pass_inc[png_ptr->pass] - 1 -
  196516. png_pass_start[png_ptr->pass]) /
  196517. png_pass_inc[png_ptr->pass];
  196518. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196519. png_ptr->iwidth) + 1;
  196520. if (!(png_ptr->transformations & PNG_INTERLACE))
  196521. {
  196522. png_ptr->num_rows = (png_ptr->height +
  196523. png_pass_yinc[png_ptr->pass] - 1 -
  196524. png_pass_ystart[png_ptr->pass]) /
  196525. png_pass_yinc[png_ptr->pass];
  196526. if (!(png_ptr->num_rows))
  196527. continue;
  196528. }
  196529. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196530. break;
  196531. } while (png_ptr->iwidth == 0);
  196532. if (png_ptr->pass < 7)
  196533. return;
  196534. }
  196535. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196536. {
  196537. #ifdef PNG_USE_LOCAL_ARRAYS
  196538. PNG_CONST PNG_IDAT;
  196539. #endif
  196540. char extra;
  196541. int ret;
  196542. png_ptr->zstream.next_out = (Bytef *)&extra;
  196543. png_ptr->zstream.avail_out = (uInt)1;
  196544. for(;;)
  196545. {
  196546. if (!(png_ptr->zstream.avail_in))
  196547. {
  196548. while (!png_ptr->idat_size)
  196549. {
  196550. png_byte chunk_length[4];
  196551. png_crc_finish(png_ptr, 0);
  196552. png_read_data(png_ptr, chunk_length, 4);
  196553. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196554. png_reset_crc(png_ptr);
  196555. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196556. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196557. png_error(png_ptr, "Not enough image data");
  196558. }
  196559. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196560. png_ptr->zstream.next_in = png_ptr->zbuf;
  196561. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196562. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196563. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196564. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196565. }
  196566. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196567. if (ret == Z_STREAM_END)
  196568. {
  196569. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196570. png_ptr->idat_size)
  196571. png_warning(png_ptr, "Extra compressed data");
  196572. png_ptr->mode |= PNG_AFTER_IDAT;
  196573. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196574. break;
  196575. }
  196576. if (ret != Z_OK)
  196577. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196578. "Decompression Error");
  196579. if (!(png_ptr->zstream.avail_out))
  196580. {
  196581. png_warning(png_ptr, "Extra compressed data.");
  196582. png_ptr->mode |= PNG_AFTER_IDAT;
  196583. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196584. break;
  196585. }
  196586. }
  196587. png_ptr->zstream.avail_out = 0;
  196588. }
  196589. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196590. png_warning(png_ptr, "Extra compression data");
  196591. inflateReset(&png_ptr->zstream);
  196592. png_ptr->mode |= PNG_AFTER_IDAT;
  196593. }
  196594. void /* PRIVATE */
  196595. png_read_start_row(png_structp png_ptr)
  196596. {
  196597. #ifdef PNG_USE_LOCAL_ARRAYS
  196598. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196599. /* start of interlace block */
  196600. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196601. /* offset to next interlace block */
  196602. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196603. /* start of interlace block in the y direction */
  196604. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196605. /* offset to next interlace block in the y direction */
  196606. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196607. #endif
  196608. int max_pixel_depth;
  196609. png_uint_32 row_bytes;
  196610. png_debug(1, "in png_read_start_row\n");
  196611. png_ptr->zstream.avail_in = 0;
  196612. png_init_read_transformations(png_ptr);
  196613. if (png_ptr->interlaced)
  196614. {
  196615. if (!(png_ptr->transformations & PNG_INTERLACE))
  196616. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196617. png_pass_ystart[0]) / png_pass_yinc[0];
  196618. else
  196619. png_ptr->num_rows = png_ptr->height;
  196620. png_ptr->iwidth = (png_ptr->width +
  196621. png_pass_inc[png_ptr->pass] - 1 -
  196622. png_pass_start[png_ptr->pass]) /
  196623. png_pass_inc[png_ptr->pass];
  196624. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196625. png_ptr->irowbytes = (png_size_t)row_bytes;
  196626. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196627. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196628. }
  196629. else
  196630. {
  196631. png_ptr->num_rows = png_ptr->height;
  196632. png_ptr->iwidth = png_ptr->width;
  196633. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196634. }
  196635. max_pixel_depth = png_ptr->pixel_depth;
  196636. #if defined(PNG_READ_PACK_SUPPORTED)
  196637. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196638. max_pixel_depth = 8;
  196639. #endif
  196640. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196641. if (png_ptr->transformations & PNG_EXPAND)
  196642. {
  196643. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196644. {
  196645. if (png_ptr->num_trans)
  196646. max_pixel_depth = 32;
  196647. else
  196648. max_pixel_depth = 24;
  196649. }
  196650. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196651. {
  196652. if (max_pixel_depth < 8)
  196653. max_pixel_depth = 8;
  196654. if (png_ptr->num_trans)
  196655. max_pixel_depth *= 2;
  196656. }
  196657. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196658. {
  196659. if (png_ptr->num_trans)
  196660. {
  196661. max_pixel_depth *= 4;
  196662. max_pixel_depth /= 3;
  196663. }
  196664. }
  196665. }
  196666. #endif
  196667. #if defined(PNG_READ_FILLER_SUPPORTED)
  196668. if (png_ptr->transformations & (PNG_FILLER))
  196669. {
  196670. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196671. max_pixel_depth = 32;
  196672. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196673. {
  196674. if (max_pixel_depth <= 8)
  196675. max_pixel_depth = 16;
  196676. else
  196677. max_pixel_depth = 32;
  196678. }
  196679. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196680. {
  196681. if (max_pixel_depth <= 32)
  196682. max_pixel_depth = 32;
  196683. else
  196684. max_pixel_depth = 64;
  196685. }
  196686. }
  196687. #endif
  196688. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196689. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196690. {
  196691. if (
  196692. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196693. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196694. #endif
  196695. #if defined(PNG_READ_FILLER_SUPPORTED)
  196696. (png_ptr->transformations & (PNG_FILLER)) ||
  196697. #endif
  196698. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196699. {
  196700. if (max_pixel_depth <= 16)
  196701. max_pixel_depth = 32;
  196702. else
  196703. max_pixel_depth = 64;
  196704. }
  196705. else
  196706. {
  196707. if (max_pixel_depth <= 8)
  196708. {
  196709. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196710. max_pixel_depth = 32;
  196711. else
  196712. max_pixel_depth = 24;
  196713. }
  196714. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196715. max_pixel_depth = 64;
  196716. else
  196717. max_pixel_depth = 48;
  196718. }
  196719. }
  196720. #endif
  196721. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196722. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196723. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196724. {
  196725. int user_pixel_depth=png_ptr->user_transform_depth*
  196726. png_ptr->user_transform_channels;
  196727. if(user_pixel_depth > max_pixel_depth)
  196728. max_pixel_depth=user_pixel_depth;
  196729. }
  196730. #endif
  196731. /* align the width on the next larger 8 pixels. Mainly used
  196732. for interlacing */
  196733. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196734. /* calculate the maximum bytes needed, adding a byte and a pixel
  196735. for safety's sake */
  196736. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196737. 1 + ((max_pixel_depth + 7) >> 3);
  196738. #ifdef PNG_MAX_MALLOC_64K
  196739. if (row_bytes > (png_uint_32)65536L)
  196740. png_error(png_ptr, "This image requires a row greater than 64KB");
  196741. #endif
  196742. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196743. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196744. #ifdef PNG_MAX_MALLOC_64K
  196745. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196746. png_error(png_ptr, "This image requires a row greater than 64KB");
  196747. #endif
  196748. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196749. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196750. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196751. png_ptr->rowbytes + 1));
  196752. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196753. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196754. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196755. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196756. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196757. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196758. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196759. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196760. }
  196761. #endif /* PNG_READ_SUPPORTED */
  196762. /*** End of inlined file: pngrutil.c ***/
  196763. /*** Start of inlined file: pngset.c ***/
  196764. /* pngset.c - storage of image information into info struct
  196765. *
  196766. * Last changed in libpng 1.2.21 [October 4, 2007]
  196767. * For conditions of distribution and use, see copyright notice in png.h
  196768. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196769. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196770. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196771. *
  196772. * The functions here are used during reads to store data from the file
  196773. * into the info struct, and during writes to store application data
  196774. * into the info struct for writing into the file. This abstracts the
  196775. * info struct and allows us to change the structure in the future.
  196776. */
  196777. #define PNG_INTERNAL
  196778. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196779. #if defined(PNG_bKGD_SUPPORTED)
  196780. void PNGAPI
  196781. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196782. {
  196783. png_debug1(1, "in %s storage function\n", "bKGD");
  196784. if (png_ptr == NULL || info_ptr == NULL)
  196785. return;
  196786. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196787. info_ptr->valid |= PNG_INFO_bKGD;
  196788. }
  196789. #endif
  196790. #if defined(PNG_cHRM_SUPPORTED)
  196791. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196792. void PNGAPI
  196793. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196794. double white_x, double white_y, double red_x, double red_y,
  196795. double green_x, double green_y, double blue_x, double blue_y)
  196796. {
  196797. png_debug1(1, "in %s storage function\n", "cHRM");
  196798. if (png_ptr == NULL || info_ptr == NULL)
  196799. return;
  196800. if (white_x < 0.0 || white_y < 0.0 ||
  196801. red_x < 0.0 || red_y < 0.0 ||
  196802. green_x < 0.0 || green_y < 0.0 ||
  196803. blue_x < 0.0 || blue_y < 0.0)
  196804. {
  196805. png_warning(png_ptr,
  196806. "Ignoring attempt to set negative chromaticity value");
  196807. return;
  196808. }
  196809. if (white_x > 21474.83 || white_y > 21474.83 ||
  196810. red_x > 21474.83 || red_y > 21474.83 ||
  196811. green_x > 21474.83 || green_y > 21474.83 ||
  196812. blue_x > 21474.83 || blue_y > 21474.83)
  196813. {
  196814. png_warning(png_ptr,
  196815. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196816. return;
  196817. }
  196818. info_ptr->x_white = (float)white_x;
  196819. info_ptr->y_white = (float)white_y;
  196820. info_ptr->x_red = (float)red_x;
  196821. info_ptr->y_red = (float)red_y;
  196822. info_ptr->x_green = (float)green_x;
  196823. info_ptr->y_green = (float)green_y;
  196824. info_ptr->x_blue = (float)blue_x;
  196825. info_ptr->y_blue = (float)blue_y;
  196826. #ifdef PNG_FIXED_POINT_SUPPORTED
  196827. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196828. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196829. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196830. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196831. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196832. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196833. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196834. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196835. #endif
  196836. info_ptr->valid |= PNG_INFO_cHRM;
  196837. }
  196838. #endif
  196839. #ifdef PNG_FIXED_POINT_SUPPORTED
  196840. void PNGAPI
  196841. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196842. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196843. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196844. png_fixed_point blue_x, png_fixed_point blue_y)
  196845. {
  196846. png_debug1(1, "in %s storage function\n", "cHRM");
  196847. if (png_ptr == NULL || info_ptr == NULL)
  196848. return;
  196849. if (white_x < 0 || white_y < 0 ||
  196850. red_x < 0 || red_y < 0 ||
  196851. green_x < 0 || green_y < 0 ||
  196852. blue_x < 0 || blue_y < 0)
  196853. {
  196854. png_warning(png_ptr,
  196855. "Ignoring attempt to set negative chromaticity value");
  196856. return;
  196857. }
  196858. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196859. if (white_x > (double) PNG_UINT_31_MAX ||
  196860. white_y > (double) PNG_UINT_31_MAX ||
  196861. red_x > (double) PNG_UINT_31_MAX ||
  196862. red_y > (double) PNG_UINT_31_MAX ||
  196863. green_x > (double) PNG_UINT_31_MAX ||
  196864. green_y > (double) PNG_UINT_31_MAX ||
  196865. blue_x > (double) PNG_UINT_31_MAX ||
  196866. blue_y > (double) PNG_UINT_31_MAX)
  196867. #else
  196868. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196869. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196870. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196871. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196872. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196873. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196874. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196875. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196876. #endif
  196877. {
  196878. png_warning(png_ptr,
  196879. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196880. return;
  196881. }
  196882. info_ptr->int_x_white = white_x;
  196883. info_ptr->int_y_white = white_y;
  196884. info_ptr->int_x_red = red_x;
  196885. info_ptr->int_y_red = red_y;
  196886. info_ptr->int_x_green = green_x;
  196887. info_ptr->int_y_green = green_y;
  196888. info_ptr->int_x_blue = blue_x;
  196889. info_ptr->int_y_blue = blue_y;
  196890. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196891. info_ptr->x_white = (float)(white_x/100000.);
  196892. info_ptr->y_white = (float)(white_y/100000.);
  196893. info_ptr->x_red = (float)( red_x/100000.);
  196894. info_ptr->y_red = (float)( red_y/100000.);
  196895. info_ptr->x_green = (float)(green_x/100000.);
  196896. info_ptr->y_green = (float)(green_y/100000.);
  196897. info_ptr->x_blue = (float)( blue_x/100000.);
  196898. info_ptr->y_blue = (float)( blue_y/100000.);
  196899. #endif
  196900. info_ptr->valid |= PNG_INFO_cHRM;
  196901. }
  196902. #endif
  196903. #endif
  196904. #if defined(PNG_gAMA_SUPPORTED)
  196905. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196906. void PNGAPI
  196907. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196908. {
  196909. double gamma;
  196910. png_debug1(1, "in %s storage function\n", "gAMA");
  196911. if (png_ptr == NULL || info_ptr == NULL)
  196912. return;
  196913. /* Check for overflow */
  196914. if (file_gamma > 21474.83)
  196915. {
  196916. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196917. gamma=21474.83;
  196918. }
  196919. else
  196920. gamma=file_gamma;
  196921. info_ptr->gamma = (float)gamma;
  196922. #ifdef PNG_FIXED_POINT_SUPPORTED
  196923. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196924. #endif
  196925. info_ptr->valid |= PNG_INFO_gAMA;
  196926. if(gamma == 0.0)
  196927. png_warning(png_ptr, "Setting gamma=0");
  196928. }
  196929. #endif
  196930. void PNGAPI
  196931. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196932. int_gamma)
  196933. {
  196934. png_fixed_point gamma;
  196935. png_debug1(1, "in %s storage function\n", "gAMA");
  196936. if (png_ptr == NULL || info_ptr == NULL)
  196937. return;
  196938. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196939. {
  196940. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196941. gamma=PNG_UINT_31_MAX;
  196942. }
  196943. else
  196944. {
  196945. if (int_gamma < 0)
  196946. {
  196947. png_warning(png_ptr, "Setting negative gamma to zero");
  196948. gamma=0;
  196949. }
  196950. else
  196951. gamma=int_gamma;
  196952. }
  196953. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196954. info_ptr->gamma = (float)(gamma/100000.);
  196955. #endif
  196956. #ifdef PNG_FIXED_POINT_SUPPORTED
  196957. info_ptr->int_gamma = gamma;
  196958. #endif
  196959. info_ptr->valid |= PNG_INFO_gAMA;
  196960. if(gamma == 0)
  196961. png_warning(png_ptr, "Setting gamma=0");
  196962. }
  196963. #endif
  196964. #if defined(PNG_hIST_SUPPORTED)
  196965. void PNGAPI
  196966. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196967. {
  196968. int i;
  196969. png_debug1(1, "in %s storage function\n", "hIST");
  196970. if (png_ptr == NULL || info_ptr == NULL)
  196971. return;
  196972. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196973. > PNG_MAX_PALETTE_LENGTH)
  196974. {
  196975. png_warning(png_ptr,
  196976. "Invalid palette size, hIST allocation skipped.");
  196977. return;
  196978. }
  196979. #ifdef PNG_FREE_ME_SUPPORTED
  196980. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196981. #endif
  196982. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196983. 1.2.1 */
  196984. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196985. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196986. if (png_ptr->hist == NULL)
  196987. {
  196988. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196989. return;
  196990. }
  196991. for (i = 0; i < info_ptr->num_palette; i++)
  196992. png_ptr->hist[i] = hist[i];
  196993. info_ptr->hist = png_ptr->hist;
  196994. info_ptr->valid |= PNG_INFO_hIST;
  196995. #ifdef PNG_FREE_ME_SUPPORTED
  196996. info_ptr->free_me |= PNG_FREE_HIST;
  196997. #else
  196998. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196999. #endif
  197000. }
  197001. #endif
  197002. void PNGAPI
  197003. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  197004. png_uint_32 width, png_uint_32 height, int bit_depth,
  197005. int color_type, int interlace_type, int compression_type,
  197006. int filter_type)
  197007. {
  197008. png_debug1(1, "in %s storage function\n", "IHDR");
  197009. if (png_ptr == NULL || info_ptr == NULL)
  197010. return;
  197011. /* check for width and height valid values */
  197012. if (width == 0 || height == 0)
  197013. png_error(png_ptr, "Image width or height is zero in IHDR");
  197014. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197015. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  197016. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197017. #else
  197018. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  197019. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197020. #endif
  197021. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  197022. png_error(png_ptr, "Invalid image size in IHDR");
  197023. if ( width > (PNG_UINT_32_MAX
  197024. >> 3) /* 8-byte RGBA pixels */
  197025. - 64 /* bigrowbuf hack */
  197026. - 1 /* filter byte */
  197027. - 7*8 /* rounding of width to multiple of 8 pixels */
  197028. - 8) /* extra max_pixel_depth pad */
  197029. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  197030. /* check other values */
  197031. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  197032. bit_depth != 8 && bit_depth != 16)
  197033. png_error(png_ptr, "Invalid bit depth in IHDR");
  197034. if (color_type < 0 || color_type == 1 ||
  197035. color_type == 5 || color_type > 6)
  197036. png_error(png_ptr, "Invalid color type in IHDR");
  197037. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  197038. ((color_type == PNG_COLOR_TYPE_RGB ||
  197039. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  197040. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  197041. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  197042. if (interlace_type >= PNG_INTERLACE_LAST)
  197043. png_error(png_ptr, "Unknown interlace method in IHDR");
  197044. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197045. png_error(png_ptr, "Unknown compression method in IHDR");
  197046. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197047. /* Accept filter_method 64 (intrapixel differencing) only if
  197048. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197049. * 2. Libpng did not read a PNG signature (this filter_method is only
  197050. * used in PNG datastreams that are embedded in MNG datastreams) and
  197051. * 3. The application called png_permit_mng_features with a mask that
  197052. * included PNG_FLAG_MNG_FILTER_64 and
  197053. * 4. The filter_method is 64 and
  197054. * 5. The color_type is RGB or RGBA
  197055. */
  197056. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  197057. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197058. if(filter_type != PNG_FILTER_TYPE_BASE)
  197059. {
  197060. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197061. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  197062. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197063. (color_type == PNG_COLOR_TYPE_RGB ||
  197064. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  197065. png_error(png_ptr, "Unknown filter method in IHDR");
  197066. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197067. png_warning(png_ptr, "Invalid filter method in IHDR");
  197068. }
  197069. #else
  197070. if(filter_type != PNG_FILTER_TYPE_BASE)
  197071. png_error(png_ptr, "Unknown filter method in IHDR");
  197072. #endif
  197073. info_ptr->width = width;
  197074. info_ptr->height = height;
  197075. info_ptr->bit_depth = (png_byte)bit_depth;
  197076. info_ptr->color_type =(png_byte) color_type;
  197077. info_ptr->compression_type = (png_byte)compression_type;
  197078. info_ptr->filter_type = (png_byte)filter_type;
  197079. info_ptr->interlace_type = (png_byte)interlace_type;
  197080. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197081. info_ptr->channels = 1;
  197082. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197083. info_ptr->channels = 3;
  197084. else
  197085. info_ptr->channels = 1;
  197086. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197087. info_ptr->channels++;
  197088. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197089. /* check for potential overflow */
  197090. if (width > (PNG_UINT_32_MAX
  197091. >> 3) /* 8-byte RGBA pixels */
  197092. - 64 /* bigrowbuf hack */
  197093. - 1 /* filter byte */
  197094. - 7*8 /* rounding of width to multiple of 8 pixels */
  197095. - 8) /* extra max_pixel_depth pad */
  197096. info_ptr->rowbytes = (png_size_t)0;
  197097. else
  197098. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197099. }
  197100. #if defined(PNG_oFFs_SUPPORTED)
  197101. void PNGAPI
  197102. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197103. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197104. {
  197105. png_debug1(1, "in %s storage function\n", "oFFs");
  197106. if (png_ptr == NULL || info_ptr == NULL)
  197107. return;
  197108. info_ptr->x_offset = offset_x;
  197109. info_ptr->y_offset = offset_y;
  197110. info_ptr->offset_unit_type = (png_byte)unit_type;
  197111. info_ptr->valid |= PNG_INFO_oFFs;
  197112. }
  197113. #endif
  197114. #if defined(PNG_pCAL_SUPPORTED)
  197115. void PNGAPI
  197116. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197117. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197118. png_charp units, png_charpp params)
  197119. {
  197120. png_uint_32 length;
  197121. int i;
  197122. png_debug1(1, "in %s storage function\n", "pCAL");
  197123. if (png_ptr == NULL || info_ptr == NULL)
  197124. return;
  197125. length = png_strlen(purpose) + 1;
  197126. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197127. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197128. if (info_ptr->pcal_purpose == NULL)
  197129. {
  197130. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197131. return;
  197132. }
  197133. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197134. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197135. info_ptr->pcal_X0 = X0;
  197136. info_ptr->pcal_X1 = X1;
  197137. info_ptr->pcal_type = (png_byte)type;
  197138. info_ptr->pcal_nparams = (png_byte)nparams;
  197139. length = png_strlen(units) + 1;
  197140. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197141. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197142. if (info_ptr->pcal_units == NULL)
  197143. {
  197144. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197145. return;
  197146. }
  197147. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197148. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197149. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197150. if (info_ptr->pcal_params == NULL)
  197151. {
  197152. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197153. return;
  197154. }
  197155. info_ptr->pcal_params[nparams] = NULL;
  197156. for (i = 0; i < nparams; i++)
  197157. {
  197158. length = png_strlen(params[i]) + 1;
  197159. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197160. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197161. if (info_ptr->pcal_params[i] == NULL)
  197162. {
  197163. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197164. return;
  197165. }
  197166. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197167. }
  197168. info_ptr->valid |= PNG_INFO_pCAL;
  197169. #ifdef PNG_FREE_ME_SUPPORTED
  197170. info_ptr->free_me |= PNG_FREE_PCAL;
  197171. #endif
  197172. }
  197173. #endif
  197174. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197175. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197176. void PNGAPI
  197177. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197178. int unit, double width, double height)
  197179. {
  197180. png_debug1(1, "in %s storage function\n", "sCAL");
  197181. if (png_ptr == NULL || info_ptr == NULL)
  197182. return;
  197183. info_ptr->scal_unit = (png_byte)unit;
  197184. info_ptr->scal_pixel_width = width;
  197185. info_ptr->scal_pixel_height = height;
  197186. info_ptr->valid |= PNG_INFO_sCAL;
  197187. }
  197188. #else
  197189. #ifdef PNG_FIXED_POINT_SUPPORTED
  197190. void PNGAPI
  197191. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197192. int unit, png_charp swidth, png_charp sheight)
  197193. {
  197194. png_uint_32 length;
  197195. png_debug1(1, "in %s storage function\n", "sCAL");
  197196. if (png_ptr == NULL || info_ptr == NULL)
  197197. return;
  197198. info_ptr->scal_unit = (png_byte)unit;
  197199. length = png_strlen(swidth) + 1;
  197200. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197201. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197202. if (info_ptr->scal_s_width == NULL)
  197203. {
  197204. png_warning(png_ptr,
  197205. "Memory allocation failed while processing sCAL.");
  197206. }
  197207. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197208. length = png_strlen(sheight) + 1;
  197209. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197210. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197211. if (info_ptr->scal_s_height == NULL)
  197212. {
  197213. png_free (png_ptr, info_ptr->scal_s_width);
  197214. png_warning(png_ptr,
  197215. "Memory allocation failed while processing sCAL.");
  197216. }
  197217. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197218. info_ptr->valid |= PNG_INFO_sCAL;
  197219. #ifdef PNG_FREE_ME_SUPPORTED
  197220. info_ptr->free_me |= PNG_FREE_SCAL;
  197221. #endif
  197222. }
  197223. #endif
  197224. #endif
  197225. #endif
  197226. #if defined(PNG_pHYs_SUPPORTED)
  197227. void PNGAPI
  197228. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197229. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197230. {
  197231. png_debug1(1, "in %s storage function\n", "pHYs");
  197232. if (png_ptr == NULL || info_ptr == NULL)
  197233. return;
  197234. info_ptr->x_pixels_per_unit = res_x;
  197235. info_ptr->y_pixels_per_unit = res_y;
  197236. info_ptr->phys_unit_type = (png_byte)unit_type;
  197237. info_ptr->valid |= PNG_INFO_pHYs;
  197238. }
  197239. #endif
  197240. void PNGAPI
  197241. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197242. png_colorp palette, int num_palette)
  197243. {
  197244. png_debug1(1, "in %s storage function\n", "PLTE");
  197245. if (png_ptr == NULL || info_ptr == NULL)
  197246. return;
  197247. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197248. {
  197249. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197250. png_error(png_ptr, "Invalid palette length");
  197251. else
  197252. {
  197253. png_warning(png_ptr, "Invalid palette length");
  197254. return;
  197255. }
  197256. }
  197257. /*
  197258. * It may not actually be necessary to set png_ptr->palette here;
  197259. * we do it for backward compatibility with the way the png_handle_tRNS
  197260. * function used to do the allocation.
  197261. */
  197262. #ifdef PNG_FREE_ME_SUPPORTED
  197263. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197264. #endif
  197265. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197266. of num_palette entries,
  197267. in case of an invalid PNG file that has too-large sample values. */
  197268. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197269. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197270. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197271. png_sizeof(png_color));
  197272. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197273. info_ptr->palette = png_ptr->palette;
  197274. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197275. #ifdef PNG_FREE_ME_SUPPORTED
  197276. info_ptr->free_me |= PNG_FREE_PLTE;
  197277. #else
  197278. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197279. #endif
  197280. info_ptr->valid |= PNG_INFO_PLTE;
  197281. }
  197282. #if defined(PNG_sBIT_SUPPORTED)
  197283. void PNGAPI
  197284. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197285. png_color_8p sig_bit)
  197286. {
  197287. png_debug1(1, "in %s storage function\n", "sBIT");
  197288. if (png_ptr == NULL || info_ptr == NULL)
  197289. return;
  197290. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197291. info_ptr->valid |= PNG_INFO_sBIT;
  197292. }
  197293. #endif
  197294. #if defined(PNG_sRGB_SUPPORTED)
  197295. void PNGAPI
  197296. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197297. {
  197298. png_debug1(1, "in %s storage function\n", "sRGB");
  197299. if (png_ptr == NULL || info_ptr == NULL)
  197300. return;
  197301. info_ptr->srgb_intent = (png_byte)intent;
  197302. info_ptr->valid |= PNG_INFO_sRGB;
  197303. }
  197304. void PNGAPI
  197305. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197306. int intent)
  197307. {
  197308. #if defined(PNG_gAMA_SUPPORTED)
  197309. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197310. float file_gamma;
  197311. #endif
  197312. #ifdef PNG_FIXED_POINT_SUPPORTED
  197313. png_fixed_point int_file_gamma;
  197314. #endif
  197315. #endif
  197316. #if defined(PNG_cHRM_SUPPORTED)
  197317. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197318. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197319. #endif
  197320. #ifdef PNG_FIXED_POINT_SUPPORTED
  197321. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197322. int_green_y, int_blue_x, int_blue_y;
  197323. #endif
  197324. #endif
  197325. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197326. if (png_ptr == NULL || info_ptr == NULL)
  197327. return;
  197328. png_set_sRGB(png_ptr, info_ptr, intent);
  197329. #if defined(PNG_gAMA_SUPPORTED)
  197330. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197331. file_gamma = (float).45455;
  197332. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197333. #endif
  197334. #ifdef PNG_FIXED_POINT_SUPPORTED
  197335. int_file_gamma = 45455L;
  197336. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197337. #endif
  197338. #endif
  197339. #if defined(PNG_cHRM_SUPPORTED)
  197340. #ifdef PNG_FIXED_POINT_SUPPORTED
  197341. int_white_x = 31270L;
  197342. int_white_y = 32900L;
  197343. int_red_x = 64000L;
  197344. int_red_y = 33000L;
  197345. int_green_x = 30000L;
  197346. int_green_y = 60000L;
  197347. int_blue_x = 15000L;
  197348. int_blue_y = 6000L;
  197349. png_set_cHRM_fixed(png_ptr, info_ptr,
  197350. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197351. int_blue_x, int_blue_y);
  197352. #endif
  197353. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197354. white_x = (float).3127;
  197355. white_y = (float).3290;
  197356. red_x = (float).64;
  197357. red_y = (float).33;
  197358. green_x = (float).30;
  197359. green_y = (float).60;
  197360. blue_x = (float).15;
  197361. blue_y = (float).06;
  197362. png_set_cHRM(png_ptr, info_ptr,
  197363. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197364. #endif
  197365. #endif
  197366. }
  197367. #endif
  197368. #if defined(PNG_iCCP_SUPPORTED)
  197369. void PNGAPI
  197370. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197371. png_charp name, int compression_type,
  197372. png_charp profile, png_uint_32 proflen)
  197373. {
  197374. png_charp new_iccp_name;
  197375. png_charp new_iccp_profile;
  197376. png_debug1(1, "in %s storage function\n", "iCCP");
  197377. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197378. return;
  197379. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197380. if (new_iccp_name == NULL)
  197381. {
  197382. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197383. return;
  197384. }
  197385. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197386. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197387. if (new_iccp_profile == NULL)
  197388. {
  197389. png_free (png_ptr, new_iccp_name);
  197390. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197391. return;
  197392. }
  197393. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197394. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197395. info_ptr->iccp_proflen = proflen;
  197396. info_ptr->iccp_name = new_iccp_name;
  197397. info_ptr->iccp_profile = new_iccp_profile;
  197398. /* Compression is always zero but is here so the API and info structure
  197399. * does not have to change if we introduce multiple compression types */
  197400. info_ptr->iccp_compression = (png_byte)compression_type;
  197401. #ifdef PNG_FREE_ME_SUPPORTED
  197402. info_ptr->free_me |= PNG_FREE_ICCP;
  197403. #endif
  197404. info_ptr->valid |= PNG_INFO_iCCP;
  197405. }
  197406. #endif
  197407. #if defined(PNG_TEXT_SUPPORTED)
  197408. void PNGAPI
  197409. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197410. int num_text)
  197411. {
  197412. int ret;
  197413. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197414. if (ret)
  197415. png_error(png_ptr, "Insufficient memory to store text");
  197416. }
  197417. int /* PRIVATE */
  197418. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197419. int num_text)
  197420. {
  197421. int i;
  197422. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197423. "text" : (png_const_charp)png_ptr->chunk_name));
  197424. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197425. return(0);
  197426. /* Make sure we have enough space in the "text" array in info_struct
  197427. * to hold all of the incoming text_ptr objects.
  197428. */
  197429. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197430. {
  197431. if (info_ptr->text != NULL)
  197432. {
  197433. png_textp old_text;
  197434. int old_max;
  197435. old_max = info_ptr->max_text;
  197436. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197437. old_text = info_ptr->text;
  197438. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197439. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197440. if (info_ptr->text == NULL)
  197441. {
  197442. png_free(png_ptr, old_text);
  197443. return(1);
  197444. }
  197445. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197446. png_sizeof(png_text)));
  197447. png_free(png_ptr, old_text);
  197448. }
  197449. else
  197450. {
  197451. info_ptr->max_text = num_text + 8;
  197452. info_ptr->num_text = 0;
  197453. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197454. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197455. if (info_ptr->text == NULL)
  197456. return(1);
  197457. #ifdef PNG_FREE_ME_SUPPORTED
  197458. info_ptr->free_me |= PNG_FREE_TEXT;
  197459. #endif
  197460. }
  197461. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197462. info_ptr->max_text);
  197463. }
  197464. for (i = 0; i < num_text; i++)
  197465. {
  197466. png_size_t text_length,key_len;
  197467. png_size_t lang_len,lang_key_len;
  197468. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197469. if (text_ptr[i].key == NULL)
  197470. continue;
  197471. key_len = png_strlen(text_ptr[i].key);
  197472. if(text_ptr[i].compression <= 0)
  197473. {
  197474. lang_len = 0;
  197475. lang_key_len = 0;
  197476. }
  197477. else
  197478. #ifdef PNG_iTXt_SUPPORTED
  197479. {
  197480. /* set iTXt data */
  197481. if (text_ptr[i].lang != NULL)
  197482. lang_len = png_strlen(text_ptr[i].lang);
  197483. else
  197484. lang_len = 0;
  197485. if (text_ptr[i].lang_key != NULL)
  197486. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197487. else
  197488. lang_key_len = 0;
  197489. }
  197490. #else
  197491. {
  197492. png_warning(png_ptr, "iTXt chunk not supported.");
  197493. continue;
  197494. }
  197495. #endif
  197496. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197497. {
  197498. text_length = 0;
  197499. #ifdef PNG_iTXt_SUPPORTED
  197500. if(text_ptr[i].compression > 0)
  197501. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197502. else
  197503. #endif
  197504. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197505. }
  197506. else
  197507. {
  197508. text_length = png_strlen(text_ptr[i].text);
  197509. textp->compression = text_ptr[i].compression;
  197510. }
  197511. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197512. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197513. if (textp->key == NULL)
  197514. return(1);
  197515. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197516. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197517. (int)textp->key);
  197518. png_memcpy(textp->key, text_ptr[i].key,
  197519. (png_size_t)(key_len));
  197520. *(textp->key+key_len) = '\0';
  197521. #ifdef PNG_iTXt_SUPPORTED
  197522. if (text_ptr[i].compression > 0)
  197523. {
  197524. textp->lang=textp->key + key_len + 1;
  197525. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197526. *(textp->lang+lang_len) = '\0';
  197527. textp->lang_key=textp->lang + lang_len + 1;
  197528. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197529. *(textp->lang_key+lang_key_len) = '\0';
  197530. textp->text=textp->lang_key + lang_key_len + 1;
  197531. }
  197532. else
  197533. #endif
  197534. {
  197535. #ifdef PNG_iTXt_SUPPORTED
  197536. textp->lang=NULL;
  197537. textp->lang_key=NULL;
  197538. #endif
  197539. textp->text=textp->key + key_len + 1;
  197540. }
  197541. if(text_length)
  197542. png_memcpy(textp->text, text_ptr[i].text,
  197543. (png_size_t)(text_length));
  197544. *(textp->text+text_length) = '\0';
  197545. #ifdef PNG_iTXt_SUPPORTED
  197546. if(textp->compression > 0)
  197547. {
  197548. textp->text_length = 0;
  197549. textp->itxt_length = text_length;
  197550. }
  197551. else
  197552. #endif
  197553. {
  197554. textp->text_length = text_length;
  197555. #ifdef PNG_iTXt_SUPPORTED
  197556. textp->itxt_length = 0;
  197557. #endif
  197558. }
  197559. info_ptr->num_text++;
  197560. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197561. }
  197562. return(0);
  197563. }
  197564. #endif
  197565. #if defined(PNG_tIME_SUPPORTED)
  197566. void PNGAPI
  197567. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197568. {
  197569. png_debug1(1, "in %s storage function\n", "tIME");
  197570. if (png_ptr == NULL || info_ptr == NULL ||
  197571. (png_ptr->mode & PNG_WROTE_tIME))
  197572. return;
  197573. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197574. info_ptr->valid |= PNG_INFO_tIME;
  197575. }
  197576. #endif
  197577. #if defined(PNG_tRNS_SUPPORTED)
  197578. void PNGAPI
  197579. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197580. png_bytep trans, int num_trans, png_color_16p trans_values)
  197581. {
  197582. png_debug1(1, "in %s storage function\n", "tRNS");
  197583. if (png_ptr == NULL || info_ptr == NULL)
  197584. return;
  197585. if (trans != NULL)
  197586. {
  197587. /*
  197588. * It may not actually be necessary to set png_ptr->trans here;
  197589. * we do it for backward compatibility with the way the png_handle_tRNS
  197590. * function used to do the allocation.
  197591. */
  197592. #ifdef PNG_FREE_ME_SUPPORTED
  197593. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197594. #endif
  197595. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197596. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197597. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197598. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197599. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197600. #ifdef PNG_FREE_ME_SUPPORTED
  197601. info_ptr->free_me |= PNG_FREE_TRNS;
  197602. #else
  197603. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197604. #endif
  197605. }
  197606. if (trans_values != NULL)
  197607. {
  197608. png_memcpy(&(info_ptr->trans_values), trans_values,
  197609. png_sizeof(png_color_16));
  197610. if (num_trans == 0)
  197611. num_trans = 1;
  197612. }
  197613. info_ptr->num_trans = (png_uint_16)num_trans;
  197614. info_ptr->valid |= PNG_INFO_tRNS;
  197615. }
  197616. #endif
  197617. #if defined(PNG_sPLT_SUPPORTED)
  197618. void PNGAPI
  197619. png_set_sPLT(png_structp png_ptr,
  197620. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197621. {
  197622. png_sPLT_tp np;
  197623. int i;
  197624. if (png_ptr == NULL || info_ptr == NULL)
  197625. return;
  197626. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197627. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197628. if (np == NULL)
  197629. {
  197630. png_warning(png_ptr, "No memory for sPLT palettes.");
  197631. return;
  197632. }
  197633. png_memcpy(np, info_ptr->splt_palettes,
  197634. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197635. png_free(png_ptr, info_ptr->splt_palettes);
  197636. info_ptr->splt_palettes=NULL;
  197637. for (i = 0; i < nentries; i++)
  197638. {
  197639. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197640. png_sPLT_tp from = entries + i;
  197641. to->name = (png_charp)png_malloc_warn(png_ptr,
  197642. png_strlen(from->name) + 1);
  197643. if (to->name == NULL)
  197644. {
  197645. png_warning(png_ptr,
  197646. "Out of memory while processing sPLT chunk");
  197647. }
  197648. /* TODO: use png_malloc_warn */
  197649. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197650. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197651. from->nentries * png_sizeof(png_sPLT_entry));
  197652. /* TODO: use png_malloc_warn */
  197653. png_memcpy(to->entries, from->entries,
  197654. from->nentries * png_sizeof(png_sPLT_entry));
  197655. if (to->entries == NULL)
  197656. {
  197657. png_warning(png_ptr,
  197658. "Out of memory while processing sPLT chunk");
  197659. png_free(png_ptr,to->name);
  197660. to->name = NULL;
  197661. }
  197662. to->nentries = from->nentries;
  197663. to->depth = from->depth;
  197664. }
  197665. info_ptr->splt_palettes = np;
  197666. info_ptr->splt_palettes_num += nentries;
  197667. info_ptr->valid |= PNG_INFO_sPLT;
  197668. #ifdef PNG_FREE_ME_SUPPORTED
  197669. info_ptr->free_me |= PNG_FREE_SPLT;
  197670. #endif
  197671. }
  197672. #endif /* PNG_sPLT_SUPPORTED */
  197673. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197674. void PNGAPI
  197675. png_set_unknown_chunks(png_structp png_ptr,
  197676. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197677. {
  197678. png_unknown_chunkp np;
  197679. int i;
  197680. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197681. return;
  197682. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197683. (info_ptr->unknown_chunks_num + num_unknowns) *
  197684. png_sizeof(png_unknown_chunk));
  197685. if (np == NULL)
  197686. {
  197687. png_warning(png_ptr,
  197688. "Out of memory while processing unknown chunk.");
  197689. return;
  197690. }
  197691. png_memcpy(np, info_ptr->unknown_chunks,
  197692. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197693. png_free(png_ptr, info_ptr->unknown_chunks);
  197694. info_ptr->unknown_chunks=NULL;
  197695. for (i = 0; i < num_unknowns; i++)
  197696. {
  197697. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197698. png_unknown_chunkp from = unknowns + i;
  197699. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197700. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197701. if (to->data == NULL)
  197702. {
  197703. png_warning(png_ptr,
  197704. "Out of memory while processing unknown chunk.");
  197705. }
  197706. else
  197707. {
  197708. png_memcpy(to->data, from->data, from->size);
  197709. to->size = from->size;
  197710. /* note our location in the read or write sequence */
  197711. to->location = (png_byte)(png_ptr->mode & 0xff);
  197712. }
  197713. }
  197714. info_ptr->unknown_chunks = np;
  197715. info_ptr->unknown_chunks_num += num_unknowns;
  197716. #ifdef PNG_FREE_ME_SUPPORTED
  197717. info_ptr->free_me |= PNG_FREE_UNKN;
  197718. #endif
  197719. }
  197720. void PNGAPI
  197721. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197722. int chunk, int location)
  197723. {
  197724. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197725. (int)info_ptr->unknown_chunks_num)
  197726. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197727. }
  197728. #endif
  197729. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197730. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197731. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197732. void PNGAPI
  197733. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197734. {
  197735. /* This function is deprecated in favor of png_permit_mng_features()
  197736. and will be removed from libpng-1.3.0 */
  197737. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197738. if (png_ptr == NULL)
  197739. return;
  197740. png_ptr->mng_features_permitted = (png_byte)
  197741. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197742. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197743. }
  197744. #endif
  197745. #endif
  197746. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197747. png_uint_32 PNGAPI
  197748. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197749. {
  197750. png_debug(1, "in png_permit_mng_features\n");
  197751. if (png_ptr == NULL)
  197752. return (png_uint_32)0;
  197753. png_ptr->mng_features_permitted =
  197754. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197755. return (png_uint_32)png_ptr->mng_features_permitted;
  197756. }
  197757. #endif
  197758. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197759. void PNGAPI
  197760. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197761. chunk_list, int num_chunks)
  197762. {
  197763. png_bytep new_list, p;
  197764. int i, old_num_chunks;
  197765. if (png_ptr == NULL)
  197766. return;
  197767. if (num_chunks == 0)
  197768. {
  197769. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197770. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197771. else
  197772. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197773. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197774. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197775. else
  197776. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197777. return;
  197778. }
  197779. if (chunk_list == NULL)
  197780. return;
  197781. old_num_chunks=png_ptr->num_chunk_list;
  197782. new_list=(png_bytep)png_malloc(png_ptr,
  197783. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197784. if(png_ptr->chunk_list != NULL)
  197785. {
  197786. png_memcpy(new_list, png_ptr->chunk_list,
  197787. (png_size_t)(5*old_num_chunks));
  197788. png_free(png_ptr, png_ptr->chunk_list);
  197789. png_ptr->chunk_list=NULL;
  197790. }
  197791. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197792. (png_size_t)(5*num_chunks));
  197793. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197794. *p=(png_byte)keep;
  197795. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197796. png_ptr->chunk_list=new_list;
  197797. #ifdef PNG_FREE_ME_SUPPORTED
  197798. png_ptr->free_me |= PNG_FREE_LIST;
  197799. #endif
  197800. }
  197801. #endif
  197802. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197803. void PNGAPI
  197804. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197805. png_user_chunk_ptr read_user_chunk_fn)
  197806. {
  197807. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197808. if (png_ptr == NULL)
  197809. return;
  197810. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197811. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197812. }
  197813. #endif
  197814. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197815. void PNGAPI
  197816. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197817. {
  197818. png_debug1(1, "in %s storage function\n", "rows");
  197819. if (png_ptr == NULL || info_ptr == NULL)
  197820. return;
  197821. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197822. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197823. info_ptr->row_pointers = row_pointers;
  197824. if(row_pointers)
  197825. info_ptr->valid |= PNG_INFO_IDAT;
  197826. }
  197827. #endif
  197828. #ifdef PNG_WRITE_SUPPORTED
  197829. void PNGAPI
  197830. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197831. {
  197832. if (png_ptr == NULL)
  197833. return;
  197834. if(png_ptr->zbuf)
  197835. png_free(png_ptr, png_ptr->zbuf);
  197836. png_ptr->zbuf_size = (png_size_t)size;
  197837. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197838. png_ptr->zstream.next_out = png_ptr->zbuf;
  197839. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197840. }
  197841. #endif
  197842. void PNGAPI
  197843. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197844. {
  197845. if (png_ptr && info_ptr)
  197846. info_ptr->valid &= ~(mask);
  197847. }
  197848. #ifndef PNG_1_0_X
  197849. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197850. /* function was added to libpng 1.2.0 and should always exist by default */
  197851. void PNGAPI
  197852. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197853. {
  197854. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197855. if (png_ptr != NULL)
  197856. png_ptr->asm_flags = 0;
  197857. }
  197858. /* this function was added to libpng 1.2.0 */
  197859. void PNGAPI
  197860. png_set_mmx_thresholds (png_structp png_ptr,
  197861. png_byte,
  197862. png_uint_32)
  197863. {
  197864. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197865. if (png_ptr == NULL)
  197866. return;
  197867. }
  197868. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197869. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197870. /* this function was added to libpng 1.2.6 */
  197871. void PNGAPI
  197872. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197873. png_uint_32 user_height_max)
  197874. {
  197875. /* Images with dimensions larger than these limits will be
  197876. * rejected by png_set_IHDR(). To accept any PNG datastream
  197877. * regardless of dimensions, set both limits to 0x7ffffffL.
  197878. */
  197879. if(png_ptr == NULL) return;
  197880. png_ptr->user_width_max = user_width_max;
  197881. png_ptr->user_height_max = user_height_max;
  197882. }
  197883. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197884. #endif /* ?PNG_1_0_X */
  197885. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197886. /*** End of inlined file: pngset.c ***/
  197887. /*** Start of inlined file: pngtrans.c ***/
  197888. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197889. *
  197890. * Last changed in libpng 1.2.17 May 15, 2007
  197891. * For conditions of distribution and use, see copyright notice in png.h
  197892. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197893. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197894. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197895. */
  197896. #define PNG_INTERNAL
  197897. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197898. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197899. /* turn on BGR-to-RGB mapping */
  197900. void PNGAPI
  197901. png_set_bgr(png_structp png_ptr)
  197902. {
  197903. png_debug(1, "in png_set_bgr\n");
  197904. if(png_ptr == NULL) return;
  197905. png_ptr->transformations |= PNG_BGR;
  197906. }
  197907. #endif
  197908. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197909. /* turn on 16 bit byte swapping */
  197910. void PNGAPI
  197911. png_set_swap(png_structp png_ptr)
  197912. {
  197913. png_debug(1, "in png_set_swap\n");
  197914. if(png_ptr == NULL) return;
  197915. if (png_ptr->bit_depth == 16)
  197916. png_ptr->transformations |= PNG_SWAP_BYTES;
  197917. }
  197918. #endif
  197919. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197920. /* turn on pixel packing */
  197921. void PNGAPI
  197922. png_set_packing(png_structp png_ptr)
  197923. {
  197924. png_debug(1, "in png_set_packing\n");
  197925. if(png_ptr == NULL) return;
  197926. if (png_ptr->bit_depth < 8)
  197927. {
  197928. png_ptr->transformations |= PNG_PACK;
  197929. png_ptr->usr_bit_depth = 8;
  197930. }
  197931. }
  197932. #endif
  197933. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197934. /* turn on packed pixel swapping */
  197935. void PNGAPI
  197936. png_set_packswap(png_structp png_ptr)
  197937. {
  197938. png_debug(1, "in png_set_packswap\n");
  197939. if(png_ptr == NULL) return;
  197940. if (png_ptr->bit_depth < 8)
  197941. png_ptr->transformations |= PNG_PACKSWAP;
  197942. }
  197943. #endif
  197944. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197945. void PNGAPI
  197946. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197947. {
  197948. png_debug(1, "in png_set_shift\n");
  197949. if(png_ptr == NULL) return;
  197950. png_ptr->transformations |= PNG_SHIFT;
  197951. png_ptr->shift = *true_bits;
  197952. }
  197953. #endif
  197954. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197955. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197956. int PNGAPI
  197957. png_set_interlace_handling(png_structp png_ptr)
  197958. {
  197959. png_debug(1, "in png_set_interlace handling\n");
  197960. if (png_ptr && png_ptr->interlaced)
  197961. {
  197962. png_ptr->transformations |= PNG_INTERLACE;
  197963. return (7);
  197964. }
  197965. return (1);
  197966. }
  197967. #endif
  197968. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197969. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197970. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197971. * for 48-bit input data, as well as to avoid problems with some compilers
  197972. * that don't like bytes as parameters.
  197973. */
  197974. void PNGAPI
  197975. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197976. {
  197977. png_debug(1, "in png_set_filler\n");
  197978. if(png_ptr == NULL) return;
  197979. png_ptr->transformations |= PNG_FILLER;
  197980. png_ptr->filler = (png_byte)filler;
  197981. if (filler_loc == PNG_FILLER_AFTER)
  197982. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197983. else
  197984. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197985. /* This should probably go in the "do_read_filler" routine.
  197986. * I attempted to do that in libpng-1.0.1a but that caused problems
  197987. * so I restored it in libpng-1.0.2a
  197988. */
  197989. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197990. {
  197991. png_ptr->usr_channels = 4;
  197992. }
  197993. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197994. * a less-than-8-bit grayscale to GA? */
  197995. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197996. {
  197997. png_ptr->usr_channels = 2;
  197998. }
  197999. }
  198000. #if !defined(PNG_1_0_X)
  198001. /* Added to libpng-1.2.7 */
  198002. void PNGAPI
  198003. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198004. {
  198005. png_debug(1, "in png_set_add_alpha\n");
  198006. if(png_ptr == NULL) return;
  198007. png_set_filler(png_ptr, filler, filler_loc);
  198008. png_ptr->transformations |= PNG_ADD_ALPHA;
  198009. }
  198010. #endif
  198011. #endif
  198012. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  198013. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198014. void PNGAPI
  198015. png_set_swap_alpha(png_structp png_ptr)
  198016. {
  198017. png_debug(1, "in png_set_swap_alpha\n");
  198018. if(png_ptr == NULL) return;
  198019. png_ptr->transformations |= PNG_SWAP_ALPHA;
  198020. }
  198021. #endif
  198022. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  198023. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198024. void PNGAPI
  198025. png_set_invert_alpha(png_structp png_ptr)
  198026. {
  198027. png_debug(1, "in png_set_invert_alpha\n");
  198028. if(png_ptr == NULL) return;
  198029. png_ptr->transformations |= PNG_INVERT_ALPHA;
  198030. }
  198031. #endif
  198032. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  198033. void PNGAPI
  198034. png_set_invert_mono(png_structp png_ptr)
  198035. {
  198036. png_debug(1, "in png_set_invert_mono\n");
  198037. if(png_ptr == NULL) return;
  198038. png_ptr->transformations |= PNG_INVERT_MONO;
  198039. }
  198040. /* invert monochrome grayscale data */
  198041. void /* PRIVATE */
  198042. png_do_invert(png_row_infop row_info, png_bytep row)
  198043. {
  198044. png_debug(1, "in png_do_invert\n");
  198045. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198046. * if (row_info->bit_depth == 1 &&
  198047. */
  198048. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198049. if (row == NULL || row_info == NULL)
  198050. return;
  198051. #endif
  198052. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  198053. {
  198054. png_bytep rp = row;
  198055. png_uint_32 i;
  198056. png_uint_32 istop = row_info->rowbytes;
  198057. for (i = 0; i < istop; i++)
  198058. {
  198059. *rp = (png_byte)(~(*rp));
  198060. rp++;
  198061. }
  198062. }
  198063. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198064. row_info->bit_depth == 8)
  198065. {
  198066. png_bytep rp = row;
  198067. png_uint_32 i;
  198068. png_uint_32 istop = row_info->rowbytes;
  198069. for (i = 0; i < istop; i+=2)
  198070. {
  198071. *rp = (png_byte)(~(*rp));
  198072. rp+=2;
  198073. }
  198074. }
  198075. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198076. row_info->bit_depth == 16)
  198077. {
  198078. png_bytep rp = row;
  198079. png_uint_32 i;
  198080. png_uint_32 istop = row_info->rowbytes;
  198081. for (i = 0; i < istop; i+=4)
  198082. {
  198083. *rp = (png_byte)(~(*rp));
  198084. *(rp+1) = (png_byte)(~(*(rp+1)));
  198085. rp+=4;
  198086. }
  198087. }
  198088. }
  198089. #endif
  198090. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198091. /* swaps byte order on 16 bit depth images */
  198092. void /* PRIVATE */
  198093. png_do_swap(png_row_infop row_info, png_bytep row)
  198094. {
  198095. png_debug(1, "in png_do_swap\n");
  198096. if (
  198097. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198098. row != NULL && row_info != NULL &&
  198099. #endif
  198100. row_info->bit_depth == 16)
  198101. {
  198102. png_bytep rp = row;
  198103. png_uint_32 i;
  198104. png_uint_32 istop= row_info->width * row_info->channels;
  198105. for (i = 0; i < istop; i++, rp += 2)
  198106. {
  198107. png_byte t = *rp;
  198108. *rp = *(rp + 1);
  198109. *(rp + 1) = t;
  198110. }
  198111. }
  198112. }
  198113. #endif
  198114. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198115. static PNG_CONST png_byte onebppswaptable[256] = {
  198116. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198117. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198118. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198119. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198120. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198121. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198122. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198123. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198124. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198125. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198126. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198127. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198128. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198129. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198130. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198131. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198132. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198133. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198134. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198135. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198136. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198137. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198138. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198139. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198140. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198141. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198142. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198143. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198144. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198145. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198146. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198147. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198148. };
  198149. static PNG_CONST png_byte twobppswaptable[256] = {
  198150. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198151. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198152. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198153. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198154. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198155. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198156. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198157. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198158. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198159. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198160. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198161. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198162. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198163. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198164. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198165. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198166. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198167. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198168. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198169. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198170. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198171. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198172. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198173. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198174. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198175. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198176. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198177. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198178. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198179. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198180. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198181. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198182. };
  198183. static PNG_CONST png_byte fourbppswaptable[256] = {
  198184. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198185. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198186. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198187. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198188. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198189. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198190. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198191. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198192. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198193. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198194. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198195. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198196. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198197. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198198. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198199. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198200. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198201. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198202. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198203. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198204. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198205. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198206. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198207. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198208. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198209. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198210. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198211. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198212. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198213. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198214. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198215. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198216. };
  198217. /* swaps pixel packing order within bytes */
  198218. void /* PRIVATE */
  198219. png_do_packswap(png_row_infop row_info, png_bytep row)
  198220. {
  198221. png_debug(1, "in png_do_packswap\n");
  198222. if (
  198223. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198224. row != NULL && row_info != NULL &&
  198225. #endif
  198226. row_info->bit_depth < 8)
  198227. {
  198228. png_bytep rp, end, table;
  198229. end = row + row_info->rowbytes;
  198230. if (row_info->bit_depth == 1)
  198231. table = (png_bytep)onebppswaptable;
  198232. else if (row_info->bit_depth == 2)
  198233. table = (png_bytep)twobppswaptable;
  198234. else if (row_info->bit_depth == 4)
  198235. table = (png_bytep)fourbppswaptable;
  198236. else
  198237. return;
  198238. for (rp = row; rp < end; rp++)
  198239. *rp = table[*rp];
  198240. }
  198241. }
  198242. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198243. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198244. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198245. /* remove filler or alpha byte(s) */
  198246. void /* PRIVATE */
  198247. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198248. {
  198249. png_debug(1, "in png_do_strip_filler\n");
  198250. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198251. if (row != NULL && row_info != NULL)
  198252. #endif
  198253. {
  198254. png_bytep sp=row;
  198255. png_bytep dp=row;
  198256. png_uint_32 row_width=row_info->width;
  198257. png_uint_32 i;
  198258. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198259. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198260. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198261. row_info->channels == 4)
  198262. {
  198263. if (row_info->bit_depth == 8)
  198264. {
  198265. /* This converts from RGBX or RGBA to RGB */
  198266. if (flags & PNG_FLAG_FILLER_AFTER)
  198267. {
  198268. dp+=3; sp+=4;
  198269. for (i = 1; i < row_width; i++)
  198270. {
  198271. *dp++ = *sp++;
  198272. *dp++ = *sp++;
  198273. *dp++ = *sp++;
  198274. sp++;
  198275. }
  198276. }
  198277. /* This converts from XRGB or ARGB to RGB */
  198278. else
  198279. {
  198280. for (i = 0; i < row_width; i++)
  198281. {
  198282. sp++;
  198283. *dp++ = *sp++;
  198284. *dp++ = *sp++;
  198285. *dp++ = *sp++;
  198286. }
  198287. }
  198288. row_info->pixel_depth = 24;
  198289. row_info->rowbytes = row_width * 3;
  198290. }
  198291. else /* if (row_info->bit_depth == 16) */
  198292. {
  198293. if (flags & PNG_FLAG_FILLER_AFTER)
  198294. {
  198295. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198296. sp += 8; dp += 6;
  198297. for (i = 1; i < row_width; i++)
  198298. {
  198299. /* This could be (although png_memcpy is probably slower):
  198300. png_memcpy(dp, sp, 6);
  198301. sp += 8;
  198302. dp += 6;
  198303. */
  198304. *dp++ = *sp++;
  198305. *dp++ = *sp++;
  198306. *dp++ = *sp++;
  198307. *dp++ = *sp++;
  198308. *dp++ = *sp++;
  198309. *dp++ = *sp++;
  198310. sp += 2;
  198311. }
  198312. }
  198313. else
  198314. {
  198315. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198316. for (i = 0; i < row_width; i++)
  198317. {
  198318. /* This could be (although png_memcpy is probably slower):
  198319. png_memcpy(dp, sp, 6);
  198320. sp += 8;
  198321. dp += 6;
  198322. */
  198323. sp+=2;
  198324. *dp++ = *sp++;
  198325. *dp++ = *sp++;
  198326. *dp++ = *sp++;
  198327. *dp++ = *sp++;
  198328. *dp++ = *sp++;
  198329. *dp++ = *sp++;
  198330. }
  198331. }
  198332. row_info->pixel_depth = 48;
  198333. row_info->rowbytes = row_width * 6;
  198334. }
  198335. row_info->channels = 3;
  198336. }
  198337. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198338. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198339. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198340. row_info->channels == 2)
  198341. {
  198342. if (row_info->bit_depth == 8)
  198343. {
  198344. /* This converts from GX or GA to G */
  198345. if (flags & PNG_FLAG_FILLER_AFTER)
  198346. {
  198347. for (i = 0; i < row_width; i++)
  198348. {
  198349. *dp++ = *sp++;
  198350. sp++;
  198351. }
  198352. }
  198353. /* This converts from XG or AG to G */
  198354. else
  198355. {
  198356. for (i = 0; i < row_width; i++)
  198357. {
  198358. sp++;
  198359. *dp++ = *sp++;
  198360. }
  198361. }
  198362. row_info->pixel_depth = 8;
  198363. row_info->rowbytes = row_width;
  198364. }
  198365. else /* if (row_info->bit_depth == 16) */
  198366. {
  198367. if (flags & PNG_FLAG_FILLER_AFTER)
  198368. {
  198369. /* This converts from GGXX or GGAA to GG */
  198370. sp += 4; dp += 2;
  198371. for (i = 1; i < row_width; i++)
  198372. {
  198373. *dp++ = *sp++;
  198374. *dp++ = *sp++;
  198375. sp += 2;
  198376. }
  198377. }
  198378. else
  198379. {
  198380. /* This converts from XXGG or AAGG to GG */
  198381. for (i = 0; i < row_width; i++)
  198382. {
  198383. sp += 2;
  198384. *dp++ = *sp++;
  198385. *dp++ = *sp++;
  198386. }
  198387. }
  198388. row_info->pixel_depth = 16;
  198389. row_info->rowbytes = row_width * 2;
  198390. }
  198391. row_info->channels = 1;
  198392. }
  198393. if (flags & PNG_FLAG_STRIP_ALPHA)
  198394. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198395. }
  198396. }
  198397. #endif
  198398. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198399. /* swaps red and blue bytes within a pixel */
  198400. void /* PRIVATE */
  198401. png_do_bgr(png_row_infop row_info, png_bytep row)
  198402. {
  198403. png_debug(1, "in png_do_bgr\n");
  198404. if (
  198405. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198406. row != NULL && row_info != NULL &&
  198407. #endif
  198408. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198409. {
  198410. png_uint_32 row_width = row_info->width;
  198411. if (row_info->bit_depth == 8)
  198412. {
  198413. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198414. {
  198415. png_bytep rp;
  198416. png_uint_32 i;
  198417. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198418. {
  198419. png_byte save = *rp;
  198420. *rp = *(rp + 2);
  198421. *(rp + 2) = save;
  198422. }
  198423. }
  198424. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198425. {
  198426. png_bytep rp;
  198427. png_uint_32 i;
  198428. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198429. {
  198430. png_byte save = *rp;
  198431. *rp = *(rp + 2);
  198432. *(rp + 2) = save;
  198433. }
  198434. }
  198435. }
  198436. else if (row_info->bit_depth == 16)
  198437. {
  198438. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198439. {
  198440. png_bytep rp;
  198441. png_uint_32 i;
  198442. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198443. {
  198444. png_byte save = *rp;
  198445. *rp = *(rp + 4);
  198446. *(rp + 4) = save;
  198447. save = *(rp + 1);
  198448. *(rp + 1) = *(rp + 5);
  198449. *(rp + 5) = save;
  198450. }
  198451. }
  198452. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198453. {
  198454. png_bytep rp;
  198455. png_uint_32 i;
  198456. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198457. {
  198458. png_byte save = *rp;
  198459. *rp = *(rp + 4);
  198460. *(rp + 4) = save;
  198461. save = *(rp + 1);
  198462. *(rp + 1) = *(rp + 5);
  198463. *(rp + 5) = save;
  198464. }
  198465. }
  198466. }
  198467. }
  198468. }
  198469. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198470. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198471. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198472. defined(PNG_LEGACY_SUPPORTED)
  198473. void PNGAPI
  198474. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198475. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198476. {
  198477. png_debug(1, "in png_set_user_transform_info\n");
  198478. if(png_ptr == NULL) return;
  198479. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198480. png_ptr->user_transform_ptr = user_transform_ptr;
  198481. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198482. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198483. #else
  198484. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198485. png_warning(png_ptr,
  198486. "This version of libpng does not support user transform info");
  198487. #endif
  198488. }
  198489. #endif
  198490. /* This function returns a pointer to the user_transform_ptr associated with
  198491. * the user transform functions. The application should free any memory
  198492. * associated with this pointer before png_write_destroy and png_read_destroy
  198493. * are called.
  198494. */
  198495. png_voidp PNGAPI
  198496. png_get_user_transform_ptr(png_structp png_ptr)
  198497. {
  198498. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198499. if (png_ptr == NULL) return (NULL);
  198500. return ((png_voidp)png_ptr->user_transform_ptr);
  198501. #else
  198502. return (NULL);
  198503. #endif
  198504. }
  198505. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198506. /*** End of inlined file: pngtrans.c ***/
  198507. /*** Start of inlined file: pngwio.c ***/
  198508. /* pngwio.c - functions for data output
  198509. *
  198510. * Last changed in libpng 1.2.13 November 13, 2006
  198511. * For conditions of distribution and use, see copyright notice in png.h
  198512. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198513. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198514. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198515. *
  198516. * This file provides a location for all output. Users who need
  198517. * special handling are expected to write functions that have the same
  198518. * arguments as these and perform similar functions, but that possibly
  198519. * use different output methods. Note that you shouldn't change these
  198520. * functions, but rather write replacement functions and then change
  198521. * them at run time with png_set_write_fn(...).
  198522. */
  198523. #define PNG_INTERNAL
  198524. #ifdef PNG_WRITE_SUPPORTED
  198525. /* Write the data to whatever output you are using. The default routine
  198526. writes to a file pointer. Note that this routine sometimes gets called
  198527. with very small lengths, so you should implement some kind of simple
  198528. buffering if you are using unbuffered writes. This should never be asked
  198529. to write more than 64K on a 16 bit machine. */
  198530. void /* PRIVATE */
  198531. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198532. {
  198533. if (png_ptr->write_data_fn != NULL )
  198534. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198535. else
  198536. png_error(png_ptr, "Call to NULL write function");
  198537. }
  198538. #if !defined(PNG_NO_STDIO)
  198539. /* This is the function that does the actual writing of data. If you are
  198540. not writing to a standard C stream, you should create a replacement
  198541. write_data function and use it at run time with png_set_write_fn(), rather
  198542. than changing the library. */
  198543. #ifndef USE_FAR_KEYWORD
  198544. void PNGAPI
  198545. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198546. {
  198547. png_uint_32 check;
  198548. if(png_ptr == NULL) return;
  198549. #if defined(_WIN32_WCE)
  198550. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198551. check = 0;
  198552. #else
  198553. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198554. #endif
  198555. if (check != length)
  198556. png_error(png_ptr, "Write Error");
  198557. }
  198558. #else
  198559. /* this is the model-independent version. Since the standard I/O library
  198560. can't handle far buffers in the medium and small models, we have to copy
  198561. the data.
  198562. */
  198563. #define NEAR_BUF_SIZE 1024
  198564. #define MIN(a,b) (a <= b ? a : b)
  198565. void PNGAPI
  198566. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198567. {
  198568. png_uint_32 check;
  198569. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198570. png_FILE_p io_ptr;
  198571. if(png_ptr == NULL) return;
  198572. /* Check if data really is near. If so, use usual code. */
  198573. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198574. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198575. if ((png_bytep)near_data == data)
  198576. {
  198577. #if defined(_WIN32_WCE)
  198578. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198579. check = 0;
  198580. #else
  198581. check = fwrite(near_data, 1, length, io_ptr);
  198582. #endif
  198583. }
  198584. else
  198585. {
  198586. png_byte buf[NEAR_BUF_SIZE];
  198587. png_size_t written, remaining, err;
  198588. check = 0;
  198589. remaining = length;
  198590. do
  198591. {
  198592. written = MIN(NEAR_BUF_SIZE, remaining);
  198593. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198594. #if defined(_WIN32_WCE)
  198595. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198596. err = 0;
  198597. #else
  198598. err = fwrite(buf, 1, written, io_ptr);
  198599. #endif
  198600. if (err != written)
  198601. break;
  198602. else
  198603. check += err;
  198604. data += written;
  198605. remaining -= written;
  198606. }
  198607. while (remaining != 0);
  198608. }
  198609. if (check != length)
  198610. png_error(png_ptr, "Write Error");
  198611. }
  198612. #endif
  198613. #endif
  198614. /* This function is called to output any data pending writing (normally
  198615. to disk). After png_flush is called, there should be no data pending
  198616. writing in any buffers. */
  198617. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198618. void /* PRIVATE */
  198619. png_flush(png_structp png_ptr)
  198620. {
  198621. if (png_ptr->output_flush_fn != NULL)
  198622. (*(png_ptr->output_flush_fn))(png_ptr);
  198623. }
  198624. #if !defined(PNG_NO_STDIO)
  198625. void PNGAPI
  198626. png_default_flush(png_structp png_ptr)
  198627. {
  198628. #if !defined(_WIN32_WCE)
  198629. png_FILE_p io_ptr;
  198630. #endif
  198631. if(png_ptr == NULL) return;
  198632. #if !defined(_WIN32_WCE)
  198633. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198634. if (io_ptr != NULL)
  198635. fflush(io_ptr);
  198636. #endif
  198637. }
  198638. #endif
  198639. #endif
  198640. /* This function allows the application to supply new output functions for
  198641. libpng if standard C streams aren't being used.
  198642. This function takes as its arguments:
  198643. png_ptr - pointer to a png output data structure
  198644. io_ptr - pointer to user supplied structure containing info about
  198645. the output functions. May be NULL.
  198646. write_data_fn - pointer to a new output function that takes as its
  198647. arguments a pointer to a png_struct, a pointer to
  198648. data to be written, and a 32-bit unsigned int that is
  198649. the number of bytes to be written. The new write
  198650. function should call png_error(png_ptr, "Error msg")
  198651. to exit and output any fatal error messages.
  198652. flush_data_fn - pointer to a new flush function that takes as its
  198653. arguments a pointer to a png_struct. After a call to
  198654. the flush function, there should be no data in any buffers
  198655. or pending transmission. If the output method doesn't do
  198656. any buffering of ouput, a function prototype must still be
  198657. supplied although it doesn't have to do anything. If
  198658. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198659. time, output_flush_fn will be ignored, although it must be
  198660. supplied for compatibility. */
  198661. void PNGAPI
  198662. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198663. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198664. {
  198665. if(png_ptr == NULL) return;
  198666. png_ptr->io_ptr = io_ptr;
  198667. #if !defined(PNG_NO_STDIO)
  198668. if (write_data_fn != NULL)
  198669. png_ptr->write_data_fn = write_data_fn;
  198670. else
  198671. png_ptr->write_data_fn = png_default_write_data;
  198672. #else
  198673. png_ptr->write_data_fn = write_data_fn;
  198674. #endif
  198675. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198676. #if !defined(PNG_NO_STDIO)
  198677. if (output_flush_fn != NULL)
  198678. png_ptr->output_flush_fn = output_flush_fn;
  198679. else
  198680. png_ptr->output_flush_fn = png_default_flush;
  198681. #else
  198682. png_ptr->output_flush_fn = output_flush_fn;
  198683. #endif
  198684. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198685. /* It is an error to read while writing a png file */
  198686. if (png_ptr->read_data_fn != NULL)
  198687. {
  198688. png_ptr->read_data_fn = NULL;
  198689. png_warning(png_ptr,
  198690. "Attempted to set both read_data_fn and write_data_fn in");
  198691. png_warning(png_ptr,
  198692. "the same structure. Resetting read_data_fn to NULL.");
  198693. }
  198694. }
  198695. #if defined(USE_FAR_KEYWORD)
  198696. #if defined(_MSC_VER)
  198697. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198698. {
  198699. void *near_ptr;
  198700. void FAR *far_ptr;
  198701. FP_OFF(near_ptr) = FP_OFF(ptr);
  198702. far_ptr = (void FAR *)near_ptr;
  198703. if(check != 0)
  198704. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198705. png_error(png_ptr,"segment lost in conversion");
  198706. return(near_ptr);
  198707. }
  198708. # else
  198709. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198710. {
  198711. void *near_ptr;
  198712. void FAR *far_ptr;
  198713. near_ptr = (void FAR *)ptr;
  198714. far_ptr = (void FAR *)near_ptr;
  198715. if(check != 0)
  198716. if(far_ptr != ptr)
  198717. png_error(png_ptr,"segment lost in conversion");
  198718. return(near_ptr);
  198719. }
  198720. # endif
  198721. # endif
  198722. #endif /* PNG_WRITE_SUPPORTED */
  198723. /*** End of inlined file: pngwio.c ***/
  198724. /*** Start of inlined file: pngwrite.c ***/
  198725. /* pngwrite.c - general routines to write a PNG file
  198726. *
  198727. * Last changed in libpng 1.2.15 January 5, 2007
  198728. * For conditions of distribution and use, see copyright notice in png.h
  198729. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198730. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198731. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198732. */
  198733. /* get internal access to png.h */
  198734. #define PNG_INTERNAL
  198735. #ifdef PNG_WRITE_SUPPORTED
  198736. /* Writes all the PNG information. This is the suggested way to use the
  198737. * library. If you have a new chunk to add, make a function to write it,
  198738. * and put it in the correct location here. If you want the chunk written
  198739. * after the image data, put it in png_write_end(). I strongly encourage
  198740. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198741. * the chunk, as that will keep the code from breaking if you want to just
  198742. * write a plain PNG file. If you have long comments, I suggest writing
  198743. * them in png_write_end(), and compressing them.
  198744. */
  198745. void PNGAPI
  198746. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198747. {
  198748. png_debug(1, "in png_write_info_before_PLTE\n");
  198749. if (png_ptr == NULL || info_ptr == NULL)
  198750. return;
  198751. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198752. {
  198753. png_write_sig(png_ptr); /* write PNG signature */
  198754. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198755. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198756. {
  198757. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198758. png_ptr->mng_features_permitted=0;
  198759. }
  198760. #endif
  198761. /* write IHDR information. */
  198762. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198763. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198764. info_ptr->filter_type,
  198765. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198766. info_ptr->interlace_type);
  198767. #else
  198768. 0);
  198769. #endif
  198770. /* the rest of these check to see if the valid field has the appropriate
  198771. flag set, and if it does, writes the chunk. */
  198772. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198773. if (info_ptr->valid & PNG_INFO_gAMA)
  198774. {
  198775. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198776. png_write_gAMA(png_ptr, info_ptr->gamma);
  198777. #else
  198778. #ifdef PNG_FIXED_POINT_SUPPORTED
  198779. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198780. # endif
  198781. #endif
  198782. }
  198783. #endif
  198784. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198785. if (info_ptr->valid & PNG_INFO_sRGB)
  198786. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198787. #endif
  198788. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198789. if (info_ptr->valid & PNG_INFO_iCCP)
  198790. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198791. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198792. #endif
  198793. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198794. if (info_ptr->valid & PNG_INFO_sBIT)
  198795. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198796. #endif
  198797. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198798. if (info_ptr->valid & PNG_INFO_cHRM)
  198799. {
  198800. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198801. png_write_cHRM(png_ptr,
  198802. info_ptr->x_white, info_ptr->y_white,
  198803. info_ptr->x_red, info_ptr->y_red,
  198804. info_ptr->x_green, info_ptr->y_green,
  198805. info_ptr->x_blue, info_ptr->y_blue);
  198806. #else
  198807. # ifdef PNG_FIXED_POINT_SUPPORTED
  198808. png_write_cHRM_fixed(png_ptr,
  198809. info_ptr->int_x_white, info_ptr->int_y_white,
  198810. info_ptr->int_x_red, info_ptr->int_y_red,
  198811. info_ptr->int_x_green, info_ptr->int_y_green,
  198812. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198813. # endif
  198814. #endif
  198815. }
  198816. #endif
  198817. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198818. if (info_ptr->unknown_chunks_num)
  198819. {
  198820. png_unknown_chunk *up;
  198821. png_debug(5, "writing extra chunks\n");
  198822. for (up = info_ptr->unknown_chunks;
  198823. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198824. up++)
  198825. {
  198826. int keep=png_handle_as_unknown(png_ptr, up->name);
  198827. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198828. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198829. !(up->location & PNG_HAVE_IDAT) &&
  198830. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198831. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198832. {
  198833. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198834. }
  198835. }
  198836. }
  198837. #endif
  198838. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198839. }
  198840. }
  198841. void PNGAPI
  198842. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198843. {
  198844. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198845. int i;
  198846. #endif
  198847. png_debug(1, "in png_write_info\n");
  198848. if (png_ptr == NULL || info_ptr == NULL)
  198849. return;
  198850. png_write_info_before_PLTE(png_ptr, info_ptr);
  198851. if (info_ptr->valid & PNG_INFO_PLTE)
  198852. png_write_PLTE(png_ptr, info_ptr->palette,
  198853. (png_uint_32)info_ptr->num_palette);
  198854. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198855. png_error(png_ptr, "Valid palette required for paletted images");
  198856. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198857. if (info_ptr->valid & PNG_INFO_tRNS)
  198858. {
  198859. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198860. /* invert the alpha channel (in tRNS) */
  198861. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198862. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198863. {
  198864. int j;
  198865. for (j=0; j<(int)info_ptr->num_trans; j++)
  198866. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198867. }
  198868. #endif
  198869. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198870. info_ptr->num_trans, info_ptr->color_type);
  198871. }
  198872. #endif
  198873. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198874. if (info_ptr->valid & PNG_INFO_bKGD)
  198875. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198876. #endif
  198877. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198878. if (info_ptr->valid & PNG_INFO_hIST)
  198879. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198880. #endif
  198881. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198882. if (info_ptr->valid & PNG_INFO_oFFs)
  198883. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198884. info_ptr->offset_unit_type);
  198885. #endif
  198886. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198887. if (info_ptr->valid & PNG_INFO_pCAL)
  198888. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198889. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198890. info_ptr->pcal_units, info_ptr->pcal_params);
  198891. #endif
  198892. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198893. if (info_ptr->valid & PNG_INFO_sCAL)
  198894. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198895. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198896. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198897. #else
  198898. #ifdef PNG_FIXED_POINT_SUPPORTED
  198899. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198900. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198901. #else
  198902. png_warning(png_ptr,
  198903. "png_write_sCAL not supported; sCAL chunk not written.");
  198904. #endif
  198905. #endif
  198906. #endif
  198907. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198908. if (info_ptr->valid & PNG_INFO_pHYs)
  198909. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198910. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198911. #endif
  198912. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198913. if (info_ptr->valid & PNG_INFO_tIME)
  198914. {
  198915. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198916. png_ptr->mode |= PNG_WROTE_tIME;
  198917. }
  198918. #endif
  198919. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198920. if (info_ptr->valid & PNG_INFO_sPLT)
  198921. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198922. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198923. #endif
  198924. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198925. /* Check to see if we need to write text chunks */
  198926. for (i = 0; i < info_ptr->num_text; i++)
  198927. {
  198928. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198929. info_ptr->text[i].compression);
  198930. /* an internationalized chunk? */
  198931. if (info_ptr->text[i].compression > 0)
  198932. {
  198933. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198934. /* write international chunk */
  198935. png_write_iTXt(png_ptr,
  198936. info_ptr->text[i].compression,
  198937. info_ptr->text[i].key,
  198938. info_ptr->text[i].lang,
  198939. info_ptr->text[i].lang_key,
  198940. info_ptr->text[i].text);
  198941. #else
  198942. png_warning(png_ptr, "Unable to write international text");
  198943. #endif
  198944. /* Mark this chunk as written */
  198945. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198946. }
  198947. /* If we want a compressed text chunk */
  198948. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198949. {
  198950. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198951. /* write compressed chunk */
  198952. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198953. info_ptr->text[i].text, 0,
  198954. info_ptr->text[i].compression);
  198955. #else
  198956. png_warning(png_ptr, "Unable to write compressed text");
  198957. #endif
  198958. /* Mark this chunk as written */
  198959. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198960. }
  198961. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198962. {
  198963. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198964. /* write uncompressed chunk */
  198965. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198966. info_ptr->text[i].text,
  198967. 0);
  198968. #else
  198969. png_warning(png_ptr, "Unable to write uncompressed text");
  198970. #endif
  198971. /* Mark this chunk as written */
  198972. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198973. }
  198974. }
  198975. #endif
  198976. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198977. if (info_ptr->unknown_chunks_num)
  198978. {
  198979. png_unknown_chunk *up;
  198980. png_debug(5, "writing extra chunks\n");
  198981. for (up = info_ptr->unknown_chunks;
  198982. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198983. up++)
  198984. {
  198985. int keep=png_handle_as_unknown(png_ptr, up->name);
  198986. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198987. up->location && (up->location & PNG_HAVE_PLTE) &&
  198988. !(up->location & PNG_HAVE_IDAT) &&
  198989. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198990. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198991. {
  198992. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198993. }
  198994. }
  198995. }
  198996. #endif
  198997. }
  198998. /* Writes the end of the PNG file. If you don't want to write comments or
  198999. * time information, you can pass NULL for info. If you already wrote these
  199000. * in png_write_info(), do not write them again here. If you have long
  199001. * comments, I suggest writing them here, and compressing them.
  199002. */
  199003. void PNGAPI
  199004. png_write_end(png_structp png_ptr, png_infop info_ptr)
  199005. {
  199006. png_debug(1, "in png_write_end\n");
  199007. if (png_ptr == NULL)
  199008. return;
  199009. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  199010. png_error(png_ptr, "No IDATs written into file");
  199011. /* see if user wants us to write information chunks */
  199012. if (info_ptr != NULL)
  199013. {
  199014. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199015. int i; /* local index variable */
  199016. #endif
  199017. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199018. /* check to see if user has supplied a time chunk */
  199019. if ((info_ptr->valid & PNG_INFO_tIME) &&
  199020. !(png_ptr->mode & PNG_WROTE_tIME))
  199021. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199022. #endif
  199023. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199024. /* loop through comment chunks */
  199025. for (i = 0; i < info_ptr->num_text; i++)
  199026. {
  199027. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  199028. info_ptr->text[i].compression);
  199029. /* an internationalized chunk? */
  199030. if (info_ptr->text[i].compression > 0)
  199031. {
  199032. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199033. /* write international chunk */
  199034. png_write_iTXt(png_ptr,
  199035. info_ptr->text[i].compression,
  199036. info_ptr->text[i].key,
  199037. info_ptr->text[i].lang,
  199038. info_ptr->text[i].lang_key,
  199039. info_ptr->text[i].text);
  199040. #else
  199041. png_warning(png_ptr, "Unable to write international text");
  199042. #endif
  199043. /* Mark this chunk as written */
  199044. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199045. }
  199046. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199047. {
  199048. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199049. /* write compressed chunk */
  199050. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199051. info_ptr->text[i].text, 0,
  199052. info_ptr->text[i].compression);
  199053. #else
  199054. png_warning(png_ptr, "Unable to write compressed text");
  199055. #endif
  199056. /* Mark this chunk as written */
  199057. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199058. }
  199059. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199060. {
  199061. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199062. /* write uncompressed chunk */
  199063. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199064. info_ptr->text[i].text, 0);
  199065. #else
  199066. png_warning(png_ptr, "Unable to write uncompressed text");
  199067. #endif
  199068. /* Mark this chunk as written */
  199069. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199070. }
  199071. }
  199072. #endif
  199073. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199074. if (info_ptr->unknown_chunks_num)
  199075. {
  199076. png_unknown_chunk *up;
  199077. png_debug(5, "writing extra chunks\n");
  199078. for (up = info_ptr->unknown_chunks;
  199079. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199080. up++)
  199081. {
  199082. int keep=png_handle_as_unknown(png_ptr, up->name);
  199083. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199084. up->location && (up->location & PNG_AFTER_IDAT) &&
  199085. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199086. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199087. {
  199088. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199089. }
  199090. }
  199091. }
  199092. #endif
  199093. }
  199094. png_ptr->mode |= PNG_AFTER_IDAT;
  199095. /* write end of PNG file */
  199096. png_write_IEND(png_ptr);
  199097. }
  199098. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199099. #if !defined(_WIN32_WCE)
  199100. /* "time.h" functions are not supported on WindowsCE */
  199101. void PNGAPI
  199102. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199103. {
  199104. png_debug(1, "in png_convert_from_struct_tm\n");
  199105. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199106. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199107. ptime->day = (png_byte)ttime->tm_mday;
  199108. ptime->hour = (png_byte)ttime->tm_hour;
  199109. ptime->minute = (png_byte)ttime->tm_min;
  199110. ptime->second = (png_byte)ttime->tm_sec;
  199111. }
  199112. void PNGAPI
  199113. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199114. {
  199115. struct tm *tbuf;
  199116. png_debug(1, "in png_convert_from_time_t\n");
  199117. tbuf = gmtime(&ttime);
  199118. png_convert_from_struct_tm(ptime, tbuf);
  199119. }
  199120. #endif
  199121. #endif
  199122. /* Initialize png_ptr structure, and allocate any memory needed */
  199123. png_structp PNGAPI
  199124. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199125. png_error_ptr error_fn, png_error_ptr warn_fn)
  199126. {
  199127. #ifdef PNG_USER_MEM_SUPPORTED
  199128. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199129. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199130. }
  199131. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199132. png_structp PNGAPI
  199133. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199134. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199135. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199136. {
  199137. #endif /* PNG_USER_MEM_SUPPORTED */
  199138. png_structp png_ptr;
  199139. #ifdef PNG_SETJMP_SUPPORTED
  199140. #ifdef USE_FAR_KEYWORD
  199141. jmp_buf jmpbuf;
  199142. #endif
  199143. #endif
  199144. int i;
  199145. png_debug(1, "in png_create_write_struct\n");
  199146. #ifdef PNG_USER_MEM_SUPPORTED
  199147. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199148. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199149. #else
  199150. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199151. #endif /* PNG_USER_MEM_SUPPORTED */
  199152. if (png_ptr == NULL)
  199153. return (NULL);
  199154. /* added at libpng-1.2.6 */
  199155. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199156. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199157. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199158. #endif
  199159. #ifdef PNG_SETJMP_SUPPORTED
  199160. #ifdef USE_FAR_KEYWORD
  199161. if (setjmp(jmpbuf))
  199162. #else
  199163. if (setjmp(png_ptr->jmpbuf))
  199164. #endif
  199165. {
  199166. png_free(png_ptr, png_ptr->zbuf);
  199167. png_ptr->zbuf=NULL;
  199168. png_destroy_struct(png_ptr);
  199169. return (NULL);
  199170. }
  199171. #ifdef USE_FAR_KEYWORD
  199172. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199173. #endif
  199174. #endif
  199175. #ifdef PNG_USER_MEM_SUPPORTED
  199176. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199177. #endif /* PNG_USER_MEM_SUPPORTED */
  199178. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199179. i=0;
  199180. do
  199181. {
  199182. if(user_png_ver[i] != png_libpng_ver[i])
  199183. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199184. } while (png_libpng_ver[i++]);
  199185. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199186. {
  199187. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199188. * we must recompile any applications that use any older library version.
  199189. * For versions after libpng 1.0, we will be compatible, so we need
  199190. * only check the first digit.
  199191. */
  199192. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199193. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199194. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199195. {
  199196. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199197. char msg[80];
  199198. if (user_png_ver)
  199199. {
  199200. png_snprintf(msg, 80,
  199201. "Application was compiled with png.h from libpng-%.20s",
  199202. user_png_ver);
  199203. png_warning(png_ptr, msg);
  199204. }
  199205. png_snprintf(msg, 80,
  199206. "Application is running with png.c from libpng-%.20s",
  199207. png_libpng_ver);
  199208. png_warning(png_ptr, msg);
  199209. #endif
  199210. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199211. png_ptr->flags=0;
  199212. #endif
  199213. png_error(png_ptr,
  199214. "Incompatible libpng version in application and library");
  199215. }
  199216. }
  199217. /* initialize zbuf - compression buffer */
  199218. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199219. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199220. (png_uint_32)png_ptr->zbuf_size);
  199221. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199222. png_flush_ptr_NULL);
  199223. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199224. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199225. 1, png_doublep_NULL, png_doublep_NULL);
  199226. #endif
  199227. #ifdef PNG_SETJMP_SUPPORTED
  199228. /* Applications that neglect to set up their own setjmp() and then encounter
  199229. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199230. abort instead of returning. */
  199231. #ifdef USE_FAR_KEYWORD
  199232. if (setjmp(jmpbuf))
  199233. PNG_ABORT();
  199234. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199235. #else
  199236. if (setjmp(png_ptr->jmpbuf))
  199237. PNG_ABORT();
  199238. #endif
  199239. #endif
  199240. return (png_ptr);
  199241. }
  199242. /* Initialize png_ptr structure, and allocate any memory needed */
  199243. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199244. /* Deprecated. */
  199245. #undef png_write_init
  199246. void PNGAPI
  199247. png_write_init(png_structp png_ptr)
  199248. {
  199249. /* We only come here via pre-1.0.7-compiled applications */
  199250. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199251. }
  199252. void PNGAPI
  199253. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199254. png_size_t png_struct_size, png_size_t png_info_size)
  199255. {
  199256. /* We only come here via pre-1.0.12-compiled applications */
  199257. if(png_ptr == NULL) return;
  199258. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199259. if(png_sizeof(png_struct) > png_struct_size ||
  199260. png_sizeof(png_info) > png_info_size)
  199261. {
  199262. char msg[80];
  199263. png_ptr->warning_fn=NULL;
  199264. if (user_png_ver)
  199265. {
  199266. png_snprintf(msg, 80,
  199267. "Application was compiled with png.h from libpng-%.20s",
  199268. user_png_ver);
  199269. png_warning(png_ptr, msg);
  199270. }
  199271. png_snprintf(msg, 80,
  199272. "Application is running with png.c from libpng-%.20s",
  199273. png_libpng_ver);
  199274. png_warning(png_ptr, msg);
  199275. }
  199276. #endif
  199277. if(png_sizeof(png_struct) > png_struct_size)
  199278. {
  199279. png_ptr->error_fn=NULL;
  199280. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199281. png_ptr->flags=0;
  199282. #endif
  199283. png_error(png_ptr,
  199284. "The png struct allocated by the application for writing is too small.");
  199285. }
  199286. if(png_sizeof(png_info) > png_info_size)
  199287. {
  199288. png_ptr->error_fn=NULL;
  199289. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199290. png_ptr->flags=0;
  199291. #endif
  199292. png_error(png_ptr,
  199293. "The info struct allocated by the application for writing is too small.");
  199294. }
  199295. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199296. }
  199297. #endif /* PNG_1_0_X || PNG_1_2_X */
  199298. void PNGAPI
  199299. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199300. png_size_t png_struct_size)
  199301. {
  199302. png_structp png_ptr=*ptr_ptr;
  199303. #ifdef PNG_SETJMP_SUPPORTED
  199304. jmp_buf tmp_jmp; /* to save current jump buffer */
  199305. #endif
  199306. int i = 0;
  199307. if (png_ptr == NULL)
  199308. return;
  199309. do
  199310. {
  199311. if (user_png_ver[i] != png_libpng_ver[i])
  199312. {
  199313. #ifdef PNG_LEGACY_SUPPORTED
  199314. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199315. #else
  199316. png_ptr->warning_fn=NULL;
  199317. png_warning(png_ptr,
  199318. "Application uses deprecated png_write_init() and should be recompiled.");
  199319. break;
  199320. #endif
  199321. }
  199322. } while (png_libpng_ver[i++]);
  199323. png_debug(1, "in png_write_init_3\n");
  199324. #ifdef PNG_SETJMP_SUPPORTED
  199325. /* save jump buffer and error functions */
  199326. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199327. #endif
  199328. if (png_sizeof(png_struct) > png_struct_size)
  199329. {
  199330. png_destroy_struct(png_ptr);
  199331. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199332. *ptr_ptr = png_ptr;
  199333. }
  199334. /* reset all variables to 0 */
  199335. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199336. /* added at libpng-1.2.6 */
  199337. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199338. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199339. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199340. #endif
  199341. #ifdef PNG_SETJMP_SUPPORTED
  199342. /* restore jump buffer */
  199343. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199344. #endif
  199345. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199346. png_flush_ptr_NULL);
  199347. /* initialize zbuf - compression buffer */
  199348. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199349. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199350. (png_uint_32)png_ptr->zbuf_size);
  199351. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199352. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199353. 1, png_doublep_NULL, png_doublep_NULL);
  199354. #endif
  199355. }
  199356. /* Write a few rows of image data. If the image is interlaced,
  199357. * either you will have to write the 7 sub images, or, if you
  199358. * have called png_set_interlace_handling(), you will have to
  199359. * "write" the image seven times.
  199360. */
  199361. void PNGAPI
  199362. png_write_rows(png_structp png_ptr, png_bytepp row,
  199363. png_uint_32 num_rows)
  199364. {
  199365. png_uint_32 i; /* row counter */
  199366. png_bytepp rp; /* row pointer */
  199367. png_debug(1, "in png_write_rows\n");
  199368. if (png_ptr == NULL)
  199369. return;
  199370. /* loop through the rows */
  199371. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199372. {
  199373. png_write_row(png_ptr, *rp);
  199374. }
  199375. }
  199376. /* Write the image. You only need to call this function once, even
  199377. * if you are writing an interlaced image.
  199378. */
  199379. void PNGAPI
  199380. png_write_image(png_structp png_ptr, png_bytepp image)
  199381. {
  199382. png_uint_32 i; /* row index */
  199383. int pass, num_pass; /* pass variables */
  199384. png_bytepp rp; /* points to current row */
  199385. if (png_ptr == NULL)
  199386. return;
  199387. png_debug(1, "in png_write_image\n");
  199388. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199389. /* intialize interlace handling. If image is not interlaced,
  199390. this will set pass to 1 */
  199391. num_pass = png_set_interlace_handling(png_ptr);
  199392. #else
  199393. num_pass = 1;
  199394. #endif
  199395. /* loop through passes */
  199396. for (pass = 0; pass < num_pass; pass++)
  199397. {
  199398. /* loop through image */
  199399. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199400. {
  199401. png_write_row(png_ptr, *rp);
  199402. }
  199403. }
  199404. }
  199405. /* called by user to write a row of image data */
  199406. void PNGAPI
  199407. png_write_row(png_structp png_ptr, png_bytep row)
  199408. {
  199409. if (png_ptr == NULL)
  199410. return;
  199411. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199412. png_ptr->row_number, png_ptr->pass);
  199413. /* initialize transformations and other stuff if first time */
  199414. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199415. {
  199416. /* make sure we wrote the header info */
  199417. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199418. png_error(png_ptr,
  199419. "png_write_info was never called before png_write_row.");
  199420. /* check for transforms that have been set but were defined out */
  199421. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199422. if (png_ptr->transformations & PNG_INVERT_MONO)
  199423. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199424. #endif
  199425. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199426. if (png_ptr->transformations & PNG_FILLER)
  199427. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199428. #endif
  199429. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199430. if (png_ptr->transformations & PNG_PACKSWAP)
  199431. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199432. #endif
  199433. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199434. if (png_ptr->transformations & PNG_PACK)
  199435. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199436. #endif
  199437. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199438. if (png_ptr->transformations & PNG_SHIFT)
  199439. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199440. #endif
  199441. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199442. if (png_ptr->transformations & PNG_BGR)
  199443. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199444. #endif
  199445. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199446. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199447. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199448. #endif
  199449. png_write_start_row(png_ptr);
  199450. }
  199451. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199452. /* if interlaced and not interested in row, return */
  199453. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199454. {
  199455. switch (png_ptr->pass)
  199456. {
  199457. case 0:
  199458. if (png_ptr->row_number & 0x07)
  199459. {
  199460. png_write_finish_row(png_ptr);
  199461. return;
  199462. }
  199463. break;
  199464. case 1:
  199465. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199466. {
  199467. png_write_finish_row(png_ptr);
  199468. return;
  199469. }
  199470. break;
  199471. case 2:
  199472. if ((png_ptr->row_number & 0x07) != 4)
  199473. {
  199474. png_write_finish_row(png_ptr);
  199475. return;
  199476. }
  199477. break;
  199478. case 3:
  199479. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199480. {
  199481. png_write_finish_row(png_ptr);
  199482. return;
  199483. }
  199484. break;
  199485. case 4:
  199486. if ((png_ptr->row_number & 0x03) != 2)
  199487. {
  199488. png_write_finish_row(png_ptr);
  199489. return;
  199490. }
  199491. break;
  199492. case 5:
  199493. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199494. {
  199495. png_write_finish_row(png_ptr);
  199496. return;
  199497. }
  199498. break;
  199499. case 6:
  199500. if (!(png_ptr->row_number & 0x01))
  199501. {
  199502. png_write_finish_row(png_ptr);
  199503. return;
  199504. }
  199505. break;
  199506. }
  199507. }
  199508. #endif
  199509. /* set up row info for transformations */
  199510. png_ptr->row_info.color_type = png_ptr->color_type;
  199511. png_ptr->row_info.width = png_ptr->usr_width;
  199512. png_ptr->row_info.channels = png_ptr->usr_channels;
  199513. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199514. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199515. png_ptr->row_info.channels);
  199516. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199517. png_ptr->row_info.width);
  199518. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199519. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199520. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199521. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199522. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199523. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199524. /* Copy user's row into buffer, leaving room for filter byte. */
  199525. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199526. png_ptr->row_info.rowbytes);
  199527. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199528. /* handle interlacing */
  199529. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199530. (png_ptr->transformations & PNG_INTERLACE))
  199531. {
  199532. png_do_write_interlace(&(png_ptr->row_info),
  199533. png_ptr->row_buf + 1, png_ptr->pass);
  199534. /* this should always get caught above, but still ... */
  199535. if (!(png_ptr->row_info.width))
  199536. {
  199537. png_write_finish_row(png_ptr);
  199538. return;
  199539. }
  199540. }
  199541. #endif
  199542. /* handle other transformations */
  199543. if (png_ptr->transformations)
  199544. png_do_write_transformations(png_ptr);
  199545. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199546. /* Write filter_method 64 (intrapixel differencing) only if
  199547. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199548. * 2. Libpng did not write a PNG signature (this filter_method is only
  199549. * used in PNG datastreams that are embedded in MNG datastreams) and
  199550. * 3. The application called png_permit_mng_features with a mask that
  199551. * included PNG_FLAG_MNG_FILTER_64 and
  199552. * 4. The filter_method is 64 and
  199553. * 5. The color_type is RGB or RGBA
  199554. */
  199555. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199556. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199557. {
  199558. /* Intrapixel differencing */
  199559. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199560. }
  199561. #endif
  199562. /* Find a filter if necessary, filter the row and write it out. */
  199563. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199564. if (png_ptr->write_row_fn != NULL)
  199565. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199566. }
  199567. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199568. /* Set the automatic flush interval or 0 to turn flushing off */
  199569. void PNGAPI
  199570. png_set_flush(png_structp png_ptr, int nrows)
  199571. {
  199572. png_debug(1, "in png_set_flush\n");
  199573. if (png_ptr == NULL)
  199574. return;
  199575. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199576. }
  199577. /* flush the current output buffers now */
  199578. void PNGAPI
  199579. png_write_flush(png_structp png_ptr)
  199580. {
  199581. int wrote_IDAT;
  199582. png_debug(1, "in png_write_flush\n");
  199583. if (png_ptr == NULL)
  199584. return;
  199585. /* We have already written out all of the data */
  199586. if (png_ptr->row_number >= png_ptr->num_rows)
  199587. return;
  199588. do
  199589. {
  199590. int ret;
  199591. /* compress the data */
  199592. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199593. wrote_IDAT = 0;
  199594. /* check for compression errors */
  199595. if (ret != Z_OK)
  199596. {
  199597. if (png_ptr->zstream.msg != NULL)
  199598. png_error(png_ptr, png_ptr->zstream.msg);
  199599. else
  199600. png_error(png_ptr, "zlib error");
  199601. }
  199602. if (!(png_ptr->zstream.avail_out))
  199603. {
  199604. /* write the IDAT and reset the zlib output buffer */
  199605. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199606. png_ptr->zbuf_size);
  199607. png_ptr->zstream.next_out = png_ptr->zbuf;
  199608. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199609. wrote_IDAT = 1;
  199610. }
  199611. } while(wrote_IDAT == 1);
  199612. /* If there is any data left to be output, write it into a new IDAT */
  199613. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199614. {
  199615. /* write the IDAT and reset the zlib output buffer */
  199616. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199617. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199618. png_ptr->zstream.next_out = png_ptr->zbuf;
  199619. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199620. }
  199621. png_ptr->flush_rows = 0;
  199622. png_flush(png_ptr);
  199623. }
  199624. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199625. /* free all memory used by the write */
  199626. void PNGAPI
  199627. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199628. {
  199629. png_structp png_ptr = NULL;
  199630. png_infop info_ptr = NULL;
  199631. #ifdef PNG_USER_MEM_SUPPORTED
  199632. png_free_ptr free_fn = NULL;
  199633. png_voidp mem_ptr = NULL;
  199634. #endif
  199635. png_debug(1, "in png_destroy_write_struct\n");
  199636. if (png_ptr_ptr != NULL)
  199637. {
  199638. png_ptr = *png_ptr_ptr;
  199639. #ifdef PNG_USER_MEM_SUPPORTED
  199640. free_fn = png_ptr->free_fn;
  199641. mem_ptr = png_ptr->mem_ptr;
  199642. #endif
  199643. }
  199644. if (info_ptr_ptr != NULL)
  199645. info_ptr = *info_ptr_ptr;
  199646. if (info_ptr != NULL)
  199647. {
  199648. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199649. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199650. if (png_ptr->num_chunk_list)
  199651. {
  199652. png_free(png_ptr, png_ptr->chunk_list);
  199653. png_ptr->chunk_list=NULL;
  199654. png_ptr->num_chunk_list=0;
  199655. }
  199656. #endif
  199657. #ifdef PNG_USER_MEM_SUPPORTED
  199658. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199659. (png_voidp)mem_ptr);
  199660. #else
  199661. png_destroy_struct((png_voidp)info_ptr);
  199662. #endif
  199663. *info_ptr_ptr = NULL;
  199664. }
  199665. if (png_ptr != NULL)
  199666. {
  199667. png_write_destroy(png_ptr);
  199668. #ifdef PNG_USER_MEM_SUPPORTED
  199669. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199670. (png_voidp)mem_ptr);
  199671. #else
  199672. png_destroy_struct((png_voidp)png_ptr);
  199673. #endif
  199674. *png_ptr_ptr = NULL;
  199675. }
  199676. }
  199677. /* Free any memory used in png_ptr struct (old method) */
  199678. void /* PRIVATE */
  199679. png_write_destroy(png_structp png_ptr)
  199680. {
  199681. #ifdef PNG_SETJMP_SUPPORTED
  199682. jmp_buf tmp_jmp; /* save jump buffer */
  199683. #endif
  199684. png_error_ptr error_fn;
  199685. png_error_ptr warning_fn;
  199686. png_voidp error_ptr;
  199687. #ifdef PNG_USER_MEM_SUPPORTED
  199688. png_free_ptr free_fn;
  199689. #endif
  199690. png_debug(1, "in png_write_destroy\n");
  199691. /* free any memory zlib uses */
  199692. deflateEnd(&png_ptr->zstream);
  199693. /* free our memory. png_free checks NULL for us. */
  199694. png_free(png_ptr, png_ptr->zbuf);
  199695. png_free(png_ptr, png_ptr->row_buf);
  199696. png_free(png_ptr, png_ptr->prev_row);
  199697. png_free(png_ptr, png_ptr->sub_row);
  199698. png_free(png_ptr, png_ptr->up_row);
  199699. png_free(png_ptr, png_ptr->avg_row);
  199700. png_free(png_ptr, png_ptr->paeth_row);
  199701. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199702. png_free(png_ptr, png_ptr->time_buffer);
  199703. #endif
  199704. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199705. png_free(png_ptr, png_ptr->prev_filters);
  199706. png_free(png_ptr, png_ptr->filter_weights);
  199707. png_free(png_ptr, png_ptr->inv_filter_weights);
  199708. png_free(png_ptr, png_ptr->filter_costs);
  199709. png_free(png_ptr, png_ptr->inv_filter_costs);
  199710. #endif
  199711. #ifdef PNG_SETJMP_SUPPORTED
  199712. /* reset structure */
  199713. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199714. #endif
  199715. error_fn = png_ptr->error_fn;
  199716. warning_fn = png_ptr->warning_fn;
  199717. error_ptr = png_ptr->error_ptr;
  199718. #ifdef PNG_USER_MEM_SUPPORTED
  199719. free_fn = png_ptr->free_fn;
  199720. #endif
  199721. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199722. png_ptr->error_fn = error_fn;
  199723. png_ptr->warning_fn = warning_fn;
  199724. png_ptr->error_ptr = error_ptr;
  199725. #ifdef PNG_USER_MEM_SUPPORTED
  199726. png_ptr->free_fn = free_fn;
  199727. #endif
  199728. #ifdef PNG_SETJMP_SUPPORTED
  199729. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199730. #endif
  199731. }
  199732. /* Allow the application to select one or more row filters to use. */
  199733. void PNGAPI
  199734. png_set_filter(png_structp png_ptr, int method, int filters)
  199735. {
  199736. png_debug(1, "in png_set_filter\n");
  199737. if (png_ptr == NULL)
  199738. return;
  199739. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199740. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199741. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199742. method = PNG_FILTER_TYPE_BASE;
  199743. #endif
  199744. if (method == PNG_FILTER_TYPE_BASE)
  199745. {
  199746. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199747. {
  199748. #ifndef PNG_NO_WRITE_FILTER
  199749. case 5:
  199750. case 6:
  199751. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199752. #endif /* PNG_NO_WRITE_FILTER */
  199753. case PNG_FILTER_VALUE_NONE:
  199754. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199755. #ifndef PNG_NO_WRITE_FILTER
  199756. case PNG_FILTER_VALUE_SUB:
  199757. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199758. case PNG_FILTER_VALUE_UP:
  199759. png_ptr->do_filter=PNG_FILTER_UP; break;
  199760. case PNG_FILTER_VALUE_AVG:
  199761. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199762. case PNG_FILTER_VALUE_PAETH:
  199763. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199764. default: png_ptr->do_filter = (png_byte)filters; break;
  199765. #else
  199766. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199767. #endif /* PNG_NO_WRITE_FILTER */
  199768. }
  199769. /* If we have allocated the row_buf, this means we have already started
  199770. * with the image and we should have allocated all of the filter buffers
  199771. * that have been selected. If prev_row isn't already allocated, then
  199772. * it is too late to start using the filters that need it, since we
  199773. * will be missing the data in the previous row. If an application
  199774. * wants to start and stop using particular filters during compression,
  199775. * it should start out with all of the filters, and then add and
  199776. * remove them after the start of compression.
  199777. */
  199778. if (png_ptr->row_buf != NULL)
  199779. {
  199780. #ifndef PNG_NO_WRITE_FILTER
  199781. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199782. {
  199783. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199784. (png_ptr->rowbytes + 1));
  199785. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199786. }
  199787. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199788. {
  199789. if (png_ptr->prev_row == NULL)
  199790. {
  199791. png_warning(png_ptr, "Can't add Up filter after starting");
  199792. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199793. }
  199794. else
  199795. {
  199796. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199797. (png_ptr->rowbytes + 1));
  199798. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199799. }
  199800. }
  199801. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199802. {
  199803. if (png_ptr->prev_row == NULL)
  199804. {
  199805. png_warning(png_ptr, "Can't add Average filter after starting");
  199806. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199807. }
  199808. else
  199809. {
  199810. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199811. (png_ptr->rowbytes + 1));
  199812. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199813. }
  199814. }
  199815. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199816. png_ptr->paeth_row == NULL)
  199817. {
  199818. if (png_ptr->prev_row == NULL)
  199819. {
  199820. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199821. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199822. }
  199823. else
  199824. {
  199825. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199826. (png_ptr->rowbytes + 1));
  199827. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199828. }
  199829. }
  199830. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199831. #endif /* PNG_NO_WRITE_FILTER */
  199832. png_ptr->do_filter = PNG_FILTER_NONE;
  199833. }
  199834. }
  199835. else
  199836. png_error(png_ptr, "Unknown custom filter method");
  199837. }
  199838. /* This allows us to influence the way in which libpng chooses the "best"
  199839. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199840. * differences metric is relatively fast and effective, there is some
  199841. * question as to whether it can be improved upon by trying to keep the
  199842. * filtered data going to zlib more consistent, hopefully resulting in
  199843. * better compression.
  199844. */
  199845. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199846. void PNGAPI
  199847. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199848. int num_weights, png_doublep filter_weights,
  199849. png_doublep filter_costs)
  199850. {
  199851. int i;
  199852. png_debug(1, "in png_set_filter_heuristics\n");
  199853. if (png_ptr == NULL)
  199854. return;
  199855. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199856. {
  199857. png_warning(png_ptr, "Unknown filter heuristic method");
  199858. return;
  199859. }
  199860. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199861. {
  199862. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199863. }
  199864. if (num_weights < 0 || filter_weights == NULL ||
  199865. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199866. {
  199867. num_weights = 0;
  199868. }
  199869. png_ptr->num_prev_filters = (png_byte)num_weights;
  199870. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199871. if (num_weights > 0)
  199872. {
  199873. if (png_ptr->prev_filters == NULL)
  199874. {
  199875. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199876. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199877. /* To make sure that the weighting starts out fairly */
  199878. for (i = 0; i < num_weights; i++)
  199879. {
  199880. png_ptr->prev_filters[i] = 255;
  199881. }
  199882. }
  199883. if (png_ptr->filter_weights == NULL)
  199884. {
  199885. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199886. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199887. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199888. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199889. for (i = 0; i < num_weights; i++)
  199890. {
  199891. png_ptr->inv_filter_weights[i] =
  199892. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199893. }
  199894. }
  199895. for (i = 0; i < num_weights; i++)
  199896. {
  199897. if (filter_weights[i] < 0.0)
  199898. {
  199899. png_ptr->inv_filter_weights[i] =
  199900. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199901. }
  199902. else
  199903. {
  199904. png_ptr->inv_filter_weights[i] =
  199905. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199906. png_ptr->filter_weights[i] =
  199907. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199908. }
  199909. }
  199910. }
  199911. /* If, in the future, there are other filter methods, this would
  199912. * need to be based on png_ptr->filter.
  199913. */
  199914. if (png_ptr->filter_costs == NULL)
  199915. {
  199916. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199917. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199918. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199919. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199920. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199921. {
  199922. png_ptr->inv_filter_costs[i] =
  199923. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199924. }
  199925. }
  199926. /* Here is where we set the relative costs of the different filters. We
  199927. * should take the desired compression level into account when setting
  199928. * the costs, so that Paeth, for instance, has a high relative cost at low
  199929. * compression levels, while it has a lower relative cost at higher
  199930. * compression settings. The filter types are in order of increasing
  199931. * relative cost, so it would be possible to do this with an algorithm.
  199932. */
  199933. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199934. {
  199935. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199936. {
  199937. png_ptr->inv_filter_costs[i] =
  199938. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199939. }
  199940. else if (filter_costs[i] >= 1.0)
  199941. {
  199942. png_ptr->inv_filter_costs[i] =
  199943. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199944. png_ptr->filter_costs[i] =
  199945. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199946. }
  199947. }
  199948. }
  199949. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199950. void PNGAPI
  199951. png_set_compression_level(png_structp png_ptr, int level)
  199952. {
  199953. png_debug(1, "in png_set_compression_level\n");
  199954. if (png_ptr == NULL)
  199955. return;
  199956. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199957. png_ptr->zlib_level = level;
  199958. }
  199959. void PNGAPI
  199960. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199961. {
  199962. png_debug(1, "in png_set_compression_mem_level\n");
  199963. if (png_ptr == NULL)
  199964. return;
  199965. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199966. png_ptr->zlib_mem_level = mem_level;
  199967. }
  199968. void PNGAPI
  199969. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199970. {
  199971. png_debug(1, "in png_set_compression_strategy\n");
  199972. if (png_ptr == NULL)
  199973. return;
  199974. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199975. png_ptr->zlib_strategy = strategy;
  199976. }
  199977. void PNGAPI
  199978. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199979. {
  199980. if (png_ptr == NULL)
  199981. return;
  199982. if (window_bits > 15)
  199983. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199984. else if (window_bits < 8)
  199985. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199986. #ifndef WBITS_8_OK
  199987. /* avoid libpng bug with 256-byte windows */
  199988. if (window_bits == 8)
  199989. {
  199990. png_warning(png_ptr, "Compression window is being reset to 512");
  199991. window_bits=9;
  199992. }
  199993. #endif
  199994. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199995. png_ptr->zlib_window_bits = window_bits;
  199996. }
  199997. void PNGAPI
  199998. png_set_compression_method(png_structp png_ptr, int method)
  199999. {
  200000. png_debug(1, "in png_set_compression_method\n");
  200001. if (png_ptr == NULL)
  200002. return;
  200003. if (method != 8)
  200004. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  200005. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  200006. png_ptr->zlib_method = method;
  200007. }
  200008. void PNGAPI
  200009. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  200010. {
  200011. if (png_ptr == NULL)
  200012. return;
  200013. png_ptr->write_row_fn = write_row_fn;
  200014. }
  200015. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200016. void PNGAPI
  200017. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  200018. write_user_transform_fn)
  200019. {
  200020. png_debug(1, "in png_set_write_user_transform_fn\n");
  200021. if (png_ptr == NULL)
  200022. return;
  200023. png_ptr->transformations |= PNG_USER_TRANSFORM;
  200024. png_ptr->write_user_transform_fn = write_user_transform_fn;
  200025. }
  200026. #endif
  200027. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  200028. void PNGAPI
  200029. png_write_png(png_structp png_ptr, png_infop info_ptr,
  200030. int transforms, voidp params)
  200031. {
  200032. if (png_ptr == NULL || info_ptr == NULL)
  200033. return;
  200034. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200035. /* invert the alpha channel from opacity to transparency */
  200036. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  200037. png_set_invert_alpha(png_ptr);
  200038. #endif
  200039. /* Write the file header information. */
  200040. png_write_info(png_ptr, info_ptr);
  200041. /* ------ these transformations don't touch the info structure ------- */
  200042. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200043. /* invert monochrome pixels */
  200044. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200045. png_set_invert_mono(png_ptr);
  200046. #endif
  200047. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200048. /* Shift the pixels up to a legal bit depth and fill in
  200049. * as appropriate to correctly scale the image.
  200050. */
  200051. if ((transforms & PNG_TRANSFORM_SHIFT)
  200052. && (info_ptr->valid & PNG_INFO_sBIT))
  200053. png_set_shift(png_ptr, &info_ptr->sig_bit);
  200054. #endif
  200055. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200056. /* pack pixels into bytes */
  200057. if (transforms & PNG_TRANSFORM_PACKING)
  200058. png_set_packing(png_ptr);
  200059. #endif
  200060. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200061. /* swap location of alpha bytes from ARGB to RGBA */
  200062. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  200063. png_set_swap_alpha(png_ptr);
  200064. #endif
  200065. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200066. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200067. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200068. */
  200069. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200070. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200071. #endif
  200072. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200073. /* flip BGR pixels to RGB */
  200074. if (transforms & PNG_TRANSFORM_BGR)
  200075. png_set_bgr(png_ptr);
  200076. #endif
  200077. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200078. /* swap bytes of 16-bit files to most significant byte first */
  200079. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200080. png_set_swap(png_ptr);
  200081. #endif
  200082. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200083. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200084. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200085. png_set_packswap(png_ptr);
  200086. #endif
  200087. /* ----------------------- end of transformations ------------------- */
  200088. /* write the bits */
  200089. if (info_ptr->valid & PNG_INFO_IDAT)
  200090. png_write_image(png_ptr, info_ptr->row_pointers);
  200091. /* It is REQUIRED to call this to finish writing the rest of the file */
  200092. png_write_end(png_ptr, info_ptr);
  200093. transforms = transforms; /* quiet compiler warnings */
  200094. params = params;
  200095. }
  200096. #endif
  200097. #endif /* PNG_WRITE_SUPPORTED */
  200098. /*** End of inlined file: pngwrite.c ***/
  200099. /*** Start of inlined file: pngwtran.c ***/
  200100. /* pngwtran.c - transforms the data in a row for PNG writers
  200101. *
  200102. * Last changed in libpng 1.2.9 April 14, 2006
  200103. * For conditions of distribution and use, see copyright notice in png.h
  200104. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200105. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200106. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200107. */
  200108. #define PNG_INTERNAL
  200109. #ifdef PNG_WRITE_SUPPORTED
  200110. /* Transform the data according to the user's wishes. The order of
  200111. * transformations is significant.
  200112. */
  200113. void /* PRIVATE */
  200114. png_do_write_transformations(png_structp png_ptr)
  200115. {
  200116. png_debug(1, "in png_do_write_transformations\n");
  200117. if (png_ptr == NULL)
  200118. return;
  200119. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200120. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200121. if(png_ptr->write_user_transform_fn != NULL)
  200122. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200123. (png_ptr, /* png_ptr */
  200124. &(png_ptr->row_info), /* row_info: */
  200125. /* png_uint_32 width; width of row */
  200126. /* png_uint_32 rowbytes; number of bytes in row */
  200127. /* png_byte color_type; color type of pixels */
  200128. /* png_byte bit_depth; bit depth of samples */
  200129. /* png_byte channels; number of channels (1-4) */
  200130. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200131. png_ptr->row_buf + 1); /* start of pixel data for row */
  200132. #endif
  200133. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200134. if (png_ptr->transformations & PNG_FILLER)
  200135. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200136. png_ptr->flags);
  200137. #endif
  200138. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200139. if (png_ptr->transformations & PNG_PACKSWAP)
  200140. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200141. #endif
  200142. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200143. if (png_ptr->transformations & PNG_PACK)
  200144. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200145. (png_uint_32)png_ptr->bit_depth);
  200146. #endif
  200147. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200148. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200149. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200150. #endif
  200151. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200152. if (png_ptr->transformations & PNG_SHIFT)
  200153. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200154. &(png_ptr->shift));
  200155. #endif
  200156. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200157. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200158. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200159. #endif
  200160. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200161. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200162. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200163. #endif
  200164. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200165. if (png_ptr->transformations & PNG_BGR)
  200166. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200167. #endif
  200168. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200169. if (png_ptr->transformations & PNG_INVERT_MONO)
  200170. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200171. #endif
  200172. }
  200173. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200174. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200175. * row_info bit depth should be 8 (one pixel per byte). The channels
  200176. * should be 1 (this only happens on grayscale and paletted images).
  200177. */
  200178. void /* PRIVATE */
  200179. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200180. {
  200181. png_debug(1, "in png_do_pack\n");
  200182. if (row_info->bit_depth == 8 &&
  200183. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200184. row != NULL && row_info != NULL &&
  200185. #endif
  200186. row_info->channels == 1)
  200187. {
  200188. switch ((int)bit_depth)
  200189. {
  200190. case 1:
  200191. {
  200192. png_bytep sp, dp;
  200193. int mask, v;
  200194. png_uint_32 i;
  200195. png_uint_32 row_width = row_info->width;
  200196. sp = row;
  200197. dp = row;
  200198. mask = 0x80;
  200199. v = 0;
  200200. for (i = 0; i < row_width; i++)
  200201. {
  200202. if (*sp != 0)
  200203. v |= mask;
  200204. sp++;
  200205. if (mask > 1)
  200206. mask >>= 1;
  200207. else
  200208. {
  200209. mask = 0x80;
  200210. *dp = (png_byte)v;
  200211. dp++;
  200212. v = 0;
  200213. }
  200214. }
  200215. if (mask != 0x80)
  200216. *dp = (png_byte)v;
  200217. break;
  200218. }
  200219. case 2:
  200220. {
  200221. png_bytep sp, dp;
  200222. int shift, v;
  200223. png_uint_32 i;
  200224. png_uint_32 row_width = row_info->width;
  200225. sp = row;
  200226. dp = row;
  200227. shift = 6;
  200228. v = 0;
  200229. for (i = 0; i < row_width; i++)
  200230. {
  200231. png_byte value;
  200232. value = (png_byte)(*sp & 0x03);
  200233. v |= (value << shift);
  200234. if (shift == 0)
  200235. {
  200236. shift = 6;
  200237. *dp = (png_byte)v;
  200238. dp++;
  200239. v = 0;
  200240. }
  200241. else
  200242. shift -= 2;
  200243. sp++;
  200244. }
  200245. if (shift != 6)
  200246. *dp = (png_byte)v;
  200247. break;
  200248. }
  200249. case 4:
  200250. {
  200251. png_bytep sp, dp;
  200252. int shift, v;
  200253. png_uint_32 i;
  200254. png_uint_32 row_width = row_info->width;
  200255. sp = row;
  200256. dp = row;
  200257. shift = 4;
  200258. v = 0;
  200259. for (i = 0; i < row_width; i++)
  200260. {
  200261. png_byte value;
  200262. value = (png_byte)(*sp & 0x0f);
  200263. v |= (value << shift);
  200264. if (shift == 0)
  200265. {
  200266. shift = 4;
  200267. *dp = (png_byte)v;
  200268. dp++;
  200269. v = 0;
  200270. }
  200271. else
  200272. shift -= 4;
  200273. sp++;
  200274. }
  200275. if (shift != 4)
  200276. *dp = (png_byte)v;
  200277. break;
  200278. }
  200279. }
  200280. row_info->bit_depth = (png_byte)bit_depth;
  200281. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200282. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200283. row_info->width);
  200284. }
  200285. }
  200286. #endif
  200287. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200288. /* Shift pixel values to take advantage of whole range. Pass the
  200289. * true number of bits in bit_depth. The row should be packed
  200290. * according to row_info->bit_depth. Thus, if you had a row of
  200291. * bit depth 4, but the pixels only had values from 0 to 7, you
  200292. * would pass 3 as bit_depth, and this routine would translate the
  200293. * data to 0 to 15.
  200294. */
  200295. void /* PRIVATE */
  200296. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200297. {
  200298. png_debug(1, "in png_do_shift\n");
  200299. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200300. if (row != NULL && row_info != NULL &&
  200301. #else
  200302. if (
  200303. #endif
  200304. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200305. {
  200306. int shift_start[4], shift_dec[4];
  200307. int channels = 0;
  200308. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200309. {
  200310. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200311. shift_dec[channels] = bit_depth->red;
  200312. channels++;
  200313. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200314. shift_dec[channels] = bit_depth->green;
  200315. channels++;
  200316. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200317. shift_dec[channels] = bit_depth->blue;
  200318. channels++;
  200319. }
  200320. else
  200321. {
  200322. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200323. shift_dec[channels] = bit_depth->gray;
  200324. channels++;
  200325. }
  200326. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200327. {
  200328. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200329. shift_dec[channels] = bit_depth->alpha;
  200330. channels++;
  200331. }
  200332. /* with low row depths, could only be grayscale, so one channel */
  200333. if (row_info->bit_depth < 8)
  200334. {
  200335. png_bytep bp = row;
  200336. png_uint_32 i;
  200337. png_byte mask;
  200338. png_uint_32 row_bytes = row_info->rowbytes;
  200339. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200340. mask = 0x55;
  200341. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200342. mask = 0x11;
  200343. else
  200344. mask = 0xff;
  200345. for (i = 0; i < row_bytes; i++, bp++)
  200346. {
  200347. png_uint_16 v;
  200348. int j;
  200349. v = *bp;
  200350. *bp = 0;
  200351. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200352. {
  200353. if (j > 0)
  200354. *bp |= (png_byte)((v << j) & 0xff);
  200355. else
  200356. *bp |= (png_byte)((v >> (-j)) & mask);
  200357. }
  200358. }
  200359. }
  200360. else if (row_info->bit_depth == 8)
  200361. {
  200362. png_bytep bp = row;
  200363. png_uint_32 i;
  200364. png_uint_32 istop = channels * row_info->width;
  200365. for (i = 0; i < istop; i++, bp++)
  200366. {
  200367. png_uint_16 v;
  200368. int j;
  200369. int c = (int)(i%channels);
  200370. v = *bp;
  200371. *bp = 0;
  200372. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200373. {
  200374. if (j > 0)
  200375. *bp |= (png_byte)((v << j) & 0xff);
  200376. else
  200377. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200378. }
  200379. }
  200380. }
  200381. else
  200382. {
  200383. png_bytep bp;
  200384. png_uint_32 i;
  200385. png_uint_32 istop = channels * row_info->width;
  200386. for (bp = row, i = 0; i < istop; i++)
  200387. {
  200388. int c = (int)(i%channels);
  200389. png_uint_16 value, v;
  200390. int j;
  200391. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200392. value = 0;
  200393. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200394. {
  200395. if (j > 0)
  200396. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200397. else
  200398. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200399. }
  200400. *bp++ = (png_byte)(value >> 8);
  200401. *bp++ = (png_byte)(value & 0xff);
  200402. }
  200403. }
  200404. }
  200405. }
  200406. #endif
  200407. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200408. void /* PRIVATE */
  200409. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200410. {
  200411. png_debug(1, "in png_do_write_swap_alpha\n");
  200412. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200413. if (row != NULL && row_info != NULL)
  200414. #endif
  200415. {
  200416. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200417. {
  200418. /* This converts from ARGB to RGBA */
  200419. if (row_info->bit_depth == 8)
  200420. {
  200421. png_bytep sp, dp;
  200422. png_uint_32 i;
  200423. png_uint_32 row_width = row_info->width;
  200424. for (i = 0, sp = dp = row; i < row_width; i++)
  200425. {
  200426. png_byte save = *(sp++);
  200427. *(dp++) = *(sp++);
  200428. *(dp++) = *(sp++);
  200429. *(dp++) = *(sp++);
  200430. *(dp++) = save;
  200431. }
  200432. }
  200433. /* This converts from AARRGGBB to RRGGBBAA */
  200434. else
  200435. {
  200436. png_bytep sp, dp;
  200437. png_uint_32 i;
  200438. png_uint_32 row_width = row_info->width;
  200439. for (i = 0, sp = dp = row; i < row_width; i++)
  200440. {
  200441. png_byte save[2];
  200442. save[0] = *(sp++);
  200443. save[1] = *(sp++);
  200444. *(dp++) = *(sp++);
  200445. *(dp++) = *(sp++);
  200446. *(dp++) = *(sp++);
  200447. *(dp++) = *(sp++);
  200448. *(dp++) = *(sp++);
  200449. *(dp++) = *(sp++);
  200450. *(dp++) = save[0];
  200451. *(dp++) = save[1];
  200452. }
  200453. }
  200454. }
  200455. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200456. {
  200457. /* This converts from AG to GA */
  200458. if (row_info->bit_depth == 8)
  200459. {
  200460. png_bytep sp, dp;
  200461. png_uint_32 i;
  200462. png_uint_32 row_width = row_info->width;
  200463. for (i = 0, sp = dp = row; i < row_width; i++)
  200464. {
  200465. png_byte save = *(sp++);
  200466. *(dp++) = *(sp++);
  200467. *(dp++) = save;
  200468. }
  200469. }
  200470. /* This converts from AAGG to GGAA */
  200471. else
  200472. {
  200473. png_bytep sp, dp;
  200474. png_uint_32 i;
  200475. png_uint_32 row_width = row_info->width;
  200476. for (i = 0, sp = dp = row; i < row_width; i++)
  200477. {
  200478. png_byte save[2];
  200479. save[0] = *(sp++);
  200480. save[1] = *(sp++);
  200481. *(dp++) = *(sp++);
  200482. *(dp++) = *(sp++);
  200483. *(dp++) = save[0];
  200484. *(dp++) = save[1];
  200485. }
  200486. }
  200487. }
  200488. }
  200489. }
  200490. #endif
  200491. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200492. void /* PRIVATE */
  200493. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200494. {
  200495. png_debug(1, "in png_do_write_invert_alpha\n");
  200496. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200497. if (row != NULL && row_info != NULL)
  200498. #endif
  200499. {
  200500. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200501. {
  200502. /* This inverts the alpha channel in RGBA */
  200503. if (row_info->bit_depth == 8)
  200504. {
  200505. png_bytep sp, dp;
  200506. png_uint_32 i;
  200507. png_uint_32 row_width = row_info->width;
  200508. for (i = 0, sp = dp = row; i < row_width; i++)
  200509. {
  200510. /* does nothing
  200511. *(dp++) = *(sp++);
  200512. *(dp++) = *(sp++);
  200513. *(dp++) = *(sp++);
  200514. */
  200515. sp+=3; dp = sp;
  200516. *(dp++) = (png_byte)(255 - *(sp++));
  200517. }
  200518. }
  200519. /* This inverts the alpha channel in RRGGBBAA */
  200520. else
  200521. {
  200522. png_bytep sp, dp;
  200523. png_uint_32 i;
  200524. png_uint_32 row_width = row_info->width;
  200525. for (i = 0, sp = dp = row; i < row_width; i++)
  200526. {
  200527. /* does nothing
  200528. *(dp++) = *(sp++);
  200529. *(dp++) = *(sp++);
  200530. *(dp++) = *(sp++);
  200531. *(dp++) = *(sp++);
  200532. *(dp++) = *(sp++);
  200533. *(dp++) = *(sp++);
  200534. */
  200535. sp+=6; dp = sp;
  200536. *(dp++) = (png_byte)(255 - *(sp++));
  200537. *(dp++) = (png_byte)(255 - *(sp++));
  200538. }
  200539. }
  200540. }
  200541. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200542. {
  200543. /* This inverts the alpha channel in GA */
  200544. if (row_info->bit_depth == 8)
  200545. {
  200546. png_bytep sp, dp;
  200547. png_uint_32 i;
  200548. png_uint_32 row_width = row_info->width;
  200549. for (i = 0, sp = dp = row; i < row_width; i++)
  200550. {
  200551. *(dp++) = *(sp++);
  200552. *(dp++) = (png_byte)(255 - *(sp++));
  200553. }
  200554. }
  200555. /* This inverts the alpha channel in GGAA */
  200556. else
  200557. {
  200558. png_bytep sp, dp;
  200559. png_uint_32 i;
  200560. png_uint_32 row_width = row_info->width;
  200561. for (i = 0, sp = dp = row; i < row_width; i++)
  200562. {
  200563. /* does nothing
  200564. *(dp++) = *(sp++);
  200565. *(dp++) = *(sp++);
  200566. */
  200567. sp+=2; dp = sp;
  200568. *(dp++) = (png_byte)(255 - *(sp++));
  200569. *(dp++) = (png_byte)(255 - *(sp++));
  200570. }
  200571. }
  200572. }
  200573. }
  200574. }
  200575. #endif
  200576. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200577. /* undoes intrapixel differencing */
  200578. void /* PRIVATE */
  200579. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200580. {
  200581. png_debug(1, "in png_do_write_intrapixel\n");
  200582. if (
  200583. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200584. row != NULL && row_info != NULL &&
  200585. #endif
  200586. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200587. {
  200588. int bytes_per_pixel;
  200589. png_uint_32 row_width = row_info->width;
  200590. if (row_info->bit_depth == 8)
  200591. {
  200592. png_bytep rp;
  200593. png_uint_32 i;
  200594. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200595. bytes_per_pixel = 3;
  200596. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200597. bytes_per_pixel = 4;
  200598. else
  200599. return;
  200600. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200601. {
  200602. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200603. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200604. }
  200605. }
  200606. else if (row_info->bit_depth == 16)
  200607. {
  200608. png_bytep rp;
  200609. png_uint_32 i;
  200610. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200611. bytes_per_pixel = 6;
  200612. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200613. bytes_per_pixel = 8;
  200614. else
  200615. return;
  200616. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200617. {
  200618. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200619. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200620. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200621. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200622. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200623. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200624. *(rp+1) = (png_byte)(red & 0xff);
  200625. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200626. *(rp+5) = (png_byte)(blue & 0xff);
  200627. }
  200628. }
  200629. }
  200630. }
  200631. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200632. #endif /* PNG_WRITE_SUPPORTED */
  200633. /*** End of inlined file: pngwtran.c ***/
  200634. /*** Start of inlined file: pngwutil.c ***/
  200635. /* pngwutil.c - utilities to write a PNG file
  200636. *
  200637. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200638. * For conditions of distribution and use, see copyright notice in png.h
  200639. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200640. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200641. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200642. */
  200643. #define PNG_INTERNAL
  200644. #ifdef PNG_WRITE_SUPPORTED
  200645. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200646. * with unsigned numbers for convenience, although one supported
  200647. * ancillary chunk uses signed (two's complement) numbers.
  200648. */
  200649. void PNGAPI
  200650. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200651. {
  200652. buf[0] = (png_byte)((i >> 24) & 0xff);
  200653. buf[1] = (png_byte)((i >> 16) & 0xff);
  200654. buf[2] = (png_byte)((i >> 8) & 0xff);
  200655. buf[3] = (png_byte)(i & 0xff);
  200656. }
  200657. /* The png_save_int_32 function assumes integers are stored in two's
  200658. * complement format. If this isn't the case, then this routine needs to
  200659. * be modified to write data in two's complement format.
  200660. */
  200661. void PNGAPI
  200662. png_save_int_32(png_bytep buf, png_int_32 i)
  200663. {
  200664. buf[0] = (png_byte)((i >> 24) & 0xff);
  200665. buf[1] = (png_byte)((i >> 16) & 0xff);
  200666. buf[2] = (png_byte)((i >> 8) & 0xff);
  200667. buf[3] = (png_byte)(i & 0xff);
  200668. }
  200669. /* Place a 16-bit number into a buffer in PNG byte order.
  200670. * The parameter is declared unsigned int, not png_uint_16,
  200671. * just to avoid potential problems on pre-ANSI C compilers.
  200672. */
  200673. void PNGAPI
  200674. png_save_uint_16(png_bytep buf, unsigned int i)
  200675. {
  200676. buf[0] = (png_byte)((i >> 8) & 0xff);
  200677. buf[1] = (png_byte)(i & 0xff);
  200678. }
  200679. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200680. * representing the chunk name. The array must be at least 4 bytes in
  200681. * length, and does not need to be null terminated. To be safe, pass the
  200682. * pre-defined chunk names here, and if you need a new one, define it
  200683. * where the others are defined. The length is the length of the data.
  200684. * All the data must be present. If that is not possible, use the
  200685. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200686. * functions instead.
  200687. */
  200688. void PNGAPI
  200689. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200690. png_bytep data, png_size_t length)
  200691. {
  200692. if(png_ptr == NULL) return;
  200693. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200694. png_write_chunk_data(png_ptr, data, length);
  200695. png_write_chunk_end(png_ptr);
  200696. }
  200697. /* Write the start of a PNG chunk. The type is the chunk type.
  200698. * The total_length is the sum of the lengths of all the data you will be
  200699. * passing in png_write_chunk_data().
  200700. */
  200701. void PNGAPI
  200702. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200703. png_uint_32 length)
  200704. {
  200705. png_byte buf[4];
  200706. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200707. if(png_ptr == NULL) return;
  200708. /* write the length */
  200709. png_save_uint_32(buf, length);
  200710. png_write_data(png_ptr, buf, (png_size_t)4);
  200711. /* write the chunk name */
  200712. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200713. /* reset the crc and run it over the chunk name */
  200714. png_reset_crc(png_ptr);
  200715. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200716. }
  200717. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200718. * Note that multiple calls to this function are allowed, and that the
  200719. * sum of the lengths from these calls *must* add up to the total_length
  200720. * given to png_write_chunk_start().
  200721. */
  200722. void PNGAPI
  200723. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200724. {
  200725. /* write the data, and run the CRC over it */
  200726. if(png_ptr == NULL) return;
  200727. if (data != NULL && length > 0)
  200728. {
  200729. png_calculate_crc(png_ptr, data, length);
  200730. png_write_data(png_ptr, data, length);
  200731. }
  200732. }
  200733. /* Finish a chunk started with png_write_chunk_start(). */
  200734. void PNGAPI
  200735. png_write_chunk_end(png_structp png_ptr)
  200736. {
  200737. png_byte buf[4];
  200738. if(png_ptr == NULL) return;
  200739. /* write the crc */
  200740. png_save_uint_32(buf, png_ptr->crc);
  200741. png_write_data(png_ptr, buf, (png_size_t)4);
  200742. }
  200743. /* Simple function to write the signature. If we have already written
  200744. * the magic bytes of the signature, or more likely, the PNG stream is
  200745. * being embedded into another stream and doesn't need its own signature,
  200746. * we should call png_set_sig_bytes() to tell libpng how many of the
  200747. * bytes have already been written.
  200748. */
  200749. void /* PRIVATE */
  200750. png_write_sig(png_structp png_ptr)
  200751. {
  200752. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200753. /* write the rest of the 8 byte signature */
  200754. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200755. (png_size_t)8 - png_ptr->sig_bytes);
  200756. if(png_ptr->sig_bytes < 3)
  200757. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200758. }
  200759. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200760. /*
  200761. * This pair of functions encapsulates the operation of (a) compressing a
  200762. * text string, and (b) issuing it later as a series of chunk data writes.
  200763. * The compression_state structure is shared context for these functions
  200764. * set up by the caller in order to make the whole mess thread-safe.
  200765. */
  200766. typedef struct
  200767. {
  200768. char *input; /* the uncompressed input data */
  200769. int input_len; /* its length */
  200770. int num_output_ptr; /* number of output pointers used */
  200771. int max_output_ptr; /* size of output_ptr */
  200772. png_charpp output_ptr; /* array of pointers to output */
  200773. } compression_state;
  200774. /* compress given text into storage in the png_ptr structure */
  200775. static int /* PRIVATE */
  200776. png_text_compress(png_structp png_ptr,
  200777. png_charp text, png_size_t text_len, int compression,
  200778. compression_state *comp)
  200779. {
  200780. int ret;
  200781. comp->num_output_ptr = 0;
  200782. comp->max_output_ptr = 0;
  200783. comp->output_ptr = NULL;
  200784. comp->input = NULL;
  200785. comp->input_len = 0;
  200786. /* we may just want to pass the text right through */
  200787. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200788. {
  200789. comp->input = text;
  200790. comp->input_len = text_len;
  200791. return((int)text_len);
  200792. }
  200793. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200794. {
  200795. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200796. char msg[50];
  200797. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200798. png_warning(png_ptr, msg);
  200799. #else
  200800. png_warning(png_ptr, "Unknown compression type");
  200801. #endif
  200802. }
  200803. /* We can't write the chunk until we find out how much data we have,
  200804. * which means we need to run the compressor first and save the
  200805. * output. This shouldn't be a problem, as the vast majority of
  200806. * comments should be reasonable, but we will set up an array of
  200807. * malloc'd pointers to be sure.
  200808. *
  200809. * If we knew the application was well behaved, we could simplify this
  200810. * greatly by assuming we can always malloc an output buffer large
  200811. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200812. * and malloc this directly. The only time this would be a bad idea is
  200813. * if we can't malloc more than 64K and we have 64K of random input
  200814. * data, or if the input string is incredibly large (although this
  200815. * wouldn't cause a failure, just a slowdown due to swapping).
  200816. */
  200817. /* set up the compression buffers */
  200818. png_ptr->zstream.avail_in = (uInt)text_len;
  200819. png_ptr->zstream.next_in = (Bytef *)text;
  200820. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200821. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200822. /* this is the same compression loop as in png_write_row() */
  200823. do
  200824. {
  200825. /* compress the data */
  200826. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200827. if (ret != Z_OK)
  200828. {
  200829. /* error */
  200830. if (png_ptr->zstream.msg != NULL)
  200831. png_error(png_ptr, png_ptr->zstream.msg);
  200832. else
  200833. png_error(png_ptr, "zlib error");
  200834. }
  200835. /* check to see if we need more room */
  200836. if (!(png_ptr->zstream.avail_out))
  200837. {
  200838. /* make sure the output array has room */
  200839. if (comp->num_output_ptr >= comp->max_output_ptr)
  200840. {
  200841. int old_max;
  200842. old_max = comp->max_output_ptr;
  200843. comp->max_output_ptr = comp->num_output_ptr + 4;
  200844. if (comp->output_ptr != NULL)
  200845. {
  200846. png_charpp old_ptr;
  200847. old_ptr = comp->output_ptr;
  200848. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200849. (png_uint_32)(comp->max_output_ptr *
  200850. png_sizeof (png_charpp)));
  200851. png_memcpy(comp->output_ptr, old_ptr, old_max
  200852. * png_sizeof (png_charp));
  200853. png_free(png_ptr, old_ptr);
  200854. }
  200855. else
  200856. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200857. (png_uint_32)(comp->max_output_ptr *
  200858. png_sizeof (png_charp)));
  200859. }
  200860. /* save the data */
  200861. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200862. (png_uint_32)png_ptr->zbuf_size);
  200863. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200864. png_ptr->zbuf_size);
  200865. comp->num_output_ptr++;
  200866. /* and reset the buffer */
  200867. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200868. png_ptr->zstream.next_out = png_ptr->zbuf;
  200869. }
  200870. /* continue until we don't have any more to compress */
  200871. } while (png_ptr->zstream.avail_in);
  200872. /* finish the compression */
  200873. do
  200874. {
  200875. /* tell zlib we are finished */
  200876. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200877. if (ret == Z_OK)
  200878. {
  200879. /* check to see if we need more room */
  200880. if (!(png_ptr->zstream.avail_out))
  200881. {
  200882. /* check to make sure our output array has room */
  200883. if (comp->num_output_ptr >= comp->max_output_ptr)
  200884. {
  200885. int old_max;
  200886. old_max = comp->max_output_ptr;
  200887. comp->max_output_ptr = comp->num_output_ptr + 4;
  200888. if (comp->output_ptr != NULL)
  200889. {
  200890. png_charpp old_ptr;
  200891. old_ptr = comp->output_ptr;
  200892. /* This could be optimized to realloc() */
  200893. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200894. (png_uint_32)(comp->max_output_ptr *
  200895. png_sizeof (png_charpp)));
  200896. png_memcpy(comp->output_ptr, old_ptr,
  200897. old_max * png_sizeof (png_charp));
  200898. png_free(png_ptr, old_ptr);
  200899. }
  200900. else
  200901. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200902. (png_uint_32)(comp->max_output_ptr *
  200903. png_sizeof (png_charp)));
  200904. }
  200905. /* save off the data */
  200906. comp->output_ptr[comp->num_output_ptr] =
  200907. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200908. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200909. png_ptr->zbuf_size);
  200910. comp->num_output_ptr++;
  200911. /* and reset the buffer pointers */
  200912. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200913. png_ptr->zstream.next_out = png_ptr->zbuf;
  200914. }
  200915. }
  200916. else if (ret != Z_STREAM_END)
  200917. {
  200918. /* we got an error */
  200919. if (png_ptr->zstream.msg != NULL)
  200920. png_error(png_ptr, png_ptr->zstream.msg);
  200921. else
  200922. png_error(png_ptr, "zlib error");
  200923. }
  200924. } while (ret != Z_STREAM_END);
  200925. /* text length is number of buffers plus last buffer */
  200926. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200927. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200928. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200929. return((int)text_len);
  200930. }
  200931. /* ship the compressed text out via chunk writes */
  200932. static void /* PRIVATE */
  200933. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200934. {
  200935. int i;
  200936. /* handle the no-compression case */
  200937. if (comp->input)
  200938. {
  200939. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200940. (png_size_t)comp->input_len);
  200941. return;
  200942. }
  200943. /* write saved output buffers, if any */
  200944. for (i = 0; i < comp->num_output_ptr; i++)
  200945. {
  200946. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200947. png_ptr->zbuf_size);
  200948. png_free(png_ptr, comp->output_ptr[i]);
  200949. comp->output_ptr[i]=NULL;
  200950. }
  200951. if (comp->max_output_ptr != 0)
  200952. png_free(png_ptr, comp->output_ptr);
  200953. comp->output_ptr=NULL;
  200954. /* write anything left in zbuf */
  200955. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200956. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200957. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200958. /* reset zlib for another zTXt/iTXt or image data */
  200959. deflateReset(&png_ptr->zstream);
  200960. png_ptr->zstream.data_type = Z_BINARY;
  200961. }
  200962. #endif
  200963. /* Write the IHDR chunk, and update the png_struct with the necessary
  200964. * information. Note that the rest of this code depends upon this
  200965. * information being correct.
  200966. */
  200967. void /* PRIVATE */
  200968. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200969. int bit_depth, int color_type, int compression_type, int filter_type,
  200970. int interlace_type)
  200971. {
  200972. #ifdef PNG_USE_LOCAL_ARRAYS
  200973. PNG_IHDR;
  200974. #endif
  200975. png_byte buf[13]; /* buffer to store the IHDR info */
  200976. png_debug(1, "in png_write_IHDR\n");
  200977. /* Check that we have valid input data from the application info */
  200978. switch (color_type)
  200979. {
  200980. case PNG_COLOR_TYPE_GRAY:
  200981. switch (bit_depth)
  200982. {
  200983. case 1:
  200984. case 2:
  200985. case 4:
  200986. case 8:
  200987. case 16: png_ptr->channels = 1; break;
  200988. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200989. }
  200990. break;
  200991. case PNG_COLOR_TYPE_RGB:
  200992. if (bit_depth != 8 && bit_depth != 16)
  200993. png_error(png_ptr, "Invalid bit depth for RGB image");
  200994. png_ptr->channels = 3;
  200995. break;
  200996. case PNG_COLOR_TYPE_PALETTE:
  200997. switch (bit_depth)
  200998. {
  200999. case 1:
  201000. case 2:
  201001. case 4:
  201002. case 8: png_ptr->channels = 1; break;
  201003. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  201004. }
  201005. break;
  201006. case PNG_COLOR_TYPE_GRAY_ALPHA:
  201007. if (bit_depth != 8 && bit_depth != 16)
  201008. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  201009. png_ptr->channels = 2;
  201010. break;
  201011. case PNG_COLOR_TYPE_RGB_ALPHA:
  201012. if (bit_depth != 8 && bit_depth != 16)
  201013. png_error(png_ptr, "Invalid bit depth for RGBA image");
  201014. png_ptr->channels = 4;
  201015. break;
  201016. default:
  201017. png_error(png_ptr, "Invalid image color type specified");
  201018. }
  201019. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201020. {
  201021. png_warning(png_ptr, "Invalid compression type specified");
  201022. compression_type = PNG_COMPRESSION_TYPE_BASE;
  201023. }
  201024. /* Write filter_method 64 (intrapixel differencing) only if
  201025. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  201026. * 2. Libpng did not write a PNG signature (this filter_method is only
  201027. * used in PNG datastreams that are embedded in MNG datastreams) and
  201028. * 3. The application called png_permit_mng_features with a mask that
  201029. * included PNG_FLAG_MNG_FILTER_64 and
  201030. * 4. The filter_method is 64 and
  201031. * 5. The color_type is RGB or RGBA
  201032. */
  201033. if (
  201034. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201035. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  201036. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  201037. (color_type == PNG_COLOR_TYPE_RGB ||
  201038. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  201039. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  201040. #endif
  201041. filter_type != PNG_FILTER_TYPE_BASE)
  201042. {
  201043. png_warning(png_ptr, "Invalid filter type specified");
  201044. filter_type = PNG_FILTER_TYPE_BASE;
  201045. }
  201046. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201047. if (interlace_type != PNG_INTERLACE_NONE &&
  201048. interlace_type != PNG_INTERLACE_ADAM7)
  201049. {
  201050. png_warning(png_ptr, "Invalid interlace type specified");
  201051. interlace_type = PNG_INTERLACE_ADAM7;
  201052. }
  201053. #else
  201054. interlace_type=PNG_INTERLACE_NONE;
  201055. #endif
  201056. /* save off the relevent information */
  201057. png_ptr->bit_depth = (png_byte)bit_depth;
  201058. png_ptr->color_type = (png_byte)color_type;
  201059. png_ptr->interlaced = (png_byte)interlace_type;
  201060. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201061. png_ptr->filter_type = (png_byte)filter_type;
  201062. #endif
  201063. png_ptr->compression_type = (png_byte)compression_type;
  201064. png_ptr->width = width;
  201065. png_ptr->height = height;
  201066. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201067. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201068. /* set the usr info, so any transformations can modify it */
  201069. png_ptr->usr_width = png_ptr->width;
  201070. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201071. png_ptr->usr_channels = png_ptr->channels;
  201072. /* pack the header information into the buffer */
  201073. png_save_uint_32(buf, width);
  201074. png_save_uint_32(buf + 4, height);
  201075. buf[8] = (png_byte)bit_depth;
  201076. buf[9] = (png_byte)color_type;
  201077. buf[10] = (png_byte)compression_type;
  201078. buf[11] = (png_byte)filter_type;
  201079. buf[12] = (png_byte)interlace_type;
  201080. /* write the chunk */
  201081. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201082. /* initialize zlib with PNG info */
  201083. png_ptr->zstream.zalloc = png_zalloc;
  201084. png_ptr->zstream.zfree = png_zfree;
  201085. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201086. if (!(png_ptr->do_filter))
  201087. {
  201088. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201089. png_ptr->bit_depth < 8)
  201090. png_ptr->do_filter = PNG_FILTER_NONE;
  201091. else
  201092. png_ptr->do_filter = PNG_ALL_FILTERS;
  201093. }
  201094. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201095. {
  201096. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201097. png_ptr->zlib_strategy = Z_FILTERED;
  201098. else
  201099. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201100. }
  201101. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201102. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201103. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201104. png_ptr->zlib_mem_level = 8;
  201105. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201106. png_ptr->zlib_window_bits = 15;
  201107. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201108. png_ptr->zlib_method = 8;
  201109. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201110. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201111. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201112. png_error(png_ptr, "zlib failed to initialize compressor");
  201113. png_ptr->zstream.next_out = png_ptr->zbuf;
  201114. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201115. /* libpng is not interested in zstream.data_type */
  201116. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201117. png_ptr->zstream.data_type = Z_BINARY;
  201118. png_ptr->mode = PNG_HAVE_IHDR;
  201119. }
  201120. /* write the palette. We are careful not to trust png_color to be in the
  201121. * correct order for PNG, so people can redefine it to any convenient
  201122. * structure.
  201123. */
  201124. void /* PRIVATE */
  201125. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201126. {
  201127. #ifdef PNG_USE_LOCAL_ARRAYS
  201128. PNG_PLTE;
  201129. #endif
  201130. png_uint_32 i;
  201131. png_colorp pal_ptr;
  201132. png_byte buf[3];
  201133. png_debug(1, "in png_write_PLTE\n");
  201134. if ((
  201135. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201136. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201137. #endif
  201138. num_pal == 0) || num_pal > 256)
  201139. {
  201140. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201141. {
  201142. png_error(png_ptr, "Invalid number of colors in palette");
  201143. }
  201144. else
  201145. {
  201146. png_warning(png_ptr, "Invalid number of colors in palette");
  201147. return;
  201148. }
  201149. }
  201150. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201151. {
  201152. png_warning(png_ptr,
  201153. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201154. return;
  201155. }
  201156. png_ptr->num_palette = (png_uint_16)num_pal;
  201157. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201158. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201159. #ifndef PNG_NO_POINTER_INDEXING
  201160. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201161. {
  201162. buf[0] = pal_ptr->red;
  201163. buf[1] = pal_ptr->green;
  201164. buf[2] = pal_ptr->blue;
  201165. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201166. }
  201167. #else
  201168. /* This is a little slower but some buggy compilers need to do this instead */
  201169. pal_ptr=palette;
  201170. for (i = 0; i < num_pal; i++)
  201171. {
  201172. buf[0] = pal_ptr[i].red;
  201173. buf[1] = pal_ptr[i].green;
  201174. buf[2] = pal_ptr[i].blue;
  201175. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201176. }
  201177. #endif
  201178. png_write_chunk_end(png_ptr);
  201179. png_ptr->mode |= PNG_HAVE_PLTE;
  201180. }
  201181. /* write an IDAT chunk */
  201182. void /* PRIVATE */
  201183. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201184. {
  201185. #ifdef PNG_USE_LOCAL_ARRAYS
  201186. PNG_IDAT;
  201187. #endif
  201188. png_debug(1, "in png_write_IDAT\n");
  201189. /* Optimize the CMF field in the zlib stream. */
  201190. /* This hack of the zlib stream is compliant to the stream specification. */
  201191. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201192. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201193. {
  201194. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201195. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201196. {
  201197. /* Avoid memory underflows and multiplication overflows. */
  201198. /* The conditions below are practically always satisfied;
  201199. however, they still must be checked. */
  201200. if (length >= 2 &&
  201201. png_ptr->height < 16384 && png_ptr->width < 16384)
  201202. {
  201203. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201204. ((png_ptr->width *
  201205. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201206. unsigned int z_cinfo = z_cmf >> 4;
  201207. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201208. while (uncompressed_idat_size <= half_z_window_size &&
  201209. half_z_window_size >= 256)
  201210. {
  201211. z_cinfo--;
  201212. half_z_window_size >>= 1;
  201213. }
  201214. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201215. if (data[0] != (png_byte)z_cmf)
  201216. {
  201217. data[0] = (png_byte)z_cmf;
  201218. data[1] &= 0xe0;
  201219. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201220. }
  201221. }
  201222. }
  201223. else
  201224. png_error(png_ptr,
  201225. "Invalid zlib compression method or flags in IDAT");
  201226. }
  201227. png_write_chunk(png_ptr, png_IDAT, data, length);
  201228. png_ptr->mode |= PNG_HAVE_IDAT;
  201229. }
  201230. /* write an IEND chunk */
  201231. void /* PRIVATE */
  201232. png_write_IEND(png_structp png_ptr)
  201233. {
  201234. #ifdef PNG_USE_LOCAL_ARRAYS
  201235. PNG_IEND;
  201236. #endif
  201237. png_debug(1, "in png_write_IEND\n");
  201238. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201239. (png_size_t)0);
  201240. png_ptr->mode |= PNG_HAVE_IEND;
  201241. }
  201242. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201243. /* write a gAMA chunk */
  201244. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201245. void /* PRIVATE */
  201246. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201247. {
  201248. #ifdef PNG_USE_LOCAL_ARRAYS
  201249. PNG_gAMA;
  201250. #endif
  201251. png_uint_32 igamma;
  201252. png_byte buf[4];
  201253. png_debug(1, "in png_write_gAMA\n");
  201254. /* file_gamma is saved in 1/100,000ths */
  201255. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201256. png_save_uint_32(buf, igamma);
  201257. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201258. }
  201259. #endif
  201260. #ifdef PNG_FIXED_POINT_SUPPORTED
  201261. void /* PRIVATE */
  201262. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201263. {
  201264. #ifdef PNG_USE_LOCAL_ARRAYS
  201265. PNG_gAMA;
  201266. #endif
  201267. png_byte buf[4];
  201268. png_debug(1, "in png_write_gAMA\n");
  201269. /* file_gamma is saved in 1/100,000ths */
  201270. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201271. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201272. }
  201273. #endif
  201274. #endif
  201275. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201276. /* write a sRGB chunk */
  201277. void /* PRIVATE */
  201278. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201279. {
  201280. #ifdef PNG_USE_LOCAL_ARRAYS
  201281. PNG_sRGB;
  201282. #endif
  201283. png_byte buf[1];
  201284. png_debug(1, "in png_write_sRGB\n");
  201285. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201286. png_warning(png_ptr,
  201287. "Invalid sRGB rendering intent specified");
  201288. buf[0]=(png_byte)srgb_intent;
  201289. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201290. }
  201291. #endif
  201292. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201293. /* write an iCCP chunk */
  201294. void /* PRIVATE */
  201295. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201296. png_charp profile, int profile_len)
  201297. {
  201298. #ifdef PNG_USE_LOCAL_ARRAYS
  201299. PNG_iCCP;
  201300. #endif
  201301. png_size_t name_len;
  201302. png_charp new_name;
  201303. compression_state comp;
  201304. int embedded_profile_len = 0;
  201305. png_debug(1, "in png_write_iCCP\n");
  201306. comp.num_output_ptr = 0;
  201307. comp.max_output_ptr = 0;
  201308. comp.output_ptr = NULL;
  201309. comp.input = NULL;
  201310. comp.input_len = 0;
  201311. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201312. &new_name)) == 0)
  201313. {
  201314. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201315. return;
  201316. }
  201317. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201318. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201319. if (profile == NULL)
  201320. profile_len = 0;
  201321. if (profile_len > 3)
  201322. embedded_profile_len =
  201323. ((*( (png_bytep)profile ))<<24) |
  201324. ((*( (png_bytep)profile+1))<<16) |
  201325. ((*( (png_bytep)profile+2))<< 8) |
  201326. ((*( (png_bytep)profile+3)) );
  201327. if (profile_len < embedded_profile_len)
  201328. {
  201329. png_warning(png_ptr,
  201330. "Embedded profile length too large in iCCP chunk");
  201331. return;
  201332. }
  201333. if (profile_len > embedded_profile_len)
  201334. {
  201335. png_warning(png_ptr,
  201336. "Truncating profile to actual length in iCCP chunk");
  201337. profile_len = embedded_profile_len;
  201338. }
  201339. if (profile_len)
  201340. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201341. PNG_COMPRESSION_TYPE_BASE, &comp);
  201342. /* make sure we include the NULL after the name and the compression type */
  201343. png_write_chunk_start(png_ptr, png_iCCP,
  201344. (png_uint_32)name_len+profile_len+2);
  201345. new_name[name_len+1]=0x00;
  201346. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201347. if (profile_len)
  201348. png_write_compressed_data_out(png_ptr, &comp);
  201349. png_write_chunk_end(png_ptr);
  201350. png_free(png_ptr, new_name);
  201351. }
  201352. #endif
  201353. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201354. /* write a sPLT chunk */
  201355. void /* PRIVATE */
  201356. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201357. {
  201358. #ifdef PNG_USE_LOCAL_ARRAYS
  201359. PNG_sPLT;
  201360. #endif
  201361. png_size_t name_len;
  201362. png_charp new_name;
  201363. png_byte entrybuf[10];
  201364. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201365. int palette_size = entry_size * spalette->nentries;
  201366. png_sPLT_entryp ep;
  201367. #ifdef PNG_NO_POINTER_INDEXING
  201368. int i;
  201369. #endif
  201370. png_debug(1, "in png_write_sPLT\n");
  201371. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201372. spalette->name, &new_name))==0)
  201373. {
  201374. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201375. return;
  201376. }
  201377. /* make sure we include the NULL after the name */
  201378. png_write_chunk_start(png_ptr, png_sPLT,
  201379. (png_uint_32)(name_len + 2 + palette_size));
  201380. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201381. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201382. /* loop through each palette entry, writing appropriately */
  201383. #ifndef PNG_NO_POINTER_INDEXING
  201384. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201385. {
  201386. if (spalette->depth == 8)
  201387. {
  201388. entrybuf[0] = (png_byte)ep->red;
  201389. entrybuf[1] = (png_byte)ep->green;
  201390. entrybuf[2] = (png_byte)ep->blue;
  201391. entrybuf[3] = (png_byte)ep->alpha;
  201392. png_save_uint_16(entrybuf + 4, ep->frequency);
  201393. }
  201394. else
  201395. {
  201396. png_save_uint_16(entrybuf + 0, ep->red);
  201397. png_save_uint_16(entrybuf + 2, ep->green);
  201398. png_save_uint_16(entrybuf + 4, ep->blue);
  201399. png_save_uint_16(entrybuf + 6, ep->alpha);
  201400. png_save_uint_16(entrybuf + 8, ep->frequency);
  201401. }
  201402. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201403. }
  201404. #else
  201405. ep=spalette->entries;
  201406. for (i=0; i>spalette->nentries; i++)
  201407. {
  201408. if (spalette->depth == 8)
  201409. {
  201410. entrybuf[0] = (png_byte)ep[i].red;
  201411. entrybuf[1] = (png_byte)ep[i].green;
  201412. entrybuf[2] = (png_byte)ep[i].blue;
  201413. entrybuf[3] = (png_byte)ep[i].alpha;
  201414. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201415. }
  201416. else
  201417. {
  201418. png_save_uint_16(entrybuf + 0, ep[i].red);
  201419. png_save_uint_16(entrybuf + 2, ep[i].green);
  201420. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201421. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201422. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201423. }
  201424. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201425. }
  201426. #endif
  201427. png_write_chunk_end(png_ptr);
  201428. png_free(png_ptr, new_name);
  201429. }
  201430. #endif
  201431. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201432. /* write the sBIT chunk */
  201433. void /* PRIVATE */
  201434. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201435. {
  201436. #ifdef PNG_USE_LOCAL_ARRAYS
  201437. PNG_sBIT;
  201438. #endif
  201439. png_byte buf[4];
  201440. png_size_t size;
  201441. png_debug(1, "in png_write_sBIT\n");
  201442. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201443. if (color_type & PNG_COLOR_MASK_COLOR)
  201444. {
  201445. png_byte maxbits;
  201446. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201447. png_ptr->usr_bit_depth);
  201448. if (sbit->red == 0 || sbit->red > maxbits ||
  201449. sbit->green == 0 || sbit->green > maxbits ||
  201450. sbit->blue == 0 || sbit->blue > maxbits)
  201451. {
  201452. png_warning(png_ptr, "Invalid sBIT depth specified");
  201453. return;
  201454. }
  201455. buf[0] = sbit->red;
  201456. buf[1] = sbit->green;
  201457. buf[2] = sbit->blue;
  201458. size = 3;
  201459. }
  201460. else
  201461. {
  201462. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201463. {
  201464. png_warning(png_ptr, "Invalid sBIT depth specified");
  201465. return;
  201466. }
  201467. buf[0] = sbit->gray;
  201468. size = 1;
  201469. }
  201470. if (color_type & PNG_COLOR_MASK_ALPHA)
  201471. {
  201472. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201473. {
  201474. png_warning(png_ptr, "Invalid sBIT depth specified");
  201475. return;
  201476. }
  201477. buf[size++] = sbit->alpha;
  201478. }
  201479. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201480. }
  201481. #endif
  201482. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201483. /* write the cHRM chunk */
  201484. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201485. void /* PRIVATE */
  201486. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201487. double red_x, double red_y, double green_x, double green_y,
  201488. double blue_x, double blue_y)
  201489. {
  201490. #ifdef PNG_USE_LOCAL_ARRAYS
  201491. PNG_cHRM;
  201492. #endif
  201493. png_byte buf[32];
  201494. png_uint_32 itemp;
  201495. png_debug(1, "in png_write_cHRM\n");
  201496. /* each value is saved in 1/100,000ths */
  201497. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201498. white_x + white_y > 1.0)
  201499. {
  201500. png_warning(png_ptr, "Invalid cHRM white point specified");
  201501. #if !defined(PNG_NO_CONSOLE_IO)
  201502. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201503. #endif
  201504. return;
  201505. }
  201506. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201507. png_save_uint_32(buf, itemp);
  201508. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201509. png_save_uint_32(buf + 4, itemp);
  201510. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201511. {
  201512. png_warning(png_ptr, "Invalid cHRM red point specified");
  201513. return;
  201514. }
  201515. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201516. png_save_uint_32(buf + 8, itemp);
  201517. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201518. png_save_uint_32(buf + 12, itemp);
  201519. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201520. {
  201521. png_warning(png_ptr, "Invalid cHRM green point specified");
  201522. return;
  201523. }
  201524. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201525. png_save_uint_32(buf + 16, itemp);
  201526. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201527. png_save_uint_32(buf + 20, itemp);
  201528. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201529. {
  201530. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201531. return;
  201532. }
  201533. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201534. png_save_uint_32(buf + 24, itemp);
  201535. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201536. png_save_uint_32(buf + 28, itemp);
  201537. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201538. }
  201539. #endif
  201540. #ifdef PNG_FIXED_POINT_SUPPORTED
  201541. void /* PRIVATE */
  201542. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201543. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201544. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201545. png_fixed_point blue_y)
  201546. {
  201547. #ifdef PNG_USE_LOCAL_ARRAYS
  201548. PNG_cHRM;
  201549. #endif
  201550. png_byte buf[32];
  201551. png_debug(1, "in png_write_cHRM\n");
  201552. /* each value is saved in 1/100,000ths */
  201553. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201554. {
  201555. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201556. #if !defined(PNG_NO_CONSOLE_IO)
  201557. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201558. #endif
  201559. return;
  201560. }
  201561. png_save_uint_32(buf, (png_uint_32)white_x);
  201562. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201563. if (red_x + red_y > 100000L)
  201564. {
  201565. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201566. return;
  201567. }
  201568. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201569. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201570. if (green_x + green_y > 100000L)
  201571. {
  201572. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201573. return;
  201574. }
  201575. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201576. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201577. if (blue_x + blue_y > 100000L)
  201578. {
  201579. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201580. return;
  201581. }
  201582. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201583. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201584. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201585. }
  201586. #endif
  201587. #endif
  201588. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201589. /* write the tRNS chunk */
  201590. void /* PRIVATE */
  201591. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201592. int num_trans, int color_type)
  201593. {
  201594. #ifdef PNG_USE_LOCAL_ARRAYS
  201595. PNG_tRNS;
  201596. #endif
  201597. png_byte buf[6];
  201598. png_debug(1, "in png_write_tRNS\n");
  201599. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201600. {
  201601. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201602. {
  201603. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201604. return;
  201605. }
  201606. /* write the chunk out as it is */
  201607. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201608. }
  201609. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201610. {
  201611. /* one 16 bit value */
  201612. if(tran->gray >= (1 << png_ptr->bit_depth))
  201613. {
  201614. png_warning(png_ptr,
  201615. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201616. return;
  201617. }
  201618. png_save_uint_16(buf, tran->gray);
  201619. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201620. }
  201621. else if (color_type == PNG_COLOR_TYPE_RGB)
  201622. {
  201623. /* three 16 bit values */
  201624. png_save_uint_16(buf, tran->red);
  201625. png_save_uint_16(buf + 2, tran->green);
  201626. png_save_uint_16(buf + 4, tran->blue);
  201627. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201628. {
  201629. png_warning(png_ptr,
  201630. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201631. return;
  201632. }
  201633. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201634. }
  201635. else
  201636. {
  201637. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201638. }
  201639. }
  201640. #endif
  201641. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201642. /* write the background chunk */
  201643. void /* PRIVATE */
  201644. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201645. {
  201646. #ifdef PNG_USE_LOCAL_ARRAYS
  201647. PNG_bKGD;
  201648. #endif
  201649. png_byte buf[6];
  201650. png_debug(1, "in png_write_bKGD\n");
  201651. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201652. {
  201653. if (
  201654. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201655. (png_ptr->num_palette ||
  201656. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201657. #endif
  201658. back->index > png_ptr->num_palette)
  201659. {
  201660. png_warning(png_ptr, "Invalid background palette index");
  201661. return;
  201662. }
  201663. buf[0] = back->index;
  201664. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201665. }
  201666. else if (color_type & PNG_COLOR_MASK_COLOR)
  201667. {
  201668. png_save_uint_16(buf, back->red);
  201669. png_save_uint_16(buf + 2, back->green);
  201670. png_save_uint_16(buf + 4, back->blue);
  201671. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201672. {
  201673. png_warning(png_ptr,
  201674. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201675. return;
  201676. }
  201677. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201678. }
  201679. else
  201680. {
  201681. if(back->gray >= (1 << png_ptr->bit_depth))
  201682. {
  201683. png_warning(png_ptr,
  201684. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201685. return;
  201686. }
  201687. png_save_uint_16(buf, back->gray);
  201688. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201689. }
  201690. }
  201691. #endif
  201692. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201693. /* write the histogram */
  201694. void /* PRIVATE */
  201695. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201696. {
  201697. #ifdef PNG_USE_LOCAL_ARRAYS
  201698. PNG_hIST;
  201699. #endif
  201700. int i;
  201701. png_byte buf[3];
  201702. png_debug(1, "in png_write_hIST\n");
  201703. if (num_hist > (int)png_ptr->num_palette)
  201704. {
  201705. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201706. png_ptr->num_palette);
  201707. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201708. return;
  201709. }
  201710. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201711. for (i = 0; i < num_hist; i++)
  201712. {
  201713. png_save_uint_16(buf, hist[i]);
  201714. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201715. }
  201716. png_write_chunk_end(png_ptr);
  201717. }
  201718. #endif
  201719. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201720. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201721. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201722. * and if invalid, correct the keyword rather than discarding the entire
  201723. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201724. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201725. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201726. *
  201727. * The new_key is allocated to hold the corrected keyword and must be freed
  201728. * by the calling routine. This avoids problems with trying to write to
  201729. * static keywords without having to have duplicate copies of the strings.
  201730. */
  201731. png_size_t /* PRIVATE */
  201732. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201733. {
  201734. png_size_t key_len;
  201735. png_charp kp, dp;
  201736. int kflag;
  201737. int kwarn=0;
  201738. png_debug(1, "in png_check_keyword\n");
  201739. *new_key = NULL;
  201740. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201741. {
  201742. png_warning(png_ptr, "zero length keyword");
  201743. return ((png_size_t)0);
  201744. }
  201745. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201746. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201747. if (*new_key == NULL)
  201748. {
  201749. png_warning(png_ptr, "Out of memory while procesing keyword");
  201750. return ((png_size_t)0);
  201751. }
  201752. /* Replace non-printing characters with a blank and print a warning */
  201753. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201754. {
  201755. if ((png_byte)*kp < 0x20 ||
  201756. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201757. {
  201758. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201759. char msg[40];
  201760. png_snprintf(msg, 40,
  201761. "invalid keyword character 0x%02X", (png_byte)*kp);
  201762. png_warning(png_ptr, msg);
  201763. #else
  201764. png_warning(png_ptr, "invalid character in keyword");
  201765. #endif
  201766. *dp = ' ';
  201767. }
  201768. else
  201769. {
  201770. *dp = *kp;
  201771. }
  201772. }
  201773. *dp = '\0';
  201774. /* Remove any trailing white space. */
  201775. kp = *new_key + key_len - 1;
  201776. if (*kp == ' ')
  201777. {
  201778. png_warning(png_ptr, "trailing spaces removed from keyword");
  201779. while (*kp == ' ')
  201780. {
  201781. *(kp--) = '\0';
  201782. key_len--;
  201783. }
  201784. }
  201785. /* Remove any leading white space. */
  201786. kp = *new_key;
  201787. if (*kp == ' ')
  201788. {
  201789. png_warning(png_ptr, "leading spaces removed from keyword");
  201790. while (*kp == ' ')
  201791. {
  201792. kp++;
  201793. key_len--;
  201794. }
  201795. }
  201796. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201797. /* Remove multiple internal spaces. */
  201798. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201799. {
  201800. if (*kp == ' ' && kflag == 0)
  201801. {
  201802. *(dp++) = *kp;
  201803. kflag = 1;
  201804. }
  201805. else if (*kp == ' ')
  201806. {
  201807. key_len--;
  201808. kwarn=1;
  201809. }
  201810. else
  201811. {
  201812. *(dp++) = *kp;
  201813. kflag = 0;
  201814. }
  201815. }
  201816. *dp = '\0';
  201817. if(kwarn)
  201818. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201819. if (key_len == 0)
  201820. {
  201821. png_free(png_ptr, *new_key);
  201822. *new_key=NULL;
  201823. png_warning(png_ptr, "Zero length keyword");
  201824. }
  201825. if (key_len > 79)
  201826. {
  201827. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201828. new_key[79] = '\0';
  201829. key_len = 79;
  201830. }
  201831. return (key_len);
  201832. }
  201833. #endif
  201834. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201835. /* write a tEXt chunk */
  201836. void /* PRIVATE */
  201837. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201838. png_size_t text_len)
  201839. {
  201840. #ifdef PNG_USE_LOCAL_ARRAYS
  201841. PNG_tEXt;
  201842. #endif
  201843. png_size_t key_len;
  201844. png_charp new_key;
  201845. png_debug(1, "in png_write_tEXt\n");
  201846. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201847. {
  201848. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201849. return;
  201850. }
  201851. if (text == NULL || *text == '\0')
  201852. text_len = 0;
  201853. else
  201854. text_len = png_strlen(text);
  201855. /* make sure we include the 0 after the key */
  201856. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201857. /*
  201858. * We leave it to the application to meet PNG-1.0 requirements on the
  201859. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201860. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201861. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201862. */
  201863. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201864. if (text_len)
  201865. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201866. png_write_chunk_end(png_ptr);
  201867. png_free(png_ptr, new_key);
  201868. }
  201869. #endif
  201870. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201871. /* write a compressed text chunk */
  201872. void /* PRIVATE */
  201873. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201874. png_size_t text_len, int compression)
  201875. {
  201876. #ifdef PNG_USE_LOCAL_ARRAYS
  201877. PNG_zTXt;
  201878. #endif
  201879. png_size_t key_len;
  201880. char buf[1];
  201881. png_charp new_key;
  201882. compression_state comp;
  201883. png_debug(1, "in png_write_zTXt\n");
  201884. comp.num_output_ptr = 0;
  201885. comp.max_output_ptr = 0;
  201886. comp.output_ptr = NULL;
  201887. comp.input = NULL;
  201888. comp.input_len = 0;
  201889. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201890. {
  201891. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201892. return;
  201893. }
  201894. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201895. {
  201896. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201897. png_free(png_ptr, new_key);
  201898. return;
  201899. }
  201900. text_len = png_strlen(text);
  201901. /* compute the compressed data; do it now for the length */
  201902. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201903. &comp);
  201904. /* write start of chunk */
  201905. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201906. (key_len+text_len+2));
  201907. /* write key */
  201908. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201909. png_free(png_ptr, new_key);
  201910. buf[0] = (png_byte)compression;
  201911. /* write compression */
  201912. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201913. /* write the compressed data */
  201914. png_write_compressed_data_out(png_ptr, &comp);
  201915. /* close the chunk */
  201916. png_write_chunk_end(png_ptr);
  201917. }
  201918. #endif
  201919. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201920. /* write an iTXt chunk */
  201921. void /* PRIVATE */
  201922. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201923. png_charp lang, png_charp lang_key, png_charp text)
  201924. {
  201925. #ifdef PNG_USE_LOCAL_ARRAYS
  201926. PNG_iTXt;
  201927. #endif
  201928. png_size_t lang_len, key_len, lang_key_len, text_len;
  201929. png_charp new_lang, new_key;
  201930. png_byte cbuf[2];
  201931. compression_state comp;
  201932. png_debug(1, "in png_write_iTXt\n");
  201933. comp.num_output_ptr = 0;
  201934. comp.max_output_ptr = 0;
  201935. comp.output_ptr = NULL;
  201936. comp.input = NULL;
  201937. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201938. {
  201939. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201940. return;
  201941. }
  201942. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201943. {
  201944. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201945. new_lang = NULL;
  201946. lang_len = 0;
  201947. }
  201948. if (lang_key == NULL)
  201949. lang_key_len = 0;
  201950. else
  201951. lang_key_len = png_strlen(lang_key);
  201952. if (text == NULL)
  201953. text_len = 0;
  201954. else
  201955. text_len = png_strlen(text);
  201956. /* compute the compressed data; do it now for the length */
  201957. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201958. &comp);
  201959. /* make sure we include the compression flag, the compression byte,
  201960. * and the NULs after the key, lang, and lang_key parts */
  201961. png_write_chunk_start(png_ptr, png_iTXt,
  201962. (png_uint_32)(
  201963. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201964. + key_len
  201965. + lang_len
  201966. + lang_key_len
  201967. + text_len));
  201968. /*
  201969. * We leave it to the application to meet PNG-1.0 requirements on the
  201970. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201971. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201972. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201973. */
  201974. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201975. /* set the compression flag */
  201976. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201977. compression == PNG_TEXT_COMPRESSION_NONE)
  201978. cbuf[0] = 0;
  201979. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201980. cbuf[0] = 1;
  201981. /* set the compression method */
  201982. cbuf[1] = 0;
  201983. png_write_chunk_data(png_ptr, cbuf, 2);
  201984. cbuf[0] = 0;
  201985. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201986. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201987. png_write_compressed_data_out(png_ptr, &comp);
  201988. png_write_chunk_end(png_ptr);
  201989. png_free(png_ptr, new_key);
  201990. if (new_lang)
  201991. png_free(png_ptr, new_lang);
  201992. }
  201993. #endif
  201994. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201995. /* write the oFFs chunk */
  201996. void /* PRIVATE */
  201997. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201998. int unit_type)
  201999. {
  202000. #ifdef PNG_USE_LOCAL_ARRAYS
  202001. PNG_oFFs;
  202002. #endif
  202003. png_byte buf[9];
  202004. png_debug(1, "in png_write_oFFs\n");
  202005. if (unit_type >= PNG_OFFSET_LAST)
  202006. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  202007. png_save_int_32(buf, x_offset);
  202008. png_save_int_32(buf + 4, y_offset);
  202009. buf[8] = (png_byte)unit_type;
  202010. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  202011. }
  202012. #endif
  202013. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  202014. /* write the pCAL chunk (described in the PNG extensions document) */
  202015. void /* PRIVATE */
  202016. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  202017. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  202018. {
  202019. #ifdef PNG_USE_LOCAL_ARRAYS
  202020. PNG_pCAL;
  202021. #endif
  202022. png_size_t purpose_len, units_len, total_len;
  202023. png_uint_32p params_len;
  202024. png_byte buf[10];
  202025. png_charp new_purpose;
  202026. int i;
  202027. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  202028. if (type >= PNG_EQUATION_LAST)
  202029. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  202030. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  202031. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  202032. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  202033. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  202034. total_len = purpose_len + units_len + 10;
  202035. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  202036. *png_sizeof(png_uint_32)));
  202037. /* Find the length of each parameter, making sure we don't count the
  202038. null terminator for the last parameter. */
  202039. for (i = 0; i < nparams; i++)
  202040. {
  202041. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  202042. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202043. total_len += (png_size_t)params_len[i];
  202044. }
  202045. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202046. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202047. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202048. png_save_int_32(buf, X0);
  202049. png_save_int_32(buf + 4, X1);
  202050. buf[8] = (png_byte)type;
  202051. buf[9] = (png_byte)nparams;
  202052. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  202053. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  202054. png_free(png_ptr, new_purpose);
  202055. for (i = 0; i < nparams; i++)
  202056. {
  202057. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  202058. (png_size_t)params_len[i]);
  202059. }
  202060. png_free(png_ptr, params_len);
  202061. png_write_chunk_end(png_ptr);
  202062. }
  202063. #endif
  202064. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  202065. /* write the sCAL chunk */
  202066. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202067. void /* PRIVATE */
  202068. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202069. {
  202070. #ifdef PNG_USE_LOCAL_ARRAYS
  202071. PNG_sCAL;
  202072. #endif
  202073. char buf[64];
  202074. png_size_t total_len;
  202075. png_debug(1, "in png_write_sCAL\n");
  202076. buf[0] = (char)unit;
  202077. #if defined(_WIN32_WCE)
  202078. /* sprintf() function is not supported on WindowsCE */
  202079. {
  202080. wchar_t wc_buf[32];
  202081. size_t wc_len;
  202082. swprintf(wc_buf, TEXT("%12.12e"), width);
  202083. wc_len = wcslen(wc_buf);
  202084. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202085. total_len = wc_len + 2;
  202086. swprintf(wc_buf, TEXT("%12.12e"), height);
  202087. wc_len = wcslen(wc_buf);
  202088. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202089. NULL, NULL);
  202090. total_len += wc_len;
  202091. }
  202092. #else
  202093. png_snprintf(buf + 1, 63, "%12.12e", width);
  202094. total_len = 1 + png_strlen(buf + 1) + 1;
  202095. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202096. total_len += png_strlen(buf + total_len);
  202097. #endif
  202098. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202099. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202100. }
  202101. #else
  202102. #ifdef PNG_FIXED_POINT_SUPPORTED
  202103. void /* PRIVATE */
  202104. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202105. png_charp height)
  202106. {
  202107. #ifdef PNG_USE_LOCAL_ARRAYS
  202108. PNG_sCAL;
  202109. #endif
  202110. png_byte buf[64];
  202111. png_size_t wlen, hlen, total_len;
  202112. png_debug(1, "in png_write_sCAL_s\n");
  202113. wlen = png_strlen(width);
  202114. hlen = png_strlen(height);
  202115. total_len = wlen + hlen + 2;
  202116. if (total_len > 64)
  202117. {
  202118. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202119. return;
  202120. }
  202121. buf[0] = (png_byte)unit;
  202122. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202123. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202124. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202125. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202126. }
  202127. #endif
  202128. #endif
  202129. #endif
  202130. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202131. /* write the pHYs chunk */
  202132. void /* PRIVATE */
  202133. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202134. png_uint_32 y_pixels_per_unit,
  202135. int unit_type)
  202136. {
  202137. #ifdef PNG_USE_LOCAL_ARRAYS
  202138. PNG_pHYs;
  202139. #endif
  202140. png_byte buf[9];
  202141. png_debug(1, "in png_write_pHYs\n");
  202142. if (unit_type >= PNG_RESOLUTION_LAST)
  202143. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202144. png_save_uint_32(buf, x_pixels_per_unit);
  202145. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202146. buf[8] = (png_byte)unit_type;
  202147. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202148. }
  202149. #endif
  202150. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202151. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202152. * or png_convert_from_time_t(), or fill in the structure yourself.
  202153. */
  202154. void /* PRIVATE */
  202155. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202156. {
  202157. #ifdef PNG_USE_LOCAL_ARRAYS
  202158. PNG_tIME;
  202159. #endif
  202160. png_byte buf[7];
  202161. png_debug(1, "in png_write_tIME\n");
  202162. if (mod_time->month > 12 || mod_time->month < 1 ||
  202163. mod_time->day > 31 || mod_time->day < 1 ||
  202164. mod_time->hour > 23 || mod_time->second > 60)
  202165. {
  202166. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202167. return;
  202168. }
  202169. png_save_uint_16(buf, mod_time->year);
  202170. buf[2] = mod_time->month;
  202171. buf[3] = mod_time->day;
  202172. buf[4] = mod_time->hour;
  202173. buf[5] = mod_time->minute;
  202174. buf[6] = mod_time->second;
  202175. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202176. }
  202177. #endif
  202178. /* initializes the row writing capability of libpng */
  202179. void /* PRIVATE */
  202180. png_write_start_row(png_structp png_ptr)
  202181. {
  202182. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202183. #ifdef PNG_USE_LOCAL_ARRAYS
  202184. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202185. /* start of interlace block */
  202186. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202187. /* offset to next interlace block */
  202188. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202189. /* start of interlace block in the y direction */
  202190. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202191. /* offset to next interlace block in the y direction */
  202192. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202193. #endif
  202194. #endif
  202195. png_size_t buf_size;
  202196. png_debug(1, "in png_write_start_row\n");
  202197. buf_size = (png_size_t)(PNG_ROWBYTES(
  202198. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202199. /* set up row buffer */
  202200. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202201. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202202. #ifndef PNG_NO_WRITE_FILTERING
  202203. /* set up filtering buffer, if using this filter */
  202204. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202205. {
  202206. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202207. (png_ptr->rowbytes + 1));
  202208. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202209. }
  202210. /* We only need to keep the previous row if we are using one of these. */
  202211. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202212. {
  202213. /* set up previous row buffer */
  202214. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202215. png_memset(png_ptr->prev_row, 0, buf_size);
  202216. if (png_ptr->do_filter & PNG_FILTER_UP)
  202217. {
  202218. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202219. (png_ptr->rowbytes + 1));
  202220. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202221. }
  202222. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202223. {
  202224. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202225. (png_ptr->rowbytes + 1));
  202226. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202227. }
  202228. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202229. {
  202230. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202231. (png_ptr->rowbytes + 1));
  202232. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202233. }
  202234. #endif /* PNG_NO_WRITE_FILTERING */
  202235. }
  202236. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202237. /* if interlaced, we need to set up width and height of pass */
  202238. if (png_ptr->interlaced)
  202239. {
  202240. if (!(png_ptr->transformations & PNG_INTERLACE))
  202241. {
  202242. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202243. png_pass_ystart[0]) / png_pass_yinc[0];
  202244. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202245. png_pass_start[0]) / png_pass_inc[0];
  202246. }
  202247. else
  202248. {
  202249. png_ptr->num_rows = png_ptr->height;
  202250. png_ptr->usr_width = png_ptr->width;
  202251. }
  202252. }
  202253. else
  202254. #endif
  202255. {
  202256. png_ptr->num_rows = png_ptr->height;
  202257. png_ptr->usr_width = png_ptr->width;
  202258. }
  202259. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202260. png_ptr->zstream.next_out = png_ptr->zbuf;
  202261. }
  202262. /* Internal use only. Called when finished processing a row of data. */
  202263. void /* PRIVATE */
  202264. png_write_finish_row(png_structp png_ptr)
  202265. {
  202266. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202267. #ifdef PNG_USE_LOCAL_ARRAYS
  202268. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202269. /* start of interlace block */
  202270. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202271. /* offset to next interlace block */
  202272. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202273. /* start of interlace block in the y direction */
  202274. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202275. /* offset to next interlace block in the y direction */
  202276. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202277. #endif
  202278. #endif
  202279. int ret;
  202280. png_debug(1, "in png_write_finish_row\n");
  202281. /* next row */
  202282. png_ptr->row_number++;
  202283. /* see if we are done */
  202284. if (png_ptr->row_number < png_ptr->num_rows)
  202285. return;
  202286. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202287. /* if interlaced, go to next pass */
  202288. if (png_ptr->interlaced)
  202289. {
  202290. png_ptr->row_number = 0;
  202291. if (png_ptr->transformations & PNG_INTERLACE)
  202292. {
  202293. png_ptr->pass++;
  202294. }
  202295. else
  202296. {
  202297. /* loop until we find a non-zero width or height pass */
  202298. do
  202299. {
  202300. png_ptr->pass++;
  202301. if (png_ptr->pass >= 7)
  202302. break;
  202303. png_ptr->usr_width = (png_ptr->width +
  202304. png_pass_inc[png_ptr->pass] - 1 -
  202305. png_pass_start[png_ptr->pass]) /
  202306. png_pass_inc[png_ptr->pass];
  202307. png_ptr->num_rows = (png_ptr->height +
  202308. png_pass_yinc[png_ptr->pass] - 1 -
  202309. png_pass_ystart[png_ptr->pass]) /
  202310. png_pass_yinc[png_ptr->pass];
  202311. if (png_ptr->transformations & PNG_INTERLACE)
  202312. break;
  202313. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202314. }
  202315. /* reset the row above the image for the next pass */
  202316. if (png_ptr->pass < 7)
  202317. {
  202318. if (png_ptr->prev_row != NULL)
  202319. png_memset(png_ptr->prev_row, 0,
  202320. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202321. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202322. return;
  202323. }
  202324. }
  202325. #endif
  202326. /* if we get here, we've just written the last row, so we need
  202327. to flush the compressor */
  202328. do
  202329. {
  202330. /* tell the compressor we are done */
  202331. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202332. /* check for an error */
  202333. if (ret == Z_OK)
  202334. {
  202335. /* check to see if we need more room */
  202336. if (!(png_ptr->zstream.avail_out))
  202337. {
  202338. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202339. png_ptr->zstream.next_out = png_ptr->zbuf;
  202340. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202341. }
  202342. }
  202343. else if (ret != Z_STREAM_END)
  202344. {
  202345. if (png_ptr->zstream.msg != NULL)
  202346. png_error(png_ptr, png_ptr->zstream.msg);
  202347. else
  202348. png_error(png_ptr, "zlib error");
  202349. }
  202350. } while (ret != Z_STREAM_END);
  202351. /* write any extra space */
  202352. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202353. {
  202354. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202355. png_ptr->zstream.avail_out);
  202356. }
  202357. deflateReset(&png_ptr->zstream);
  202358. png_ptr->zstream.data_type = Z_BINARY;
  202359. }
  202360. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202361. /* Pick out the correct pixels for the interlace pass.
  202362. * The basic idea here is to go through the row with a source
  202363. * pointer and a destination pointer (sp and dp), and copy the
  202364. * correct pixels for the pass. As the row gets compacted,
  202365. * sp will always be >= dp, so we should never overwrite anything.
  202366. * See the default: case for the easiest code to understand.
  202367. */
  202368. void /* PRIVATE */
  202369. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202370. {
  202371. #ifdef PNG_USE_LOCAL_ARRAYS
  202372. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202373. /* start of interlace block */
  202374. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202375. /* offset to next interlace block */
  202376. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202377. #endif
  202378. png_debug(1, "in png_do_write_interlace\n");
  202379. /* we don't have to do anything on the last pass (6) */
  202380. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202381. if (row != NULL && row_info != NULL && pass < 6)
  202382. #else
  202383. if (pass < 6)
  202384. #endif
  202385. {
  202386. /* each pixel depth is handled separately */
  202387. switch (row_info->pixel_depth)
  202388. {
  202389. case 1:
  202390. {
  202391. png_bytep sp;
  202392. png_bytep dp;
  202393. int shift;
  202394. int d;
  202395. int value;
  202396. png_uint_32 i;
  202397. png_uint_32 row_width = row_info->width;
  202398. dp = row;
  202399. d = 0;
  202400. shift = 7;
  202401. for (i = png_pass_start[pass]; i < row_width;
  202402. i += png_pass_inc[pass])
  202403. {
  202404. sp = row + (png_size_t)(i >> 3);
  202405. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202406. d |= (value << shift);
  202407. if (shift == 0)
  202408. {
  202409. shift = 7;
  202410. *dp++ = (png_byte)d;
  202411. d = 0;
  202412. }
  202413. else
  202414. shift--;
  202415. }
  202416. if (shift != 7)
  202417. *dp = (png_byte)d;
  202418. break;
  202419. }
  202420. case 2:
  202421. {
  202422. png_bytep sp;
  202423. png_bytep dp;
  202424. int shift;
  202425. int d;
  202426. int value;
  202427. png_uint_32 i;
  202428. png_uint_32 row_width = row_info->width;
  202429. dp = row;
  202430. shift = 6;
  202431. d = 0;
  202432. for (i = png_pass_start[pass]; i < row_width;
  202433. i += png_pass_inc[pass])
  202434. {
  202435. sp = row + (png_size_t)(i >> 2);
  202436. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202437. d |= (value << shift);
  202438. if (shift == 0)
  202439. {
  202440. shift = 6;
  202441. *dp++ = (png_byte)d;
  202442. d = 0;
  202443. }
  202444. else
  202445. shift -= 2;
  202446. }
  202447. if (shift != 6)
  202448. *dp = (png_byte)d;
  202449. break;
  202450. }
  202451. case 4:
  202452. {
  202453. png_bytep sp;
  202454. png_bytep dp;
  202455. int shift;
  202456. int d;
  202457. int value;
  202458. png_uint_32 i;
  202459. png_uint_32 row_width = row_info->width;
  202460. dp = row;
  202461. shift = 4;
  202462. d = 0;
  202463. for (i = png_pass_start[pass]; i < row_width;
  202464. i += png_pass_inc[pass])
  202465. {
  202466. sp = row + (png_size_t)(i >> 1);
  202467. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202468. d |= (value << shift);
  202469. if (shift == 0)
  202470. {
  202471. shift = 4;
  202472. *dp++ = (png_byte)d;
  202473. d = 0;
  202474. }
  202475. else
  202476. shift -= 4;
  202477. }
  202478. if (shift != 4)
  202479. *dp = (png_byte)d;
  202480. break;
  202481. }
  202482. default:
  202483. {
  202484. png_bytep sp;
  202485. png_bytep dp;
  202486. png_uint_32 i;
  202487. png_uint_32 row_width = row_info->width;
  202488. png_size_t pixel_bytes;
  202489. /* start at the beginning */
  202490. dp = row;
  202491. /* find out how many bytes each pixel takes up */
  202492. pixel_bytes = (row_info->pixel_depth >> 3);
  202493. /* loop through the row, only looking at the pixels that
  202494. matter */
  202495. for (i = png_pass_start[pass]; i < row_width;
  202496. i += png_pass_inc[pass])
  202497. {
  202498. /* find out where the original pixel is */
  202499. sp = row + (png_size_t)i * pixel_bytes;
  202500. /* move the pixel */
  202501. if (dp != sp)
  202502. png_memcpy(dp, sp, pixel_bytes);
  202503. /* next pixel */
  202504. dp += pixel_bytes;
  202505. }
  202506. break;
  202507. }
  202508. }
  202509. /* set new row width */
  202510. row_info->width = (row_info->width +
  202511. png_pass_inc[pass] - 1 -
  202512. png_pass_start[pass]) /
  202513. png_pass_inc[pass];
  202514. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202515. row_info->width);
  202516. }
  202517. }
  202518. #endif
  202519. /* This filters the row, chooses which filter to use, if it has not already
  202520. * been specified by the application, and then writes the row out with the
  202521. * chosen filter.
  202522. */
  202523. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202524. #define PNG_HISHIFT 10
  202525. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202526. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202527. void /* PRIVATE */
  202528. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202529. {
  202530. png_bytep best_row;
  202531. #ifndef PNG_NO_WRITE_FILTER
  202532. png_bytep prev_row, row_buf;
  202533. png_uint_32 mins, bpp;
  202534. png_byte filter_to_do = png_ptr->do_filter;
  202535. png_uint_32 row_bytes = row_info->rowbytes;
  202536. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202537. int num_p_filters = (int)png_ptr->num_prev_filters;
  202538. #endif
  202539. png_debug(1, "in png_write_find_filter\n");
  202540. /* find out how many bytes offset each pixel is */
  202541. bpp = (row_info->pixel_depth + 7) >> 3;
  202542. prev_row = png_ptr->prev_row;
  202543. #endif
  202544. best_row = png_ptr->row_buf;
  202545. #ifndef PNG_NO_WRITE_FILTER
  202546. row_buf = best_row;
  202547. mins = PNG_MAXSUM;
  202548. /* The prediction method we use is to find which method provides the
  202549. * smallest value when summing the absolute values of the distances
  202550. * from zero, using anything >= 128 as negative numbers. This is known
  202551. * as the "minimum sum of absolute differences" heuristic. Other
  202552. * heuristics are the "weighted minimum sum of absolute differences"
  202553. * (experimental and can in theory improve compression), and the "zlib
  202554. * predictive" method (not implemented yet), which does test compressions
  202555. * of lines using different filter methods, and then chooses the
  202556. * (series of) filter(s) that give minimum compressed data size (VERY
  202557. * computationally expensive).
  202558. *
  202559. * GRR 980525: consider also
  202560. * (1) minimum sum of absolute differences from running average (i.e.,
  202561. * keep running sum of non-absolute differences & count of bytes)
  202562. * [track dispersion, too? restart average if dispersion too large?]
  202563. * (1b) minimum sum of absolute differences from sliding average, probably
  202564. * with window size <= deflate window (usually 32K)
  202565. * (2) minimum sum of squared differences from zero or running average
  202566. * (i.e., ~ root-mean-square approach)
  202567. */
  202568. /* We don't need to test the 'no filter' case if this is the only filter
  202569. * that has been chosen, as it doesn't actually do anything to the data.
  202570. */
  202571. if ((filter_to_do & PNG_FILTER_NONE) &&
  202572. filter_to_do != PNG_FILTER_NONE)
  202573. {
  202574. png_bytep rp;
  202575. png_uint_32 sum = 0;
  202576. png_uint_32 i;
  202577. int v;
  202578. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202579. {
  202580. v = *rp;
  202581. sum += (v < 128) ? v : 256 - v;
  202582. }
  202583. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202584. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202585. {
  202586. png_uint_32 sumhi, sumlo;
  202587. int j;
  202588. sumlo = sum & PNG_LOMASK;
  202589. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202590. /* Reduce the sum if we match any of the previous rows */
  202591. for (j = 0; j < num_p_filters; j++)
  202592. {
  202593. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202594. {
  202595. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202596. PNG_WEIGHT_SHIFT;
  202597. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202598. PNG_WEIGHT_SHIFT;
  202599. }
  202600. }
  202601. /* Factor in the cost of this filter (this is here for completeness,
  202602. * but it makes no sense to have a "cost" for the NONE filter, as
  202603. * it has the minimum possible computational cost - none).
  202604. */
  202605. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202606. PNG_COST_SHIFT;
  202607. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202608. PNG_COST_SHIFT;
  202609. if (sumhi > PNG_HIMASK)
  202610. sum = PNG_MAXSUM;
  202611. else
  202612. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202613. }
  202614. #endif
  202615. mins = sum;
  202616. }
  202617. /* sub filter */
  202618. if (filter_to_do == PNG_FILTER_SUB)
  202619. /* it's the only filter so no testing is needed */
  202620. {
  202621. png_bytep rp, lp, dp;
  202622. png_uint_32 i;
  202623. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202624. i++, rp++, dp++)
  202625. {
  202626. *dp = *rp;
  202627. }
  202628. for (lp = row_buf + 1; i < row_bytes;
  202629. i++, rp++, lp++, dp++)
  202630. {
  202631. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202632. }
  202633. best_row = png_ptr->sub_row;
  202634. }
  202635. else if (filter_to_do & PNG_FILTER_SUB)
  202636. {
  202637. png_bytep rp, dp, lp;
  202638. png_uint_32 sum = 0, lmins = mins;
  202639. png_uint_32 i;
  202640. int v;
  202641. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202642. /* We temporarily increase the "minimum sum" by the factor we
  202643. * would reduce the sum of this filter, so that we can do the
  202644. * early exit comparison without scaling the sum each time.
  202645. */
  202646. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202647. {
  202648. int j;
  202649. png_uint_32 lmhi, lmlo;
  202650. lmlo = lmins & PNG_LOMASK;
  202651. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202652. for (j = 0; j < num_p_filters; j++)
  202653. {
  202654. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202655. {
  202656. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202657. PNG_WEIGHT_SHIFT;
  202658. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202659. PNG_WEIGHT_SHIFT;
  202660. }
  202661. }
  202662. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202663. PNG_COST_SHIFT;
  202664. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202665. PNG_COST_SHIFT;
  202666. if (lmhi > PNG_HIMASK)
  202667. lmins = PNG_MAXSUM;
  202668. else
  202669. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202670. }
  202671. #endif
  202672. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202673. i++, rp++, dp++)
  202674. {
  202675. v = *dp = *rp;
  202676. sum += (v < 128) ? v : 256 - v;
  202677. }
  202678. for (lp = row_buf + 1; i < row_bytes;
  202679. i++, rp++, lp++, dp++)
  202680. {
  202681. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202682. sum += (v < 128) ? v : 256 - v;
  202683. if (sum > lmins) /* We are already worse, don't continue. */
  202684. break;
  202685. }
  202686. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202687. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202688. {
  202689. int j;
  202690. png_uint_32 sumhi, sumlo;
  202691. sumlo = sum & PNG_LOMASK;
  202692. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202693. for (j = 0; j < num_p_filters; j++)
  202694. {
  202695. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202696. {
  202697. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202698. PNG_WEIGHT_SHIFT;
  202699. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202700. PNG_WEIGHT_SHIFT;
  202701. }
  202702. }
  202703. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202704. PNG_COST_SHIFT;
  202705. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202706. PNG_COST_SHIFT;
  202707. if (sumhi > PNG_HIMASK)
  202708. sum = PNG_MAXSUM;
  202709. else
  202710. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202711. }
  202712. #endif
  202713. if (sum < mins)
  202714. {
  202715. mins = sum;
  202716. best_row = png_ptr->sub_row;
  202717. }
  202718. }
  202719. /* up filter */
  202720. if (filter_to_do == PNG_FILTER_UP)
  202721. {
  202722. png_bytep rp, dp, pp;
  202723. png_uint_32 i;
  202724. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202725. pp = prev_row + 1; i < row_bytes;
  202726. i++, rp++, pp++, dp++)
  202727. {
  202728. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202729. }
  202730. best_row = png_ptr->up_row;
  202731. }
  202732. else if (filter_to_do & PNG_FILTER_UP)
  202733. {
  202734. png_bytep rp, dp, pp;
  202735. png_uint_32 sum = 0, lmins = mins;
  202736. png_uint_32 i;
  202737. int v;
  202738. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202739. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202740. {
  202741. int j;
  202742. png_uint_32 lmhi, lmlo;
  202743. lmlo = lmins & PNG_LOMASK;
  202744. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202745. for (j = 0; j < num_p_filters; j++)
  202746. {
  202747. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202748. {
  202749. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202750. PNG_WEIGHT_SHIFT;
  202751. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202752. PNG_WEIGHT_SHIFT;
  202753. }
  202754. }
  202755. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202756. PNG_COST_SHIFT;
  202757. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202758. PNG_COST_SHIFT;
  202759. if (lmhi > PNG_HIMASK)
  202760. lmins = PNG_MAXSUM;
  202761. else
  202762. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202763. }
  202764. #endif
  202765. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202766. pp = prev_row + 1; i < row_bytes; i++)
  202767. {
  202768. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202769. sum += (v < 128) ? v : 256 - v;
  202770. if (sum > lmins) /* We are already worse, don't continue. */
  202771. break;
  202772. }
  202773. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202774. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202775. {
  202776. int j;
  202777. png_uint_32 sumhi, sumlo;
  202778. sumlo = sum & PNG_LOMASK;
  202779. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202780. for (j = 0; j < num_p_filters; j++)
  202781. {
  202782. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202783. {
  202784. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202785. PNG_WEIGHT_SHIFT;
  202786. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202787. PNG_WEIGHT_SHIFT;
  202788. }
  202789. }
  202790. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202791. PNG_COST_SHIFT;
  202792. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202793. PNG_COST_SHIFT;
  202794. if (sumhi > PNG_HIMASK)
  202795. sum = PNG_MAXSUM;
  202796. else
  202797. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202798. }
  202799. #endif
  202800. if (sum < mins)
  202801. {
  202802. mins = sum;
  202803. best_row = png_ptr->up_row;
  202804. }
  202805. }
  202806. /* avg filter */
  202807. if (filter_to_do == PNG_FILTER_AVG)
  202808. {
  202809. png_bytep rp, dp, pp, lp;
  202810. png_uint_32 i;
  202811. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202812. pp = prev_row + 1; i < bpp; i++)
  202813. {
  202814. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202815. }
  202816. for (lp = row_buf + 1; i < row_bytes; i++)
  202817. {
  202818. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202819. & 0xff);
  202820. }
  202821. best_row = png_ptr->avg_row;
  202822. }
  202823. else if (filter_to_do & PNG_FILTER_AVG)
  202824. {
  202825. png_bytep rp, dp, pp, lp;
  202826. png_uint_32 sum = 0, lmins = mins;
  202827. png_uint_32 i;
  202828. int v;
  202829. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202830. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202831. {
  202832. int j;
  202833. png_uint_32 lmhi, lmlo;
  202834. lmlo = lmins & PNG_LOMASK;
  202835. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202836. for (j = 0; j < num_p_filters; j++)
  202837. {
  202838. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202839. {
  202840. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202841. PNG_WEIGHT_SHIFT;
  202842. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202843. PNG_WEIGHT_SHIFT;
  202844. }
  202845. }
  202846. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202847. PNG_COST_SHIFT;
  202848. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202849. PNG_COST_SHIFT;
  202850. if (lmhi > PNG_HIMASK)
  202851. lmins = PNG_MAXSUM;
  202852. else
  202853. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202854. }
  202855. #endif
  202856. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202857. pp = prev_row + 1; i < bpp; i++)
  202858. {
  202859. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202860. sum += (v < 128) ? v : 256 - v;
  202861. }
  202862. for (lp = row_buf + 1; i < row_bytes; i++)
  202863. {
  202864. v = *dp++ =
  202865. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202866. sum += (v < 128) ? v : 256 - v;
  202867. if (sum > lmins) /* We are already worse, don't continue. */
  202868. break;
  202869. }
  202870. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202871. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202872. {
  202873. int j;
  202874. png_uint_32 sumhi, sumlo;
  202875. sumlo = sum & PNG_LOMASK;
  202876. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202877. for (j = 0; j < num_p_filters; j++)
  202878. {
  202879. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202880. {
  202881. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202882. PNG_WEIGHT_SHIFT;
  202883. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202884. PNG_WEIGHT_SHIFT;
  202885. }
  202886. }
  202887. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202888. PNG_COST_SHIFT;
  202889. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202890. PNG_COST_SHIFT;
  202891. if (sumhi > PNG_HIMASK)
  202892. sum = PNG_MAXSUM;
  202893. else
  202894. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202895. }
  202896. #endif
  202897. if (sum < mins)
  202898. {
  202899. mins = sum;
  202900. best_row = png_ptr->avg_row;
  202901. }
  202902. }
  202903. /* Paeth filter */
  202904. if (filter_to_do == PNG_FILTER_PAETH)
  202905. {
  202906. png_bytep rp, dp, pp, cp, lp;
  202907. png_uint_32 i;
  202908. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202909. pp = prev_row + 1; i < bpp; i++)
  202910. {
  202911. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202912. }
  202913. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202914. {
  202915. int a, b, c, pa, pb, pc, p;
  202916. b = *pp++;
  202917. c = *cp++;
  202918. a = *lp++;
  202919. p = b - c;
  202920. pc = a - c;
  202921. #ifdef PNG_USE_ABS
  202922. pa = abs(p);
  202923. pb = abs(pc);
  202924. pc = abs(p + pc);
  202925. #else
  202926. pa = p < 0 ? -p : p;
  202927. pb = pc < 0 ? -pc : pc;
  202928. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202929. #endif
  202930. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202931. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202932. }
  202933. best_row = png_ptr->paeth_row;
  202934. }
  202935. else if (filter_to_do & PNG_FILTER_PAETH)
  202936. {
  202937. png_bytep rp, dp, pp, cp, lp;
  202938. png_uint_32 sum = 0, lmins = mins;
  202939. png_uint_32 i;
  202940. int v;
  202941. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202942. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202943. {
  202944. int j;
  202945. png_uint_32 lmhi, lmlo;
  202946. lmlo = lmins & PNG_LOMASK;
  202947. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202948. for (j = 0; j < num_p_filters; j++)
  202949. {
  202950. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202951. {
  202952. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202953. PNG_WEIGHT_SHIFT;
  202954. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202955. PNG_WEIGHT_SHIFT;
  202956. }
  202957. }
  202958. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202959. PNG_COST_SHIFT;
  202960. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202961. PNG_COST_SHIFT;
  202962. if (lmhi > PNG_HIMASK)
  202963. lmins = PNG_MAXSUM;
  202964. else
  202965. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202966. }
  202967. #endif
  202968. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202969. pp = prev_row + 1; i < bpp; i++)
  202970. {
  202971. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202972. sum += (v < 128) ? v : 256 - v;
  202973. }
  202974. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202975. {
  202976. int a, b, c, pa, pb, pc, p;
  202977. b = *pp++;
  202978. c = *cp++;
  202979. a = *lp++;
  202980. #ifndef PNG_SLOW_PAETH
  202981. p = b - c;
  202982. pc = a - c;
  202983. #ifdef PNG_USE_ABS
  202984. pa = abs(p);
  202985. pb = abs(pc);
  202986. pc = abs(p + pc);
  202987. #else
  202988. pa = p < 0 ? -p : p;
  202989. pb = pc < 0 ? -pc : pc;
  202990. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202991. #endif
  202992. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202993. #else /* PNG_SLOW_PAETH */
  202994. p = a + b - c;
  202995. pa = abs(p - a);
  202996. pb = abs(p - b);
  202997. pc = abs(p - c);
  202998. if (pa <= pb && pa <= pc)
  202999. p = a;
  203000. else if (pb <= pc)
  203001. p = b;
  203002. else
  203003. p = c;
  203004. #endif /* PNG_SLOW_PAETH */
  203005. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203006. sum += (v < 128) ? v : 256 - v;
  203007. if (sum > lmins) /* We are already worse, don't continue. */
  203008. break;
  203009. }
  203010. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203011. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203012. {
  203013. int j;
  203014. png_uint_32 sumhi, sumlo;
  203015. sumlo = sum & PNG_LOMASK;
  203016. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203017. for (j = 0; j < num_p_filters; j++)
  203018. {
  203019. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203020. {
  203021. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203022. PNG_WEIGHT_SHIFT;
  203023. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203024. PNG_WEIGHT_SHIFT;
  203025. }
  203026. }
  203027. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203028. PNG_COST_SHIFT;
  203029. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203030. PNG_COST_SHIFT;
  203031. if (sumhi > PNG_HIMASK)
  203032. sum = PNG_MAXSUM;
  203033. else
  203034. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203035. }
  203036. #endif
  203037. if (sum < mins)
  203038. {
  203039. best_row = png_ptr->paeth_row;
  203040. }
  203041. }
  203042. #endif /* PNG_NO_WRITE_FILTER */
  203043. /* Do the actual writing of the filtered row data from the chosen filter. */
  203044. png_write_filtered_row(png_ptr, best_row);
  203045. #ifndef PNG_NO_WRITE_FILTER
  203046. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203047. /* Save the type of filter we picked this time for future calculations */
  203048. if (png_ptr->num_prev_filters > 0)
  203049. {
  203050. int j;
  203051. for (j = 1; j < num_p_filters; j++)
  203052. {
  203053. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  203054. }
  203055. png_ptr->prev_filters[j] = best_row[0];
  203056. }
  203057. #endif
  203058. #endif /* PNG_NO_WRITE_FILTER */
  203059. }
  203060. /* Do the actual writing of a previously filtered row. */
  203061. void /* PRIVATE */
  203062. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  203063. {
  203064. png_debug(1, "in png_write_filtered_row\n");
  203065. png_debug1(2, "filter = %d\n", filtered_row[0]);
  203066. /* set up the zlib input buffer */
  203067. png_ptr->zstream.next_in = filtered_row;
  203068. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203069. /* repeat until we have compressed all the data */
  203070. do
  203071. {
  203072. int ret; /* return of zlib */
  203073. /* compress the data */
  203074. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203075. /* check for compression errors */
  203076. if (ret != Z_OK)
  203077. {
  203078. if (png_ptr->zstream.msg != NULL)
  203079. png_error(png_ptr, png_ptr->zstream.msg);
  203080. else
  203081. png_error(png_ptr, "zlib error");
  203082. }
  203083. /* see if it is time to write another IDAT */
  203084. if (!(png_ptr->zstream.avail_out))
  203085. {
  203086. /* write the IDAT and reset the zlib output buffer */
  203087. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203088. png_ptr->zstream.next_out = png_ptr->zbuf;
  203089. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203090. }
  203091. /* repeat until all data has been compressed */
  203092. } while (png_ptr->zstream.avail_in);
  203093. /* swap the current and previous rows */
  203094. if (png_ptr->prev_row != NULL)
  203095. {
  203096. png_bytep tptr;
  203097. tptr = png_ptr->prev_row;
  203098. png_ptr->prev_row = png_ptr->row_buf;
  203099. png_ptr->row_buf = tptr;
  203100. }
  203101. /* finish row - updates counters and flushes zlib if last row */
  203102. png_write_finish_row(png_ptr);
  203103. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203104. png_ptr->flush_rows++;
  203105. if (png_ptr->flush_dist > 0 &&
  203106. png_ptr->flush_rows >= png_ptr->flush_dist)
  203107. {
  203108. png_write_flush(png_ptr);
  203109. }
  203110. #endif
  203111. }
  203112. #endif /* PNG_WRITE_SUPPORTED */
  203113. /*** End of inlined file: pngwutil.c ***/
  203114. #else
  203115. extern "C"
  203116. {
  203117. #include <png.h>
  203118. #include <pngconf.h>
  203119. }
  203120. #endif
  203121. }
  203122. #undef max
  203123. #undef min
  203124. #if JUCE_MSVC
  203125. #pragma warning (pop)
  203126. #endif
  203127. BEGIN_JUCE_NAMESPACE
  203128. using ::calloc;
  203129. using ::malloc;
  203130. using ::free;
  203131. namespace PNGHelpers
  203132. {
  203133. using namespace pnglibNamespace;
  203134. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  203135. {
  203136. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203137. }
  203138. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203139. {
  203140. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203141. }
  203142. struct PNGErrorStruct {};
  203143. static void errorCallback (png_structp, png_const_charp)
  203144. {
  203145. throw PNGErrorStruct();
  203146. }
  203147. }
  203148. PNGImageFormat::PNGImageFormat() {}
  203149. PNGImageFormat::~PNGImageFormat() {}
  203150. const String PNGImageFormat::getFormatName()
  203151. {
  203152. return "PNG";
  203153. }
  203154. bool PNGImageFormat::canUnderstand (InputStream& in)
  203155. {
  203156. const int bytesNeeded = 4;
  203157. char header [bytesNeeded];
  203158. return in.read (header, bytesNeeded) == bytesNeeded
  203159. && header[1] == 'P'
  203160. && header[2] == 'N'
  203161. && header[3] == 'G';
  203162. }
  203163. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203164. const Image juce_loadWithCoreImage (InputStream& input);
  203165. #endif
  203166. const Image PNGImageFormat::decodeImage (InputStream& in)
  203167. {
  203168. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203169. return juce_loadWithCoreImage (in);
  203170. #else
  203171. using namespace pnglibNamespace;
  203172. Image image;
  203173. png_structp pngReadStruct;
  203174. png_infop pngInfoStruct;
  203175. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203176. if (pngReadStruct != 0)
  203177. {
  203178. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203179. if (pngInfoStruct == 0)
  203180. {
  203181. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203182. return Image::null;
  203183. }
  203184. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203185. // read the header..
  203186. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203187. png_uint_32 width, height;
  203188. int bitDepth, colorType, interlaceType;
  203189. png_read_info (pngReadStruct, pngInfoStruct);
  203190. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203191. &width, &height,
  203192. &bitDepth, &colorType,
  203193. &interlaceType, 0, 0);
  203194. if (bitDepth == 16)
  203195. png_set_strip_16 (pngReadStruct);
  203196. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203197. png_set_expand (pngReadStruct);
  203198. if (bitDepth < 8)
  203199. png_set_expand (pngReadStruct);
  203200. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203201. png_set_expand (pngReadStruct);
  203202. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203203. png_set_gray_to_rgb (pngReadStruct);
  203204. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203205. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203206. || pngInfoStruct->num_trans > 0;
  203207. // Load the image into a temp buffer in the pnglib format..
  203208. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203209. {
  203210. HeapBlock <png_bytep> rows (height);
  203211. for (int y = (int) height; --y >= 0;)
  203212. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203213. png_read_image (pngReadStruct, rows);
  203214. png_read_end (pngReadStruct, pngInfoStruct);
  203215. }
  203216. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203217. // now convert the data to a juce image format..
  203218. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203219. (int) width, (int) height, hasAlphaChan);
  203220. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203221. const Image::BitmapData destData (image, true);
  203222. uint8* srcRow = tempBuffer;
  203223. uint8* destRow = destData.data;
  203224. for (int y = 0; y < (int) height; ++y)
  203225. {
  203226. const uint8* src = srcRow;
  203227. srcRow += (width << 2);
  203228. uint8* dest = destRow;
  203229. destRow += destData.lineStride;
  203230. if (hasAlphaChan)
  203231. {
  203232. for (int i = (int) width; --i >= 0;)
  203233. {
  203234. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203235. ((PixelARGB*) dest)->premultiply();
  203236. dest += destData.pixelStride;
  203237. src += 4;
  203238. }
  203239. }
  203240. else
  203241. {
  203242. for (int i = (int) width; --i >= 0;)
  203243. {
  203244. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203245. dest += destData.pixelStride;
  203246. src += 4;
  203247. }
  203248. }
  203249. }
  203250. }
  203251. return image;
  203252. #endif
  203253. }
  203254. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203255. {
  203256. using namespace pnglibNamespace;
  203257. const int width = image.getWidth();
  203258. const int height = image.getHeight();
  203259. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203260. if (pngWriteStruct == 0)
  203261. return false;
  203262. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203263. if (pngInfoStruct == 0)
  203264. {
  203265. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203266. return false;
  203267. }
  203268. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203269. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203270. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203271. : PNG_COLOR_TYPE_RGB,
  203272. PNG_INTERLACE_NONE,
  203273. PNG_COMPRESSION_TYPE_BASE,
  203274. PNG_FILTER_TYPE_BASE);
  203275. HeapBlock <uint8> rowData (width * 4);
  203276. png_color_8 sig_bit;
  203277. sig_bit.red = 8;
  203278. sig_bit.green = 8;
  203279. sig_bit.blue = 8;
  203280. sig_bit.alpha = 8;
  203281. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203282. png_write_info (pngWriteStruct, pngInfoStruct);
  203283. png_set_shift (pngWriteStruct, &sig_bit);
  203284. png_set_packing (pngWriteStruct);
  203285. const Image::BitmapData srcData (image, false);
  203286. for (int y = 0; y < height; ++y)
  203287. {
  203288. uint8* dst = rowData;
  203289. const uint8* src = srcData.getLinePointer (y);
  203290. if (image.hasAlphaChannel())
  203291. {
  203292. for (int i = width; --i >= 0;)
  203293. {
  203294. PixelARGB p (*(const PixelARGB*) src);
  203295. p.unpremultiply();
  203296. *dst++ = p.getRed();
  203297. *dst++ = p.getGreen();
  203298. *dst++ = p.getBlue();
  203299. *dst++ = p.getAlpha();
  203300. src += srcData.pixelStride;
  203301. }
  203302. }
  203303. else
  203304. {
  203305. for (int i = width; --i >= 0;)
  203306. {
  203307. *dst++ = ((const PixelRGB*) src)->getRed();
  203308. *dst++ = ((const PixelRGB*) src)->getGreen();
  203309. *dst++ = ((const PixelRGB*) src)->getBlue();
  203310. src += srcData.pixelStride;
  203311. }
  203312. }
  203313. png_bytep rowPtr = rowData;
  203314. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203315. }
  203316. png_write_end (pngWriteStruct, pngInfoStruct);
  203317. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203318. out.flush();
  203319. return true;
  203320. }
  203321. END_JUCE_NAMESPACE
  203322. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203323. #endif
  203324. //==============================================================================
  203325. #if JUCE_BUILD_NATIVE
  203326. #if JUCE_WINDOWS
  203327. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203328. /*
  203329. This file wraps together all the win32-specific code, so that
  203330. we can include all the native headers just once, and compile all our
  203331. platform-specific stuff in one big lump, keeping it out of the way of
  203332. the rest of the codebase.
  203333. */
  203334. #if JUCE_WINDOWS
  203335. BEGIN_JUCE_NAMESPACE
  203336. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203337. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203338. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203339. /**
  203340. Helper class that takes chunks of incoming midi bytes, packages them into
  203341. messages, and dispatches them to a midi callback.
  203342. */
  203343. class MidiDataConcatenator
  203344. {
  203345. public:
  203346. MidiDataConcatenator (const int initialBufferSize)
  203347. : pendingData (initialBufferSize),
  203348. pendingBytes (0), pendingDataTime (0)
  203349. {
  203350. }
  203351. void reset()
  203352. {
  203353. pendingBytes = 0;
  203354. pendingDataTime = 0;
  203355. }
  203356. void pushMidiData (const void* data, int numBytes, double time,
  203357. MidiInput* input, MidiInputCallback& callback)
  203358. {
  203359. const uint8* d = static_cast <const uint8*> (data);
  203360. while (numBytes > 0)
  203361. {
  203362. if (pendingBytes > 0 || d[0] == 0xf0)
  203363. {
  203364. processSysex (d, numBytes, time, input, callback);
  203365. }
  203366. else
  203367. {
  203368. int used = 0;
  203369. const MidiMessage m (d, numBytes, used, 0, time);
  203370. if (used <= 0)
  203371. break; // malformed message..
  203372. callback.handleIncomingMidiMessage (input, m);
  203373. numBytes -= used;
  203374. d += used;
  203375. }
  203376. }
  203377. }
  203378. private:
  203379. void processSysex (const uint8*& d, int& numBytes, double time,
  203380. MidiInput* input, MidiInputCallback& callback)
  203381. {
  203382. if (*d == 0xf0)
  203383. {
  203384. pendingBytes = 0;
  203385. pendingDataTime = time;
  203386. }
  203387. pendingData.ensureSize (pendingBytes + numBytes, false);
  203388. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203389. uint8* dest = totalMessage + pendingBytes;
  203390. do
  203391. {
  203392. if (pendingBytes > 0 && *d >= 0x80)
  203393. {
  203394. if (*d >= 0xfa || *d == 0xf8)
  203395. {
  203396. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203397. ++d;
  203398. --numBytes;
  203399. }
  203400. else
  203401. {
  203402. if (*d == 0xf7)
  203403. {
  203404. *dest++ = *d++;
  203405. pendingBytes++;
  203406. --numBytes;
  203407. }
  203408. break;
  203409. }
  203410. }
  203411. else
  203412. {
  203413. *dest++ = *d++;
  203414. pendingBytes++;
  203415. --numBytes;
  203416. }
  203417. }
  203418. while (numBytes > 0);
  203419. if (pendingBytes > 0)
  203420. {
  203421. if (totalMessage [pendingBytes - 1] == 0xf7)
  203422. {
  203423. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203424. pendingBytes = 0;
  203425. }
  203426. else
  203427. {
  203428. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203429. }
  203430. }
  203431. }
  203432. MemoryBlock pendingData;
  203433. int pendingBytes;
  203434. double pendingDataTime;
  203435. MidiDataConcatenator (const MidiDataConcatenator&);
  203436. MidiDataConcatenator& operator= (const MidiDataConcatenator&);
  203437. };
  203438. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203439. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203440. #define JUCE_INCLUDED_FILE 1
  203441. // Now include the actual code files..
  203442. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203443. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203444. // compiled on its own).
  203445. #if JUCE_INCLUDED_FILE
  203446. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203447. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203448. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203449. #ifndef DOXYGEN
  203450. // use with DynamicLibraryLoader to simplify importing functions
  203451. //
  203452. // functionName: function to import
  203453. // localFunctionName: name you want to use to actually call it (must be different)
  203454. // returnType: the return type
  203455. // object: the DynamicLibraryLoader to use
  203456. // params: list of params (bracketed)
  203457. //
  203458. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203459. typedef returnType (WINAPI *type##localFunctionName) params; \
  203460. type##localFunctionName localFunctionName \
  203461. = (type##localFunctionName)object.findProcAddress (#functionName);
  203462. // loads and unloads a DLL automatically
  203463. class JUCE_API DynamicLibraryLoader
  203464. {
  203465. public:
  203466. DynamicLibraryLoader (const String& name);
  203467. ~DynamicLibraryLoader();
  203468. void* findProcAddress (const String& functionName);
  203469. private:
  203470. void* libHandle;
  203471. };
  203472. #endif
  203473. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203474. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203475. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203476. {
  203477. libHandle = LoadLibrary (name);
  203478. }
  203479. DynamicLibraryLoader::~DynamicLibraryLoader()
  203480. {
  203481. FreeLibrary ((HMODULE) libHandle);
  203482. }
  203483. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203484. {
  203485. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toCString()); // (void* cast is required for mingw)
  203486. }
  203487. #endif
  203488. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203489. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203490. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203491. // compiled on its own).
  203492. #if JUCE_INCLUDED_FILE
  203493. extern void juce_initialiseThreadEvents();
  203494. void Logger::outputDebugString (const String& text)
  203495. {
  203496. OutputDebugString (text + "\n");
  203497. }
  203498. static int64 hiResTicksPerSecond;
  203499. static double hiResTicksScaleFactor;
  203500. #if JUCE_USE_INTRINSICS
  203501. // CPU info functions using intrinsics...
  203502. #pragma intrinsic (__cpuid)
  203503. #pragma intrinsic (__rdtsc)
  203504. const String SystemStats::getCpuVendor()
  203505. {
  203506. int info [4];
  203507. __cpuid (info, 0);
  203508. char v [12];
  203509. memcpy (v, info + 1, 4);
  203510. memcpy (v + 4, info + 3, 4);
  203511. memcpy (v + 8, info + 2, 4);
  203512. return String (v, 12);
  203513. }
  203514. #else
  203515. // CPU info functions using old fashioned inline asm...
  203516. static void juce_getCpuVendor (char* const v)
  203517. {
  203518. int vendor[4];
  203519. zeromem (vendor, 16);
  203520. #ifdef JUCE_64BIT
  203521. #else
  203522. #ifndef __MINGW32__
  203523. __try
  203524. #endif
  203525. {
  203526. #if JUCE_GCC
  203527. unsigned int dummy = 0;
  203528. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203529. #else
  203530. __asm
  203531. {
  203532. mov eax, 0
  203533. cpuid
  203534. mov [vendor], ebx
  203535. mov [vendor + 4], edx
  203536. mov [vendor + 8], ecx
  203537. }
  203538. #endif
  203539. }
  203540. #ifndef __MINGW32__
  203541. __except (EXCEPTION_EXECUTE_HANDLER)
  203542. {
  203543. *v = 0;
  203544. }
  203545. #endif
  203546. #endif
  203547. memcpy (v, vendor, 16);
  203548. }
  203549. const String SystemStats::getCpuVendor()
  203550. {
  203551. char v [16];
  203552. juce_getCpuVendor (v);
  203553. return String (v, 16);
  203554. }
  203555. #endif
  203556. void SystemStats::initialiseStats()
  203557. {
  203558. juce_initialiseThreadEvents();
  203559. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203560. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203561. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203562. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203563. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203564. #else
  203565. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203566. #endif
  203567. {
  203568. SYSTEM_INFO systemInfo;
  203569. GetSystemInfo (&systemInfo);
  203570. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203571. }
  203572. LARGE_INTEGER f;
  203573. QueryPerformanceFrequency (&f);
  203574. hiResTicksPerSecond = f.QuadPart;
  203575. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203576. String s (SystemStats::getJUCEVersion());
  203577. const MMRESULT res = timeBeginPeriod (1);
  203578. (void) res;
  203579. jassert (res == TIMERR_NOERROR);
  203580. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203581. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203582. #endif
  203583. }
  203584. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203585. {
  203586. OSVERSIONINFO info;
  203587. info.dwOSVersionInfoSize = sizeof (info);
  203588. GetVersionEx (&info);
  203589. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203590. {
  203591. switch (info.dwMajorVersion)
  203592. {
  203593. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203594. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203595. default: jassertfalse; break; // !! not a supported OS!
  203596. }
  203597. }
  203598. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203599. {
  203600. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203601. return Win98;
  203602. }
  203603. return UnknownOS;
  203604. }
  203605. const String SystemStats::getOperatingSystemName()
  203606. {
  203607. const char* name = "Unknown OS";
  203608. switch (getOperatingSystemType())
  203609. {
  203610. case Windows7: name = "Windows 7"; break;
  203611. case WinVista: name = "Windows Vista"; break;
  203612. case WinXP: name = "Windows XP"; break;
  203613. case Win2000: name = "Windows 2000"; break;
  203614. case Win98: name = "Windows 98"; break;
  203615. default: jassertfalse; break; // !! new type of OS?
  203616. }
  203617. return name;
  203618. }
  203619. bool SystemStats::isOperatingSystem64Bit()
  203620. {
  203621. #ifdef _WIN64
  203622. return true;
  203623. #else
  203624. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203625. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203626. BOOL isWow64 = FALSE;
  203627. return (fnIsWow64Process != 0)
  203628. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203629. && (isWow64 != FALSE);
  203630. #endif
  203631. }
  203632. int SystemStats::getMemorySizeInMegabytes()
  203633. {
  203634. MEMORYSTATUSEX mem;
  203635. mem.dwLength = sizeof (mem);
  203636. GlobalMemoryStatusEx (&mem);
  203637. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203638. }
  203639. uint32 juce_millisecondsSinceStartup() throw()
  203640. {
  203641. return (uint32) timeGetTime();
  203642. }
  203643. int64 Time::getHighResolutionTicks() throw()
  203644. {
  203645. LARGE_INTEGER ticks;
  203646. QueryPerformanceCounter (&ticks);
  203647. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  203648. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203649. // fix for a very obscure PCI hardware bug that can make the counter
  203650. // sometimes jump forwards by a few seconds..
  203651. static int64 hiResTicksOffset = 0;
  203652. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203653. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203654. hiResTicksOffset = newOffset;
  203655. return ticks.QuadPart + hiResTicksOffset;
  203656. }
  203657. double Time::getMillisecondCounterHiRes() throw()
  203658. {
  203659. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203660. }
  203661. int64 Time::getHighResolutionTicksPerSecond() throw()
  203662. {
  203663. return hiResTicksPerSecond;
  203664. }
  203665. static int64 juce_getClockCycleCounter() throw()
  203666. {
  203667. #if JUCE_USE_INTRINSICS
  203668. // MS intrinsics version...
  203669. return __rdtsc();
  203670. #elif JUCE_GCC
  203671. // GNU inline asm version...
  203672. unsigned int hi = 0, lo = 0;
  203673. __asm__ __volatile__ (
  203674. "xor %%eax, %%eax \n\
  203675. xor %%edx, %%edx \n\
  203676. rdtsc \n\
  203677. movl %%eax, %[lo] \n\
  203678. movl %%edx, %[hi]"
  203679. :
  203680. : [hi] "m" (hi),
  203681. [lo] "m" (lo)
  203682. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203683. return (int64) ((((uint64) hi) << 32) | lo);
  203684. #else
  203685. // MSVC inline asm version...
  203686. unsigned int hi = 0, lo = 0;
  203687. __asm
  203688. {
  203689. xor eax, eax
  203690. xor edx, edx
  203691. rdtsc
  203692. mov lo, eax
  203693. mov hi, edx
  203694. }
  203695. return (int64) ((((uint64) hi) << 32) | lo);
  203696. #endif
  203697. }
  203698. int SystemStats::getCpuSpeedInMegaherz()
  203699. {
  203700. const int64 cycles = juce_getClockCycleCounter();
  203701. const uint32 millis = Time::getMillisecondCounter();
  203702. int lastResult = 0;
  203703. for (;;)
  203704. {
  203705. int n = 1000000;
  203706. while (--n > 0) {}
  203707. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203708. const int64 cyclesNow = juce_getClockCycleCounter();
  203709. if (millisElapsed > 80)
  203710. {
  203711. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203712. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203713. return newResult;
  203714. lastResult = newResult;
  203715. }
  203716. }
  203717. }
  203718. bool Time::setSystemTimeToThisTime() const
  203719. {
  203720. SYSTEMTIME st;
  203721. st.wDayOfWeek = 0;
  203722. st.wYear = (WORD) getYear();
  203723. st.wMonth = (WORD) (getMonth() + 1);
  203724. st.wDay = (WORD) getDayOfMonth();
  203725. st.wHour = (WORD) getHours();
  203726. st.wMinute = (WORD) getMinutes();
  203727. st.wSecond = (WORD) getSeconds();
  203728. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203729. // do this twice because of daylight saving conversion problems - the
  203730. // first one sets it up, the second one kicks it in.
  203731. return SetLocalTime (&st) != 0
  203732. && SetLocalTime (&st) != 0;
  203733. }
  203734. int SystemStats::getPageSize()
  203735. {
  203736. SYSTEM_INFO systemInfo;
  203737. GetSystemInfo (&systemInfo);
  203738. return systemInfo.dwPageSize;
  203739. }
  203740. const String SystemStats::getLogonName()
  203741. {
  203742. TCHAR text [256];
  203743. DWORD len = numElementsInArray (text) - 2;
  203744. zerostruct (text);
  203745. GetUserName (text, &len);
  203746. return String (text, len);
  203747. }
  203748. const String SystemStats::getFullUserName()
  203749. {
  203750. return getLogonName();
  203751. }
  203752. #endif
  203753. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203754. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203755. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203756. // compiled on its own).
  203757. #if JUCE_INCLUDED_FILE
  203758. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203759. extern HWND juce_messageWindowHandle;
  203760. #endif
  203761. #if ! JUCE_USE_INTRINSICS
  203762. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203763. // older ones we have to actually call the ops as win32 functions..
  203764. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203765. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203766. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203767. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203768. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203769. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203770. {
  203771. jassertfalse; // This operation isn't available in old MS compiler versions!
  203772. __int64 oldValue = *value;
  203773. if (oldValue == valueToCompare)
  203774. *value = newValue;
  203775. return oldValue;
  203776. }
  203777. #endif
  203778. CriticalSection::CriticalSection() throw()
  203779. {
  203780. // (just to check the MS haven't changed this structure and broken things...)
  203781. #if _MSC_VER >= 1400
  203782. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203783. #else
  203784. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203785. #endif
  203786. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203787. }
  203788. CriticalSection::~CriticalSection() throw()
  203789. {
  203790. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203791. }
  203792. void CriticalSection::enter() const throw()
  203793. {
  203794. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203795. }
  203796. bool CriticalSection::tryEnter() const throw()
  203797. {
  203798. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203799. }
  203800. void CriticalSection::exit() const throw()
  203801. {
  203802. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203803. }
  203804. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203805. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203806. {
  203807. }
  203808. WaitableEvent::~WaitableEvent() throw()
  203809. {
  203810. CloseHandle (internal);
  203811. }
  203812. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203813. {
  203814. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203815. }
  203816. void WaitableEvent::signal() const throw()
  203817. {
  203818. SetEvent (internal);
  203819. }
  203820. void WaitableEvent::reset() const throw()
  203821. {
  203822. ResetEvent (internal);
  203823. }
  203824. void JUCE_API juce_threadEntryPoint (void*);
  203825. static unsigned int __stdcall threadEntryProc (void* userData)
  203826. {
  203827. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203828. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203829. GetCurrentThreadId(), TRUE);
  203830. #endif
  203831. juce_threadEntryPoint (userData);
  203832. _endthreadex (0);
  203833. return 0;
  203834. }
  203835. void juce_CloseThreadHandle (void* handle)
  203836. {
  203837. CloseHandle ((HANDLE) handle);
  203838. }
  203839. void* juce_createThread (void* userData)
  203840. {
  203841. unsigned int threadId;
  203842. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  203843. }
  203844. void juce_killThread (void* handle)
  203845. {
  203846. if (handle != 0)
  203847. {
  203848. #if JUCE_DEBUG
  203849. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203850. #endif
  203851. TerminateThread (handle, 0);
  203852. }
  203853. }
  203854. void juce_setCurrentThreadName (const String& name)
  203855. {
  203856. #if JUCE_DEBUG && JUCE_MSVC
  203857. struct
  203858. {
  203859. DWORD dwType;
  203860. LPCSTR szName;
  203861. DWORD dwThreadID;
  203862. DWORD dwFlags;
  203863. } info;
  203864. info.dwType = 0x1000;
  203865. info.szName = name.toCString();
  203866. info.dwThreadID = GetCurrentThreadId();
  203867. info.dwFlags = 0;
  203868. __try
  203869. {
  203870. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203871. }
  203872. __except (EXCEPTION_CONTINUE_EXECUTION)
  203873. {}
  203874. #else
  203875. (void) name;
  203876. #endif
  203877. }
  203878. Thread::ThreadID Thread::getCurrentThreadId()
  203879. {
  203880. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203881. }
  203882. // priority 1 to 10 where 5=normal, 1=low
  203883. bool juce_setThreadPriority (void* threadHandle, int priority)
  203884. {
  203885. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203886. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203887. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203888. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203889. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203890. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203891. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203892. if (threadHandle == 0)
  203893. threadHandle = GetCurrentThread();
  203894. return SetThreadPriority (threadHandle, pri) != FALSE;
  203895. }
  203896. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203897. {
  203898. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203899. }
  203900. static HANDLE sleepEvent = 0;
  203901. void juce_initialiseThreadEvents()
  203902. {
  203903. if (sleepEvent == 0)
  203904. #if JUCE_DEBUG
  203905. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  203906. #else
  203907. sleepEvent = CreateEvent (0, 0, 0, 0);
  203908. #endif
  203909. }
  203910. void Thread::yield()
  203911. {
  203912. Sleep (0);
  203913. }
  203914. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203915. {
  203916. if (millisecs >= 10)
  203917. {
  203918. Sleep (millisecs);
  203919. }
  203920. else
  203921. {
  203922. jassert (sleepEvent != 0);
  203923. // unlike Sleep() this is guaranteed to return to the current thread after
  203924. // the time expires, so we'll use this for short waits, which are more likely
  203925. // to need to be accurate
  203926. WaitForSingleObject (sleepEvent, millisecs);
  203927. }
  203928. }
  203929. static int lastProcessPriority = -1;
  203930. // called by WindowDriver because Windows does wierd things to process priority
  203931. // when you swap apps, and this forces an update when the app is brought to the front.
  203932. void juce_repeatLastProcessPriority()
  203933. {
  203934. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203935. {
  203936. DWORD p;
  203937. switch (lastProcessPriority)
  203938. {
  203939. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203940. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203941. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203942. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203943. default: jassertfalse; return; // bad priority value
  203944. }
  203945. SetPriorityClass (GetCurrentProcess(), p);
  203946. }
  203947. }
  203948. void Process::setPriority (ProcessPriority prior)
  203949. {
  203950. if (lastProcessPriority != (int) prior)
  203951. {
  203952. lastProcessPriority = (int) prior;
  203953. juce_repeatLastProcessPriority();
  203954. }
  203955. }
  203956. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  203957. {
  203958. return IsDebuggerPresent() != FALSE;
  203959. }
  203960. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203961. {
  203962. return juce_isRunningUnderDebugger();
  203963. }
  203964. void Process::raisePrivilege()
  203965. {
  203966. jassertfalse; // xxx not implemented
  203967. }
  203968. void Process::lowerPrivilege()
  203969. {
  203970. jassertfalse; // xxx not implemented
  203971. }
  203972. void Process::terminate()
  203973. {
  203974. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203975. _CrtDumpMemoryLeaks();
  203976. #endif
  203977. // bullet in the head in case there's a problem shutting down..
  203978. ExitProcess (0);
  203979. }
  203980. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203981. {
  203982. void* result = 0;
  203983. JUCE_TRY
  203984. {
  203985. result = LoadLibrary (name);
  203986. }
  203987. JUCE_CATCH_ALL
  203988. return result;
  203989. }
  203990. void PlatformUtilities::freeDynamicLibrary (void* h)
  203991. {
  203992. JUCE_TRY
  203993. {
  203994. if (h != 0)
  203995. FreeLibrary ((HMODULE) h);
  203996. }
  203997. JUCE_CATCH_ALL
  203998. }
  203999. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  204000. {
  204001. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  204002. }
  204003. class InterProcessLock::Pimpl
  204004. {
  204005. public:
  204006. Pimpl (const String& name, const int timeOutMillisecs)
  204007. : handle (0), refCount (1)
  204008. {
  204009. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  204010. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  204011. {
  204012. if (timeOutMillisecs == 0)
  204013. {
  204014. close();
  204015. return;
  204016. }
  204017. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  204018. {
  204019. case WAIT_OBJECT_0:
  204020. case WAIT_ABANDONED:
  204021. break;
  204022. case WAIT_TIMEOUT:
  204023. default:
  204024. close();
  204025. break;
  204026. }
  204027. }
  204028. }
  204029. ~Pimpl()
  204030. {
  204031. close();
  204032. }
  204033. void close()
  204034. {
  204035. if (handle != 0)
  204036. {
  204037. ReleaseMutex (handle);
  204038. CloseHandle (handle);
  204039. handle = 0;
  204040. }
  204041. }
  204042. HANDLE handle;
  204043. int refCount;
  204044. };
  204045. InterProcessLock::InterProcessLock (const String& name_)
  204046. : name (name_)
  204047. {
  204048. }
  204049. InterProcessLock::~InterProcessLock()
  204050. {
  204051. }
  204052. bool InterProcessLock::enter (const int timeOutMillisecs)
  204053. {
  204054. const ScopedLock sl (lock);
  204055. if (pimpl == 0)
  204056. {
  204057. pimpl = new Pimpl (name, timeOutMillisecs);
  204058. if (pimpl->handle == 0)
  204059. pimpl = 0;
  204060. }
  204061. else
  204062. {
  204063. pimpl->refCount++;
  204064. }
  204065. return pimpl != 0;
  204066. }
  204067. void InterProcessLock::exit()
  204068. {
  204069. const ScopedLock sl (lock);
  204070. // Trying to release the lock too many times!
  204071. jassert (pimpl != 0);
  204072. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204073. pimpl = 0;
  204074. }
  204075. #endif
  204076. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204077. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204078. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204079. // compiled on its own).
  204080. #if JUCE_INCLUDED_FILE
  204081. #ifndef CSIDL_MYMUSIC
  204082. #define CSIDL_MYMUSIC 0x000d
  204083. #endif
  204084. #ifndef CSIDL_MYVIDEO
  204085. #define CSIDL_MYVIDEO 0x000e
  204086. #endif
  204087. #ifndef INVALID_FILE_ATTRIBUTES
  204088. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204089. #endif
  204090. const juce_wchar File::separator = '\\';
  204091. const String File::separatorString ("\\");
  204092. bool File::exists() const
  204093. {
  204094. return fullPath.isNotEmpty()
  204095. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  204096. }
  204097. bool File::existsAsFile() const
  204098. {
  204099. return fullPath.isNotEmpty()
  204100. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204101. }
  204102. bool File::isDirectory() const
  204103. {
  204104. const DWORD attr = GetFileAttributes (fullPath);
  204105. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204106. }
  204107. bool File::hasWriteAccess() const
  204108. {
  204109. if (exists())
  204110. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  204111. // on windows, it seems that even read-only directories can still be written into,
  204112. // so checking the parent directory's permissions would return the wrong result..
  204113. return true;
  204114. }
  204115. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204116. {
  204117. DWORD attr = GetFileAttributes (fullPath);
  204118. if (attr == INVALID_FILE_ATTRIBUTES)
  204119. return false;
  204120. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204121. return true;
  204122. if (shouldBeReadOnly)
  204123. attr |= FILE_ATTRIBUTE_READONLY;
  204124. else
  204125. attr &= ~FILE_ATTRIBUTE_READONLY;
  204126. return SetFileAttributes (fullPath, attr) != FALSE;
  204127. }
  204128. bool File::isHidden() const
  204129. {
  204130. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204131. }
  204132. bool File::deleteFile() const
  204133. {
  204134. if (! exists())
  204135. return true;
  204136. else if (isDirectory())
  204137. return RemoveDirectory (fullPath) != 0;
  204138. else
  204139. return DeleteFile (fullPath) != 0;
  204140. }
  204141. bool File::moveToTrash() const
  204142. {
  204143. if (! exists())
  204144. return true;
  204145. SHFILEOPSTRUCT fos;
  204146. zerostruct (fos);
  204147. // The string we pass in must be double null terminated..
  204148. String doubleNullTermPath (getFullPathName() + " ");
  204149. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204150. p [getFullPathName().length()] = 0;
  204151. fos.wFunc = FO_DELETE;
  204152. fos.pFrom = p;
  204153. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204154. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204155. return SHFileOperation (&fos) == 0;
  204156. }
  204157. bool File::copyInternal (const File& dest) const
  204158. {
  204159. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204160. }
  204161. bool File::moveInternal (const File& dest) const
  204162. {
  204163. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204164. }
  204165. void File::createDirectoryInternal (const String& fileName) const
  204166. {
  204167. CreateDirectory (fileName, 0);
  204168. }
  204169. int64 juce_fileSetPosition (void* handle, int64 pos)
  204170. {
  204171. LARGE_INTEGER li;
  204172. li.QuadPart = pos;
  204173. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204174. return li.QuadPart;
  204175. }
  204176. void FileInputStream::openHandle()
  204177. {
  204178. totalSize = file.getSize();
  204179. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204180. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204181. if (h != INVALID_HANDLE_VALUE)
  204182. fileHandle = (void*) h;
  204183. }
  204184. void FileInputStream::closeHandle()
  204185. {
  204186. CloseHandle ((HANDLE) fileHandle);
  204187. }
  204188. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204189. {
  204190. if (fileHandle != 0)
  204191. {
  204192. DWORD actualNum = 0;
  204193. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204194. return (size_t) actualNum;
  204195. }
  204196. return 0;
  204197. }
  204198. void FileOutputStream::openHandle()
  204199. {
  204200. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204201. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204202. if (h != INVALID_HANDLE_VALUE)
  204203. {
  204204. LARGE_INTEGER li;
  204205. li.QuadPart = 0;
  204206. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204207. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204208. {
  204209. fileHandle = (void*) h;
  204210. currentPosition = li.QuadPart;
  204211. }
  204212. }
  204213. }
  204214. void FileOutputStream::closeHandle()
  204215. {
  204216. CloseHandle ((HANDLE) fileHandle);
  204217. }
  204218. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204219. {
  204220. if (fileHandle != 0)
  204221. {
  204222. DWORD actualNum = 0;
  204223. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204224. return (int) actualNum;
  204225. }
  204226. return 0;
  204227. }
  204228. void FileOutputStream::flushInternal()
  204229. {
  204230. if (fileHandle != 0)
  204231. FlushFileBuffers ((HANDLE) fileHandle);
  204232. }
  204233. int64 File::getSize() const
  204234. {
  204235. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204236. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204237. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204238. return 0;
  204239. }
  204240. static int64 fileTimeToTime (const FILETIME* const ft)
  204241. {
  204242. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204243. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204244. }
  204245. static void timeToFileTime (const int64 time, FILETIME* const ft)
  204246. {
  204247. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204248. }
  204249. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204250. {
  204251. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204252. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204253. {
  204254. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204255. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204256. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204257. }
  204258. else
  204259. {
  204260. creationTime = accessTime = modificationTime = 0;
  204261. }
  204262. }
  204263. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204264. {
  204265. bool ok = false;
  204266. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204267. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204268. if (h != INVALID_HANDLE_VALUE)
  204269. {
  204270. FILETIME m, a, c;
  204271. timeToFileTime (modificationTime, &m);
  204272. timeToFileTime (accessTime, &a);
  204273. timeToFileTime (creationTime, &c);
  204274. ok = SetFileTime (h,
  204275. creationTime > 0 ? &c : 0,
  204276. accessTime > 0 ? &a : 0,
  204277. modificationTime > 0 ? &m : 0) != 0;
  204278. CloseHandle (h);
  204279. }
  204280. return ok;
  204281. }
  204282. void File::findFileSystemRoots (Array<File>& destArray)
  204283. {
  204284. TCHAR buffer [2048];
  204285. buffer[0] = 0;
  204286. buffer[1] = 0;
  204287. GetLogicalDriveStrings (2048, buffer);
  204288. const TCHAR* n = buffer;
  204289. StringArray roots;
  204290. while (*n != 0)
  204291. {
  204292. roots.add (String (n));
  204293. while (*n++ != 0)
  204294. {}
  204295. }
  204296. roots.sort (true);
  204297. for (int i = 0; i < roots.size(); ++i)
  204298. destArray.add (roots [i]);
  204299. }
  204300. static const String getDriveFromPath (const String& path)
  204301. {
  204302. if (path.isNotEmpty() && path[1] == ':')
  204303. return path.substring (0, 2) + '\\';
  204304. return path;
  204305. }
  204306. const String File::getVolumeLabel() const
  204307. {
  204308. TCHAR dest[64];
  204309. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204310. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204311. dest[0] = 0;
  204312. return dest;
  204313. }
  204314. int File::getVolumeSerialNumber() const
  204315. {
  204316. TCHAR dest[64];
  204317. DWORD serialNum;
  204318. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204319. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204320. return 0;
  204321. return (int) serialNum;
  204322. }
  204323. static int64 getDiskSpaceInfo (const String& path, const bool total)
  204324. {
  204325. ULARGE_INTEGER spc, tot, totFree;
  204326. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204327. return total ? (int64) tot.QuadPart
  204328. : (int64) spc.QuadPart;
  204329. return 0;
  204330. }
  204331. int64 File::getBytesFreeOnVolume() const
  204332. {
  204333. return getDiskSpaceInfo (getFullPathName(), false);
  204334. }
  204335. int64 File::getVolumeTotalSize() const
  204336. {
  204337. return getDiskSpaceInfo (getFullPathName(), true);
  204338. }
  204339. static unsigned int getWindowsDriveType (const String& path)
  204340. {
  204341. return GetDriveType (getDriveFromPath (path));
  204342. }
  204343. bool File::isOnCDRomDrive() const
  204344. {
  204345. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204346. }
  204347. bool File::isOnHardDisk() const
  204348. {
  204349. if (fullPath.isEmpty())
  204350. return false;
  204351. const unsigned int n = getWindowsDriveType (getFullPathName());
  204352. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204353. return n != DRIVE_REMOVABLE;
  204354. else
  204355. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204356. }
  204357. bool File::isOnRemovableDrive() const
  204358. {
  204359. if (fullPath.isEmpty())
  204360. return false;
  204361. const unsigned int n = getWindowsDriveType (getFullPathName());
  204362. return n == DRIVE_CDROM
  204363. || n == DRIVE_REMOTE
  204364. || n == DRIVE_REMOVABLE
  204365. || n == DRIVE_RAMDISK;
  204366. }
  204367. static const File juce_getSpecialFolderPath (int type)
  204368. {
  204369. WCHAR path [MAX_PATH + 256];
  204370. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204371. return File (String (path));
  204372. return File::nonexistent;
  204373. }
  204374. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204375. {
  204376. int csidlType = 0;
  204377. switch (type)
  204378. {
  204379. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204380. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204381. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204382. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204383. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204384. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204385. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204386. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204387. case tempDirectory:
  204388. {
  204389. WCHAR dest [2048];
  204390. dest[0] = 0;
  204391. GetTempPath (numElementsInArray (dest), dest);
  204392. return File (String (dest));
  204393. }
  204394. case invokedExecutableFile:
  204395. case currentExecutableFile:
  204396. case currentApplicationFile:
  204397. {
  204398. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204399. WCHAR dest [MAX_PATH + 256];
  204400. dest[0] = 0;
  204401. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204402. return File (String (dest));
  204403. }
  204404. case hostApplicationPath:
  204405. {
  204406. WCHAR dest [MAX_PATH + 256];
  204407. dest[0] = 0;
  204408. GetModuleFileName (0, dest, numElementsInArray (dest));
  204409. return File (String (dest));
  204410. }
  204411. default:
  204412. jassertfalse; // unknown type?
  204413. return File::nonexistent;
  204414. }
  204415. return juce_getSpecialFolderPath (csidlType);
  204416. }
  204417. const File File::getCurrentWorkingDirectory()
  204418. {
  204419. WCHAR dest [MAX_PATH + 256];
  204420. dest[0] = 0;
  204421. GetCurrentDirectory (numElementsInArray (dest), dest);
  204422. return File (String (dest));
  204423. }
  204424. bool File::setAsCurrentWorkingDirectory() const
  204425. {
  204426. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204427. }
  204428. const String File::getVersion() const
  204429. {
  204430. String result;
  204431. DWORD handle = 0;
  204432. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204433. HeapBlock<char> buffer;
  204434. buffer.calloc (bufferSize);
  204435. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204436. {
  204437. VS_FIXEDFILEINFO* vffi;
  204438. UINT len = 0;
  204439. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204440. {
  204441. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204442. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204443. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204444. << (int) LOWORD (vffi->dwFileVersionLS);
  204445. }
  204446. }
  204447. return result;
  204448. }
  204449. const File File::getLinkedTarget() const
  204450. {
  204451. File result (*this);
  204452. String p (getFullPathName());
  204453. if (! exists())
  204454. p += ".lnk";
  204455. else if (getFileExtension() != ".lnk")
  204456. return result;
  204457. ComSmartPtr <IShellLink> shellLink;
  204458. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204459. {
  204460. ComSmartPtr <IPersistFile> persistFile;
  204461. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204462. {
  204463. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204464. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204465. {
  204466. WIN32_FIND_DATA winFindData;
  204467. WCHAR resolvedPath [MAX_PATH];
  204468. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204469. result = File (resolvedPath);
  204470. }
  204471. }
  204472. }
  204473. return result;
  204474. }
  204475. class DirectoryIterator::NativeIterator::Pimpl
  204476. {
  204477. public:
  204478. Pimpl (const File& directory, const String& wildCard)
  204479. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204480. handle (INVALID_HANDLE_VALUE)
  204481. {
  204482. }
  204483. ~Pimpl()
  204484. {
  204485. if (handle != INVALID_HANDLE_VALUE)
  204486. FindClose (handle);
  204487. }
  204488. bool next (String& filenameFound,
  204489. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204490. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204491. {
  204492. WIN32_FIND_DATA findData;
  204493. if (handle == INVALID_HANDLE_VALUE)
  204494. {
  204495. handle = FindFirstFile (directoryWithWildCard, &findData);
  204496. if (handle == INVALID_HANDLE_VALUE)
  204497. return false;
  204498. }
  204499. else
  204500. {
  204501. if (FindNextFile (handle, &findData) == 0)
  204502. return false;
  204503. }
  204504. filenameFound = findData.cFileName;
  204505. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204506. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204507. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204508. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  204509. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  204510. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204511. return true;
  204512. }
  204513. juce_UseDebuggingNewOperator
  204514. private:
  204515. const String directoryWithWildCard;
  204516. HANDLE handle;
  204517. Pimpl (const Pimpl&);
  204518. Pimpl& operator= (const Pimpl&);
  204519. };
  204520. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204521. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204522. {
  204523. }
  204524. DirectoryIterator::NativeIterator::~NativeIterator()
  204525. {
  204526. }
  204527. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204528. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204529. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204530. {
  204531. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204532. }
  204533. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204534. {
  204535. HINSTANCE hInstance = 0;
  204536. JUCE_TRY
  204537. {
  204538. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204539. }
  204540. JUCE_CATCH_ALL
  204541. return hInstance > (HINSTANCE) 32;
  204542. }
  204543. void File::revealToUser() const
  204544. {
  204545. if (isDirectory())
  204546. startAsProcess();
  204547. else if (getParentDirectory().exists())
  204548. getParentDirectory().startAsProcess();
  204549. }
  204550. class NamedPipeInternal
  204551. {
  204552. public:
  204553. NamedPipeInternal (const String& file, const bool isPipe_)
  204554. : pipeH (0),
  204555. cancelEvent (0),
  204556. connected (false),
  204557. isPipe (isPipe_)
  204558. {
  204559. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204560. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204561. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204562. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204563. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204564. }
  204565. ~NamedPipeInternal()
  204566. {
  204567. disconnectPipe();
  204568. if (pipeH != 0)
  204569. CloseHandle (pipeH);
  204570. CloseHandle (cancelEvent);
  204571. }
  204572. bool connect (const int timeOutMs)
  204573. {
  204574. if (! isPipe)
  204575. return true;
  204576. if (! connected)
  204577. {
  204578. OVERLAPPED over;
  204579. zerostruct (over);
  204580. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204581. if (ConnectNamedPipe (pipeH, &over))
  204582. {
  204583. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204584. }
  204585. else
  204586. {
  204587. const int err = GetLastError();
  204588. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204589. {
  204590. HANDLE handles[] = { over.hEvent, cancelEvent };
  204591. if (WaitForMultipleObjects (2, handles, FALSE,
  204592. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204593. connected = true;
  204594. }
  204595. else if (err == ERROR_PIPE_CONNECTED)
  204596. {
  204597. connected = true;
  204598. }
  204599. }
  204600. CloseHandle (over.hEvent);
  204601. }
  204602. return connected;
  204603. }
  204604. void disconnectPipe()
  204605. {
  204606. if (connected)
  204607. {
  204608. DisconnectNamedPipe (pipeH);
  204609. connected = false;
  204610. }
  204611. }
  204612. HANDLE pipeH;
  204613. HANDLE cancelEvent;
  204614. bool connected, isPipe;
  204615. };
  204616. void NamedPipe::close()
  204617. {
  204618. cancelPendingReads();
  204619. const ScopedLock sl (lock);
  204620. delete static_cast<NamedPipeInternal*> (internal);
  204621. internal = 0;
  204622. }
  204623. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204624. {
  204625. close();
  204626. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204627. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204628. {
  204629. internal = intern.release();
  204630. return true;
  204631. }
  204632. return false;
  204633. }
  204634. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204635. {
  204636. const ScopedLock sl (lock);
  204637. int bytesRead = -1;
  204638. bool waitAgain = true;
  204639. while (waitAgain && internal != 0)
  204640. {
  204641. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204642. waitAgain = false;
  204643. if (! intern->connect (timeOutMilliseconds))
  204644. break;
  204645. if (maxBytesToRead <= 0)
  204646. return 0;
  204647. OVERLAPPED over;
  204648. zerostruct (over);
  204649. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204650. unsigned long numRead;
  204651. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204652. {
  204653. bytesRead = (int) numRead;
  204654. }
  204655. else if (GetLastError() == ERROR_IO_PENDING)
  204656. {
  204657. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204658. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204659. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204660. : INFINITE);
  204661. if (waitResult != WAIT_OBJECT_0)
  204662. {
  204663. // if the operation timed out, let's cancel it...
  204664. CancelIo (intern->pipeH);
  204665. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204666. }
  204667. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204668. {
  204669. bytesRead = (int) numRead;
  204670. }
  204671. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204672. {
  204673. intern->disconnectPipe();
  204674. waitAgain = true;
  204675. }
  204676. }
  204677. else
  204678. {
  204679. waitAgain = internal != 0;
  204680. Sleep (5);
  204681. }
  204682. CloseHandle (over.hEvent);
  204683. }
  204684. return bytesRead;
  204685. }
  204686. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204687. {
  204688. int bytesWritten = -1;
  204689. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204690. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204691. {
  204692. if (numBytesToWrite <= 0)
  204693. return 0;
  204694. OVERLAPPED over;
  204695. zerostruct (over);
  204696. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204697. unsigned long numWritten;
  204698. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204699. {
  204700. bytesWritten = (int) numWritten;
  204701. }
  204702. else if (GetLastError() == ERROR_IO_PENDING)
  204703. {
  204704. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204705. DWORD waitResult;
  204706. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204707. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204708. : INFINITE);
  204709. if (waitResult != WAIT_OBJECT_0)
  204710. {
  204711. CancelIo (intern->pipeH);
  204712. WaitForSingleObject (over.hEvent, INFINITE);
  204713. }
  204714. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204715. {
  204716. bytesWritten = (int) numWritten;
  204717. }
  204718. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204719. {
  204720. intern->disconnectPipe();
  204721. }
  204722. }
  204723. CloseHandle (over.hEvent);
  204724. }
  204725. return bytesWritten;
  204726. }
  204727. void NamedPipe::cancelPendingReads()
  204728. {
  204729. if (internal != 0)
  204730. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204731. }
  204732. #endif
  204733. /*** End of inlined file: juce_win32_Files.cpp ***/
  204734. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204735. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204736. // compiled on its own).
  204737. #if JUCE_INCLUDED_FILE
  204738. #ifndef INTERNET_FLAG_NEED_FILE
  204739. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204740. #endif
  204741. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204742. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204743. #endif
  204744. struct ConnectionAndRequestStruct
  204745. {
  204746. HINTERNET connection, request;
  204747. };
  204748. static HINTERNET sessionHandle = 0;
  204749. #ifndef WORKAROUND_TIMEOUT_BUG
  204750. //#define WORKAROUND_TIMEOUT_BUG 1
  204751. #endif
  204752. #if WORKAROUND_TIMEOUT_BUG
  204753. // Required because of a Microsoft bug in setting a timeout
  204754. class InternetConnectThread : public Thread
  204755. {
  204756. public:
  204757. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204758. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204759. {
  204760. startThread();
  204761. }
  204762. ~InternetConnectThread()
  204763. {
  204764. stopThread (60000);
  204765. }
  204766. void run()
  204767. {
  204768. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204769. uc.nPort, _T(""), _T(""),
  204770. isFtp ? INTERNET_SERVICE_FTP
  204771. : INTERNET_SERVICE_HTTP,
  204772. 0, 0);
  204773. notify();
  204774. }
  204775. juce_UseDebuggingNewOperator
  204776. private:
  204777. URL_COMPONENTS& uc;
  204778. HINTERNET& connection;
  204779. const bool isFtp;
  204780. InternetConnectThread (const InternetConnectThread&);
  204781. InternetConnectThread& operator= (const InternetConnectThread&);
  204782. };
  204783. #endif
  204784. void* juce_openInternetFile (const String& url,
  204785. const String& headers,
  204786. const MemoryBlock& postData,
  204787. const bool isPost,
  204788. URL::OpenStreamProgressCallback* callback,
  204789. void* callbackContext,
  204790. int timeOutMs)
  204791. {
  204792. if (sessionHandle == 0)
  204793. sessionHandle = InternetOpen (_T("juce"),
  204794. INTERNET_OPEN_TYPE_PRECONFIG,
  204795. 0, 0, 0);
  204796. if (sessionHandle != 0)
  204797. {
  204798. // break up the url..
  204799. TCHAR file[1024], server[1024];
  204800. URL_COMPONENTS uc;
  204801. zerostruct (uc);
  204802. uc.dwStructSize = sizeof (uc);
  204803. uc.dwUrlPathLength = sizeof (file);
  204804. uc.dwHostNameLength = sizeof (server);
  204805. uc.lpszUrlPath = file;
  204806. uc.lpszHostName = server;
  204807. if (InternetCrackUrl (url, 0, 0, &uc))
  204808. {
  204809. int disable = 1;
  204810. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204811. if (timeOutMs == 0)
  204812. timeOutMs = 30000;
  204813. else if (timeOutMs < 0)
  204814. timeOutMs = -1;
  204815. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204816. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  204817. #if WORKAROUND_TIMEOUT_BUG
  204818. HINTERNET connection = 0;
  204819. {
  204820. InternetConnectThread connectThread (uc, connection, isFtp);
  204821. connectThread.wait (timeOutMs);
  204822. if (connection == 0)
  204823. {
  204824. InternetCloseHandle (sessionHandle);
  204825. sessionHandle = 0;
  204826. }
  204827. }
  204828. #else
  204829. HINTERNET connection = InternetConnect (sessionHandle,
  204830. uc.lpszHostName,
  204831. uc.nPort,
  204832. _T(""), _T(""),
  204833. isFtp ? INTERNET_SERVICE_FTP
  204834. : INTERNET_SERVICE_HTTP,
  204835. 0, 0);
  204836. #endif
  204837. if (connection != 0)
  204838. {
  204839. if (isFtp)
  204840. {
  204841. HINTERNET request = FtpOpenFile (connection,
  204842. uc.lpszUrlPath,
  204843. GENERIC_READ,
  204844. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  204845. 0);
  204846. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  204847. result->connection = connection;
  204848. result->request = request;
  204849. return result;
  204850. }
  204851. else
  204852. {
  204853. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204854. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204855. if (url.startsWithIgnoreCase ("https:"))
  204856. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204857. // IE7 seems to automatically work out when it's https)
  204858. HINTERNET request = HttpOpenRequest (connection,
  204859. isPost ? _T("POST")
  204860. : _T("GET"),
  204861. uc.lpszUrlPath,
  204862. 0, 0, mimeTypes, flags, 0);
  204863. if (request != 0)
  204864. {
  204865. INTERNET_BUFFERS buffers;
  204866. zerostruct (buffers);
  204867. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204868. buffers.lpcszHeader = (LPCTSTR) headers;
  204869. buffers.dwHeadersLength = headers.length();
  204870. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204871. ConnectionAndRequestStruct* result = 0;
  204872. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204873. {
  204874. int bytesSent = 0;
  204875. for (;;)
  204876. {
  204877. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204878. DWORD bytesDone = 0;
  204879. if (bytesToDo > 0
  204880. && ! InternetWriteFile (request,
  204881. static_cast <const char*> (postData.getData()) + bytesSent,
  204882. bytesToDo, &bytesDone))
  204883. {
  204884. break;
  204885. }
  204886. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204887. {
  204888. result = new ConnectionAndRequestStruct();
  204889. result->connection = connection;
  204890. result->request = request;
  204891. if (! HttpEndRequest (request, 0, 0, 0))
  204892. break;
  204893. return result;
  204894. }
  204895. bytesSent += bytesDone;
  204896. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  204897. break;
  204898. }
  204899. }
  204900. InternetCloseHandle (request);
  204901. }
  204902. InternetCloseHandle (connection);
  204903. }
  204904. }
  204905. }
  204906. }
  204907. return 0;
  204908. }
  204909. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  204910. {
  204911. DWORD bytesRead = 0;
  204912. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204913. if (crs != 0)
  204914. InternetReadFile (crs->request,
  204915. buffer, bytesToRead,
  204916. &bytesRead);
  204917. return bytesRead;
  204918. }
  204919. int juce_seekInInternetFile (void* handle, int newPosition)
  204920. {
  204921. if (handle != 0)
  204922. {
  204923. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204924. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  204925. }
  204926. return -1;
  204927. }
  204928. int64 juce_getInternetFileContentLength (void* handle)
  204929. {
  204930. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204931. if (crs != 0)
  204932. {
  204933. DWORD index = 0, result = 0, size = sizeof (result);
  204934. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204935. return (int64) result;
  204936. }
  204937. return -1;
  204938. }
  204939. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  204940. {
  204941. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204942. if (crs != 0)
  204943. {
  204944. DWORD bufferSizeBytes = 4096;
  204945. for (;;)
  204946. {
  204947. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204948. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204949. {
  204950. StringArray headersArray;
  204951. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204952. for (int i = 0; i < headersArray.size(); ++i)
  204953. {
  204954. const String& header = headersArray[i];
  204955. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204956. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204957. const String previousValue (headers [key]);
  204958. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204959. }
  204960. break;
  204961. }
  204962. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204963. break;
  204964. }
  204965. }
  204966. }
  204967. void juce_closeInternetFile (void* handle)
  204968. {
  204969. if (handle != 0)
  204970. {
  204971. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  204972. InternetCloseHandle (crs->request);
  204973. InternetCloseHandle (crs->connection);
  204974. }
  204975. }
  204976. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  204977. {
  204978. int numFound = 0;
  204979. DynamicLibraryLoader dll ("iphlpapi.dll");
  204980. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204981. if (getAdaptersInfo != 0)
  204982. {
  204983. ULONG len = sizeof (IP_ADAPTER_INFO);
  204984. MemoryBlock mb;
  204985. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204986. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204987. {
  204988. mb.setSize (len);
  204989. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204990. }
  204991. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204992. {
  204993. PIP_ADAPTER_INFO adapter = adapterInfo;
  204994. while (adapter != 0)
  204995. {
  204996. int64 mac = 0;
  204997. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  204998. mac = (mac << 8) | adapter->Address[i];
  204999. if (littleEndian)
  205000. mac = (int64) ByteOrder::swap ((uint64) mac);
  205001. if (numFound < maxNum && mac != 0)
  205002. addresses [numFound++] = mac;
  205003. adapter = adapter->Next;
  205004. }
  205005. }
  205006. }
  205007. return numFound;
  205008. }
  205009. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  205010. {
  205011. int numFound = 0;
  205012. DynamicLibraryLoader dll ("netapi32.dll");
  205013. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  205014. if (NetbiosCall != 0)
  205015. {
  205016. NCB ncb;
  205017. zerostruct (ncb);
  205018. struct ASTAT
  205019. {
  205020. ADAPTER_STATUS adapt;
  205021. NAME_BUFFER NameBuff [30];
  205022. };
  205023. ASTAT astat;
  205024. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  205025. LANA_ENUM enums;
  205026. zerostruct (enums);
  205027. ncb.ncb_command = NCBENUM;
  205028. ncb.ncb_buffer = (unsigned char*) &enums;
  205029. ncb.ncb_length = sizeof (LANA_ENUM);
  205030. NetbiosCall (&ncb);
  205031. for (int i = 0; i < enums.length; ++i)
  205032. {
  205033. zerostruct (ncb);
  205034. ncb.ncb_command = NCBRESET;
  205035. ncb.ncb_lana_num = enums.lana[i];
  205036. if (NetbiosCall (&ncb) == 0)
  205037. {
  205038. zerostruct (ncb);
  205039. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205040. ncb.ncb_command = NCBASTAT;
  205041. ncb.ncb_lana_num = enums.lana[i];
  205042. ncb.ncb_buffer = (unsigned char*) &astat;
  205043. ncb.ncb_length = sizeof (ASTAT);
  205044. if (NetbiosCall (&ncb) == 0)
  205045. {
  205046. if (astat.adapt.adapter_type == 0xfe)
  205047. {
  205048. uint64 mac = 0;
  205049. for (int i = 6; --i >= 0;)
  205050. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  205051. if (numFound < maxNum && mac != 0)
  205052. addresses [numFound++] = mac;
  205053. }
  205054. }
  205055. }
  205056. }
  205057. }
  205058. return numFound;
  205059. }
  205060. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  205061. {
  205062. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  205063. if (numFound == 0)
  205064. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  205065. return numFound;
  205066. }
  205067. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205068. const String& emailSubject,
  205069. const String& bodyText,
  205070. const StringArray& filesToAttach)
  205071. {
  205072. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205073. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205074. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205075. bool ok = false;
  205076. if (mapiSendMail != 0)
  205077. {
  205078. MapiMessage message;
  205079. zerostruct (message);
  205080. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205081. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205082. MapiRecipDesc recip;
  205083. zerostruct (recip);
  205084. recip.ulRecipClass = MAPI_TO;
  205085. String targetEmailAddress_ (targetEmailAddress);
  205086. if (targetEmailAddress_.isEmpty())
  205087. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205088. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205089. message.nRecipCount = 1;
  205090. message.lpRecips = &recip;
  205091. HeapBlock <MapiFileDesc> files;
  205092. files.calloc (filesToAttach.size());
  205093. message.nFileCount = filesToAttach.size();
  205094. message.lpFiles = files;
  205095. for (int i = 0; i < filesToAttach.size(); ++i)
  205096. {
  205097. files[i].nPosition = (ULONG) -1;
  205098. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205099. }
  205100. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205101. }
  205102. FreeLibrary (h);
  205103. return ok;
  205104. }
  205105. #endif
  205106. /*** End of inlined file: juce_win32_Network.cpp ***/
  205107. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205108. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205109. // compiled on its own).
  205110. #if JUCE_INCLUDED_FILE
  205111. static HKEY findKeyForPath (String name,
  205112. const bool createForWriting,
  205113. String& valueName)
  205114. {
  205115. HKEY rootKey = 0;
  205116. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205117. rootKey = HKEY_CURRENT_USER;
  205118. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205119. rootKey = HKEY_LOCAL_MACHINE;
  205120. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205121. rootKey = HKEY_CLASSES_ROOT;
  205122. if (rootKey != 0)
  205123. {
  205124. name = name.substring (name.indexOfChar ('\\') + 1);
  205125. const int lastSlash = name.lastIndexOfChar ('\\');
  205126. valueName = name.substring (lastSlash + 1);
  205127. name = name.substring (0, lastSlash);
  205128. HKEY key;
  205129. DWORD result;
  205130. if (createForWriting)
  205131. {
  205132. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  205133. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205134. return key;
  205135. }
  205136. else
  205137. {
  205138. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  205139. return key;
  205140. }
  205141. }
  205142. return 0;
  205143. }
  205144. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205145. const String& defaultValue)
  205146. {
  205147. String valueName, result (defaultValue);
  205148. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205149. if (k != 0)
  205150. {
  205151. WCHAR buffer [2048];
  205152. unsigned long bufferSize = sizeof (buffer);
  205153. DWORD type = REG_SZ;
  205154. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205155. {
  205156. if (type == REG_SZ)
  205157. result = buffer;
  205158. else if (type == REG_DWORD)
  205159. result = String ((int) *(DWORD*) buffer);
  205160. }
  205161. RegCloseKey (k);
  205162. }
  205163. return result;
  205164. }
  205165. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205166. const String& value)
  205167. {
  205168. String valueName;
  205169. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205170. if (k != 0)
  205171. {
  205172. RegSetValueEx (k, valueName, 0, REG_SZ,
  205173. (const BYTE*) (const WCHAR*) value,
  205174. sizeof (WCHAR) * (value.length() + 1));
  205175. RegCloseKey (k);
  205176. }
  205177. }
  205178. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205179. {
  205180. bool exists = false;
  205181. String valueName;
  205182. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205183. if (k != 0)
  205184. {
  205185. unsigned char buffer [2048];
  205186. unsigned long bufferSize = sizeof (buffer);
  205187. DWORD type = 0;
  205188. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205189. exists = true;
  205190. RegCloseKey (k);
  205191. }
  205192. return exists;
  205193. }
  205194. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205195. {
  205196. String valueName;
  205197. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205198. if (k != 0)
  205199. {
  205200. RegDeleteValue (k, valueName);
  205201. RegCloseKey (k);
  205202. }
  205203. }
  205204. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205205. {
  205206. String valueName;
  205207. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205208. if (k != 0)
  205209. {
  205210. RegDeleteKey (k, valueName);
  205211. RegCloseKey (k);
  205212. }
  205213. }
  205214. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205215. const String& symbolicDescription,
  205216. const String& fullDescription,
  205217. const File& targetExecutable,
  205218. int iconResourceNumber)
  205219. {
  205220. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205221. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205222. if (iconResourceNumber != 0)
  205223. setRegistryValue (key + "\\DefaultIcon\\",
  205224. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205225. setRegistryValue (key + "\\", fullDescription);
  205226. setRegistryValue (key + "\\shell\\open\\command\\",
  205227. targetExecutable.getFullPathName() + " %1");
  205228. }
  205229. bool juce_IsRunningInWine()
  205230. {
  205231. HKEY key;
  205232. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205233. {
  205234. RegCloseKey (key);
  205235. return true;
  205236. }
  205237. return false;
  205238. }
  205239. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205240. {
  205241. String s (::GetCommandLineW());
  205242. StringArray tokens;
  205243. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205244. return tokens.joinIntoString (" ", 1);
  205245. }
  205246. static void* currentModuleHandle = 0;
  205247. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205248. {
  205249. if (currentModuleHandle == 0)
  205250. currentModuleHandle = GetModuleHandle (0);
  205251. return currentModuleHandle;
  205252. }
  205253. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205254. {
  205255. currentModuleHandle = newHandle;
  205256. }
  205257. void PlatformUtilities::fpuReset()
  205258. {
  205259. #if JUCE_MSVC
  205260. _clearfp();
  205261. #endif
  205262. }
  205263. void PlatformUtilities::beep()
  205264. {
  205265. MessageBeep (MB_OK);
  205266. }
  205267. #endif
  205268. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205269. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205270. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205271. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205272. // compiled on its own).
  205273. #if JUCE_INCLUDED_FILE
  205274. static const unsigned int specialId = WM_APP + 0x4400;
  205275. static const unsigned int broadcastId = WM_APP + 0x4403;
  205276. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205277. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205278. HWND juce_messageWindowHandle = 0;
  205279. extern long improbableWindowNumber; // defined in windowing.cpp
  205280. #ifndef WM_APPCOMMAND
  205281. #define WM_APPCOMMAND 0x0319
  205282. #endif
  205283. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205284. const UINT message,
  205285. const WPARAM wParam,
  205286. const LPARAM lParam) throw()
  205287. {
  205288. JUCE_TRY
  205289. {
  205290. if (h == juce_messageWindowHandle)
  205291. {
  205292. if (message == specialCallbackId)
  205293. {
  205294. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205295. return (LRESULT) (*func) ((void*) lParam);
  205296. }
  205297. else if (message == specialId)
  205298. {
  205299. // these are trapped early in the dispatch call, but must also be checked
  205300. // here in case there are windows modal dialog boxes doing their own
  205301. // dispatch loop and not calling our version
  205302. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  205303. return 0;
  205304. }
  205305. else if (message == broadcastId)
  205306. {
  205307. const ScopedPointer <String> messageString ((String*) lParam);
  205308. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205309. return 0;
  205310. }
  205311. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205312. {
  205313. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205314. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205315. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205316. return 0;
  205317. }
  205318. }
  205319. }
  205320. JUCE_CATCH_EXCEPTION
  205321. return DefWindowProc (h, message, wParam, lParam);
  205322. }
  205323. static bool isEventBlockedByModalComps (MSG& m)
  205324. {
  205325. if (Component::getNumCurrentlyModalComponents() == 0
  205326. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205327. return false;
  205328. switch (m.message)
  205329. {
  205330. case WM_MOUSEMOVE:
  205331. case WM_NCMOUSEMOVE:
  205332. case 0x020A: /* WM_MOUSEWHEEL */
  205333. case 0x020E: /* WM_MOUSEHWHEEL */
  205334. case WM_KEYUP:
  205335. case WM_SYSKEYUP:
  205336. case WM_CHAR:
  205337. case WM_APPCOMMAND:
  205338. case WM_LBUTTONUP:
  205339. case WM_MBUTTONUP:
  205340. case WM_RBUTTONUP:
  205341. case WM_MOUSEACTIVATE:
  205342. case WM_NCMOUSEHOVER:
  205343. case WM_MOUSEHOVER:
  205344. return true;
  205345. case WM_NCLBUTTONDOWN:
  205346. case WM_NCLBUTTONDBLCLK:
  205347. case WM_NCRBUTTONDOWN:
  205348. case WM_NCRBUTTONDBLCLK:
  205349. case WM_NCMBUTTONDOWN:
  205350. case WM_NCMBUTTONDBLCLK:
  205351. case WM_LBUTTONDOWN:
  205352. case WM_LBUTTONDBLCLK:
  205353. case WM_MBUTTONDOWN:
  205354. case WM_MBUTTONDBLCLK:
  205355. case WM_RBUTTONDOWN:
  205356. case WM_RBUTTONDBLCLK:
  205357. case WM_KEYDOWN:
  205358. case WM_SYSKEYDOWN:
  205359. {
  205360. Component* const modal = Component::getCurrentlyModalComponent (0);
  205361. if (modal != 0)
  205362. modal->inputAttemptWhenModal();
  205363. return true;
  205364. }
  205365. default:
  205366. break;
  205367. }
  205368. return false;
  205369. }
  205370. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205371. {
  205372. MSG m;
  205373. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205374. return false;
  205375. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205376. {
  205377. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205378. {
  205379. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  205380. }
  205381. else if (m.message == WM_QUIT)
  205382. {
  205383. if (JUCEApplication::getInstance() != 0)
  205384. JUCEApplication::getInstance()->systemRequestedQuit();
  205385. }
  205386. else if (! isEventBlockedByModalComps (m))
  205387. {
  205388. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205389. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205390. {
  205391. // if it's someone else's window being clicked on, and the focus is
  205392. // currently on a juce window, pass the kb focus over..
  205393. HWND currentFocus = GetFocus();
  205394. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205395. SetFocus (m.hwnd);
  205396. }
  205397. TranslateMessage (&m);
  205398. DispatchMessage (&m);
  205399. }
  205400. }
  205401. return true;
  205402. }
  205403. bool juce_postMessageToSystemQueue (Message* message)
  205404. {
  205405. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205406. }
  205407. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205408. void* userData)
  205409. {
  205410. if (MessageManager::getInstance()->isThisTheMessageThread())
  205411. {
  205412. return (*callback) (userData);
  205413. }
  205414. else
  205415. {
  205416. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205417. // deadlock because the message manager is blocked from running, and can't
  205418. // call your function..
  205419. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205420. return (void*) SendMessage (juce_messageWindowHandle,
  205421. specialCallbackId,
  205422. (WPARAM) callback,
  205423. (LPARAM) userData);
  205424. }
  205425. }
  205426. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205427. {
  205428. if (hwnd != juce_messageWindowHandle)
  205429. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205430. return TRUE;
  205431. }
  205432. void MessageManager::broadcastMessage (const String& value)
  205433. {
  205434. Array<void*> windows;
  205435. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205436. const String localCopy (value);
  205437. COPYDATASTRUCT data;
  205438. data.dwData = broadcastId;
  205439. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205440. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205441. for (int i = windows.size(); --i >= 0;)
  205442. {
  205443. HWND hwnd = (HWND) windows.getUnchecked(i);
  205444. TCHAR windowName [64]; // no need to read longer strings than this
  205445. GetWindowText (hwnd, windowName, 64);
  205446. windowName [63] = 0;
  205447. if (String (windowName) == messageWindowName)
  205448. {
  205449. DWORD_PTR result;
  205450. SendMessageTimeout (hwnd, WM_COPYDATA,
  205451. (WPARAM) juce_messageWindowHandle,
  205452. (LPARAM) &data,
  205453. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205454. 8000,
  205455. &result);
  205456. }
  205457. }
  205458. }
  205459. static const String getMessageWindowClassName()
  205460. {
  205461. // this name has to be different for each app/dll instance because otherwise
  205462. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205463. // window class).
  205464. static int number = 0;
  205465. if (number == 0)
  205466. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205467. return "JUCEcs_" + String (number);
  205468. }
  205469. void MessageManager::doPlatformSpecificInitialisation()
  205470. {
  205471. OleInitialize (0);
  205472. const String className (getMessageWindowClassName());
  205473. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205474. WNDCLASSEX wc;
  205475. zerostruct (wc);
  205476. wc.cbSize = sizeof (wc);
  205477. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205478. wc.cbWndExtra = 4;
  205479. wc.hInstance = hmod;
  205480. wc.lpszClassName = className;
  205481. RegisterClassEx (&wc);
  205482. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205483. messageWindowName,
  205484. 0, 0, 0, 0, 0, 0, 0,
  205485. hmod, 0);
  205486. }
  205487. void MessageManager::doPlatformSpecificShutdown()
  205488. {
  205489. DestroyWindow (juce_messageWindowHandle);
  205490. UnregisterClass (getMessageWindowClassName(), 0);
  205491. OleUninitialize();
  205492. }
  205493. #endif
  205494. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205495. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205496. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205497. // compiled on its own).
  205498. #if JUCE_INCLUDED_FILE
  205499. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205500. NEWTEXTMETRICEXW*,
  205501. int type,
  205502. LPARAM lParam)
  205503. {
  205504. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205505. {
  205506. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205507. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205508. }
  205509. return 1;
  205510. }
  205511. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205512. NEWTEXTMETRICEXW*,
  205513. int type,
  205514. LPARAM lParam)
  205515. {
  205516. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205517. {
  205518. LOGFONTW lf;
  205519. zerostruct (lf);
  205520. lf.lfWeight = FW_DONTCARE;
  205521. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205522. lf.lfQuality = DEFAULT_QUALITY;
  205523. lf.lfCharSet = DEFAULT_CHARSET;
  205524. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205525. lf.lfPitchAndFamily = FF_DONTCARE;
  205526. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205527. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205528. HDC dc = CreateCompatibleDC (0);
  205529. EnumFontFamiliesEx (dc, &lf,
  205530. (FONTENUMPROCW) &wfontEnum2,
  205531. lParam, 0);
  205532. DeleteDC (dc);
  205533. }
  205534. return 1;
  205535. }
  205536. const StringArray Font::findAllTypefaceNames()
  205537. {
  205538. StringArray results;
  205539. HDC dc = CreateCompatibleDC (0);
  205540. {
  205541. LOGFONTW lf;
  205542. zerostruct (lf);
  205543. lf.lfWeight = FW_DONTCARE;
  205544. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205545. lf.lfQuality = DEFAULT_QUALITY;
  205546. lf.lfCharSet = DEFAULT_CHARSET;
  205547. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205548. lf.lfPitchAndFamily = FF_DONTCARE;
  205549. lf.lfFaceName[0] = 0;
  205550. EnumFontFamiliesEx (dc, &lf,
  205551. (FONTENUMPROCW) &wfontEnum1,
  205552. (LPARAM) &results, 0);
  205553. }
  205554. DeleteDC (dc);
  205555. results.sort (true);
  205556. return results;
  205557. }
  205558. extern bool juce_IsRunningInWine();
  205559. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  205560. {
  205561. if (juce_IsRunningInWine())
  205562. {
  205563. // If we're running in Wine, then use fonts that might be available on Linux..
  205564. defaultSans = "Bitstream Vera Sans";
  205565. defaultSerif = "Bitstream Vera Serif";
  205566. defaultFixed = "Bitstream Vera Sans Mono";
  205567. }
  205568. else
  205569. {
  205570. defaultSans = "Verdana";
  205571. defaultSerif = "Times";
  205572. defaultFixed = "Lucida Console";
  205573. }
  205574. }
  205575. class FontDCHolder : private DeletedAtShutdown
  205576. {
  205577. public:
  205578. FontDCHolder()
  205579. : dc (0), numKPs (0), size (0),
  205580. bold (false), italic (false)
  205581. {
  205582. }
  205583. ~FontDCHolder()
  205584. {
  205585. if (dc != 0)
  205586. {
  205587. DeleteDC (dc);
  205588. DeleteObject (fontH);
  205589. }
  205590. clearSingletonInstance();
  205591. }
  205592. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205593. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205594. {
  205595. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205596. {
  205597. fontName = fontName_;
  205598. bold = bold_;
  205599. italic = italic_;
  205600. size = size_;
  205601. if (dc != 0)
  205602. {
  205603. DeleteDC (dc);
  205604. DeleteObject (fontH);
  205605. kps.free();
  205606. }
  205607. fontH = 0;
  205608. dc = CreateCompatibleDC (0);
  205609. SetMapperFlags (dc, 0);
  205610. SetMapMode (dc, MM_TEXT);
  205611. LOGFONTW lfw;
  205612. zerostruct (lfw);
  205613. lfw.lfCharSet = DEFAULT_CHARSET;
  205614. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205615. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205616. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205617. lfw.lfQuality = PROOF_QUALITY;
  205618. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205619. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205620. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205621. lfw.lfHeight = size > 0 ? size : -256;
  205622. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205623. if (standardSizedFont != 0)
  205624. {
  205625. if (SelectObject (dc, standardSizedFont) != 0)
  205626. {
  205627. fontH = standardSizedFont;
  205628. if (size == 0)
  205629. {
  205630. OUTLINETEXTMETRIC otm;
  205631. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205632. {
  205633. lfw.lfHeight = -(int) otm.otmEMSquare;
  205634. fontH = CreateFontIndirect (&lfw);
  205635. SelectObject (dc, fontH);
  205636. DeleteObject (standardSizedFont);
  205637. }
  205638. }
  205639. }
  205640. else
  205641. {
  205642. jassertfalse;
  205643. }
  205644. }
  205645. else
  205646. {
  205647. jassertfalse;
  205648. }
  205649. }
  205650. return dc;
  205651. }
  205652. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205653. {
  205654. if (kps == 0)
  205655. {
  205656. numKPs = GetKerningPairs (dc, 0, 0);
  205657. kps.calloc (numKPs);
  205658. GetKerningPairs (dc, numKPs, kps);
  205659. }
  205660. numKPs_ = numKPs;
  205661. return kps;
  205662. }
  205663. private:
  205664. HFONT fontH;
  205665. HDC dc;
  205666. String fontName;
  205667. HeapBlock <KERNINGPAIR> kps;
  205668. int numKPs, size;
  205669. bool bold, italic;
  205670. FontDCHolder (const FontDCHolder&);
  205671. FontDCHolder& operator= (const FontDCHolder&);
  205672. };
  205673. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205674. class WindowsTypeface : public CustomTypeface
  205675. {
  205676. public:
  205677. WindowsTypeface (const Font& font)
  205678. {
  205679. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205680. font.isBold(), font.isItalic(), 0);
  205681. TEXTMETRIC tm;
  205682. tm.tmAscent = tm.tmHeight = 1;
  205683. tm.tmDefaultChar = 0;
  205684. GetTextMetrics (dc, &tm);
  205685. setCharacteristics (font.getTypefaceName(),
  205686. tm.tmAscent / (float) tm.tmHeight,
  205687. font.isBold(), font.isItalic(),
  205688. tm.tmDefaultChar);
  205689. }
  205690. bool loadGlyphIfPossible (juce_wchar character)
  205691. {
  205692. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205693. GLYPHMETRICS gm;
  205694. {
  205695. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205696. WORD index = 0;
  205697. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205698. && index == 0xffff)
  205699. {
  205700. return false;
  205701. }
  205702. }
  205703. Path glyphPath;
  205704. TEXTMETRIC tm;
  205705. if (! GetTextMetrics (dc, &tm))
  205706. {
  205707. addGlyph (character, glyphPath, 0);
  205708. return true;
  205709. }
  205710. const float height = (float) tm.tmHeight;
  205711. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205712. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205713. &gm, 0, 0, &identityMatrix);
  205714. if (bufSize > 0)
  205715. {
  205716. HeapBlock<char> data (bufSize);
  205717. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205718. bufSize, data, &identityMatrix);
  205719. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205720. const float scaleX = 1.0f / height;
  205721. const float scaleY = -1.0f / height;
  205722. while ((char*) pheader < data + bufSize)
  205723. {
  205724. float x = scaleX * pheader->pfxStart.x.value;
  205725. float y = scaleY * pheader->pfxStart.y.value;
  205726. glyphPath.startNewSubPath (x, y);
  205727. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205728. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205729. while ((const char*) curve < curveEnd)
  205730. {
  205731. if (curve->wType == TT_PRIM_LINE)
  205732. {
  205733. for (int i = 0; i < curve->cpfx; ++i)
  205734. {
  205735. x = scaleX * curve->apfx[i].x.value;
  205736. y = scaleY * curve->apfx[i].y.value;
  205737. glyphPath.lineTo (x, y);
  205738. }
  205739. }
  205740. else if (curve->wType == TT_PRIM_QSPLINE)
  205741. {
  205742. for (int i = 0; i < curve->cpfx - 1; ++i)
  205743. {
  205744. const float x2 = scaleX * curve->apfx[i].x.value;
  205745. const float y2 = scaleY * curve->apfx[i].y.value;
  205746. float x3, y3;
  205747. if (i < curve->cpfx - 2)
  205748. {
  205749. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205750. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205751. }
  205752. else
  205753. {
  205754. x3 = scaleX * curve->apfx[i + 1].x.value;
  205755. y3 = scaleY * curve->apfx[i + 1].y.value;
  205756. }
  205757. glyphPath.quadraticTo (x2, y2, x3, y3);
  205758. x = x3;
  205759. y = y3;
  205760. }
  205761. }
  205762. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205763. }
  205764. pheader = (const TTPOLYGONHEADER*) curve;
  205765. glyphPath.closeSubPath();
  205766. }
  205767. }
  205768. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205769. int numKPs;
  205770. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205771. for (int i = 0; i < numKPs; ++i)
  205772. {
  205773. if (kps[i].wFirst == character)
  205774. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205775. kps[i].iKernAmount / height);
  205776. }
  205777. return true;
  205778. }
  205779. juce_UseDebuggingNewOperator
  205780. };
  205781. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205782. {
  205783. return new WindowsTypeface (font);
  205784. }
  205785. #endif
  205786. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205787. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205788. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205789. // compiled on its own).
  205790. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205791. class SharedD2DFactory : public DeletedAtShutdown
  205792. {
  205793. public:
  205794. SharedD2DFactory()
  205795. {
  205796. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  205797. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  205798. if (directWriteFactory != 0)
  205799. directWriteFactory->GetSystemFontCollection (&systemFonts);
  205800. }
  205801. ~SharedD2DFactory()
  205802. {
  205803. clearSingletonInstance();
  205804. }
  205805. juce_DeclareSingleton (SharedD2DFactory, false);
  205806. ComSmartPtr <ID2D1Factory> d2dFactory;
  205807. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205808. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205809. };
  205810. juce_ImplementSingleton (SharedD2DFactory)
  205811. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205812. {
  205813. public:
  205814. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205815. : hwnd (hwnd_),
  205816. currentState (0)
  205817. {
  205818. RECT windowRect;
  205819. GetClientRect (hwnd, &windowRect);
  205820. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205821. bounds.setSize (size.width, size.height);
  205822. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205823. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205824. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  205825. // xxx check for error
  205826. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  205827. }
  205828. ~Direct2DLowLevelGraphicsContext()
  205829. {
  205830. states.clear();
  205831. }
  205832. void resized()
  205833. {
  205834. RECT windowRect;
  205835. GetClientRect (hwnd, &windowRect);
  205836. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205837. renderingTarget->Resize (size);
  205838. bounds.setSize (size.width, size.height);
  205839. }
  205840. void clear()
  205841. {
  205842. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205843. }
  205844. void start()
  205845. {
  205846. renderingTarget->BeginDraw();
  205847. saveState();
  205848. }
  205849. void end()
  205850. {
  205851. states.clear();
  205852. currentState = 0;
  205853. renderingTarget->EndDraw();
  205854. renderingTarget->CheckWindowState();
  205855. }
  205856. bool isVectorDevice() const { return false; }
  205857. void setOrigin (int x, int y)
  205858. {
  205859. currentState->origin.addXY (x, y);
  205860. }
  205861. bool clipToRectangle (const Rectangle<int>& r)
  205862. {
  205863. currentState->clipToRectangle (r);
  205864. return ! isClipEmpty();
  205865. }
  205866. bool clipToRectangleList (const RectangleList& clipRegion)
  205867. {
  205868. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205869. return ! isClipEmpty();
  205870. }
  205871. void excludeClipRectangle (const Rectangle<int>&)
  205872. {
  205873. //xxx
  205874. }
  205875. void clipToPath (const Path& path, const AffineTransform& transform)
  205876. {
  205877. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205878. }
  205879. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205880. {
  205881. currentState->clipToImage (sourceImage,transform);
  205882. }
  205883. bool clipRegionIntersects (const Rectangle<int>& r)
  205884. {
  205885. const Rectangle<int> r2 (r + currentState->origin);
  205886. return currentState->clipRect.intersects (r2);
  205887. }
  205888. const Rectangle<int> getClipBounds() const
  205889. {
  205890. // xxx could this take into account complex clip regions?
  205891. return currentState->clipRect - currentState->origin;
  205892. }
  205893. bool isClipEmpty() const
  205894. {
  205895. return currentState->clipRect.isEmpty();
  205896. }
  205897. void saveState()
  205898. {
  205899. states.add (new SavedState (*this));
  205900. currentState = states.getLast();
  205901. }
  205902. void restoreState()
  205903. {
  205904. jassert (states.size() > 1) //you should never pop the last state!
  205905. states.removeLast (1);
  205906. currentState = states.getLast();
  205907. }
  205908. void setFill (const FillType& fillType)
  205909. {
  205910. currentState->setFill (fillType);
  205911. }
  205912. void setOpacity (float newOpacity)
  205913. {
  205914. currentState->setOpacity (newOpacity);
  205915. }
  205916. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205917. {
  205918. }
  205919. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  205920. {
  205921. currentState->createBrush();
  205922. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  205923. }
  205924. void fillPath (const Path& p, const AffineTransform& transform)
  205925. {
  205926. currentState->createBrush();
  205927. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  205928. if (renderingTarget != 0)
  205929. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  205930. }
  205931. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  205932. {
  205933. const int x = currentState->origin.getX();
  205934. const int y = currentState->origin.getY();
  205935. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205936. D2D1_SIZE_U size;
  205937. size.width = image.getWidth();
  205938. size.height = image.getHeight();
  205939. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205940. Image img (image.convertedToFormat (Image::ARGB));
  205941. Image::BitmapData bd (img, false);
  205942. bp.pixelFormat = renderingTarget->GetPixelFormat();
  205943. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205944. {
  205945. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  205946. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  205947. if (tempBitmap != 0)
  205948. renderingTarget->DrawBitmap (tempBitmap);
  205949. }
  205950. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205951. }
  205952. void drawLine (const Line <float>& line)
  205953. {
  205954. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205955. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  205956. line.getEnd() + currentState->origin.toFloat());
  205957. currentState->createBrush();
  205958. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  205959. D2D1::Point2F (l.getEndX(), l.getEndY()),
  205960. currentState->currentBrush);
  205961. }
  205962. void drawVerticalLine (int x, float top, float bottom)
  205963. {
  205964. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205965. currentState->createBrush();
  205966. x += currentState->origin.getX();
  205967. const int y = currentState->origin.getY();
  205968. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  205969. D2D1::Point2F (x, y + bottom),
  205970. currentState->currentBrush);
  205971. }
  205972. void drawHorizontalLine (int y, float left, float right)
  205973. {
  205974. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205975. currentState->createBrush();
  205976. y += currentState->origin.getY();
  205977. const int x = currentState->origin.getX();
  205978. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  205979. D2D1::Point2F (x + right, y),
  205980. currentState->currentBrush);
  205981. }
  205982. void setFont (const Font& newFont)
  205983. {
  205984. currentState->setFont (newFont);
  205985. }
  205986. const Font getFont()
  205987. {
  205988. return currentState->font;
  205989. }
  205990. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  205991. {
  205992. const float x = currentState->origin.getX();
  205993. const float y = currentState->origin.getY();
  205994. currentState->createBrush();
  205995. currentState->createFont();
  205996. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  205997. float hScale = currentState->font.getHorizontalScale();
  205998. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205999. float dpiX = 0, dpiY = 0;
  206000. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  206001. UINT32 glyphNum = glyphNumber;
  206002. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  206003. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  206004. DWRITE_GLYPH_OFFSET offset;
  206005. offset.advanceOffset = 0;
  206006. offset.ascenderOffset = 0;
  206007. float glyphAdvances = 0;
  206008. DWRITE_GLYPH_RUN glyph;
  206009. glyph.fontFace = currentState->currentFontFace;
  206010. glyph.glyphCount = 1;
  206011. glyph.glyphIndices = &glyphNum1;
  206012. glyph.isSideways = FALSE;
  206013. glyph.glyphAdvances = &glyphAdvances;
  206014. glyph.glyphOffsets = &offset;
  206015. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  206016. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  206017. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206018. }
  206019. class SavedState
  206020. {
  206021. public:
  206022. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  206023. : owner (owner_), currentBrush (0),
  206024. fontScaling (1.0f), currentFontFace (0),
  206025. clipsRect (false), shouldClipRect (false),
  206026. clipsRectList (false), shouldClipRectList (false),
  206027. clipsComplex (false), shouldClipComplex (false),
  206028. clipsBitmap (false), shouldClipBitmap (false)
  206029. {
  206030. if (owner.currentState != 0)
  206031. {
  206032. // xxx seems like a very slow way to create one of these, and this is a performance
  206033. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  206034. setFill (owner.currentState->fillType);
  206035. currentBrush = owner.currentState->currentBrush;
  206036. origin = owner.currentState->origin;
  206037. clipRect = owner.currentState->clipRect;
  206038. font = owner.currentState->font;
  206039. currentFontFace = owner.currentState->currentFontFace;
  206040. }
  206041. else
  206042. {
  206043. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206044. clipRect.setSize (size.width, size.height);
  206045. setFill (FillType (Colours::black));
  206046. }
  206047. }
  206048. ~SavedState()
  206049. {
  206050. clearClip();
  206051. clearFont();
  206052. clearFill();
  206053. clearPathClip();
  206054. clearImageClip();
  206055. complexClipLayer = 0;
  206056. bitmapMaskLayer = 0;
  206057. }
  206058. void clearClip()
  206059. {
  206060. popClips();
  206061. shouldClipRect = false;
  206062. }
  206063. void clipToRectangle (const Rectangle<int>& r)
  206064. {
  206065. clearClip();
  206066. clipRect = r + origin;
  206067. shouldClipRect = true;
  206068. pushClips();
  206069. }
  206070. void clearPathClip()
  206071. {
  206072. popClips();
  206073. if (shouldClipComplex)
  206074. {
  206075. complexClipGeometry = 0;
  206076. shouldClipComplex = false;
  206077. }
  206078. }
  206079. void clipToPath (ID2D1Geometry* geometry)
  206080. {
  206081. clearPathClip();
  206082. if (complexClipLayer == 0)
  206083. owner.renderingTarget->CreateLayer (&complexClipLayer);
  206084. complexClipGeometry = geometry;
  206085. shouldClipComplex = true;
  206086. pushClips();
  206087. }
  206088. void clearRectListClip()
  206089. {
  206090. popClips();
  206091. if (shouldClipRectList)
  206092. {
  206093. rectListGeometry = 0;
  206094. shouldClipRectList = false;
  206095. }
  206096. }
  206097. void clipToRectList (ID2D1Geometry* geometry)
  206098. {
  206099. clearRectListClip();
  206100. if (rectListLayer == 0)
  206101. owner.renderingTarget->CreateLayer (&rectListLayer);
  206102. rectListGeometry = geometry;
  206103. shouldClipRectList = true;
  206104. pushClips();
  206105. }
  206106. void clearImageClip()
  206107. {
  206108. popClips();
  206109. if (shouldClipBitmap)
  206110. {
  206111. maskBitmap = 0;
  206112. bitmapMaskBrush = 0;
  206113. shouldClipBitmap = false;
  206114. }
  206115. }
  206116. void clipToImage (const Image& image, const AffineTransform& transform)
  206117. {
  206118. clearImageClip();
  206119. if (bitmapMaskLayer == 0)
  206120. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  206121. D2D1_BRUSH_PROPERTIES brushProps;
  206122. brushProps.opacity = 1;
  206123. brushProps.transform = transfromToMatrix (transform);
  206124. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206125. D2D1_SIZE_U size;
  206126. size.width = image.getWidth();
  206127. size.height = image.getHeight();
  206128. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206129. maskImage = image.convertedToFormat (Image::ARGB);
  206130. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  206131. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206132. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206133. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  206134. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  206135. imageMaskLayerParams = D2D1::LayerParameters();
  206136. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206137. shouldClipBitmap = true;
  206138. pushClips();
  206139. }
  206140. void popClips()
  206141. {
  206142. if (clipsBitmap)
  206143. {
  206144. owner.renderingTarget->PopLayer();
  206145. clipsBitmap = false;
  206146. }
  206147. if (clipsComplex)
  206148. {
  206149. owner.renderingTarget->PopLayer();
  206150. clipsComplex = false;
  206151. }
  206152. if (clipsRectList)
  206153. {
  206154. owner.renderingTarget->PopLayer();
  206155. clipsRectList = false;
  206156. }
  206157. if (clipsRect)
  206158. {
  206159. owner.renderingTarget->PopAxisAlignedClip();
  206160. clipsRect = false;
  206161. }
  206162. }
  206163. void pushClips()
  206164. {
  206165. if (shouldClipRect && ! clipsRect)
  206166. {
  206167. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206168. clipsRect = true;
  206169. }
  206170. if (shouldClipRectList && ! clipsRectList)
  206171. {
  206172. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206173. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206174. layerParams.geometricMask = rectListGeometry;
  206175. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206176. clipsRectList = true;
  206177. }
  206178. if (shouldClipComplex && ! clipsComplex)
  206179. {
  206180. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206181. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206182. layerParams.geometricMask = complexClipGeometry;
  206183. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206184. clipsComplex = true;
  206185. }
  206186. if (shouldClipBitmap && ! clipsBitmap)
  206187. {
  206188. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206189. clipsBitmap = true;
  206190. }
  206191. }
  206192. void setFill (const FillType& newFillType)
  206193. {
  206194. if (fillType != newFillType)
  206195. {
  206196. fillType = newFillType;
  206197. clearFill();
  206198. }
  206199. }
  206200. void clearFont()
  206201. {
  206202. currentFontFace = localFontFace = 0;
  206203. }
  206204. void setFont (const Font& newFont)
  206205. {
  206206. if (font != newFont)
  206207. {
  206208. font = newFont;
  206209. clearFont();
  206210. }
  206211. }
  206212. void createFont()
  206213. {
  206214. // xxx The font shouldn't be managed by the graphics context.
  206215. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206216. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206217. // WindowsTypeface class.
  206218. if (currentFontFace == 0)
  206219. {
  206220. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206221. fontScaling = systemType->getAscent();
  206222. BOOL fontFound;
  206223. uint32 fontIndex;
  206224. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206225. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206226. if (! fontFound)
  206227. fontIndex = 0;
  206228. ComSmartPtr <IDWriteFontFamily> fontFam;
  206229. fonts->GetFontFamily (fontIndex, &fontFam);
  206230. ComSmartPtr <IDWriteFont> font;
  206231. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206232. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206233. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206234. font->CreateFontFace (&localFontFace);
  206235. currentFontFace = localFontFace;
  206236. }
  206237. }
  206238. void setOpacity (float newOpacity)
  206239. {
  206240. fillType.setOpacity (newOpacity);
  206241. if (currentBrush != 0)
  206242. currentBrush->SetOpacity (newOpacity);
  206243. }
  206244. void clearFill()
  206245. {
  206246. gradientStops = 0;
  206247. linearGradient = 0;
  206248. radialGradient = 0;
  206249. bitmap = 0;
  206250. bitmapBrush = 0;
  206251. currentBrush = 0;
  206252. }
  206253. void createBrush()
  206254. {
  206255. if (currentBrush == 0)
  206256. {
  206257. const int x = origin.getX();
  206258. const int y = origin.getY();
  206259. if (fillType.isColour())
  206260. {
  206261. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206262. owner.colourBrush->SetColor (colour);
  206263. currentBrush = owner.colourBrush;
  206264. }
  206265. else if (fillType.isTiledImage())
  206266. {
  206267. D2D1_BRUSH_PROPERTIES brushProps;
  206268. brushProps.opacity = fillType.getOpacity();
  206269. brushProps.transform = transfromToMatrix (fillType.transform);
  206270. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206271. image = fillType.image;
  206272. D2D1_SIZE_U size;
  206273. size.width = image.getWidth();
  206274. size.height = image.getHeight();
  206275. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206276. this->image = image.convertedToFormat (Image::ARGB);
  206277. Image::BitmapData bd (this->image, false);
  206278. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206279. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206280. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206281. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206282. currentBrush = bitmapBrush;
  206283. }
  206284. else if (fillType.isGradient())
  206285. {
  206286. gradientStops = 0;
  206287. D2D1_BRUSH_PROPERTIES brushProps;
  206288. brushProps.opacity = fillType.getOpacity();
  206289. brushProps.transform = transfromToMatrix (fillType.transform);
  206290. const int numColors = fillType.gradient->getNumColours();
  206291. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206292. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206293. {
  206294. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206295. stops[i].position = fillType.gradient->getColourPosition(i);
  206296. }
  206297. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206298. if (fillType.gradient->isRadial)
  206299. {
  206300. radialGradient = 0;
  206301. const Point<float>& p1 = fillType.gradient->point1;
  206302. const Point<float>& p2 = fillType.gradient->point2;
  206303. float r = p1.getDistanceFrom (p2);
  206304. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206305. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206306. D2D1::Point2F (0, 0),
  206307. r, r);
  206308. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206309. currentBrush = radialGradient;
  206310. }
  206311. else
  206312. {
  206313. linearGradient = 0;
  206314. const Point<float>& p1 = fillType.gradient->point1;
  206315. const Point<float>& p2 = fillType.gradient->point2;
  206316. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206317. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206318. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206319. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206320. currentBrush = linearGradient;
  206321. }
  206322. }
  206323. }
  206324. }
  206325. juce_UseDebuggingNewOperator
  206326. //xxx most of these members should probably be private...
  206327. Direct2DLowLevelGraphicsContext& owner;
  206328. Point<int> origin;
  206329. Font font;
  206330. float fontScaling;
  206331. IDWriteFontFace* currentFontFace;
  206332. ComSmartPtr <IDWriteFontFace> localFontFace;
  206333. FillType fillType;
  206334. Image image;
  206335. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206336. Rectangle<int> clipRect;
  206337. bool clipsRect, shouldClipRect;
  206338. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206339. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206340. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206341. bool clipsComplex, shouldClipComplex;
  206342. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206343. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206344. ComSmartPtr <ID2D1Layer> rectListLayer;
  206345. bool clipsRectList, shouldClipRectList;
  206346. Image maskImage;
  206347. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206348. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206349. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206350. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206351. bool clipsBitmap, shouldClipBitmap;
  206352. ID2D1Brush* currentBrush;
  206353. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206354. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206355. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206356. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206357. private:
  206358. SavedState (const SavedState&);
  206359. SavedState& operator= (const SavedState& other);
  206360. };
  206361. juce_UseDebuggingNewOperator
  206362. private:
  206363. HWND hwnd;
  206364. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206365. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206366. Rectangle<int> bounds;
  206367. SavedState* currentState;
  206368. OwnedArray<SavedState> states;
  206369. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206370. {
  206371. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206372. }
  206373. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206374. {
  206375. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206376. }
  206377. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206378. {
  206379. transform.transformPoint (x, y);
  206380. return D2D1::Point2F (x, y);
  206381. }
  206382. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206383. {
  206384. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206385. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206386. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206387. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206388. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206389. }
  206390. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206391. {
  206392. ID2D1PathGeometry* p = 0;
  206393. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206394. ComSmartPtr <ID2D1GeometrySink> sink;
  206395. HRESULT hr = p->Open (&sink); // xxx handle error
  206396. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206397. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206398. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206399. hr = sink->Close();
  206400. return p;
  206401. }
  206402. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206403. {
  206404. Path::Iterator it (path);
  206405. while (it.next())
  206406. {
  206407. switch (it.elementType)
  206408. {
  206409. case Path::Iterator::cubicTo:
  206410. {
  206411. D2D1_BEZIER_SEGMENT seg;
  206412. transform.transformPoint (it.x1, it.y1);
  206413. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206414. transform.transformPoint (it.x2, it.y2);
  206415. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206416. transform.transformPoint(it.x3, it.y3);
  206417. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206418. sink->AddBezier (seg);
  206419. break;
  206420. }
  206421. case Path::Iterator::lineTo:
  206422. {
  206423. transform.transformPoint (it.x1, it.y1);
  206424. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206425. break;
  206426. }
  206427. case Path::Iterator::quadraticTo:
  206428. {
  206429. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206430. transform.transformPoint (it.x1, it.y1);
  206431. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206432. transform.transformPoint (it.x2, it.y2);
  206433. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206434. sink->AddQuadraticBezier (seg);
  206435. break;
  206436. }
  206437. case Path::Iterator::closePath:
  206438. {
  206439. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206440. break;
  206441. }
  206442. case Path::Iterator::startNewSubPath:
  206443. {
  206444. transform.transformPoint (it.x1, it.y1);
  206445. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206446. break;
  206447. }
  206448. }
  206449. }
  206450. }
  206451. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206452. {
  206453. ID2D1PathGeometry* p = 0;
  206454. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206455. ComSmartPtr <ID2D1GeometrySink> sink;
  206456. HRESULT hr = p->Open (&sink);
  206457. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206458. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206459. hr = sink->Close();
  206460. return p;
  206461. }
  206462. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206463. {
  206464. D2D1::Matrix3x2F matrix;
  206465. matrix._11 = transform.mat00;
  206466. matrix._12 = transform.mat10;
  206467. matrix._21 = transform.mat01;
  206468. matrix._22 = transform.mat11;
  206469. matrix._31 = transform.mat02;
  206470. matrix._32 = transform.mat12;
  206471. return matrix;
  206472. }
  206473. };
  206474. #endif
  206475. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206476. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206477. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206478. // compiled on its own).
  206479. #if JUCE_INCLUDED_FILE
  206480. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206481. // these are in the windows SDK, but need to be repeated here for GCC..
  206482. #ifndef GET_APPCOMMAND_LPARAM
  206483. #define FAPPCOMMAND_MASK 0xF000
  206484. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206485. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206486. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206487. #define APPCOMMAND_MEDIA_STOP 13
  206488. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206489. #define WM_APPCOMMAND 0x0319
  206490. #endif
  206491. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206492. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206493. extern bool juce_IsRunningInWine();
  206494. #ifndef ULW_ALPHA
  206495. #define ULW_ALPHA 0x00000002
  206496. #endif
  206497. #ifndef AC_SRC_ALPHA
  206498. #define AC_SRC_ALPHA 0x01
  206499. #endif
  206500. static HPALETTE palette = 0;
  206501. static bool createPaletteIfNeeded = true;
  206502. static bool shouldDeactivateTitleBar = true;
  206503. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY);
  206504. #define WM_TRAYNOTIFY WM_USER + 100
  206505. using ::abs;
  206506. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206507. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206508. bool Desktop::canUseSemiTransparentWindows() throw()
  206509. {
  206510. if (updateLayeredWindow == 0)
  206511. {
  206512. if (! juce_IsRunningInWine())
  206513. {
  206514. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206515. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206516. }
  206517. }
  206518. return updateLayeredWindow != 0;
  206519. }
  206520. const int extendedKeyModifier = 0x10000;
  206521. const int KeyPress::spaceKey = VK_SPACE;
  206522. const int KeyPress::returnKey = VK_RETURN;
  206523. const int KeyPress::escapeKey = VK_ESCAPE;
  206524. const int KeyPress::backspaceKey = VK_BACK;
  206525. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206526. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206527. const int KeyPress::tabKey = VK_TAB;
  206528. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206529. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206530. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206531. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206532. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206533. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206534. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206535. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206536. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206537. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206538. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206539. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206540. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206541. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206542. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206543. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206544. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206545. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206546. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206547. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206548. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206549. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206550. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206551. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206552. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206553. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206554. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206555. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206556. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206557. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206558. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206559. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206560. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206561. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206562. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206563. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206564. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206565. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206566. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206567. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206568. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206569. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206570. const int KeyPress::playKey = 0x30000;
  206571. const int KeyPress::stopKey = 0x30001;
  206572. const int KeyPress::fastForwardKey = 0x30002;
  206573. const int KeyPress::rewindKey = 0x30003;
  206574. class WindowsBitmapImage : public Image::SharedImage
  206575. {
  206576. public:
  206577. HBITMAP hBitmap;
  206578. BITMAPV4HEADER bitmapInfo;
  206579. HDC hdc;
  206580. unsigned char* bitmapData;
  206581. WindowsBitmapImage (const Image::PixelFormat format_,
  206582. const int w, const int h, const bool clearImage)
  206583. : Image::SharedImage (format_, w, h)
  206584. {
  206585. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206586. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206587. zerostruct (bitmapInfo);
  206588. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206589. bitmapInfo.bV4Width = w;
  206590. bitmapInfo.bV4Height = h;
  206591. bitmapInfo.bV4Planes = 1;
  206592. bitmapInfo.bV4CSType = 1;
  206593. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206594. if (format_ == Image::ARGB)
  206595. {
  206596. bitmapInfo.bV4AlphaMask = 0xff000000;
  206597. bitmapInfo.bV4RedMask = 0xff0000;
  206598. bitmapInfo.bV4GreenMask = 0xff00;
  206599. bitmapInfo.bV4BlueMask = 0xff;
  206600. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206601. }
  206602. else
  206603. {
  206604. bitmapInfo.bV4V4Compression = BI_RGB;
  206605. }
  206606. lineStride = -((w * pixelStride + 3) & ~3);
  206607. HDC dc = GetDC (0);
  206608. hdc = CreateCompatibleDC (dc);
  206609. ReleaseDC (0, dc);
  206610. SetMapMode (hdc, MM_TEXT);
  206611. hBitmap = CreateDIBSection (hdc,
  206612. (BITMAPINFO*) &(bitmapInfo),
  206613. DIB_RGB_COLORS,
  206614. (void**) &bitmapData,
  206615. 0, 0);
  206616. SelectObject (hdc, hBitmap);
  206617. if (format_ == Image::ARGB && clearImage)
  206618. zeromem (bitmapData, abs (h * lineStride));
  206619. imageData = bitmapData - (lineStride * (h - 1));
  206620. }
  206621. ~WindowsBitmapImage()
  206622. {
  206623. DeleteDC (hdc);
  206624. DeleteObject (hBitmap);
  206625. }
  206626. Image::ImageType getType() const { return Image::NativeImage; }
  206627. LowLevelGraphicsContext* createLowLevelContext()
  206628. {
  206629. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206630. }
  206631. SharedImage* clone()
  206632. {
  206633. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206634. for (int i = 0; i < height; ++i)
  206635. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206636. return im;
  206637. }
  206638. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206639. const int x, const int y,
  206640. const RectangleList& maskedRegion) throw()
  206641. {
  206642. static HDRAWDIB hdd = 0;
  206643. static bool needToCreateDrawDib = true;
  206644. if (needToCreateDrawDib)
  206645. {
  206646. needToCreateDrawDib = false;
  206647. HDC dc = GetDC (0);
  206648. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206649. ReleaseDC (0, dc);
  206650. // only open if we're not palettised
  206651. if (n > 8)
  206652. hdd = DrawDibOpen();
  206653. }
  206654. if (createPaletteIfNeeded)
  206655. {
  206656. HDC dc = GetDC (0);
  206657. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206658. ReleaseDC (0, dc);
  206659. if (n <= 8)
  206660. palette = CreateHalftonePalette (dc);
  206661. createPaletteIfNeeded = false;
  206662. }
  206663. if (palette != 0)
  206664. {
  206665. SelectPalette (dc, palette, FALSE);
  206666. RealizePalette (dc);
  206667. SetStretchBltMode (dc, HALFTONE);
  206668. }
  206669. SetMapMode (dc, MM_TEXT);
  206670. if (transparent)
  206671. {
  206672. POINT p, pos;
  206673. SIZE size;
  206674. RECT windowBounds;
  206675. GetWindowRect (hwnd, &windowBounds);
  206676. p.x = -x;
  206677. p.y = -y;
  206678. pos.x = windowBounds.left;
  206679. pos.y = windowBounds.top;
  206680. size.cx = windowBounds.right - windowBounds.left;
  206681. size.cy = windowBounds.bottom - windowBounds.top;
  206682. BLENDFUNCTION bf;
  206683. bf.AlphaFormat = AC_SRC_ALPHA;
  206684. bf.BlendFlags = 0;
  206685. bf.BlendOp = AC_SRC_OVER;
  206686. bf.SourceConstantAlpha = 0xff;
  206687. if (! maskedRegion.isEmpty())
  206688. {
  206689. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206690. {
  206691. const Rectangle<int>& r = *i.getRectangle();
  206692. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206693. }
  206694. }
  206695. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206696. }
  206697. else
  206698. {
  206699. int savedDC = 0;
  206700. if (! maskedRegion.isEmpty())
  206701. {
  206702. savedDC = SaveDC (dc);
  206703. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206704. {
  206705. const Rectangle<int>& r = *i.getRectangle();
  206706. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206707. }
  206708. }
  206709. if (hdd == 0)
  206710. {
  206711. StretchDIBits (dc,
  206712. x, y, width, height,
  206713. 0, 0, width, height,
  206714. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206715. DIB_RGB_COLORS, SRCCOPY);
  206716. }
  206717. else
  206718. {
  206719. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206720. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206721. 0, 0, width, height, 0);
  206722. }
  206723. if (! maskedRegion.isEmpty())
  206724. RestoreDC (dc, savedDC);
  206725. }
  206726. }
  206727. juce_UseDebuggingNewOperator
  206728. private:
  206729. WindowsBitmapImage (const WindowsBitmapImage&);
  206730. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  206731. };
  206732. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206733. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206734. {
  206735. SHORT k = (SHORT) keyCode;
  206736. if ((keyCode & extendedKeyModifier) == 0
  206737. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206738. k += (SHORT) 'A' - (SHORT) 'a';
  206739. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206740. (SHORT) '+', VK_OEM_PLUS,
  206741. (SHORT) '-', VK_OEM_MINUS,
  206742. (SHORT) '.', VK_OEM_PERIOD,
  206743. (SHORT) ';', VK_OEM_1,
  206744. (SHORT) ':', VK_OEM_1,
  206745. (SHORT) '/', VK_OEM_2,
  206746. (SHORT) '?', VK_OEM_2,
  206747. (SHORT) '[', VK_OEM_4,
  206748. (SHORT) ']', VK_OEM_6 };
  206749. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206750. if (k == translatedValues [i])
  206751. k = translatedValues [i + 1];
  206752. return (GetKeyState (k) & 0x8000) != 0;
  206753. }
  206754. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  206755. {
  206756. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  206757. return callback (userData);
  206758. else
  206759. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  206760. }
  206761. class Win32ComponentPeer : public ComponentPeer
  206762. {
  206763. public:
  206764. enum RenderingEngineType
  206765. {
  206766. softwareRenderingEngine = 0,
  206767. direct2DRenderingEngine
  206768. };
  206769. Win32ComponentPeer (Component* const component,
  206770. const int windowStyleFlags,
  206771. HWND parentToAddTo_)
  206772. : ComponentPeer (component, windowStyleFlags),
  206773. dontRepaint (false),
  206774. #if JUCE_DIRECT2D
  206775. currentRenderingEngine (direct2DRenderingEngine),
  206776. #else
  206777. currentRenderingEngine (softwareRenderingEngine),
  206778. #endif
  206779. fullScreen (false),
  206780. isDragging (false),
  206781. isMouseOver (false),
  206782. hasCreatedCaret (false),
  206783. currentWindowIcon (0),
  206784. dropTarget (0),
  206785. parentToAddTo (parentToAddTo_)
  206786. {
  206787. callFunctionIfNotLocked (&createWindowCallback, this);
  206788. setTitle (component->getName());
  206789. if ((windowStyleFlags & windowHasDropShadow) != 0
  206790. && Desktop::canUseSemiTransparentWindows())
  206791. {
  206792. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206793. if (shadower != 0)
  206794. shadower->setOwner (component);
  206795. }
  206796. }
  206797. ~Win32ComponentPeer()
  206798. {
  206799. setTaskBarIcon (Image());
  206800. shadower = 0;
  206801. // do this before the next bit to avoid messages arriving for this window
  206802. // before it's destroyed
  206803. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206804. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206805. if (currentWindowIcon != 0)
  206806. DestroyIcon (currentWindowIcon);
  206807. if (dropTarget != 0)
  206808. {
  206809. dropTarget->Release();
  206810. dropTarget = 0;
  206811. }
  206812. #if JUCE_DIRECT2D
  206813. direct2DContext = 0;
  206814. #endif
  206815. }
  206816. void* getNativeHandle() const
  206817. {
  206818. return hwnd;
  206819. }
  206820. void setVisible (bool shouldBeVisible)
  206821. {
  206822. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206823. if (shouldBeVisible)
  206824. InvalidateRect (hwnd, 0, 0);
  206825. else
  206826. lastPaintTime = 0;
  206827. }
  206828. void setTitle (const String& title)
  206829. {
  206830. SetWindowText (hwnd, title);
  206831. }
  206832. void setPosition (int x, int y)
  206833. {
  206834. offsetWithinParent (x, y);
  206835. SetWindowPos (hwnd, 0,
  206836. x - windowBorder.getLeft(),
  206837. y - windowBorder.getTop(),
  206838. 0, 0,
  206839. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206840. }
  206841. void repaintNowIfTransparent()
  206842. {
  206843. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206844. handlePaintMessage();
  206845. }
  206846. void updateBorderSize()
  206847. {
  206848. WINDOWINFO info;
  206849. info.cbSize = sizeof (info);
  206850. if (GetWindowInfo (hwnd, &info))
  206851. {
  206852. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  206853. info.rcClient.left - info.rcWindow.left,
  206854. info.rcWindow.bottom - info.rcClient.bottom,
  206855. info.rcWindow.right - info.rcClient.right);
  206856. }
  206857. #if JUCE_DIRECT2D
  206858. if (direct2DContext != 0)
  206859. direct2DContext->resized();
  206860. #endif
  206861. }
  206862. void setSize (int w, int h)
  206863. {
  206864. SetWindowPos (hwnd, 0, 0, 0,
  206865. w + windowBorder.getLeftAndRight(),
  206866. h + windowBorder.getTopAndBottom(),
  206867. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206868. updateBorderSize();
  206869. repaintNowIfTransparent();
  206870. }
  206871. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206872. {
  206873. fullScreen = isNowFullScreen;
  206874. offsetWithinParent (x, y);
  206875. SetWindowPos (hwnd, 0,
  206876. x - windowBorder.getLeft(),
  206877. y - windowBorder.getTop(),
  206878. w + windowBorder.getLeftAndRight(),
  206879. h + windowBorder.getTopAndBottom(),
  206880. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206881. updateBorderSize();
  206882. repaintNowIfTransparent();
  206883. }
  206884. const Rectangle<int> getBounds() const
  206885. {
  206886. RECT r;
  206887. GetWindowRect (hwnd, &r);
  206888. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  206889. HWND parentH = GetParent (hwnd);
  206890. if (parentH != 0)
  206891. {
  206892. GetWindowRect (parentH, &r);
  206893. bounds.translate (-r.left, -r.top);
  206894. }
  206895. return windowBorder.subtractedFrom (bounds);
  206896. }
  206897. const Point<int> getScreenPosition() const
  206898. {
  206899. RECT r;
  206900. GetWindowRect (hwnd, &r);
  206901. return Point<int> (r.left + windowBorder.getLeft(),
  206902. r.top + windowBorder.getTop());
  206903. }
  206904. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  206905. {
  206906. return relativePosition + getScreenPosition();
  206907. }
  206908. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  206909. {
  206910. return screenPosition - getScreenPosition();
  206911. }
  206912. void setMinimised (bool shouldBeMinimised)
  206913. {
  206914. if (shouldBeMinimised != isMinimised())
  206915. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206916. }
  206917. bool isMinimised() const
  206918. {
  206919. WINDOWPLACEMENT wp;
  206920. wp.length = sizeof (WINDOWPLACEMENT);
  206921. GetWindowPlacement (hwnd, &wp);
  206922. return wp.showCmd == SW_SHOWMINIMIZED;
  206923. }
  206924. void setFullScreen (bool shouldBeFullScreen)
  206925. {
  206926. setMinimised (false);
  206927. if (fullScreen != shouldBeFullScreen)
  206928. {
  206929. fullScreen = shouldBeFullScreen;
  206930. const Component::SafePointer<Component> deletionChecker (component);
  206931. if (! fullScreen)
  206932. {
  206933. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  206934. if (hasTitleBar())
  206935. ShowWindow (hwnd, SW_SHOWNORMAL);
  206936. if (! boundsCopy.isEmpty())
  206937. {
  206938. setBounds (boundsCopy.getX(),
  206939. boundsCopy.getY(),
  206940. boundsCopy.getWidth(),
  206941. boundsCopy.getHeight(),
  206942. false);
  206943. }
  206944. }
  206945. else
  206946. {
  206947. if (hasTitleBar())
  206948. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  206949. else
  206950. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  206951. }
  206952. if (deletionChecker != 0)
  206953. handleMovedOrResized();
  206954. }
  206955. }
  206956. bool isFullScreen() const
  206957. {
  206958. if (! hasTitleBar())
  206959. return fullScreen;
  206960. WINDOWPLACEMENT wp;
  206961. wp.length = sizeof (wp);
  206962. GetWindowPlacement (hwnd, &wp);
  206963. return wp.showCmd == SW_SHOWMAXIMIZED;
  206964. }
  206965. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  206966. {
  206967. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  206968. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  206969. return false;
  206970. RECT r;
  206971. GetWindowRect (hwnd, &r);
  206972. POINT p;
  206973. p.x = position.getX() + r.left + windowBorder.getLeft();
  206974. p.y = position.getY() + r.top + windowBorder.getTop();
  206975. HWND w = WindowFromPoint (p);
  206976. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  206977. }
  206978. const BorderSize getFrameSize() const
  206979. {
  206980. return windowBorder;
  206981. }
  206982. bool setAlwaysOnTop (bool alwaysOnTop)
  206983. {
  206984. const bool oldDeactivate = shouldDeactivateTitleBar;
  206985. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206986. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  206987. 0, 0, 0, 0,
  206988. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206989. shouldDeactivateTitleBar = oldDeactivate;
  206990. if (shadower != 0)
  206991. shadower->componentBroughtToFront (*component);
  206992. return true;
  206993. }
  206994. void toFront (bool makeActive)
  206995. {
  206996. setMinimised (false);
  206997. const bool oldDeactivate = shouldDeactivateTitleBar;
  206998. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206999. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  207000. shouldDeactivateTitleBar = oldDeactivate;
  207001. if (! makeActive)
  207002. {
  207003. // in this case a broughttofront call won't have occured, so do it now..
  207004. handleBroughtToFront();
  207005. }
  207006. }
  207007. void toBehind (ComponentPeer* other)
  207008. {
  207009. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  207010. jassert (otherPeer != 0); // wrong type of window?
  207011. if (otherPeer != 0)
  207012. {
  207013. setMinimised (false);
  207014. // must be careful not to try to put a topmost window behind a normal one, or win32
  207015. // promotes the normal one to be topmost!
  207016. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207017. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207018. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207019. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207020. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207021. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207022. }
  207023. }
  207024. bool isFocused() const
  207025. {
  207026. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207027. }
  207028. void grabFocus()
  207029. {
  207030. const bool oldDeactivate = shouldDeactivateTitleBar;
  207031. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207032. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207033. shouldDeactivateTitleBar = oldDeactivate;
  207034. }
  207035. void textInputRequired (const Point<int>&)
  207036. {
  207037. if (! hasCreatedCaret)
  207038. {
  207039. hasCreatedCaret = true;
  207040. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207041. }
  207042. ShowCaret (hwnd);
  207043. SetCaretPos (0, 0);
  207044. }
  207045. void repaint (const Rectangle<int>& area)
  207046. {
  207047. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207048. InvalidateRect (hwnd, &r, FALSE);
  207049. }
  207050. void performAnyPendingRepaintsNow()
  207051. {
  207052. MSG m;
  207053. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207054. DispatchMessage (&m);
  207055. }
  207056. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207057. {
  207058. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207059. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207060. return 0;
  207061. }
  207062. void setTaskBarIcon (const Image& image)
  207063. {
  207064. if (image.isValid())
  207065. {
  207066. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  207067. if (taskBarIcon == 0)
  207068. {
  207069. taskBarIcon = new NOTIFYICONDATA();
  207070. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207071. taskBarIcon->hWnd = (HWND) hwnd;
  207072. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207073. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207074. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207075. taskBarIcon->hIcon = hicon;
  207076. taskBarIcon->szTip[0] = 0;
  207077. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207078. }
  207079. else
  207080. {
  207081. HICON oldIcon = taskBarIcon->hIcon;
  207082. taskBarIcon->hIcon = hicon;
  207083. taskBarIcon->uFlags = NIF_ICON;
  207084. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207085. DestroyIcon (oldIcon);
  207086. }
  207087. DestroyIcon (hicon);
  207088. }
  207089. else if (taskBarIcon != 0)
  207090. {
  207091. taskBarIcon->uFlags = 0;
  207092. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207093. DestroyIcon (taskBarIcon->hIcon);
  207094. taskBarIcon = 0;
  207095. }
  207096. }
  207097. void setTaskBarIconToolTip (const String& toolTip) const
  207098. {
  207099. if (taskBarIcon != 0)
  207100. {
  207101. taskBarIcon->uFlags = NIF_TIP;
  207102. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207103. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207104. }
  207105. }
  207106. bool isInside (HWND h) const
  207107. {
  207108. return GetAncestor (hwnd, GA_ROOT) == h;
  207109. }
  207110. static void updateKeyModifiers() throw()
  207111. {
  207112. int keyMods = 0;
  207113. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207114. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207115. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207116. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207117. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207118. }
  207119. static void updateModifiersFromWParam (const WPARAM wParam)
  207120. {
  207121. int mouseMods = 0;
  207122. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207123. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207124. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207125. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207126. updateKeyModifiers();
  207127. }
  207128. static int64 getMouseEventTime()
  207129. {
  207130. static int64 eventTimeOffset = 0;
  207131. static DWORD lastMessageTime = 0;
  207132. const DWORD thisMessageTime = GetMessageTime();
  207133. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207134. {
  207135. lastMessageTime = thisMessageTime;
  207136. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207137. }
  207138. return eventTimeOffset + thisMessageTime;
  207139. }
  207140. juce_UseDebuggingNewOperator
  207141. bool dontRepaint;
  207142. static ModifierKeys currentModifiers;
  207143. static ModifierKeys modifiersAtLastCallback;
  207144. private:
  207145. HWND hwnd, parentToAddTo;
  207146. ScopedPointer<DropShadower> shadower;
  207147. RenderingEngineType currentRenderingEngine;
  207148. #if JUCE_DIRECT2D
  207149. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207150. #endif
  207151. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  207152. BorderSize windowBorder;
  207153. HICON currentWindowIcon;
  207154. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207155. IDropTarget* dropTarget;
  207156. class TemporaryImage : public Timer
  207157. {
  207158. public:
  207159. TemporaryImage() {}
  207160. ~TemporaryImage() {}
  207161. const Image& getImage (const bool transparent, const int w, const int h)
  207162. {
  207163. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207164. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207165. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207166. startTimer (3000);
  207167. return image;
  207168. }
  207169. void timerCallback()
  207170. {
  207171. stopTimer();
  207172. image = Image::null;
  207173. }
  207174. private:
  207175. Image image;
  207176. TemporaryImage (const TemporaryImage&);
  207177. TemporaryImage& operator= (const TemporaryImage&);
  207178. };
  207179. TemporaryImage offscreenImageGenerator;
  207180. class WindowClassHolder : public DeletedAtShutdown
  207181. {
  207182. public:
  207183. WindowClassHolder()
  207184. : windowClassName ("JUCE_")
  207185. {
  207186. // this name has to be different for each app/dll instance because otherwise
  207187. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207188. // window class).
  207189. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207190. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207191. TCHAR moduleFile [1024];
  207192. moduleFile[0] = 0;
  207193. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207194. WORD iconNum = 0;
  207195. WNDCLASSEX wcex;
  207196. wcex.cbSize = sizeof (wcex);
  207197. wcex.style = CS_OWNDC;
  207198. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207199. wcex.lpszClassName = windowClassName;
  207200. wcex.cbClsExtra = 0;
  207201. wcex.cbWndExtra = 32;
  207202. wcex.hInstance = moduleHandle;
  207203. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207204. iconNum = 1;
  207205. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207206. wcex.hCursor = 0;
  207207. wcex.hbrBackground = 0;
  207208. wcex.lpszMenuName = 0;
  207209. RegisterClassEx (&wcex);
  207210. }
  207211. ~WindowClassHolder()
  207212. {
  207213. if (ComponentPeer::getNumPeers() == 0)
  207214. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207215. clearSingletonInstance();
  207216. }
  207217. String windowClassName;
  207218. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207219. };
  207220. static void* createWindowCallback (void* userData)
  207221. {
  207222. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207223. return 0;
  207224. }
  207225. void createWindow()
  207226. {
  207227. DWORD exstyle = WS_EX_ACCEPTFILES;
  207228. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207229. if (hasTitleBar())
  207230. {
  207231. type |= WS_OVERLAPPED;
  207232. if ((styleFlags & windowHasCloseButton) != 0)
  207233. {
  207234. type |= WS_SYSMENU;
  207235. }
  207236. else
  207237. {
  207238. // annoyingly, windows won't let you have a min/max button without a close button
  207239. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207240. }
  207241. if ((styleFlags & windowIsResizable) != 0)
  207242. type |= WS_THICKFRAME;
  207243. }
  207244. else if (parentToAddTo != 0)
  207245. {
  207246. type |= WS_CHILD;
  207247. }
  207248. else
  207249. {
  207250. type |= WS_POPUP | WS_SYSMENU;
  207251. }
  207252. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207253. exstyle |= WS_EX_TOOLWINDOW;
  207254. else
  207255. exstyle |= WS_EX_APPWINDOW;
  207256. if ((styleFlags & windowHasMinimiseButton) != 0)
  207257. type |= WS_MINIMIZEBOX;
  207258. if ((styleFlags & windowHasMaximiseButton) != 0)
  207259. type |= WS_MAXIMIZEBOX;
  207260. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207261. exstyle |= WS_EX_TRANSPARENT;
  207262. if ((styleFlags & windowIsSemiTransparent) != 0
  207263. && Desktop::canUseSemiTransparentWindows())
  207264. exstyle |= WS_EX_LAYERED;
  207265. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207266. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207267. #if JUCE_DIRECT2D
  207268. updateDirect2DContext();
  207269. #endif
  207270. if (hwnd != 0)
  207271. {
  207272. SetWindowLongPtr (hwnd, 0, 0);
  207273. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207274. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207275. if (dropTarget == 0)
  207276. dropTarget = new JuceDropTarget (this);
  207277. RegisterDragDrop (hwnd, dropTarget);
  207278. updateBorderSize();
  207279. // Calling this function here is (for some reason) necessary to make Windows
  207280. // correctly enable the menu items that we specify in the wm_initmenu message.
  207281. GetSystemMenu (hwnd, false);
  207282. }
  207283. else
  207284. {
  207285. jassertfalse;
  207286. }
  207287. }
  207288. static void* destroyWindowCallback (void* handle)
  207289. {
  207290. RevokeDragDrop ((HWND) handle);
  207291. DestroyWindow ((HWND) handle);
  207292. return 0;
  207293. }
  207294. static void* toFrontCallback1 (void* h)
  207295. {
  207296. SetForegroundWindow ((HWND) h);
  207297. return 0;
  207298. }
  207299. static void* toFrontCallback2 (void* h)
  207300. {
  207301. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207302. return 0;
  207303. }
  207304. static void* setFocusCallback (void* h)
  207305. {
  207306. SetFocus ((HWND) h);
  207307. return 0;
  207308. }
  207309. static void* getFocusCallback (void*)
  207310. {
  207311. return GetFocus();
  207312. }
  207313. void offsetWithinParent (int& x, int& y) const
  207314. {
  207315. if (isTransparent())
  207316. {
  207317. HWND parentHwnd = GetParent (hwnd);
  207318. if (parentHwnd != 0)
  207319. {
  207320. RECT parentRect;
  207321. GetWindowRect (parentHwnd, &parentRect);
  207322. x += parentRect.left;
  207323. y += parentRect.top;
  207324. }
  207325. }
  207326. }
  207327. bool isTransparent() const
  207328. {
  207329. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  207330. }
  207331. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207332. void setIcon (const Image& newIcon)
  207333. {
  207334. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  207335. if (hicon != 0)
  207336. {
  207337. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207338. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207339. if (currentWindowIcon != 0)
  207340. DestroyIcon (currentWindowIcon);
  207341. currentWindowIcon = hicon;
  207342. }
  207343. }
  207344. void handlePaintMessage()
  207345. {
  207346. #if JUCE_DIRECT2D
  207347. if (direct2DContext != 0)
  207348. {
  207349. RECT r;
  207350. if (GetUpdateRect (hwnd, &r, false))
  207351. {
  207352. direct2DContext->start();
  207353. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207354. handlePaint (*direct2DContext);
  207355. direct2DContext->end();
  207356. }
  207357. }
  207358. else
  207359. #endif
  207360. {
  207361. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207362. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207363. PAINTSTRUCT paintStruct;
  207364. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207365. // message and become re-entrant, but that's OK
  207366. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207367. // corrupt the image it's using to paint into, so do a check here.
  207368. static bool reentrant = false;
  207369. if (reentrant)
  207370. {
  207371. DeleteObject (rgn);
  207372. EndPaint (hwnd, &paintStruct);
  207373. return;
  207374. }
  207375. reentrant = true;
  207376. // this is the rectangle to update..
  207377. int x = paintStruct.rcPaint.left;
  207378. int y = paintStruct.rcPaint.top;
  207379. int w = paintStruct.rcPaint.right - x;
  207380. int h = paintStruct.rcPaint.bottom - y;
  207381. const bool transparent = isTransparent();
  207382. if (transparent)
  207383. {
  207384. // it's not possible to have a transparent window with a title bar at the moment!
  207385. jassert (! hasTitleBar());
  207386. RECT r;
  207387. GetWindowRect (hwnd, &r);
  207388. x = y = 0;
  207389. w = r.right - r.left;
  207390. h = r.bottom - r.top;
  207391. }
  207392. if (w > 0 && h > 0)
  207393. {
  207394. clearMaskedRegion();
  207395. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207396. RectangleList contextClip;
  207397. const Rectangle<int> clipBounds (0, 0, w, h);
  207398. bool needToPaintAll = true;
  207399. if (regionType == COMPLEXREGION && ! transparent)
  207400. {
  207401. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207402. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207403. DeleteObject (clipRgn);
  207404. char rgnData [8192];
  207405. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207406. if (res > 0 && res <= sizeof (rgnData))
  207407. {
  207408. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207409. if (hdr->iType == RDH_RECTANGLES
  207410. && hdr->rcBound.right - hdr->rcBound.left >= w
  207411. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207412. {
  207413. needToPaintAll = false;
  207414. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207415. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207416. while (--num >= 0)
  207417. {
  207418. if (rects->right <= x + w && rects->bottom <= y + h)
  207419. {
  207420. const int cx = jmax (x, (int) rects->left);
  207421. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207422. .getIntersection (clipBounds));
  207423. }
  207424. else
  207425. {
  207426. needToPaintAll = true;
  207427. break;
  207428. }
  207429. ++rects;
  207430. }
  207431. }
  207432. }
  207433. }
  207434. if (needToPaintAll)
  207435. {
  207436. contextClip.clear();
  207437. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207438. }
  207439. if (transparent)
  207440. {
  207441. RectangleList::Iterator i (contextClip);
  207442. while (i.next())
  207443. offscreenImage.clear (*i.getRectangle());
  207444. }
  207445. // if the component's not opaque, this won't draw properly unless the platform can support this
  207446. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207447. updateCurrentModifiers();
  207448. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207449. handlePaint (context);
  207450. if (! dontRepaint)
  207451. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207452. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  207453. }
  207454. DeleteObject (rgn);
  207455. EndPaint (hwnd, &paintStruct);
  207456. reentrant = false;
  207457. }
  207458. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207459. _fpreset(); // because some graphics cards can unmask FP exceptions
  207460. #endif
  207461. lastPaintTime = Time::getMillisecondCounter();
  207462. }
  207463. void doMouseEvent (const Point<int>& position)
  207464. {
  207465. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207466. }
  207467. const StringArray getAvailableRenderingEngines()
  207468. {
  207469. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207470. #if JUCE_DIRECT2D
  207471. // xxx is this correct? Seems to enable it on Vista too??
  207472. OSVERSIONINFO info;
  207473. zerostruct (info);
  207474. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207475. GetVersionEx (&info);
  207476. if (info.dwMajorVersion >= 6)
  207477. s.add ("Direct2D");
  207478. #endif
  207479. return s;
  207480. }
  207481. int getCurrentRenderingEngine() throw()
  207482. {
  207483. return currentRenderingEngine;
  207484. }
  207485. #if JUCE_DIRECT2D
  207486. void updateDirect2DContext()
  207487. {
  207488. if (currentRenderingEngine != direct2DRenderingEngine)
  207489. direct2DContext = 0;
  207490. else if (direct2DContext == 0)
  207491. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207492. }
  207493. #endif
  207494. void setCurrentRenderingEngine (int index)
  207495. {
  207496. (void) index;
  207497. #if JUCE_DIRECT2D
  207498. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207499. updateDirect2DContext();
  207500. repaint (component->getLocalBounds());
  207501. #endif
  207502. }
  207503. void doMouseMove (const Point<int>& position)
  207504. {
  207505. if (! isMouseOver)
  207506. {
  207507. isMouseOver = true;
  207508. updateKeyModifiers();
  207509. TRACKMOUSEEVENT tme;
  207510. tme.cbSize = sizeof (tme);
  207511. tme.dwFlags = TME_LEAVE;
  207512. tme.hwndTrack = hwnd;
  207513. tme.dwHoverTime = 0;
  207514. if (! TrackMouseEvent (&tme))
  207515. jassertfalse;
  207516. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207517. }
  207518. else if (! isDragging)
  207519. {
  207520. if (! contains (position, false))
  207521. return;
  207522. }
  207523. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207524. static uint32 lastMouseTime = 0;
  207525. const uint32 now = Time::getMillisecondCounter();
  207526. const int maxMouseMovesPerSecond = 60;
  207527. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207528. {
  207529. lastMouseTime = now;
  207530. doMouseEvent (position);
  207531. }
  207532. }
  207533. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207534. {
  207535. if (GetCapture() != hwnd)
  207536. SetCapture (hwnd);
  207537. doMouseMove (position);
  207538. updateModifiersFromWParam (wParam);
  207539. isDragging = true;
  207540. doMouseEvent (position);
  207541. }
  207542. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207543. {
  207544. updateModifiersFromWParam (wParam);
  207545. isDragging = false;
  207546. // release the mouse capture if the user has released all buttons
  207547. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207548. ReleaseCapture();
  207549. doMouseEvent (position);
  207550. }
  207551. void doCaptureChanged()
  207552. {
  207553. if (isDragging)
  207554. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207555. }
  207556. void doMouseExit()
  207557. {
  207558. isMouseOver = false;
  207559. doMouseEvent (getCurrentMousePos());
  207560. }
  207561. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207562. {
  207563. updateKeyModifiers();
  207564. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207565. handleMouseWheel (0, position, getMouseEventTime(),
  207566. isVertical ? 0.0f : amount,
  207567. isVertical ? amount : 0.0f);
  207568. }
  207569. void sendModifierKeyChangeIfNeeded()
  207570. {
  207571. if (modifiersAtLastCallback != currentModifiers)
  207572. {
  207573. modifiersAtLastCallback = currentModifiers;
  207574. handleModifierKeysChange();
  207575. }
  207576. }
  207577. bool doKeyUp (const WPARAM key)
  207578. {
  207579. updateKeyModifiers();
  207580. switch (key)
  207581. {
  207582. case VK_SHIFT:
  207583. case VK_CONTROL:
  207584. case VK_MENU:
  207585. case VK_CAPITAL:
  207586. case VK_LWIN:
  207587. case VK_RWIN:
  207588. case VK_APPS:
  207589. case VK_NUMLOCK:
  207590. case VK_SCROLL:
  207591. case VK_LSHIFT:
  207592. case VK_RSHIFT:
  207593. case VK_LCONTROL:
  207594. case VK_LMENU:
  207595. case VK_RCONTROL:
  207596. case VK_RMENU:
  207597. sendModifierKeyChangeIfNeeded();
  207598. }
  207599. return handleKeyUpOrDown (false)
  207600. || Component::getCurrentlyModalComponent() != 0;
  207601. }
  207602. bool doKeyDown (const WPARAM key)
  207603. {
  207604. updateKeyModifiers();
  207605. bool used = false;
  207606. switch (key)
  207607. {
  207608. case VK_SHIFT:
  207609. case VK_LSHIFT:
  207610. case VK_RSHIFT:
  207611. case VK_CONTROL:
  207612. case VK_LCONTROL:
  207613. case VK_RCONTROL:
  207614. case VK_MENU:
  207615. case VK_LMENU:
  207616. case VK_RMENU:
  207617. case VK_LWIN:
  207618. case VK_RWIN:
  207619. case VK_CAPITAL:
  207620. case VK_NUMLOCK:
  207621. case VK_SCROLL:
  207622. case VK_APPS:
  207623. sendModifierKeyChangeIfNeeded();
  207624. break;
  207625. case VK_LEFT:
  207626. case VK_RIGHT:
  207627. case VK_UP:
  207628. case VK_DOWN:
  207629. case VK_PRIOR:
  207630. case VK_NEXT:
  207631. case VK_HOME:
  207632. case VK_END:
  207633. case VK_DELETE:
  207634. case VK_INSERT:
  207635. case VK_F1:
  207636. case VK_F2:
  207637. case VK_F3:
  207638. case VK_F4:
  207639. case VK_F5:
  207640. case VK_F6:
  207641. case VK_F7:
  207642. case VK_F8:
  207643. case VK_F9:
  207644. case VK_F10:
  207645. case VK_F11:
  207646. case VK_F12:
  207647. case VK_F13:
  207648. case VK_F14:
  207649. case VK_F15:
  207650. case VK_F16:
  207651. used = handleKeyUpOrDown (true);
  207652. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207653. break;
  207654. case VK_ADD:
  207655. case VK_SUBTRACT:
  207656. case VK_MULTIPLY:
  207657. case VK_DIVIDE:
  207658. case VK_SEPARATOR:
  207659. case VK_DECIMAL:
  207660. used = handleKeyUpOrDown (true);
  207661. break;
  207662. default:
  207663. used = handleKeyUpOrDown (true);
  207664. {
  207665. MSG msg;
  207666. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207667. {
  207668. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207669. // manually generate the key-press event that matches this key-down.
  207670. const UINT keyChar = MapVirtualKey (key, 2);
  207671. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207672. }
  207673. }
  207674. break;
  207675. }
  207676. if (Component::getCurrentlyModalComponent() != 0)
  207677. used = true;
  207678. return used;
  207679. }
  207680. bool doKeyChar (int key, const LPARAM flags)
  207681. {
  207682. updateKeyModifiers();
  207683. juce_wchar textChar = (juce_wchar) key;
  207684. const int virtualScanCode = (flags >> 16) & 0xff;
  207685. if (key >= '0' && key <= '9')
  207686. {
  207687. switch (virtualScanCode) // check for a numeric keypad scan-code
  207688. {
  207689. case 0x52:
  207690. case 0x4f:
  207691. case 0x50:
  207692. case 0x51:
  207693. case 0x4b:
  207694. case 0x4c:
  207695. case 0x4d:
  207696. case 0x47:
  207697. case 0x48:
  207698. case 0x49:
  207699. key = (key - '0') + KeyPress::numberPad0;
  207700. break;
  207701. default:
  207702. break;
  207703. }
  207704. }
  207705. else
  207706. {
  207707. // convert the scan code to an unmodified character code..
  207708. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207709. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207710. keyChar = LOWORD (keyChar);
  207711. if (keyChar != 0)
  207712. key = (int) keyChar;
  207713. // avoid sending junk text characters for some control-key combinations
  207714. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207715. textChar = 0;
  207716. }
  207717. return handleKeyPress (key, textChar);
  207718. }
  207719. bool doAppCommand (const LPARAM lParam)
  207720. {
  207721. int key = 0;
  207722. switch (GET_APPCOMMAND_LPARAM (lParam))
  207723. {
  207724. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  207725. key = KeyPress::playKey;
  207726. break;
  207727. case APPCOMMAND_MEDIA_STOP:
  207728. key = KeyPress::stopKey;
  207729. break;
  207730. case APPCOMMAND_MEDIA_NEXTTRACK:
  207731. key = KeyPress::fastForwardKey;
  207732. break;
  207733. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  207734. key = KeyPress::rewindKey;
  207735. break;
  207736. }
  207737. if (key != 0)
  207738. {
  207739. updateKeyModifiers();
  207740. if (hwnd == GetActiveWindow())
  207741. {
  207742. handleKeyPress (key, 0);
  207743. return true;
  207744. }
  207745. }
  207746. return false;
  207747. }
  207748. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207749. {
  207750. public:
  207751. JuceDropTarget (Win32ComponentPeer* const owner_)
  207752. : owner (owner_)
  207753. {
  207754. }
  207755. ~JuceDropTarget() {}
  207756. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207757. {
  207758. updateFileList (pDataObject);
  207759. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207760. *pdwEffect = DROPEFFECT_COPY;
  207761. return S_OK;
  207762. }
  207763. HRESULT __stdcall DragLeave()
  207764. {
  207765. owner->handleFileDragExit (files);
  207766. return S_OK;
  207767. }
  207768. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207769. {
  207770. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207771. *pdwEffect = DROPEFFECT_COPY;
  207772. return S_OK;
  207773. }
  207774. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207775. {
  207776. updateFileList (pDataObject);
  207777. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207778. *pdwEffect = DROPEFFECT_COPY;
  207779. return S_OK;
  207780. }
  207781. private:
  207782. Win32ComponentPeer* const owner;
  207783. StringArray files;
  207784. void updateFileList (IDataObject* const pDataObject)
  207785. {
  207786. files.clear();
  207787. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207788. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207789. if (pDataObject->GetData (&format, &medium) == S_OK)
  207790. {
  207791. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207792. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207793. unsigned int i = 0;
  207794. if (pDropFiles->fWide)
  207795. {
  207796. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  207797. for (;;)
  207798. {
  207799. unsigned int len = 0;
  207800. while (i + len < totalLen && fname [i + len] != 0)
  207801. ++len;
  207802. if (len == 0)
  207803. break;
  207804. files.add (String (fname + i, len));
  207805. i += len + 1;
  207806. }
  207807. }
  207808. else
  207809. {
  207810. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  207811. for (;;)
  207812. {
  207813. unsigned int len = 0;
  207814. while (i + len < totalLen && fname [i + len] != 0)
  207815. ++len;
  207816. if (len == 0)
  207817. break;
  207818. files.add (String (fname + i, len));
  207819. i += len + 1;
  207820. }
  207821. }
  207822. GlobalUnlock (medium.hGlobal);
  207823. }
  207824. }
  207825. JuceDropTarget (const JuceDropTarget&);
  207826. JuceDropTarget& operator= (const JuceDropTarget&);
  207827. };
  207828. void doSettingChange()
  207829. {
  207830. Desktop::getInstance().refreshMonitorSizes();
  207831. if (fullScreen && ! isMinimised())
  207832. {
  207833. const Rectangle<int> r (component->getParentMonitorArea());
  207834. SetWindowPos (hwnd, 0,
  207835. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207836. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207837. }
  207838. }
  207839. public:
  207840. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207841. {
  207842. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207843. if (peer != 0)
  207844. return peer->peerWindowProc (h, message, wParam, lParam);
  207845. return DefWindowProcW (h, message, wParam, lParam);
  207846. }
  207847. private:
  207848. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  207849. {
  207850. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  207851. }
  207852. const Point<int> getCurrentMousePos() throw()
  207853. {
  207854. RECT wr;
  207855. GetWindowRect (hwnd, &wr);
  207856. const DWORD mp = GetMessagePos();
  207857. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  207858. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  207859. }
  207860. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207861. {
  207862. if (isValidPeer (this))
  207863. {
  207864. switch (message)
  207865. {
  207866. case WM_NCHITTEST:
  207867. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207868. return HTTRANSPARENT;
  207869. if (hasTitleBar())
  207870. break;
  207871. return HTCLIENT;
  207872. case WM_PAINT:
  207873. handlePaintMessage();
  207874. return 0;
  207875. case WM_NCPAINT:
  207876. if (wParam != 1)
  207877. handlePaintMessage();
  207878. if (hasTitleBar())
  207879. break;
  207880. return 0;
  207881. case WM_ERASEBKGND:
  207882. case WM_NCCALCSIZE:
  207883. if (hasTitleBar())
  207884. break;
  207885. return 1;
  207886. case WM_MOUSEMOVE:
  207887. doMouseMove (getPointFromLParam (lParam));
  207888. return 0;
  207889. case WM_MOUSELEAVE:
  207890. doMouseExit();
  207891. return 0;
  207892. case WM_LBUTTONDOWN:
  207893. case WM_MBUTTONDOWN:
  207894. case WM_RBUTTONDOWN:
  207895. doMouseDown (getPointFromLParam (lParam), wParam);
  207896. return 0;
  207897. case WM_LBUTTONUP:
  207898. case WM_MBUTTONUP:
  207899. case WM_RBUTTONUP:
  207900. doMouseUp (getPointFromLParam (lParam), wParam);
  207901. return 0;
  207902. case WM_CAPTURECHANGED:
  207903. doCaptureChanged();
  207904. return 0;
  207905. case WM_NCMOUSEMOVE:
  207906. if (hasTitleBar())
  207907. break;
  207908. return 0;
  207909. case 0x020A: /* WM_MOUSEWHEEL */
  207910. doMouseWheel (getCurrentMousePos(), wParam, true);
  207911. return 0;
  207912. case 0x020E: /* WM_MOUSEHWHEEL */
  207913. doMouseWheel (getCurrentMousePos(), wParam, false);
  207914. return 0;
  207915. case WM_WINDOWPOSCHANGING:
  207916. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207917. {
  207918. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  207919. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  207920. {
  207921. if (constrainer != 0)
  207922. {
  207923. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  207924. component->getY() - windowBorder.getTop(),
  207925. component->getWidth() + windowBorder.getLeftAndRight(),
  207926. component->getHeight() + windowBorder.getTopAndBottom());
  207927. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  207928. constrainer->checkBounds (pos, current,
  207929. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207930. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  207931. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  207932. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  207933. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  207934. wp->x = pos.getX();
  207935. wp->y = pos.getY();
  207936. wp->cx = pos.getWidth();
  207937. wp->cy = pos.getHeight();
  207938. }
  207939. }
  207940. }
  207941. return 0;
  207942. case WM_WINDOWPOSCHANGED:
  207943. doMouseEvent (getCurrentMousePos());
  207944. handleMovedOrResized();
  207945. if (dontRepaint)
  207946. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  207947. return 0;
  207948. case WM_KEYDOWN:
  207949. case WM_SYSKEYDOWN:
  207950. if (doKeyDown (wParam))
  207951. return 0;
  207952. break;
  207953. case WM_KEYUP:
  207954. case WM_SYSKEYUP:
  207955. if (doKeyUp (wParam))
  207956. return 0;
  207957. break;
  207958. case WM_CHAR:
  207959. if (doKeyChar ((int) wParam, lParam))
  207960. return 0;
  207961. break;
  207962. case WM_APPCOMMAND:
  207963. if (doAppCommand (lParam))
  207964. return TRUE;
  207965. break;
  207966. case WM_SETFOCUS:
  207967. updateKeyModifiers();
  207968. handleFocusGain();
  207969. break;
  207970. case WM_KILLFOCUS:
  207971. if (hasCreatedCaret)
  207972. {
  207973. hasCreatedCaret = false;
  207974. DestroyCaret();
  207975. }
  207976. handleFocusLoss();
  207977. break;
  207978. case WM_ACTIVATEAPP:
  207979. // Windows does weird things to process priority when you swap apps,
  207980. // so this forces an update when the app is brought to the front
  207981. if (wParam != FALSE)
  207982. juce_repeatLastProcessPriority();
  207983. else
  207984. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  207985. juce_CheckCurrentlyFocusedTopLevelWindow();
  207986. modifiersAtLastCallback = -1;
  207987. return 0;
  207988. case WM_ACTIVATE:
  207989. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  207990. {
  207991. modifiersAtLastCallback = -1;
  207992. updateKeyModifiers();
  207993. if (isMinimised())
  207994. {
  207995. component->repaint();
  207996. handleMovedOrResized();
  207997. if (! ComponentPeer::isValidPeer (this))
  207998. return 0;
  207999. }
  208000. if (LOWORD (wParam) == WA_CLICKACTIVE
  208001. && component->isCurrentlyBlockedByAnotherModalComponent())
  208002. {
  208003. const Point<int> mousePos (component->getMouseXYRelative());
  208004. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  208005. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  208006. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  208007. return 0;
  208008. }
  208009. handleBroughtToFront();
  208010. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208011. Component::getCurrentlyModalComponent()->toFront (true);
  208012. return 0;
  208013. }
  208014. break;
  208015. case WM_NCACTIVATE:
  208016. // while a temporary window is being shown, prevent Windows from deactivating the
  208017. // title bars of our main windows.
  208018. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208019. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208020. break;
  208021. case WM_MOUSEACTIVATE:
  208022. if (! component->getMouseClickGrabsKeyboardFocus())
  208023. return MA_NOACTIVATE;
  208024. break;
  208025. case WM_SHOWWINDOW:
  208026. if (wParam != 0)
  208027. handleBroughtToFront();
  208028. break;
  208029. case WM_CLOSE:
  208030. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208031. handleUserClosingWindow();
  208032. return 0;
  208033. case WM_QUERYENDSESSION:
  208034. if (JUCEApplication::getInstance() != 0)
  208035. {
  208036. JUCEApplication::getInstance()->systemRequestedQuit();
  208037. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208038. }
  208039. return TRUE;
  208040. case WM_TRAYNOTIFY:
  208041. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208042. {
  208043. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  208044. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208045. {
  208046. Component* const current = Component::getCurrentlyModalComponent();
  208047. if (current != 0)
  208048. current->inputAttemptWhenModal();
  208049. }
  208050. }
  208051. else
  208052. {
  208053. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  208054. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  208055. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  208056. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  208057. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  208058. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208059. eventMods = eventMods.withoutMouseButtons();
  208060. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  208061. Point<int>(), eventMods, component, component, getMouseEventTime(),
  208062. Point<int>(), getMouseEventTime(), 1, false);
  208063. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  208064. {
  208065. SetFocus (hwnd);
  208066. SetForegroundWindow (hwnd);
  208067. component->mouseDown (e);
  208068. }
  208069. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208070. {
  208071. component->mouseUp (e);
  208072. }
  208073. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208074. {
  208075. component->mouseDoubleClick (e);
  208076. }
  208077. else if (lParam == WM_MOUSEMOVE)
  208078. {
  208079. component->mouseMove (e);
  208080. }
  208081. }
  208082. break;
  208083. case WM_SYNCPAINT:
  208084. return 0;
  208085. case WM_PALETTECHANGED:
  208086. InvalidateRect (h, 0, 0);
  208087. break;
  208088. case WM_DISPLAYCHANGE:
  208089. InvalidateRect (h, 0, 0);
  208090. createPaletteIfNeeded = true;
  208091. // intentional fall-through...
  208092. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208093. doSettingChange();
  208094. break;
  208095. case WM_INITMENU:
  208096. if (! hasTitleBar())
  208097. {
  208098. if (isFullScreen())
  208099. {
  208100. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208101. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208102. }
  208103. else if (! isMinimised())
  208104. {
  208105. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208106. }
  208107. }
  208108. break;
  208109. case WM_SYSCOMMAND:
  208110. switch (wParam & 0xfff0)
  208111. {
  208112. case SC_CLOSE:
  208113. if (sendInputAttemptWhenModalMessage())
  208114. return 0;
  208115. if (hasTitleBar())
  208116. {
  208117. PostMessage (h, WM_CLOSE, 0, 0);
  208118. return 0;
  208119. }
  208120. break;
  208121. case SC_KEYMENU:
  208122. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  208123. // obscure situations that can arise if a modal loop is started from an alt-key
  208124. // keypress).
  208125. if (hasTitleBar() && h == GetCapture())
  208126. ReleaseCapture();
  208127. break;
  208128. case SC_MAXIMIZE:
  208129. if (sendInputAttemptWhenModalMessage())
  208130. return 0;
  208131. setFullScreen (true);
  208132. return 0;
  208133. case SC_MINIMIZE:
  208134. if (sendInputAttemptWhenModalMessage())
  208135. return 0;
  208136. if (! hasTitleBar())
  208137. {
  208138. setMinimised (true);
  208139. return 0;
  208140. }
  208141. break;
  208142. case SC_RESTORE:
  208143. if (sendInputAttemptWhenModalMessage())
  208144. return 0;
  208145. if (hasTitleBar())
  208146. {
  208147. if (isFullScreen())
  208148. {
  208149. setFullScreen (false);
  208150. return 0;
  208151. }
  208152. }
  208153. else
  208154. {
  208155. if (isMinimised())
  208156. setMinimised (false);
  208157. else if (isFullScreen())
  208158. setFullScreen (false);
  208159. return 0;
  208160. }
  208161. break;
  208162. }
  208163. break;
  208164. case WM_NCLBUTTONDOWN:
  208165. case WM_NCRBUTTONDOWN:
  208166. case WM_NCMBUTTONDOWN:
  208167. sendInputAttemptWhenModalMessage();
  208168. break;
  208169. //case WM_IME_STARTCOMPOSITION;
  208170. // return 0;
  208171. case WM_GETDLGCODE:
  208172. return DLGC_WANTALLKEYS;
  208173. default:
  208174. break;
  208175. }
  208176. }
  208177. return DefWindowProcW (h, message, wParam, lParam);
  208178. }
  208179. bool sendInputAttemptWhenModalMessage()
  208180. {
  208181. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208182. {
  208183. Component* const current = Component::getCurrentlyModalComponent();
  208184. if (current != 0)
  208185. current->inputAttemptWhenModal();
  208186. return true;
  208187. }
  208188. return false;
  208189. }
  208190. Win32ComponentPeer (const Win32ComponentPeer&);
  208191. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  208192. };
  208193. ModifierKeys Win32ComponentPeer::currentModifiers;
  208194. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208195. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208196. {
  208197. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208198. }
  208199. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208200. void ModifierKeys::updateCurrentModifiers() throw()
  208201. {
  208202. currentModifiers = Win32ComponentPeer::currentModifiers;
  208203. }
  208204. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208205. {
  208206. Win32ComponentPeer::updateKeyModifiers();
  208207. int keyMods = 0;
  208208. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  208209. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  208210. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  208211. Win32ComponentPeer::currentModifiers
  208212. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  208213. return Win32ComponentPeer::currentModifiers;
  208214. }
  208215. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208216. {
  208217. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208218. if (wp != 0)
  208219. wp->setTaskBarIcon (newImage);
  208220. }
  208221. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208222. {
  208223. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208224. if (wp != 0)
  208225. wp->setTaskBarIconToolTip (tooltip);
  208226. }
  208227. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208228. {
  208229. DWORD val = GetWindowLong (h, styleType);
  208230. if (bitIsSet)
  208231. val |= feature;
  208232. else
  208233. val &= ~feature;
  208234. SetWindowLongPtr (h, styleType, val);
  208235. SetWindowPos (h, 0, 0, 0, 0, 0,
  208236. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208237. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208238. }
  208239. bool Process::isForegroundProcess()
  208240. {
  208241. HWND fg = GetForegroundWindow();
  208242. if (fg == 0)
  208243. return true;
  208244. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208245. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208246. // have to see if any of our windows are children of the foreground window
  208247. fg = GetAncestor (fg, GA_ROOT);
  208248. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208249. {
  208250. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208251. if (wp != 0 && wp->isInside (fg))
  208252. return true;
  208253. }
  208254. return false;
  208255. }
  208256. bool AlertWindow::showNativeDialogBox (const String& title,
  208257. const String& bodyText,
  208258. bool isOkCancel)
  208259. {
  208260. return MessageBox (0, bodyText, title,
  208261. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208262. : MB_OK)) == IDOK;
  208263. }
  208264. void Desktop::createMouseInputSources()
  208265. {
  208266. mouseSources.add (new MouseInputSource (0, true));
  208267. }
  208268. const Point<int> Desktop::getMousePosition()
  208269. {
  208270. POINT mousePos;
  208271. GetCursorPos (&mousePos);
  208272. return Point<int> (mousePos.x, mousePos.y);
  208273. }
  208274. void Desktop::setMousePosition (const Point<int>& newPosition)
  208275. {
  208276. SetCursorPos (newPosition.getX(), newPosition.getY());
  208277. }
  208278. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208279. {
  208280. return createSoftwareImage (format, width, height, clearImage);
  208281. }
  208282. class ScreenSaverDefeater : public Timer,
  208283. public DeletedAtShutdown
  208284. {
  208285. public:
  208286. ScreenSaverDefeater()
  208287. {
  208288. startTimer (10000);
  208289. timerCallback();
  208290. }
  208291. ~ScreenSaverDefeater() {}
  208292. void timerCallback()
  208293. {
  208294. if (Process::isForegroundProcess())
  208295. {
  208296. // simulate a shift key getting pressed..
  208297. INPUT input[2];
  208298. input[0].type = INPUT_KEYBOARD;
  208299. input[0].ki.wVk = VK_SHIFT;
  208300. input[0].ki.dwFlags = 0;
  208301. input[0].ki.dwExtraInfo = 0;
  208302. input[1].type = INPUT_KEYBOARD;
  208303. input[1].ki.wVk = VK_SHIFT;
  208304. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208305. input[1].ki.dwExtraInfo = 0;
  208306. SendInput (2, input, sizeof (INPUT));
  208307. }
  208308. }
  208309. };
  208310. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208311. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208312. {
  208313. if (isEnabled)
  208314. deleteAndZero (screenSaverDefeater);
  208315. else if (screenSaverDefeater == 0)
  208316. screenSaverDefeater = new ScreenSaverDefeater();
  208317. }
  208318. bool Desktop::isScreenSaverEnabled()
  208319. {
  208320. return screenSaverDefeater == 0;
  208321. }
  208322. /* (The code below is the "correct" way to disable the screen saver, but it
  208323. completely fails on winXP when the saver is password-protected...)
  208324. static bool juce_screenSaverEnabled = true;
  208325. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208326. {
  208327. juce_screenSaverEnabled = isEnabled;
  208328. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208329. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208330. }
  208331. bool Desktop::isScreenSaverEnabled() throw()
  208332. {
  208333. return juce_screenSaverEnabled;
  208334. }
  208335. */
  208336. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208337. {
  208338. if (enableOrDisable)
  208339. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208340. }
  208341. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208342. {
  208343. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208344. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208345. return TRUE;
  208346. }
  208347. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208348. {
  208349. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208350. // make sure the first in the list is the main monitor
  208351. for (int i = 1; i < monitorCoords.size(); ++i)
  208352. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208353. monitorCoords.swap (i, 0);
  208354. if (monitorCoords.size() == 0)
  208355. {
  208356. RECT r;
  208357. GetWindowRect (GetDesktopWindow(), &r);
  208358. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208359. }
  208360. if (clipToWorkArea)
  208361. {
  208362. // clip the main monitor to the active non-taskbar area
  208363. RECT r;
  208364. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208365. Rectangle<int>& screen = monitorCoords.getReference (0);
  208366. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208367. jmax (screen.getY(), (int) r.top));
  208368. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208369. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208370. }
  208371. }
  208372. static const Image createImageFromHBITMAP (HBITMAP bitmap)
  208373. {
  208374. Image im;
  208375. if (bitmap != 0)
  208376. {
  208377. BITMAP bm;
  208378. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  208379. && bm.bmWidth > 0 && bm.bmHeight > 0)
  208380. {
  208381. HDC tempDC = GetDC (0);
  208382. HDC dc = CreateCompatibleDC (tempDC);
  208383. ReleaseDC (0, tempDC);
  208384. SelectObject (dc, bitmap);
  208385. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  208386. Image::BitmapData imageData (im, true);
  208387. for (int y = bm.bmHeight; --y >= 0;)
  208388. {
  208389. for (int x = bm.bmWidth; --x >= 0;)
  208390. {
  208391. COLORREF col = GetPixel (dc, x, y);
  208392. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  208393. (uint8) GetGValue (col),
  208394. (uint8) GetBValue (col)));
  208395. }
  208396. }
  208397. DeleteDC (dc);
  208398. }
  208399. }
  208400. return im;
  208401. }
  208402. static const Image createImageFromHICON (HICON icon)
  208403. {
  208404. ICONINFO info;
  208405. if (GetIconInfo (icon, &info))
  208406. {
  208407. Image mask (createImageFromHBITMAP (info.hbmMask));
  208408. Image image (createImageFromHBITMAP (info.hbmColor));
  208409. if (mask.isValid() && image.isValid())
  208410. {
  208411. for (int y = image.getHeight(); --y >= 0;)
  208412. {
  208413. for (int x = image.getWidth(); --x >= 0;)
  208414. {
  208415. const float brightness = mask.getPixelAt (x, y).getBrightness();
  208416. if (brightness > 0.0f)
  208417. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  208418. }
  208419. }
  208420. return image;
  208421. }
  208422. }
  208423. return Image::null;
  208424. }
  208425. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  208426. {
  208427. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  208428. Image bitmap (nativeBitmap);
  208429. {
  208430. Graphics g (bitmap);
  208431. g.drawImageAt (image, 0, 0);
  208432. }
  208433. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  208434. ICONINFO info;
  208435. info.fIcon = isIcon;
  208436. info.xHotspot = hotspotX;
  208437. info.yHotspot = hotspotY;
  208438. info.hbmMask = mask;
  208439. info.hbmColor = nativeBitmap->hBitmap;
  208440. HICON hi = CreateIconIndirect (&info);
  208441. DeleteObject (mask);
  208442. return hi;
  208443. }
  208444. const Image juce_createIconForFile (const File& file)
  208445. {
  208446. Image image;
  208447. WCHAR filename [1024];
  208448. file.getFullPathName().copyToUnicode (filename, 1023);
  208449. WORD iconNum = 0;
  208450. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208451. filename, &iconNum);
  208452. if (icon != 0)
  208453. {
  208454. image = createImageFromHICON (icon);
  208455. DestroyIcon (icon);
  208456. }
  208457. return image;
  208458. }
  208459. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208460. {
  208461. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208462. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208463. Image im (image);
  208464. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208465. {
  208466. im = im.rescaled (maxW, maxH);
  208467. hotspotX = (hotspotX * maxW) / image.getWidth();
  208468. hotspotY = (hotspotY * maxH) / image.getHeight();
  208469. }
  208470. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208471. }
  208472. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208473. {
  208474. if (cursorHandle != 0 && ! isStandard)
  208475. DestroyCursor ((HCURSOR) cursorHandle);
  208476. }
  208477. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208478. {
  208479. LPCTSTR cursorName = IDC_ARROW;
  208480. switch (type)
  208481. {
  208482. case NormalCursor: break;
  208483. case NoCursor: return 0;
  208484. case WaitCursor: cursorName = IDC_WAIT; break;
  208485. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208486. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208487. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208488. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208489. case LeftRightResizeCursor:
  208490. case LeftEdgeResizeCursor:
  208491. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208492. case UpDownResizeCursor:
  208493. case TopEdgeResizeCursor:
  208494. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208495. case TopLeftCornerResizeCursor:
  208496. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208497. case TopRightCornerResizeCursor:
  208498. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208499. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208500. case DraggingHandCursor:
  208501. {
  208502. static void* dragHandCursor = 0;
  208503. if (dragHandCursor == 0)
  208504. {
  208505. static const unsigned char dragHandData[] =
  208506. { 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,
  208507. 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,
  208508. 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 };
  208509. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208510. }
  208511. return dragHandCursor;
  208512. }
  208513. default:
  208514. jassertfalse; break;
  208515. }
  208516. HCURSOR cursorH = LoadCursor (0, cursorName);
  208517. if (cursorH == 0)
  208518. cursorH = LoadCursor (0, IDC_ARROW);
  208519. return cursorH;
  208520. }
  208521. void MouseCursor::showInWindow (ComponentPeer*) const
  208522. {
  208523. SetCursor ((HCURSOR) getHandle());
  208524. }
  208525. void MouseCursor::showInAllWindows() const
  208526. {
  208527. showInWindow (0);
  208528. }
  208529. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208530. {
  208531. public:
  208532. JuceDropSource() {}
  208533. ~JuceDropSource() {}
  208534. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208535. {
  208536. if (escapePressed)
  208537. return DRAGDROP_S_CANCEL;
  208538. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208539. return DRAGDROP_S_DROP;
  208540. return S_OK;
  208541. }
  208542. HRESULT __stdcall GiveFeedback (DWORD)
  208543. {
  208544. return DRAGDROP_S_USEDEFAULTCURSORS;
  208545. }
  208546. };
  208547. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208548. {
  208549. public:
  208550. JuceEnumFormatEtc (const FORMATETC* const format_)
  208551. : format (format_),
  208552. index (0)
  208553. {
  208554. }
  208555. ~JuceEnumFormatEtc() {}
  208556. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208557. {
  208558. if (result == 0)
  208559. return E_POINTER;
  208560. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208561. newOne->index = index;
  208562. *result = newOne;
  208563. return S_OK;
  208564. }
  208565. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208566. {
  208567. if (pceltFetched != 0)
  208568. *pceltFetched = 0;
  208569. else if (celt != 1)
  208570. return S_FALSE;
  208571. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208572. {
  208573. copyFormatEtc (lpFormatEtc [0], *format);
  208574. ++index;
  208575. if (pceltFetched != 0)
  208576. *pceltFetched = 1;
  208577. return S_OK;
  208578. }
  208579. return S_FALSE;
  208580. }
  208581. HRESULT __stdcall Skip (ULONG celt)
  208582. {
  208583. if (index + (int) celt >= 1)
  208584. return S_FALSE;
  208585. index += celt;
  208586. return S_OK;
  208587. }
  208588. HRESULT __stdcall Reset()
  208589. {
  208590. index = 0;
  208591. return S_OK;
  208592. }
  208593. private:
  208594. const FORMATETC* const format;
  208595. int index;
  208596. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208597. {
  208598. dest = source;
  208599. if (source.ptd != 0)
  208600. {
  208601. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208602. *(dest.ptd) = *(source.ptd);
  208603. }
  208604. }
  208605. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  208606. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  208607. };
  208608. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208609. {
  208610. public:
  208611. JuceDataObject (JuceDropSource* const dropSource_,
  208612. const FORMATETC* const format_,
  208613. const STGMEDIUM* const medium_)
  208614. : dropSource (dropSource_),
  208615. format (format_),
  208616. medium (medium_)
  208617. {
  208618. }
  208619. virtual ~JuceDataObject()
  208620. {
  208621. jassert (refCount == 0);
  208622. }
  208623. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  208624. {
  208625. if ((pFormatEtc->tymed & format->tymed) != 0
  208626. && pFormatEtc->cfFormat == format->cfFormat
  208627. && pFormatEtc->dwAspect == format->dwAspect)
  208628. {
  208629. pMedium->tymed = format->tymed;
  208630. pMedium->pUnkForRelease = 0;
  208631. if (format->tymed == TYMED_HGLOBAL)
  208632. {
  208633. const SIZE_T len = GlobalSize (medium->hGlobal);
  208634. void* const src = GlobalLock (medium->hGlobal);
  208635. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208636. memcpy (dst, src, len);
  208637. GlobalUnlock (medium->hGlobal);
  208638. pMedium->hGlobal = dst;
  208639. return S_OK;
  208640. }
  208641. }
  208642. return DV_E_FORMATETC;
  208643. }
  208644. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  208645. {
  208646. if (f == 0)
  208647. return E_INVALIDARG;
  208648. if (f->tymed == format->tymed
  208649. && f->cfFormat == format->cfFormat
  208650. && f->dwAspect == format->dwAspect)
  208651. return S_OK;
  208652. return DV_E_FORMATETC;
  208653. }
  208654. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  208655. {
  208656. pFormatEtcOut->ptd = 0;
  208657. return E_NOTIMPL;
  208658. }
  208659. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  208660. {
  208661. if (result == 0)
  208662. return E_POINTER;
  208663. if (direction == DATADIR_GET)
  208664. {
  208665. *result = new JuceEnumFormatEtc (format);
  208666. return S_OK;
  208667. }
  208668. *result = 0;
  208669. return E_NOTIMPL;
  208670. }
  208671. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  208672. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  208673. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  208674. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208675. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  208676. private:
  208677. JuceDropSource* const dropSource;
  208678. const FORMATETC* const format;
  208679. const STGMEDIUM* const medium;
  208680. JuceDataObject (const JuceDataObject&);
  208681. JuceDataObject& operator= (const JuceDataObject&);
  208682. };
  208683. static HDROP createHDrop (const StringArray& fileNames)
  208684. {
  208685. int totalChars = 0;
  208686. for (int i = fileNames.size(); --i >= 0;)
  208687. totalChars += fileNames[i].length() + 1;
  208688. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208689. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208690. if (hDrop != 0)
  208691. {
  208692. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208693. pDropFiles->pFiles = sizeof (DROPFILES);
  208694. pDropFiles->fWide = true;
  208695. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208696. for (int i = 0; i < fileNames.size(); ++i)
  208697. {
  208698. fileNames[i].copyToUnicode (fname, 2048);
  208699. fname += fileNames[i].length() + 1;
  208700. }
  208701. *fname = 0;
  208702. GlobalUnlock (hDrop);
  208703. }
  208704. return hDrop;
  208705. }
  208706. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208707. {
  208708. JuceDropSource* const source = new JuceDropSource();
  208709. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208710. DWORD effect;
  208711. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208712. data->Release();
  208713. source->Release();
  208714. return res == DRAGDROP_S_DROP;
  208715. }
  208716. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208717. {
  208718. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208719. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208720. medium.hGlobal = createHDrop (files);
  208721. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208722. : DROPEFFECT_COPY);
  208723. }
  208724. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208725. {
  208726. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208727. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208728. const int numChars = text.length();
  208729. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208730. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208731. text.copyToUnicode (data, numChars + 1);
  208732. format.cfFormat = CF_UNICODETEXT;
  208733. GlobalUnlock (medium.hGlobal);
  208734. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208735. }
  208736. #endif
  208737. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208738. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208739. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208740. // compiled on its own).
  208741. #if JUCE_INCLUDED_FILE
  208742. namespace FileChooserHelpers
  208743. {
  208744. static bool areThereAnyAlwaysOnTopWindows()
  208745. {
  208746. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208747. {
  208748. Component* c = Desktop::getInstance().getComponent (i);
  208749. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208750. return true;
  208751. }
  208752. return false;
  208753. }
  208754. struct FileChooserCallbackInfo
  208755. {
  208756. String initialPath;
  208757. String returnedString; // need this to get non-existent pathnames from the directory chooser
  208758. ScopedPointer<Component> customComponent;
  208759. };
  208760. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  208761. {
  208762. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  208763. if (msg == BFFM_INITIALIZED)
  208764. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) static_cast <const WCHAR*> (info->initialPath));
  208765. else if (msg == BFFM_VALIDATEFAILEDW)
  208766. info->returnedString = (LPCWSTR) lParam;
  208767. else if (msg == BFFM_VALIDATEFAILEDA)
  208768. info->returnedString = (const char*) lParam;
  208769. return 0;
  208770. }
  208771. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208772. {
  208773. if (uiMsg == WM_INITDIALOG)
  208774. {
  208775. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  208776. HWND dialogH = GetParent (hdlg);
  208777. jassert (dialogH != 0);
  208778. if (dialogH == 0)
  208779. dialogH = hdlg;
  208780. RECT r, cr;
  208781. GetWindowRect (dialogH, &r);
  208782. GetClientRect (dialogH, &cr);
  208783. SetWindowPos (dialogH, 0,
  208784. r.left, r.top,
  208785. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  208786. jmax (150, (int) (r.bottom - r.top)),
  208787. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208788. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  208789. customComp->addToDesktop (0, dialogH);
  208790. }
  208791. else if (uiMsg == WM_NOTIFY)
  208792. {
  208793. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208794. if (ofn->hdr.code == CDN_SELCHANGE)
  208795. {
  208796. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  208797. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  208798. if (comp != 0)
  208799. {
  208800. WCHAR path [MAX_PATH * 2];
  208801. zerostruct (path);
  208802. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208803. comp->selectedFileChanged (File (path));
  208804. }
  208805. }
  208806. }
  208807. return 0;
  208808. }
  208809. class CustomComponentHolder : public Component
  208810. {
  208811. public:
  208812. CustomComponentHolder (Component* customComp)
  208813. {
  208814. setVisible (true);
  208815. setOpaque (true);
  208816. addAndMakeVisible (customComp);
  208817. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  208818. }
  208819. void paint (Graphics& g)
  208820. {
  208821. g.fillAll (Colours::lightgrey);
  208822. }
  208823. void resized()
  208824. {
  208825. if (getNumChildComponents() > 0)
  208826. getChildComponent(0)->setBounds (getLocalBounds());
  208827. }
  208828. juce_UseDebuggingNewOperator
  208829. private:
  208830. CustomComponentHolder (const CustomComponentHolder&);
  208831. CustomComponentHolder& operator= (const CustomComponentHolder&);
  208832. };
  208833. }
  208834. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  208835. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  208836. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  208837. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  208838. {
  208839. using namespace FileChooserHelpers;
  208840. HeapBlock<WCHAR> files;
  208841. const int charsAvailableForResult = 32768;
  208842. files.calloc (charsAvailableForResult + 1);
  208843. int filenameOffset = 0;
  208844. FileChooserCallbackInfo info;
  208845. // use a modal window as the parent for this dialog box
  208846. // to block input from other app windows
  208847. Component parentWindow (String::empty);
  208848. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208849. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208850. mainMon.getY() + mainMon.getHeight() / 4,
  208851. 0, 0);
  208852. parentWindow.setOpaque (true);
  208853. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208854. parentWindow.addToDesktop (0);
  208855. if (extraInfoComponent == 0)
  208856. parentWindow.enterModalState();
  208857. if (currentFileOrDirectory.isDirectory())
  208858. {
  208859. info.initialPath = currentFileOrDirectory.getFullPathName();
  208860. }
  208861. else
  208862. {
  208863. currentFileOrDirectory.getFileName().copyToUnicode (files, charsAvailableForResult);
  208864. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208865. }
  208866. if (selectsDirectory)
  208867. {
  208868. BROWSEINFO bi;
  208869. zerostruct (bi);
  208870. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208871. bi.pszDisplayName = files;
  208872. bi.lpszTitle = title;
  208873. bi.lParam = (LPARAM) &info;
  208874. bi.lpfn = browseCallbackProc;
  208875. #ifdef BIF_USENEWUI
  208876. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208877. #else
  208878. bi.ulFlags = 0x50;
  208879. #endif
  208880. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  208881. if (! SHGetPathFromIDListW (list, files))
  208882. {
  208883. files[0] = 0;
  208884. info.returnedString = String::empty;
  208885. }
  208886. LPMALLOC al;
  208887. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208888. al->Free (list);
  208889. if (info.returnedString.isNotEmpty())
  208890. {
  208891. results.add (File (String (files)).getSiblingFile (info.returnedString));
  208892. return;
  208893. }
  208894. }
  208895. else
  208896. {
  208897. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  208898. if (warnAboutOverwritingExistingFiles)
  208899. flags |= OFN_OVERWRITEPROMPT;
  208900. if (selectMultipleFiles)
  208901. flags |= OFN_ALLOWMULTISELECT;
  208902. if (extraInfoComponent != 0)
  208903. {
  208904. flags |= OFN_ENABLEHOOK;
  208905. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  208906. info.customComponent->enterModalState();
  208907. }
  208908. WCHAR filters [1024];
  208909. zerostruct (filters);
  208910. filter.copyToUnicode (filters, 1024);
  208911. filter.copyToUnicode (filters + filter.length() + 1, 1022 - filter.length());
  208912. OPENFILENAMEW of;
  208913. zerostruct (of);
  208914. #ifdef OPENFILENAME_SIZE_VERSION_400W
  208915. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  208916. #else
  208917. of.lStructSize = sizeof (of);
  208918. #endif
  208919. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208920. of.lpstrFilter = filters;
  208921. of.nFilterIndex = 1;
  208922. of.lpstrFile = files;
  208923. of.nMaxFile = charsAvailableForResult;
  208924. of.lpstrInitialDir = info.initialPath;
  208925. of.lpstrTitle = title;
  208926. of.Flags = flags;
  208927. of.lCustData = (LPARAM) &info;
  208928. if (extraInfoComponent != 0)
  208929. of.lpfnHook = &openCallback;
  208930. if (! (isSaveDialogue ? GetSaveFileName (&of)
  208931. : GetOpenFileName (&of)))
  208932. return;
  208933. filenameOffset = of.nFileOffset;
  208934. }
  208935. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  208936. {
  208937. const WCHAR* filename = files + filenameOffset;
  208938. while (*filename != 0)
  208939. {
  208940. results.add (File (String (files) + "\\" + String (filename)));
  208941. filename += CharacterFunctions::length (filename) + 1;
  208942. }
  208943. }
  208944. else if (files[0] != 0)
  208945. {
  208946. results.add (File (String (files)));
  208947. }
  208948. }
  208949. #endif
  208950. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  208951. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  208952. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208953. // compiled on its own).
  208954. #if JUCE_INCLUDED_FILE
  208955. void SystemClipboard::copyTextToClipboard (const String& text)
  208956. {
  208957. if (OpenClipboard (0) != 0)
  208958. {
  208959. if (EmptyClipboard() != 0)
  208960. {
  208961. const int len = text.length();
  208962. if (len > 0)
  208963. {
  208964. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  208965. (len + 1) * sizeof (wchar_t));
  208966. if (bufH != 0)
  208967. {
  208968. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  208969. text.copyToUnicode (data, len);
  208970. GlobalUnlock (bufH);
  208971. SetClipboardData (CF_UNICODETEXT, bufH);
  208972. }
  208973. }
  208974. }
  208975. CloseClipboard();
  208976. }
  208977. }
  208978. const String SystemClipboard::getTextFromClipboard()
  208979. {
  208980. String result;
  208981. if (OpenClipboard (0) != 0)
  208982. {
  208983. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  208984. if (bufH != 0)
  208985. {
  208986. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  208987. if (data != 0)
  208988. {
  208989. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  208990. GlobalUnlock (bufH);
  208991. }
  208992. }
  208993. CloseClipboard();
  208994. }
  208995. return result;
  208996. }
  208997. #endif
  208998. /*** End of inlined file: juce_win32_Misc.cpp ***/
  208999. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209000. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209001. // compiled on its own).
  209002. #if JUCE_INCLUDED_FILE
  209003. namespace ActiveXHelpers
  209004. {
  209005. class JuceIStorage : public ComBaseClassHelper <IStorage>
  209006. {
  209007. public:
  209008. JuceIStorage() {}
  209009. ~JuceIStorage() {}
  209010. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209011. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209012. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209013. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209014. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209015. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209016. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209017. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209018. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209019. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209020. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209021. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209022. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209023. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209024. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209025. juce_UseDebuggingNewOperator
  209026. };
  209027. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209028. {
  209029. HWND window;
  209030. public:
  209031. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209032. ~JuceOleInPlaceFrame() {}
  209033. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209034. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209035. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209036. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209037. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209038. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209039. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209040. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209041. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209042. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209043. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209044. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209045. juce_UseDebuggingNewOperator
  209046. };
  209047. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209048. {
  209049. HWND window;
  209050. JuceOleInPlaceFrame* frame;
  209051. public:
  209052. JuceIOleInPlaceSite (HWND window_)
  209053. : window (window_),
  209054. frame (new JuceOleInPlaceFrame (window))
  209055. {}
  209056. ~JuceIOleInPlaceSite()
  209057. {
  209058. frame->Release();
  209059. }
  209060. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209061. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209062. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209063. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209064. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209065. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209066. {
  209067. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  209068. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  209069. */
  209070. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  209071. if (lplpDoc != 0) *lplpDoc = 0;
  209072. lpFrameInfo->fMDIApp = FALSE;
  209073. lpFrameInfo->hwndFrame = window;
  209074. lpFrameInfo->haccel = 0;
  209075. lpFrameInfo->cAccelEntries = 0;
  209076. return S_OK;
  209077. }
  209078. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209079. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209080. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209081. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209082. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209083. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209084. juce_UseDebuggingNewOperator
  209085. };
  209086. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209087. {
  209088. JuceIOleInPlaceSite* inplaceSite;
  209089. public:
  209090. JuceIOleClientSite (HWND window)
  209091. : inplaceSite (new JuceIOleInPlaceSite (window))
  209092. {}
  209093. ~JuceIOleClientSite()
  209094. {
  209095. inplaceSite->Release();
  209096. }
  209097. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  209098. {
  209099. if (type == IID_IOleInPlaceSite)
  209100. {
  209101. inplaceSite->AddRef();
  209102. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209103. return S_OK;
  209104. }
  209105. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209106. }
  209107. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209108. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209109. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209110. HRESULT __stdcall ShowObject() { return S_OK; }
  209111. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209112. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209113. juce_UseDebuggingNewOperator
  209114. };
  209115. static Array<ActiveXControlComponent*> activeXComps;
  209116. static HWND getHWND (const ActiveXControlComponent* const component)
  209117. {
  209118. HWND hwnd = 0;
  209119. const IID iid = IID_IOleWindow;
  209120. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209121. if (window != 0)
  209122. {
  209123. window->GetWindow (&hwnd);
  209124. window->Release();
  209125. }
  209126. return hwnd;
  209127. }
  209128. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209129. {
  209130. RECT activeXRect, peerRect;
  209131. GetWindowRect (hwnd, &activeXRect);
  209132. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209133. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209134. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209135. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209136. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209137. switch (message)
  209138. {
  209139. case WM_MOUSEMOVE:
  209140. case WM_LBUTTONDOWN:
  209141. case WM_MBUTTONDOWN:
  209142. case WM_RBUTTONDOWN:
  209143. case WM_LBUTTONUP:
  209144. case WM_MBUTTONUP:
  209145. case WM_RBUTTONUP:
  209146. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209147. break;
  209148. default:
  209149. break;
  209150. }
  209151. }
  209152. }
  209153. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209154. {
  209155. ActiveXControlComponent& owner;
  209156. bool wasShowing;
  209157. public:
  209158. HWND controlHWND;
  209159. IStorage* storage;
  209160. IOleClientSite* clientSite;
  209161. IOleObject* control;
  209162. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  209163. : ComponentMovementWatcher (&owner_),
  209164. owner (owner_),
  209165. wasShowing (owner_.isShowing()),
  209166. controlHWND (0),
  209167. storage (new ActiveXHelpers::JuceIStorage()),
  209168. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209169. control (0)
  209170. {
  209171. }
  209172. ~Pimpl()
  209173. {
  209174. if (control != 0)
  209175. {
  209176. control->Close (OLECLOSE_NOSAVE);
  209177. control->Release();
  209178. }
  209179. clientSite->Release();
  209180. storage->Release();
  209181. }
  209182. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209183. {
  209184. Component* const topComp = owner.getTopLevelComponent();
  209185. if (topComp->getPeer() != 0)
  209186. {
  209187. const Point<int> pos (owner.relativePositionToOtherComponent (topComp, Point<int>()));
  209188. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  209189. }
  209190. }
  209191. void componentPeerChanged()
  209192. {
  209193. const bool isShowingNow = owner.isShowing();
  209194. if (wasShowing != isShowingNow)
  209195. {
  209196. wasShowing = isShowingNow;
  209197. owner.setControlVisible (isShowingNow);
  209198. }
  209199. componentMovedOrResized (true, true);
  209200. }
  209201. void componentVisibilityChanged (Component&)
  209202. {
  209203. componentPeerChanged();
  209204. }
  209205. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209206. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209207. {
  209208. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209209. {
  209210. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209211. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209212. {
  209213. switch (message)
  209214. {
  209215. case WM_MOUSEMOVE:
  209216. case WM_LBUTTONDOWN:
  209217. case WM_MBUTTONDOWN:
  209218. case WM_RBUTTONDOWN:
  209219. case WM_LBUTTONUP:
  209220. case WM_MBUTTONUP:
  209221. case WM_RBUTTONUP:
  209222. case WM_LBUTTONDBLCLK:
  209223. case WM_MBUTTONDBLCLK:
  209224. case WM_RBUTTONDBLCLK:
  209225. if (ax->isShowing())
  209226. {
  209227. ComponentPeer* const peer = ax->getPeer();
  209228. if (peer != 0)
  209229. {
  209230. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209231. if (! ax->areMouseEventsAllowed())
  209232. return 0;
  209233. }
  209234. }
  209235. break;
  209236. default:
  209237. break;
  209238. }
  209239. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209240. }
  209241. }
  209242. return DefWindowProc (hwnd, message, wParam, lParam);
  209243. }
  209244. };
  209245. ActiveXControlComponent::ActiveXControlComponent()
  209246. : originalWndProc (0),
  209247. mouseEventsAllowed (true)
  209248. {
  209249. ActiveXHelpers::activeXComps.add (this);
  209250. }
  209251. ActiveXControlComponent::~ActiveXControlComponent()
  209252. {
  209253. deleteControl();
  209254. ActiveXHelpers::activeXComps.removeValue (this);
  209255. }
  209256. void ActiveXControlComponent::paint (Graphics& g)
  209257. {
  209258. if (control == 0)
  209259. g.fillAll (Colours::lightgrey);
  209260. }
  209261. bool ActiveXControlComponent::createControl (const void* controlIID)
  209262. {
  209263. deleteControl();
  209264. ComponentPeer* const peer = getPeer();
  209265. // the component must have already been added to a real window when you call this!
  209266. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209267. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209268. {
  209269. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  209270. HWND hwnd = (HWND) peer->getNativeHandle();
  209271. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209272. HRESULT hr;
  209273. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209274. newControl->clientSite, newControl->storage,
  209275. (void**) &(newControl->control))) == S_OK)
  209276. {
  209277. newControl->control->SetHostNames (L"Juce", 0);
  209278. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209279. {
  209280. RECT rect;
  209281. rect.left = pos.getX();
  209282. rect.top = pos.getY();
  209283. rect.right = pos.getX() + getWidth();
  209284. rect.bottom = pos.getY() + getHeight();
  209285. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209286. {
  209287. control = newControl;
  209288. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209289. control->controlHWND = ActiveXHelpers::getHWND (this);
  209290. if (control->controlHWND != 0)
  209291. {
  209292. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209293. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209294. }
  209295. return true;
  209296. }
  209297. }
  209298. }
  209299. }
  209300. return false;
  209301. }
  209302. void ActiveXControlComponent::deleteControl()
  209303. {
  209304. control = 0;
  209305. originalWndProc = 0;
  209306. }
  209307. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209308. {
  209309. void* result = 0;
  209310. if (control != 0 && control->control != 0
  209311. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209312. return result;
  209313. return 0;
  209314. }
  209315. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209316. {
  209317. if (control->controlHWND != 0)
  209318. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209319. }
  209320. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209321. {
  209322. if (control->controlHWND != 0)
  209323. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209324. }
  209325. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209326. {
  209327. mouseEventsAllowed = eventsCanReachControl;
  209328. }
  209329. #endif
  209330. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209331. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209332. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209333. // compiled on its own).
  209334. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209335. using namespace QTOLibrary;
  209336. using namespace QTOControlLib;
  209337. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209338. static bool isQTAvailable = false;
  209339. class QuickTimeMovieComponent::Pimpl
  209340. {
  209341. public:
  209342. Pimpl() : dataHandle (0)
  209343. {
  209344. }
  209345. ~Pimpl()
  209346. {
  209347. clearHandle();
  209348. }
  209349. void clearHandle()
  209350. {
  209351. if (dataHandle != 0)
  209352. {
  209353. DisposeHandle (dataHandle);
  209354. dataHandle = 0;
  209355. }
  209356. }
  209357. IQTControlPtr qtControl;
  209358. IQTMoviePtr qtMovie;
  209359. Handle dataHandle;
  209360. };
  209361. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209362. : movieLoaded (false),
  209363. controllerVisible (true)
  209364. {
  209365. pimpl = new Pimpl();
  209366. setMouseEventsAllowed (false);
  209367. }
  209368. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209369. {
  209370. closeMovie();
  209371. pimpl->qtControl = 0;
  209372. deleteControl();
  209373. pimpl = 0;
  209374. }
  209375. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209376. {
  209377. if (! isQTAvailable)
  209378. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209379. return isQTAvailable;
  209380. }
  209381. void QuickTimeMovieComponent::createControlIfNeeded()
  209382. {
  209383. if (isShowing() && ! isControlCreated())
  209384. {
  209385. const IID qtIID = __uuidof (QTControl);
  209386. if (createControl (&qtIID))
  209387. {
  209388. const IID qtInterfaceIID = __uuidof (IQTControl);
  209389. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209390. if (pimpl->qtControl != 0)
  209391. {
  209392. pimpl->qtControl->Release(); // it has one ref too many at this point
  209393. pimpl->qtControl->QuickTimeInitialize();
  209394. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209395. if (movieFile != File::nonexistent)
  209396. loadMovie (movieFile, controllerVisible);
  209397. }
  209398. }
  209399. }
  209400. }
  209401. bool QuickTimeMovieComponent::isControlCreated() const
  209402. {
  209403. return isControlOpen();
  209404. }
  209405. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209406. const bool isControllerVisible)
  209407. {
  209408. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209409. movieFile = File::nonexistent;
  209410. movieLoaded = false;
  209411. pimpl->qtMovie = 0;
  209412. controllerVisible = isControllerVisible;
  209413. createControlIfNeeded();
  209414. if (isControlCreated())
  209415. {
  209416. if (pimpl->qtControl != 0)
  209417. {
  209418. pimpl->qtControl->Put_MovieHandle (0);
  209419. pimpl->clearHandle();
  209420. Movie movie;
  209421. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209422. {
  209423. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209424. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209425. if (pimpl->qtMovie != 0)
  209426. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209427. : qtMovieControllerTypeNone);
  209428. }
  209429. if (movie == 0)
  209430. pimpl->clearHandle();
  209431. }
  209432. movieLoaded = (pimpl->qtMovie != 0);
  209433. }
  209434. else
  209435. {
  209436. // You're trying to open a movie when the control hasn't yet been created, probably because
  209437. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209438. jassertfalse;
  209439. }
  209440. return movieLoaded;
  209441. }
  209442. void QuickTimeMovieComponent::closeMovie()
  209443. {
  209444. stop();
  209445. movieFile = File::nonexistent;
  209446. movieLoaded = false;
  209447. pimpl->qtMovie = 0;
  209448. if (pimpl->qtControl != 0)
  209449. pimpl->qtControl->Put_MovieHandle (0);
  209450. pimpl->clearHandle();
  209451. }
  209452. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209453. {
  209454. return movieFile;
  209455. }
  209456. bool QuickTimeMovieComponent::isMovieOpen() const
  209457. {
  209458. return movieLoaded;
  209459. }
  209460. double QuickTimeMovieComponent::getMovieDuration() const
  209461. {
  209462. if (pimpl->qtMovie != 0)
  209463. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209464. return 0.0;
  209465. }
  209466. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209467. {
  209468. if (pimpl->qtMovie != 0)
  209469. {
  209470. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209471. width = r.right - r.left;
  209472. height = r.bottom - r.top;
  209473. }
  209474. else
  209475. {
  209476. width = height = 0;
  209477. }
  209478. }
  209479. void QuickTimeMovieComponent::play()
  209480. {
  209481. if (pimpl->qtMovie != 0)
  209482. pimpl->qtMovie->Play();
  209483. }
  209484. void QuickTimeMovieComponent::stop()
  209485. {
  209486. if (pimpl->qtMovie != 0)
  209487. pimpl->qtMovie->Stop();
  209488. }
  209489. bool QuickTimeMovieComponent::isPlaying() const
  209490. {
  209491. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209492. }
  209493. void QuickTimeMovieComponent::setPosition (const double seconds)
  209494. {
  209495. if (pimpl->qtMovie != 0)
  209496. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209497. }
  209498. double QuickTimeMovieComponent::getPosition() const
  209499. {
  209500. if (pimpl->qtMovie != 0)
  209501. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209502. return 0.0;
  209503. }
  209504. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209505. {
  209506. if (pimpl->qtMovie != 0)
  209507. pimpl->qtMovie->PutRate (newSpeed);
  209508. }
  209509. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209510. {
  209511. if (pimpl->qtMovie != 0)
  209512. {
  209513. pimpl->qtMovie->PutAudioVolume (newVolume);
  209514. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209515. }
  209516. }
  209517. float QuickTimeMovieComponent::getMovieVolume() const
  209518. {
  209519. if (pimpl->qtMovie != 0)
  209520. return pimpl->qtMovie->GetAudioVolume();
  209521. return 0.0f;
  209522. }
  209523. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209524. {
  209525. if (pimpl->qtMovie != 0)
  209526. pimpl->qtMovie->PutLoop (shouldLoop);
  209527. }
  209528. bool QuickTimeMovieComponent::isLooping() const
  209529. {
  209530. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209531. }
  209532. bool QuickTimeMovieComponent::isControllerVisible() const
  209533. {
  209534. return controllerVisible;
  209535. }
  209536. void QuickTimeMovieComponent::parentHierarchyChanged()
  209537. {
  209538. createControlIfNeeded();
  209539. QTCompBaseClass::parentHierarchyChanged();
  209540. }
  209541. void QuickTimeMovieComponent::visibilityChanged()
  209542. {
  209543. createControlIfNeeded();
  209544. QTCompBaseClass::visibilityChanged();
  209545. }
  209546. void QuickTimeMovieComponent::paint (Graphics& g)
  209547. {
  209548. if (! isControlCreated())
  209549. g.fillAll (Colours::black);
  209550. }
  209551. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209552. {
  209553. Handle dataRef = 0;
  209554. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209555. if (err == noErr)
  209556. {
  209557. Str255 suffix;
  209558. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209559. StringPtr name = suffix;
  209560. err = PtrAndHand (name, dataRef, name[0] + 1);
  209561. if (err == noErr)
  209562. {
  209563. long atoms[3];
  209564. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209565. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209566. atoms[2] = EndianU32_NtoB (MovieFileType);
  209567. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209568. if (err == noErr)
  209569. return dataRef;
  209570. }
  209571. DisposeHandle (dataRef);
  209572. }
  209573. return 0;
  209574. }
  209575. static CFStringRef juceStringToCFString (const String& s)
  209576. {
  209577. const int len = s.length();
  209578. const juce_wchar* const t = s;
  209579. HeapBlock <UniChar> temp (len + 2);
  209580. for (int i = 0; i <= len; ++i)
  209581. temp[i] = t[i];
  209582. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209583. }
  209584. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209585. {
  209586. Boolean trueBool = true;
  209587. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209588. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209589. props[prop].propValueSize = sizeof (trueBool);
  209590. props[prop].propValueAddress = &trueBool;
  209591. ++prop;
  209592. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209593. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209594. props[prop].propValueSize = sizeof (trueBool);
  209595. props[prop].propValueAddress = &trueBool;
  209596. ++prop;
  209597. Boolean isActive = true;
  209598. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209599. props[prop].propID = kQTNewMoviePropertyID_Active;
  209600. props[prop].propValueSize = sizeof (isActive);
  209601. props[prop].propValueAddress = &isActive;
  209602. ++prop;
  209603. MacSetPort (0);
  209604. jassert (prop <= 5);
  209605. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209606. return err == noErr;
  209607. }
  209608. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209609. {
  209610. if (input == 0)
  209611. return false;
  209612. dataHandle = 0;
  209613. bool ok = false;
  209614. QTNewMoviePropertyElement props[5];
  209615. zeromem (props, sizeof (props));
  209616. int prop = 0;
  209617. DataReferenceRecord dr;
  209618. props[prop].propClass = kQTPropertyClass_DataLocation;
  209619. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209620. props[prop].propValueSize = sizeof (dr);
  209621. props[prop].propValueAddress = &dr;
  209622. ++prop;
  209623. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209624. if (fin != 0)
  209625. {
  209626. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209627. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209628. &dr.dataRef, &dr.dataRefType);
  209629. ok = openMovie (props, prop, movie);
  209630. DisposeHandle (dr.dataRef);
  209631. CFRelease (filePath);
  209632. }
  209633. else
  209634. {
  209635. // sanity-check because this currently needs to load the whole stream into memory..
  209636. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209637. dataHandle = NewHandle ((Size) input->getTotalLength());
  209638. HLock (dataHandle);
  209639. // read the entire stream into memory - this is a pain, but can't get it to work
  209640. // properly using a custom callback to supply the data.
  209641. input->read (*dataHandle, (int) input->getTotalLength());
  209642. HUnlock (dataHandle);
  209643. // different types to get QT to try. (We should really be a bit smarter here by
  209644. // working out in advance which one the stream contains, rather than just trying
  209645. // each one)
  209646. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209647. "\04.avi", "\04.m4a" };
  209648. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209649. {
  209650. /* // this fails for some bizarre reason - it can be bodged to work with
  209651. // movies, but can't seem to do it for other file types..
  209652. QTNewMovieUserProcRecord procInfo;
  209653. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209654. procInfo.getMovieUserProcRefcon = this;
  209655. procInfo.defaultDataRef.dataRef = dataRef;
  209656. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209657. props[prop].propClass = kQTPropertyClass_DataLocation;
  209658. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209659. props[prop].propValueSize = sizeof (procInfo);
  209660. props[prop].propValueAddress = (void*) &procInfo;
  209661. ++prop; */
  209662. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209663. dr.dataRefType = HandleDataHandlerSubType;
  209664. ok = openMovie (props, prop, movie);
  209665. DisposeHandle (dr.dataRef);
  209666. }
  209667. }
  209668. return ok;
  209669. }
  209670. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209671. const bool isControllerVisible)
  209672. {
  209673. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209674. movieFile = movieFile_;
  209675. return ok;
  209676. }
  209677. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209678. const bool isControllerVisible)
  209679. {
  209680. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209681. }
  209682. void QuickTimeMovieComponent::goToStart()
  209683. {
  209684. setPosition (0.0);
  209685. }
  209686. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209687. const RectanglePlacement& placement)
  209688. {
  209689. int normalWidth, normalHeight;
  209690. getMovieNormalSize (normalWidth, normalHeight);
  209691. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209692. {
  209693. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209694. placement.applyTo (x, y, w, h,
  209695. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209696. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209697. if (w > 0 && h > 0)
  209698. {
  209699. setBounds (roundToInt (x), roundToInt (y),
  209700. roundToInt (w), roundToInt (h));
  209701. }
  209702. }
  209703. else
  209704. {
  209705. setBounds (spaceToFitWithin);
  209706. }
  209707. }
  209708. #endif
  209709. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209710. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209711. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209712. // compiled on its own).
  209713. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209714. class WebBrowserComponentInternal : public ActiveXControlComponent
  209715. {
  209716. public:
  209717. WebBrowserComponentInternal()
  209718. : browser (0),
  209719. connectionPoint (0),
  209720. adviseCookie (0)
  209721. {
  209722. }
  209723. ~WebBrowserComponentInternal()
  209724. {
  209725. if (connectionPoint != 0)
  209726. connectionPoint->Unadvise (adviseCookie);
  209727. if (browser != 0)
  209728. browser->Release();
  209729. }
  209730. void createBrowser()
  209731. {
  209732. createControl (&CLSID_WebBrowser);
  209733. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209734. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209735. if (connectionPointContainer != 0)
  209736. {
  209737. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209738. &connectionPoint);
  209739. if (connectionPoint != 0)
  209740. {
  209741. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209742. jassert (owner != 0);
  209743. EventHandler* handler = new EventHandler (owner);
  209744. connectionPoint->Advise (handler, &adviseCookie);
  209745. handler->Release();
  209746. }
  209747. }
  209748. }
  209749. void goToURL (const String& url,
  209750. const StringArray* headers,
  209751. const MemoryBlock* postData)
  209752. {
  209753. if (browser != 0)
  209754. {
  209755. LPSAFEARRAY sa = 0;
  209756. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209757. VariantInit (&flags);
  209758. VariantInit (&frame);
  209759. VariantInit (&postDataVar);
  209760. VariantInit (&headersVar);
  209761. if (headers != 0)
  209762. {
  209763. V_VT (&headersVar) = VT_BSTR;
  209764. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  209765. }
  209766. if (postData != 0 && postData->getSize() > 0)
  209767. {
  209768. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209769. if (sa != 0)
  209770. {
  209771. void* data = 0;
  209772. SafeArrayAccessData (sa, &data);
  209773. jassert (data != 0);
  209774. if (data != 0)
  209775. {
  209776. postData->copyTo (data, 0, postData->getSize());
  209777. SafeArrayUnaccessData (sa);
  209778. VARIANT postDataVar2;
  209779. VariantInit (&postDataVar2);
  209780. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209781. V_ARRAY (&postDataVar2) = sa;
  209782. postDataVar = postDataVar2;
  209783. }
  209784. }
  209785. }
  209786. browser->Navigate ((BSTR) (const OLECHAR*) url,
  209787. &flags, &frame,
  209788. &postDataVar, &headersVar);
  209789. if (sa != 0)
  209790. SafeArrayDestroy (sa);
  209791. VariantClear (&flags);
  209792. VariantClear (&frame);
  209793. VariantClear (&postDataVar);
  209794. VariantClear (&headersVar);
  209795. }
  209796. }
  209797. IWebBrowser2* browser;
  209798. juce_UseDebuggingNewOperator
  209799. private:
  209800. IConnectionPoint* connectionPoint;
  209801. DWORD adviseCookie;
  209802. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209803. public ComponentMovementWatcher
  209804. {
  209805. public:
  209806. EventHandler (WebBrowserComponent* owner_)
  209807. : ComponentMovementWatcher (owner_),
  209808. owner (owner_)
  209809. {
  209810. }
  209811. ~EventHandler()
  209812. {
  209813. }
  209814. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  209815. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  209816. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  209817. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  209818. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  209819. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  209820. UINT __RPC_FAR* /*puArgErr*/)
  209821. {
  209822. switch (dispIdMember)
  209823. {
  209824. case DISPID_BEFORENAVIGATE2:
  209825. {
  209826. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209827. String url;
  209828. if ((vurl->vt & VT_BYREF) != 0)
  209829. url = *vurl->pbstrVal;
  209830. else
  209831. url = vurl->bstrVal;
  209832. *pDispParams->rgvarg->pboolVal
  209833. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  209834. : VARIANT_TRUE;
  209835. return S_OK;
  209836. }
  209837. default:
  209838. break;
  209839. }
  209840. return E_NOTIMPL;
  209841. }
  209842. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  209843. void componentPeerChanged() {}
  209844. void componentVisibilityChanged (Component&)
  209845. {
  209846. owner->visibilityChanged();
  209847. }
  209848. juce_UseDebuggingNewOperator
  209849. private:
  209850. WebBrowserComponent* const owner;
  209851. EventHandler (const EventHandler&);
  209852. EventHandler& operator= (const EventHandler&);
  209853. };
  209854. };
  209855. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209856. : browser (0),
  209857. blankPageShown (false),
  209858. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209859. {
  209860. setOpaque (true);
  209861. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209862. }
  209863. WebBrowserComponent::~WebBrowserComponent()
  209864. {
  209865. delete browser;
  209866. }
  209867. void WebBrowserComponent::goToURL (const String& url,
  209868. const StringArray* headers,
  209869. const MemoryBlock* postData)
  209870. {
  209871. lastURL = url;
  209872. lastHeaders.clear();
  209873. if (headers != 0)
  209874. lastHeaders = *headers;
  209875. lastPostData.setSize (0);
  209876. if (postData != 0)
  209877. lastPostData = *postData;
  209878. blankPageShown = false;
  209879. browser->goToURL (url, headers, postData);
  209880. }
  209881. void WebBrowserComponent::stop()
  209882. {
  209883. if (browser->browser != 0)
  209884. browser->browser->Stop();
  209885. }
  209886. void WebBrowserComponent::goBack()
  209887. {
  209888. lastURL = String::empty;
  209889. blankPageShown = false;
  209890. if (browser->browser != 0)
  209891. browser->browser->GoBack();
  209892. }
  209893. void WebBrowserComponent::goForward()
  209894. {
  209895. lastURL = String::empty;
  209896. if (browser->browser != 0)
  209897. browser->browser->GoForward();
  209898. }
  209899. void WebBrowserComponent::refresh()
  209900. {
  209901. if (browser->browser != 0)
  209902. browser->browser->Refresh();
  209903. }
  209904. void WebBrowserComponent::paint (Graphics& g)
  209905. {
  209906. if (browser->browser == 0)
  209907. g.fillAll (Colours::white);
  209908. }
  209909. void WebBrowserComponent::checkWindowAssociation()
  209910. {
  209911. if (isShowing())
  209912. {
  209913. if (browser->browser == 0 && getPeer() != 0)
  209914. {
  209915. browser->createBrowser();
  209916. reloadLastURL();
  209917. }
  209918. else
  209919. {
  209920. if (blankPageShown)
  209921. goBack();
  209922. }
  209923. }
  209924. else
  209925. {
  209926. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  209927. {
  209928. // when the component becomes invisible, some stuff like flash
  209929. // carries on playing audio, so we need to force it onto a blank
  209930. // page to avoid this..
  209931. blankPageShown = true;
  209932. browser->goToURL ("about:blank", 0, 0);
  209933. }
  209934. }
  209935. }
  209936. void WebBrowserComponent::reloadLastURL()
  209937. {
  209938. if (lastURL.isNotEmpty())
  209939. {
  209940. goToURL (lastURL, &lastHeaders, &lastPostData);
  209941. lastURL = String::empty;
  209942. }
  209943. }
  209944. void WebBrowserComponent::parentHierarchyChanged()
  209945. {
  209946. checkWindowAssociation();
  209947. }
  209948. void WebBrowserComponent::resized()
  209949. {
  209950. browser->setSize (getWidth(), getHeight());
  209951. }
  209952. void WebBrowserComponent::visibilityChanged()
  209953. {
  209954. checkWindowAssociation();
  209955. }
  209956. bool WebBrowserComponent::pageAboutToLoad (const String&)
  209957. {
  209958. return true;
  209959. }
  209960. #endif
  209961. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209962. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  209963. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209964. // compiled on its own).
  209965. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  209966. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  209967. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  209968. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  209969. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  209970. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  209971. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  209972. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  209973. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  209974. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  209975. #define WGL_ACCELERATION_ARB 0x2003
  209976. #define WGL_SWAP_METHOD_ARB 0x2007
  209977. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  209978. #define WGL_PIXEL_TYPE_ARB 0x2013
  209979. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  209980. #define WGL_COLOR_BITS_ARB 0x2014
  209981. #define WGL_RED_BITS_ARB 0x2015
  209982. #define WGL_GREEN_BITS_ARB 0x2017
  209983. #define WGL_BLUE_BITS_ARB 0x2019
  209984. #define WGL_ALPHA_BITS_ARB 0x201B
  209985. #define WGL_DEPTH_BITS_ARB 0x2022
  209986. #define WGL_STENCIL_BITS_ARB 0x2023
  209987. #define WGL_FULL_ACCELERATION_ARB 0x2027
  209988. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  209989. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  209990. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  209991. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  209992. #define WGL_STEREO_ARB 0x2012
  209993. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  209994. #define WGL_SAMPLES_ARB 0x2042
  209995. #define WGL_TYPE_RGBA_ARB 0x202B
  209996. static void getWglExtensions (HDC dc, StringArray& result) throw()
  209997. {
  209998. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  209999. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210000. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210001. else
  210002. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  210003. }
  210004. class WindowedGLContext : public OpenGLContext
  210005. {
  210006. public:
  210007. WindowedGLContext (Component* const component_,
  210008. HGLRC contextToShareWith,
  210009. const OpenGLPixelFormat& pixelFormat)
  210010. : renderContext (0),
  210011. dc (0),
  210012. component (component_)
  210013. {
  210014. jassert (component != 0);
  210015. createNativeWindow();
  210016. // Use a default pixel format that should be supported everywhere
  210017. PIXELFORMATDESCRIPTOR pfd;
  210018. zerostruct (pfd);
  210019. pfd.nSize = sizeof (pfd);
  210020. pfd.nVersion = 1;
  210021. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210022. pfd.iPixelType = PFD_TYPE_RGBA;
  210023. pfd.cColorBits = 24;
  210024. pfd.cDepthBits = 16;
  210025. const int format = ChoosePixelFormat (dc, &pfd);
  210026. if (format != 0)
  210027. SetPixelFormat (dc, format, &pfd);
  210028. renderContext = wglCreateContext (dc);
  210029. makeActive();
  210030. setPixelFormat (pixelFormat);
  210031. if (contextToShareWith != 0 && renderContext != 0)
  210032. wglShareLists (contextToShareWith, renderContext);
  210033. }
  210034. ~WindowedGLContext()
  210035. {
  210036. deleteContext();
  210037. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210038. nativeWindow = 0;
  210039. }
  210040. void deleteContext()
  210041. {
  210042. makeInactive();
  210043. if (renderContext != 0)
  210044. {
  210045. wglDeleteContext (renderContext);
  210046. renderContext = 0;
  210047. }
  210048. }
  210049. bool makeActive() const throw()
  210050. {
  210051. jassert (renderContext != 0);
  210052. return wglMakeCurrent (dc, renderContext) != 0;
  210053. }
  210054. bool makeInactive() const throw()
  210055. {
  210056. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210057. }
  210058. bool isActive() const throw()
  210059. {
  210060. return wglGetCurrentContext() == renderContext;
  210061. }
  210062. const OpenGLPixelFormat getPixelFormat() const
  210063. {
  210064. OpenGLPixelFormat pf;
  210065. makeActive();
  210066. StringArray availableExtensions;
  210067. getWglExtensions (dc, availableExtensions);
  210068. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210069. return pf;
  210070. }
  210071. void* getRawContext() const throw()
  210072. {
  210073. return renderContext;
  210074. }
  210075. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210076. {
  210077. makeActive();
  210078. PIXELFORMATDESCRIPTOR pfd;
  210079. zerostruct (pfd);
  210080. pfd.nSize = sizeof (pfd);
  210081. pfd.nVersion = 1;
  210082. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210083. pfd.iPixelType = PFD_TYPE_RGBA;
  210084. pfd.iLayerType = PFD_MAIN_PLANE;
  210085. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210086. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210087. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210088. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210089. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210090. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210091. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210092. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210093. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210094. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210095. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210096. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210097. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210098. int format = 0;
  210099. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210100. StringArray availableExtensions;
  210101. getWglExtensions (dc, availableExtensions);
  210102. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210103. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210104. {
  210105. int attributes[64];
  210106. int n = 0;
  210107. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210108. attributes[n++] = GL_TRUE;
  210109. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210110. attributes[n++] = GL_TRUE;
  210111. attributes[n++] = WGL_ACCELERATION_ARB;
  210112. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210113. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210114. attributes[n++] = GL_TRUE;
  210115. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210116. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210117. attributes[n++] = WGL_COLOR_BITS_ARB;
  210118. attributes[n++] = pfd.cColorBits;
  210119. attributes[n++] = WGL_RED_BITS_ARB;
  210120. attributes[n++] = pixelFormat.redBits;
  210121. attributes[n++] = WGL_GREEN_BITS_ARB;
  210122. attributes[n++] = pixelFormat.greenBits;
  210123. attributes[n++] = WGL_BLUE_BITS_ARB;
  210124. attributes[n++] = pixelFormat.blueBits;
  210125. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210126. attributes[n++] = pixelFormat.alphaBits;
  210127. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210128. attributes[n++] = pixelFormat.depthBufferBits;
  210129. if (pixelFormat.stencilBufferBits > 0)
  210130. {
  210131. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210132. attributes[n++] = pixelFormat.stencilBufferBits;
  210133. }
  210134. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210135. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210136. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210137. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210138. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210139. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210140. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210141. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210142. if (availableExtensions.contains ("WGL_ARB_multisample")
  210143. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210144. {
  210145. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210146. attributes[n++] = 1;
  210147. attributes[n++] = WGL_SAMPLES_ARB;
  210148. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210149. }
  210150. attributes[n++] = 0;
  210151. UINT formatsCount;
  210152. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210153. (void) ok;
  210154. jassert (ok);
  210155. }
  210156. else
  210157. {
  210158. format = ChoosePixelFormat (dc, &pfd);
  210159. }
  210160. if (format != 0)
  210161. {
  210162. makeInactive();
  210163. // win32 can't change the pixel format of a window, so need to delete the
  210164. // old one and create a new one..
  210165. jassert (nativeWindow != 0);
  210166. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210167. nativeWindow = 0;
  210168. createNativeWindow();
  210169. if (SetPixelFormat (dc, format, &pfd))
  210170. {
  210171. wglDeleteContext (renderContext);
  210172. renderContext = wglCreateContext (dc);
  210173. jassert (renderContext != 0);
  210174. return renderContext != 0;
  210175. }
  210176. }
  210177. return false;
  210178. }
  210179. void updateWindowPosition (int x, int y, int w, int h, int)
  210180. {
  210181. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210182. x, y, w, h,
  210183. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210184. }
  210185. void repaint()
  210186. {
  210187. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210188. }
  210189. void swapBuffers()
  210190. {
  210191. SwapBuffers (dc);
  210192. }
  210193. bool setSwapInterval (int numFramesPerSwap)
  210194. {
  210195. makeActive();
  210196. StringArray availableExtensions;
  210197. getWglExtensions (dc, availableExtensions);
  210198. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210199. return availableExtensions.contains ("WGL_EXT_swap_control")
  210200. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210201. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210202. }
  210203. int getSwapInterval() const
  210204. {
  210205. makeActive();
  210206. StringArray availableExtensions;
  210207. getWglExtensions (dc, availableExtensions);
  210208. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210209. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210210. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210211. return wglGetSwapIntervalEXT();
  210212. return 0;
  210213. }
  210214. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210215. {
  210216. jassert (isActive());
  210217. StringArray availableExtensions;
  210218. getWglExtensions (dc, availableExtensions);
  210219. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210220. int numTypes = 0;
  210221. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210222. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210223. {
  210224. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210225. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210226. jassertfalse;
  210227. }
  210228. else
  210229. {
  210230. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210231. }
  210232. OpenGLPixelFormat pf;
  210233. for (int i = 0; i < numTypes; ++i)
  210234. {
  210235. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210236. {
  210237. bool alreadyListed = false;
  210238. for (int j = results.size(); --j >= 0;)
  210239. if (pf == *results.getUnchecked(j))
  210240. alreadyListed = true;
  210241. if (! alreadyListed)
  210242. results.add (new OpenGLPixelFormat (pf));
  210243. }
  210244. }
  210245. }
  210246. void* getNativeWindowHandle() const
  210247. {
  210248. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210249. }
  210250. juce_UseDebuggingNewOperator
  210251. HGLRC renderContext;
  210252. private:
  210253. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210254. Component* const component;
  210255. HDC dc;
  210256. void createNativeWindow()
  210257. {
  210258. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210259. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210260. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210261. nativeWindow->dontRepaint = true;
  210262. nativeWindow->setVisible (true);
  210263. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210264. }
  210265. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210266. OpenGLPixelFormat& result,
  210267. const StringArray& availableExtensions) const throw()
  210268. {
  210269. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210270. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210271. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210272. {
  210273. int attributes[32];
  210274. int numAttributes = 0;
  210275. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210276. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210277. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210278. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210279. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210280. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210281. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210282. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210283. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210284. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210285. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210286. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210287. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210288. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210289. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210290. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210291. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210292. int values[32];
  210293. zeromem (values, sizeof (values));
  210294. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210295. {
  210296. int n = 0;
  210297. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210298. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210299. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210300. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210301. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210302. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210303. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210304. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210305. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210306. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210307. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210308. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210309. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210310. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210311. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210312. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210313. return isValidFormat;
  210314. }
  210315. else
  210316. {
  210317. jassertfalse;
  210318. }
  210319. }
  210320. else
  210321. {
  210322. PIXELFORMATDESCRIPTOR pfd;
  210323. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210324. {
  210325. result.redBits = pfd.cRedBits;
  210326. result.greenBits = pfd.cGreenBits;
  210327. result.blueBits = pfd.cBlueBits;
  210328. result.alphaBits = pfd.cAlphaBits;
  210329. result.depthBufferBits = pfd.cDepthBits;
  210330. result.stencilBufferBits = pfd.cStencilBits;
  210331. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210332. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210333. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210334. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210335. result.fullSceneAntiAliasingNumSamples = 0;
  210336. return true;
  210337. }
  210338. else
  210339. {
  210340. jassertfalse;
  210341. }
  210342. }
  210343. return false;
  210344. }
  210345. WindowedGLContext (const WindowedGLContext&);
  210346. WindowedGLContext& operator= (const WindowedGLContext&);
  210347. };
  210348. OpenGLContext* OpenGLComponent::createContext()
  210349. {
  210350. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210351. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210352. preferredPixelFormat));
  210353. return (c->renderContext != 0) ? c.release() : 0;
  210354. }
  210355. void* OpenGLComponent::getNativeWindowHandle() const
  210356. {
  210357. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210358. }
  210359. void juce_glViewport (const int w, const int h)
  210360. {
  210361. glViewport (0, 0, w, h);
  210362. }
  210363. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210364. OwnedArray <OpenGLPixelFormat>& results)
  210365. {
  210366. Component tempComp;
  210367. {
  210368. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210369. wc.makeActive();
  210370. wc.findAlternativeOpenGLPixelFormats (results);
  210371. }
  210372. }
  210373. #endif
  210374. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210375. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210376. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210377. // compiled on its own).
  210378. #if JUCE_INCLUDED_FILE
  210379. #if JUCE_USE_CDREADER
  210380. namespace CDReaderHelpers
  210381. {
  210382. //***************************************************************************
  210383. // %%% TARGET STATUS VALUES %%%
  210384. //***************************************************************************
  210385. #define STATUS_GOOD 0x00 // Status Good
  210386. #define STATUS_CHKCOND 0x02 // Check Condition
  210387. #define STATUS_CONDMET 0x04 // Condition Met
  210388. #define STATUS_BUSY 0x08 // Busy
  210389. #define STATUS_INTERM 0x10 // Intermediate
  210390. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  210391. #define STATUS_RESCONF 0x18 // Reservation conflict
  210392. #define STATUS_COMTERM 0x22 // Command Terminated
  210393. #define STATUS_QFULL 0x28 // Queue full
  210394. //***************************************************************************
  210395. // %%% SCSI MISCELLANEOUS EQUATES %%%
  210396. //***************************************************************************
  210397. #define MAXLUN 7 // Maximum Logical Unit Id
  210398. #define MAXTARG 7 // Maximum Target Id
  210399. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  210400. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  210401. //***************************************************************************
  210402. // %%% Commands for all Device Types %%%
  210403. //***************************************************************************
  210404. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  210405. #define SCSI_COMPARE 0x39 // Compare (O)
  210406. #define SCSI_COPY 0x18 // Copy (O)
  210407. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  210408. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  210409. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  210410. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  210411. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  210412. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  210413. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  210414. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  210415. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  210416. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  210417. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  210418. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  210419. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  210420. //***************************************************************************
  210421. // %%% Commands Unique to Direct Access Devices %%%
  210422. //***************************************************************************
  210423. #define SCSI_COMPARE 0x39 // Compare (O)
  210424. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  210425. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  210426. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  210427. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  210428. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  210429. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  210430. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  210431. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  210432. #define SCSI_READ_LONG 0x3E // Read Long (O)
  210433. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  210434. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  210435. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  210436. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  210437. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  210438. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  210439. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  210440. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  210441. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  210442. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  210443. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  210444. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  210445. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  210446. #define SCSI_VERIFY 0x2F // Verify (O)
  210447. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  210448. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  210449. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  210450. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  210451. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  210452. //***************************************************************************
  210453. // %%% Commands Unique to Sequential Access Devices %%%
  210454. //***************************************************************************
  210455. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  210456. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  210457. #define SCSI_LOCATE 0x2B // Locate (O)
  210458. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  210459. #define SCSI_READ_POS 0x34 // Read Position (O)
  210460. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  210461. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  210462. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  210463. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  210464. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  210465. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  210466. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  210467. //***************************************************************************
  210468. // %%% Commands Unique to Printer Devices %%%
  210469. //***************************************************************************
  210470. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  210471. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  210472. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  210473. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  210474. //***************************************************************************
  210475. // %%% Commands Unique to Processor Devices %%%
  210476. //***************************************************************************
  210477. #define SCSI_RECEIVE 0x08 // Receive (O)
  210478. #define SCSI_SEND 0x0A // Send (O)
  210479. //***************************************************************************
  210480. // %%% Commands Unique to Write-Once Devices %%%
  210481. //***************************************************************************
  210482. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  210483. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  210484. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  210485. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  210486. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  210487. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  210488. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  210489. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  210490. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  210491. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  210492. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  210493. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  210494. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  210495. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  210496. //***************************************************************************
  210497. // %%% Commands Unique to CD-ROM Devices %%%
  210498. //***************************************************************************
  210499. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  210500. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  210501. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  210502. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  210503. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  210504. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  210505. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  210506. #define SCSI_READHEADER 0x44 // Read Header (O)
  210507. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  210508. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  210509. //***************************************************************************
  210510. // %%% Commands Unique to Scanner Devices %%%
  210511. //***************************************************************************
  210512. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  210513. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  210514. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  210515. #define SCSI_SCAN 0x1B // Scan (O)
  210516. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  210517. //***************************************************************************
  210518. // %%% Commands Unique to Optical Memory Devices %%%
  210519. //***************************************************************************
  210520. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  210521. //***************************************************************************
  210522. // %%% Commands Unique to Medium Changer Devices %%%
  210523. //***************************************************************************
  210524. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  210525. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  210526. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  210527. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  210528. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  210529. //***************************************************************************
  210530. // %%% Commands Unique to Communication Devices %%%
  210531. //***************************************************************************
  210532. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  210533. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  210534. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  210535. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  210536. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  210537. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  210538. //***************************************************************************
  210539. // %%% Request Sense Data Format %%%
  210540. //***************************************************************************
  210541. typedef struct {
  210542. BYTE ErrorCode; // Error Code (70H or 71H)
  210543. BYTE SegmentNum; // Number of current segment descriptor
  210544. BYTE SenseKey; // Sense Key(See bit definitions too)
  210545. BYTE InfoByte0; // Information MSB
  210546. BYTE InfoByte1; // Information MID
  210547. BYTE InfoByte2; // Information MID
  210548. BYTE InfoByte3; // Information LSB
  210549. BYTE AddSenLen; // Additional Sense Length
  210550. BYTE ComSpecInf0; // Command Specific Information MSB
  210551. BYTE ComSpecInf1; // Command Specific Information MID
  210552. BYTE ComSpecInf2; // Command Specific Information MID
  210553. BYTE ComSpecInf3; // Command Specific Information LSB
  210554. BYTE AddSenseCode; // Additional Sense Code
  210555. BYTE AddSenQual; // Additional Sense Code Qualifier
  210556. BYTE FieldRepUCode; // Field Replaceable Unit Code
  210557. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  210558. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  210559. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  210560. BYTE AddSenseBytes; // Additional Sense Bytes
  210561. } SENSE_DATA_FMT;
  210562. //***************************************************************************
  210563. // %%% REQUEST SENSE ERROR CODE %%%
  210564. //***************************************************************************
  210565. #define SERROR_CURRENT 0x70 // Current Errors
  210566. #define SERROR_DEFERED 0x71 // Deferred Errors
  210567. //***************************************************************************
  210568. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  210569. //***************************************************************************
  210570. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  210571. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  210572. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  210573. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  210574. //***************************************************************************
  210575. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  210576. //***************************************************************************
  210577. #define KEY_NOSENSE 0x00 // No Sense
  210578. #define KEY_RECERROR 0x01 // Recovered Error
  210579. #define KEY_NOTREADY 0x02 // Not Ready
  210580. #define KEY_MEDIUMERR 0x03 // Medium Error
  210581. #define KEY_HARDERROR 0x04 // Hardware Error
  210582. #define KEY_ILLGLREQ 0x05 // Illegal Request
  210583. #define KEY_UNITATT 0x06 // Unit Attention
  210584. #define KEY_DATAPROT 0x07 // Data Protect
  210585. #define KEY_BLANKCHK 0x08 // Blank Check
  210586. #define KEY_VENDSPEC 0x09 // Vendor Specific
  210587. #define KEY_COPYABORT 0x0A // Copy Abort
  210588. #define KEY_EQUAL 0x0C // Equal (Search)
  210589. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  210590. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  210591. #define KEY_RESERVED 0x0F // Reserved
  210592. //***************************************************************************
  210593. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  210594. //***************************************************************************
  210595. #define DTYPE_DASD 0x00 // Disk Device
  210596. #define DTYPE_SEQD 0x01 // Tape Device
  210597. #define DTYPE_PRNT 0x02 // Printer
  210598. #define DTYPE_PROC 0x03 // Processor
  210599. #define DTYPE_WORM 0x04 // Write-once read-multiple
  210600. #define DTYPE_CROM 0x05 // CD-ROM device
  210601. #define DTYPE_SCAN 0x06 // Scanner device
  210602. #define DTYPE_OPTI 0x07 // Optical memory device
  210603. #define DTYPE_JUKE 0x08 // Medium Changer device
  210604. #define DTYPE_COMM 0x09 // Communications device
  210605. #define DTYPE_RESL 0x0A // Reserved (low)
  210606. #define DTYPE_RESH 0x1E // Reserved (high)
  210607. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  210608. //***************************************************************************
  210609. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  210610. //***************************************************************************
  210611. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  210612. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  210613. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  210614. #define ANSI_RESLO 0x3 // Reserved (low)
  210615. #define ANSI_RESHI 0x7 // Reserved (high)
  210616. typedef struct
  210617. {
  210618. USHORT Length;
  210619. UCHAR ScsiStatus;
  210620. UCHAR PathId;
  210621. UCHAR TargetId;
  210622. UCHAR Lun;
  210623. UCHAR CdbLength;
  210624. UCHAR SenseInfoLength;
  210625. UCHAR DataIn;
  210626. ULONG DataTransferLength;
  210627. ULONG TimeOutValue;
  210628. ULONG DataBufferOffset;
  210629. ULONG SenseInfoOffset;
  210630. UCHAR Cdb[16];
  210631. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  210632. typedef struct
  210633. {
  210634. USHORT Length;
  210635. UCHAR ScsiStatus;
  210636. UCHAR PathId;
  210637. UCHAR TargetId;
  210638. UCHAR Lun;
  210639. UCHAR CdbLength;
  210640. UCHAR SenseInfoLength;
  210641. UCHAR DataIn;
  210642. ULONG DataTransferLength;
  210643. ULONG TimeOutValue;
  210644. PVOID DataBuffer;
  210645. ULONG SenseInfoOffset;
  210646. UCHAR Cdb[16];
  210647. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  210648. typedef struct
  210649. {
  210650. SCSI_PASS_THROUGH_DIRECT spt;
  210651. ULONG Filler;
  210652. UCHAR ucSenseBuf[32];
  210653. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  210654. typedef struct
  210655. {
  210656. ULONG Length;
  210657. UCHAR PortNumber;
  210658. UCHAR PathId;
  210659. UCHAR TargetId;
  210660. UCHAR Lun;
  210661. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  210662. #define METHOD_BUFFERED 0
  210663. #define METHOD_IN_DIRECT 1
  210664. #define METHOD_OUT_DIRECT 2
  210665. #define METHOD_NEITHER 3
  210666. #define FILE_ANY_ACCESS 0
  210667. #ifndef FILE_READ_ACCESS
  210668. #define FILE_READ_ACCESS (0x0001)
  210669. #endif
  210670. #ifndef FILE_WRITE_ACCESS
  210671. #define FILE_WRITE_ACCESS (0x0002)
  210672. #endif
  210673. #define IOCTL_SCSI_BASE 0x00000004
  210674. #define SCSI_IOCTL_DATA_OUT 0
  210675. #define SCSI_IOCTL_DATA_IN 1
  210676. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210677. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  210678. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  210679. )
  210680. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210681. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  210682. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210683. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210684. #define SENSE_LEN 14
  210685. #define SRB_DIR_SCSI 0x00
  210686. #define SRB_POSTING 0x01
  210687. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210688. #define SRB_DIR_IN 0x08
  210689. #define SRB_DIR_OUT 0x10
  210690. #define SRB_EVENT_NOTIFY 0x40
  210691. #define RESIDUAL_COUNT_SUPPORTED 0x02
  210692. #define MAX_SRB_TIMEOUT 1080001u
  210693. #define DEFAULT_SRB_TIMEOUT 1080001u
  210694. #define SC_HA_INQUIRY 0x00
  210695. #define SC_GET_DEV_TYPE 0x01
  210696. #define SC_EXEC_SCSI_CMD 0x02
  210697. #define SC_ABORT_SRB 0x03
  210698. #define SC_RESET_DEV 0x04
  210699. #define SC_SET_HA_PARMS 0x05
  210700. #define SC_GET_DISK_INFO 0x06
  210701. #define SC_RESCAN_SCSI_BUS 0x07
  210702. #define SC_GETSET_TIMEOUTS 0x08
  210703. #define SS_PENDING 0x00
  210704. #define SS_COMP 0x01
  210705. #define SS_ABORTED 0x02
  210706. #define SS_ABORT_FAIL 0x03
  210707. #define SS_ERR 0x04
  210708. #define SS_INVALID_CMD 0x80
  210709. #define SS_INVALID_HA 0x81
  210710. #define SS_NO_DEVICE 0x82
  210711. #define SS_INVALID_SRB 0xE0
  210712. #define SS_OLD_MANAGER 0xE1
  210713. #define SS_BUFFER_ALIGN 0xE1
  210714. #define SS_ILLEGAL_MODE 0xE2
  210715. #define SS_NO_ASPI 0xE3
  210716. #define SS_FAILED_INIT 0xE4
  210717. #define SS_ASPI_IS_BUSY 0xE5
  210718. #define SS_BUFFER_TO_BIG 0xE6
  210719. #define SS_BUFFER_TOO_BIG 0xE6
  210720. #define SS_MISMATCHED_COMPONENTS 0xE7
  210721. #define SS_NO_ADAPTERS 0xE8
  210722. #define SS_INSUFFICIENT_RESOURCES 0xE9
  210723. #define SS_ASPI_IS_SHUTDOWN 0xEA
  210724. #define SS_BAD_INSTALL 0xEB
  210725. #define HASTAT_OK 0x00
  210726. #define HASTAT_SEL_TO 0x11
  210727. #define HASTAT_DO_DU 0x12
  210728. #define HASTAT_BUS_FREE 0x13
  210729. #define HASTAT_PHASE_ERR 0x14
  210730. #define HASTAT_TIMEOUT 0x09
  210731. #define HASTAT_COMMAND_TIMEOUT 0x0B
  210732. #define HASTAT_MESSAGE_REJECT 0x0D
  210733. #define HASTAT_BUS_RESET 0x0E
  210734. #define HASTAT_PARITY_ERROR 0x0F
  210735. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  210736. #define PACKED
  210737. #pragma pack(1)
  210738. typedef struct
  210739. {
  210740. BYTE SRB_Cmd;
  210741. BYTE SRB_Status;
  210742. BYTE SRB_HaID;
  210743. BYTE SRB_Flags;
  210744. DWORD SRB_Hdr_Rsvd;
  210745. BYTE HA_Count;
  210746. BYTE HA_SCSI_ID;
  210747. BYTE HA_ManagerId[16];
  210748. BYTE HA_Identifier[16];
  210749. BYTE HA_Unique[16];
  210750. WORD HA_Rsvd1;
  210751. BYTE pad[20];
  210752. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  210753. typedef struct
  210754. {
  210755. BYTE SRB_Cmd;
  210756. BYTE SRB_Status;
  210757. BYTE SRB_HaID;
  210758. BYTE SRB_Flags;
  210759. DWORD SRB_Hdr_Rsvd;
  210760. BYTE SRB_Target;
  210761. BYTE SRB_Lun;
  210762. BYTE SRB_DeviceType;
  210763. BYTE SRB_Rsvd1;
  210764. BYTE pad[68];
  210765. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  210766. typedef struct
  210767. {
  210768. BYTE SRB_Cmd;
  210769. BYTE SRB_Status;
  210770. BYTE SRB_HaID;
  210771. BYTE SRB_Flags;
  210772. DWORD SRB_Hdr_Rsvd;
  210773. BYTE SRB_Target;
  210774. BYTE SRB_Lun;
  210775. WORD SRB_Rsvd1;
  210776. DWORD SRB_BufLen;
  210777. BYTE FAR *SRB_BufPointer;
  210778. BYTE SRB_SenseLen;
  210779. BYTE SRB_CDBLen;
  210780. BYTE SRB_HaStat;
  210781. BYTE SRB_TargStat;
  210782. VOID FAR *SRB_PostProc;
  210783. BYTE SRB_Rsvd2[20];
  210784. BYTE CDBByte[16];
  210785. BYTE SenseArea[SENSE_LEN+2];
  210786. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  210787. typedef struct
  210788. {
  210789. BYTE SRB_Cmd;
  210790. BYTE SRB_Status;
  210791. BYTE SRB_HaId;
  210792. BYTE SRB_Flags;
  210793. DWORD SRB_Hdr_Rsvd;
  210794. } PACKED SRB, *PSRB, FAR *LPSRB;
  210795. #pragma pack()
  210796. struct CDDeviceInfo
  210797. {
  210798. char vendor[9];
  210799. char productId[17];
  210800. char rev[5];
  210801. char vendorSpec[21];
  210802. BYTE ha;
  210803. BYTE tgt;
  210804. BYTE lun;
  210805. char scsiDriveLetter; // will be 0 if not using scsi
  210806. };
  210807. class CDReadBuffer
  210808. {
  210809. public:
  210810. int startFrame;
  210811. int numFrames;
  210812. int dataStartOffset;
  210813. int dataLength;
  210814. int bufferSize;
  210815. HeapBlock<BYTE> buffer;
  210816. int index;
  210817. bool wantsIndex;
  210818. CDReadBuffer (const int numberOfFrames)
  210819. : startFrame (0),
  210820. numFrames (0),
  210821. dataStartOffset (0),
  210822. dataLength (0),
  210823. bufferSize (2352 * numberOfFrames),
  210824. buffer (bufferSize),
  210825. index (0),
  210826. wantsIndex (false)
  210827. {
  210828. }
  210829. bool isZero() const throw()
  210830. {
  210831. BYTE* p = buffer + dataStartOffset;
  210832. for (int i = dataLength; --i >= 0;)
  210833. if (*p++ != 0)
  210834. return false;
  210835. return true;
  210836. }
  210837. };
  210838. class CDDeviceHandle;
  210839. class CDController
  210840. {
  210841. public:
  210842. CDController();
  210843. virtual ~CDController();
  210844. virtual bool read (CDReadBuffer* t) = 0;
  210845. virtual void shutDown();
  210846. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  210847. int getLastIndex();
  210848. public:
  210849. bool initialised;
  210850. CDDeviceHandle* deviceInfo;
  210851. int framesToCheck, framesOverlap;
  210852. void prepare (SRB_ExecSCSICmd& s);
  210853. void perform (SRB_ExecSCSICmd& s);
  210854. void setPaused (bool paused);
  210855. };
  210856. #pragma pack(1)
  210857. struct TOCTRACK
  210858. {
  210859. BYTE rsvd;
  210860. BYTE ADR;
  210861. BYTE trackNumber;
  210862. BYTE rsvd2;
  210863. BYTE addr[4];
  210864. };
  210865. struct TOC
  210866. {
  210867. WORD tocLen;
  210868. BYTE firstTrack;
  210869. BYTE lastTrack;
  210870. TOCTRACK tracks[100];
  210871. };
  210872. #pragma pack()
  210873. enum
  210874. {
  210875. READTYPE_ANY = 0,
  210876. READTYPE_ATAPI1 = 1,
  210877. READTYPE_ATAPI2 = 2,
  210878. READTYPE_READ6 = 3,
  210879. READTYPE_READ10 = 4,
  210880. READTYPE_READ_D8 = 5,
  210881. READTYPE_READ_D4 = 6,
  210882. READTYPE_READ_D4_1 = 7,
  210883. READTYPE_READ10_2 = 8
  210884. };
  210885. class CDDeviceHandle
  210886. {
  210887. public:
  210888. CDDeviceHandle (const CDDeviceInfo* const device)
  210889. : scsiHandle (0),
  210890. readType (READTYPE_ANY),
  210891. controller (0)
  210892. {
  210893. memcpy (&info, device, sizeof (info));
  210894. }
  210895. ~CDDeviceHandle()
  210896. {
  210897. if (controller != 0)
  210898. {
  210899. controller->shutDown();
  210900. controller = 0;
  210901. }
  210902. if (scsiHandle != 0)
  210903. CloseHandle (scsiHandle);
  210904. }
  210905. bool readTOC (TOC* lpToc);
  210906. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  210907. void openDrawer (bool shouldBeOpen);
  210908. CDDeviceInfo info;
  210909. HANDLE scsiHandle;
  210910. BYTE readType;
  210911. private:
  210912. ScopedPointer<CDController> controller;
  210913. bool testController (const int readType,
  210914. CDController* const newController,
  210915. CDReadBuffer* const bufferToUse);
  210916. };
  210917. DWORD (*fGetASPI32SupportInfo)(void);
  210918. DWORD (*fSendASPI32Command)(LPSRB);
  210919. static HINSTANCE winAspiLib = 0;
  210920. static bool usingScsi = false;
  210921. static bool initialised = false;
  210922. static bool InitialiseCDRipper()
  210923. {
  210924. if (! initialised)
  210925. {
  210926. initialised = true;
  210927. OSVERSIONINFO info;
  210928. info.dwOSVersionInfoSize = sizeof (info);
  210929. GetVersionEx (&info);
  210930. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  210931. if (! usingScsi)
  210932. {
  210933. fGetASPI32SupportInfo = 0;
  210934. fSendASPI32Command = 0;
  210935. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  210936. if (winAspiLib != 0)
  210937. {
  210938. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  210939. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  210940. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  210941. return false;
  210942. }
  210943. else
  210944. {
  210945. usingScsi = true;
  210946. }
  210947. }
  210948. }
  210949. return true;
  210950. }
  210951. static void DeinitialiseCDRipper()
  210952. {
  210953. if (winAspiLib != 0)
  210954. {
  210955. fGetASPI32SupportInfo = 0;
  210956. fSendASPI32Command = 0;
  210957. FreeLibrary (winAspiLib);
  210958. winAspiLib = 0;
  210959. }
  210960. initialised = false;
  210961. }
  210962. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  210963. {
  210964. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210965. OSVERSIONINFO info;
  210966. info.dwOSVersionInfoSize = sizeof (info);
  210967. GetVersionEx (&info);
  210968. DWORD flags = GENERIC_READ;
  210969. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  210970. flags = GENERIC_READ | GENERIC_WRITE;
  210971. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210972. if (h == INVALID_HANDLE_VALUE)
  210973. {
  210974. flags ^= GENERIC_WRITE;
  210975. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210976. }
  210977. return h;
  210978. }
  210979. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  210980. const char driveLetter,
  210981. HANDLE& deviceHandle,
  210982. const bool retryOnFailure = true)
  210983. {
  210984. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210985. zerostruct (s);
  210986. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210987. s.spt.CdbLength = srb->SRB_CDBLen;
  210988. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210989. ? SCSI_IOCTL_DATA_IN
  210990. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210991. ? SCSI_IOCTL_DATA_OUT
  210992. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210993. s.spt.DataTransferLength = srb->SRB_BufLen;
  210994. s.spt.TimeOutValue = 5;
  210995. s.spt.DataBuffer = srb->SRB_BufPointer;
  210996. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210997. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210998. srb->SRB_Status = SS_ERR;
  210999. srb->SRB_TargStat = 0x0004;
  211000. DWORD bytesReturned = 0;
  211001. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211002. &s, sizeof (s),
  211003. &s, sizeof (s),
  211004. &bytesReturned, 0) != 0)
  211005. {
  211006. srb->SRB_Status = SS_COMP;
  211007. }
  211008. else if (retryOnFailure)
  211009. {
  211010. const DWORD error = GetLastError();
  211011. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  211012. {
  211013. if (error != ERROR_INVALID_HANDLE)
  211014. CloseHandle (deviceHandle);
  211015. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  211016. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  211017. }
  211018. }
  211019. return srb->SRB_Status;
  211020. }
  211021. // Controller types..
  211022. class ControllerType1 : public CDController
  211023. {
  211024. public:
  211025. ControllerType1() {}
  211026. ~ControllerType1() {}
  211027. bool read (CDReadBuffer* rb)
  211028. {
  211029. if (rb->numFrames * 2352 > rb->bufferSize)
  211030. return false;
  211031. SRB_ExecSCSICmd s;
  211032. prepare (s);
  211033. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211034. s.SRB_BufLen = rb->bufferSize;
  211035. s.SRB_BufPointer = rb->buffer;
  211036. s.SRB_CDBLen = 12;
  211037. s.CDBByte[0] = 0xBE;
  211038. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211039. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211040. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211041. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211042. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  211043. perform (s);
  211044. if (s.SRB_Status != SS_COMP)
  211045. return false;
  211046. rb->dataLength = rb->numFrames * 2352;
  211047. rb->dataStartOffset = 0;
  211048. return true;
  211049. }
  211050. };
  211051. class ControllerType2 : public CDController
  211052. {
  211053. public:
  211054. ControllerType2() {}
  211055. ~ControllerType2() {}
  211056. void shutDown()
  211057. {
  211058. if (initialised)
  211059. {
  211060. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  211061. SRB_ExecSCSICmd s;
  211062. prepare (s);
  211063. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  211064. s.SRB_BufLen = 0x0C;
  211065. s.SRB_BufPointer = bufPointer;
  211066. s.SRB_CDBLen = 6;
  211067. s.CDBByte[0] = 0x15;
  211068. s.CDBByte[4] = 0x0C;
  211069. perform (s);
  211070. }
  211071. }
  211072. bool init()
  211073. {
  211074. SRB_ExecSCSICmd s;
  211075. s.SRB_Status = SS_ERR;
  211076. if (deviceInfo->readType == READTYPE_READ10_2)
  211077. {
  211078. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  211079. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  211080. for (int i = 0; i < 2; ++i)
  211081. {
  211082. prepare (s);
  211083. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211084. s.SRB_BufLen = 0x14;
  211085. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211086. s.SRB_CDBLen = 6;
  211087. s.CDBByte[0] = 0x15;
  211088. s.CDBByte[1] = 0x10;
  211089. s.CDBByte[4] = 0x14;
  211090. perform (s);
  211091. if (s.SRB_Status != SS_COMP)
  211092. return false;
  211093. }
  211094. }
  211095. else
  211096. {
  211097. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211098. prepare (s);
  211099. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211100. s.SRB_BufLen = 0x0C;
  211101. s.SRB_BufPointer = bufPointer;
  211102. s.SRB_CDBLen = 6;
  211103. s.CDBByte[0] = 0x15;
  211104. s.CDBByte[4] = 0x0C;
  211105. perform (s);
  211106. }
  211107. return s.SRB_Status == SS_COMP;
  211108. }
  211109. bool read (CDReadBuffer* rb)
  211110. {
  211111. if (rb->numFrames * 2352 > rb->bufferSize)
  211112. return false;
  211113. if (!initialised)
  211114. {
  211115. initialised = init();
  211116. if (!initialised)
  211117. return false;
  211118. }
  211119. SRB_ExecSCSICmd s;
  211120. prepare (s);
  211121. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211122. s.SRB_BufLen = rb->bufferSize;
  211123. s.SRB_BufPointer = rb->buffer;
  211124. s.SRB_CDBLen = 10;
  211125. s.CDBByte[0] = 0x28;
  211126. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211127. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211128. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211129. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211130. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211131. perform (s);
  211132. if (s.SRB_Status != SS_COMP)
  211133. return false;
  211134. rb->dataLength = rb->numFrames * 2352;
  211135. rb->dataStartOffset = 0;
  211136. return true;
  211137. }
  211138. };
  211139. class ControllerType3 : public CDController
  211140. {
  211141. public:
  211142. ControllerType3() {}
  211143. ~ControllerType3() {}
  211144. bool read (CDReadBuffer* rb)
  211145. {
  211146. if (rb->numFrames * 2352 > rb->bufferSize)
  211147. return false;
  211148. if (!initialised)
  211149. {
  211150. setPaused (false);
  211151. initialised = true;
  211152. }
  211153. SRB_ExecSCSICmd s;
  211154. prepare (s);
  211155. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211156. s.SRB_BufLen = rb->numFrames * 2352;
  211157. s.SRB_BufPointer = rb->buffer;
  211158. s.SRB_CDBLen = 12;
  211159. s.CDBByte[0] = 0xD8;
  211160. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211161. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211162. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211163. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  211164. perform (s);
  211165. if (s.SRB_Status != SS_COMP)
  211166. return false;
  211167. rb->dataLength = rb->numFrames * 2352;
  211168. rb->dataStartOffset = 0;
  211169. return true;
  211170. }
  211171. };
  211172. class ControllerType4 : public CDController
  211173. {
  211174. public:
  211175. ControllerType4() {}
  211176. ~ControllerType4() {}
  211177. bool selectD4Mode()
  211178. {
  211179. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211180. SRB_ExecSCSICmd s;
  211181. prepare (s);
  211182. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211183. s.SRB_CDBLen = 6;
  211184. s.SRB_BufLen = 12;
  211185. s.SRB_BufPointer = bufPointer;
  211186. s.CDBByte[0] = 0x15;
  211187. s.CDBByte[1] = 0x10;
  211188. s.CDBByte[4] = 0x08;
  211189. perform (s);
  211190. return s.SRB_Status == SS_COMP;
  211191. }
  211192. bool read (CDReadBuffer* rb)
  211193. {
  211194. if (rb->numFrames * 2352 > rb->bufferSize)
  211195. return false;
  211196. if (!initialised)
  211197. {
  211198. setPaused (true);
  211199. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211200. selectD4Mode();
  211201. initialised = true;
  211202. }
  211203. SRB_ExecSCSICmd s;
  211204. prepare (s);
  211205. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211206. s.SRB_BufLen = rb->bufferSize;
  211207. s.SRB_BufPointer = rb->buffer;
  211208. s.SRB_CDBLen = 10;
  211209. s.CDBByte[0] = 0xD4;
  211210. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211211. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211212. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211213. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211214. perform (s);
  211215. if (s.SRB_Status != SS_COMP)
  211216. return false;
  211217. rb->dataLength = rb->numFrames * 2352;
  211218. rb->dataStartOffset = 0;
  211219. return true;
  211220. }
  211221. };
  211222. CDController::CDController() : initialised (false)
  211223. {
  211224. }
  211225. CDController::~CDController()
  211226. {
  211227. }
  211228. void CDController::prepare (SRB_ExecSCSICmd& s)
  211229. {
  211230. zerostruct (s);
  211231. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211232. s.SRB_HaID = deviceInfo->info.ha;
  211233. s.SRB_Target = deviceInfo->info.tgt;
  211234. s.SRB_Lun = deviceInfo->info.lun;
  211235. s.SRB_SenseLen = SENSE_LEN;
  211236. }
  211237. void CDController::perform (SRB_ExecSCSICmd& s)
  211238. {
  211239. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211240. s.SRB_PostProc = event;
  211241. ResetEvent (event);
  211242. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  211243. deviceInfo->info.scsiDriveLetter,
  211244. deviceInfo->scsiHandle)
  211245. : fSendASPI32Command ((LPSRB)&s);
  211246. if (status == SS_PENDING)
  211247. WaitForSingleObject (event, 4000);
  211248. CloseHandle (event);
  211249. }
  211250. void CDController::setPaused (bool paused)
  211251. {
  211252. SRB_ExecSCSICmd s;
  211253. prepare (s);
  211254. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211255. s.SRB_CDBLen = 10;
  211256. s.CDBByte[0] = 0x4B;
  211257. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211258. perform (s);
  211259. }
  211260. void CDController::shutDown()
  211261. {
  211262. }
  211263. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  211264. {
  211265. if (overlapBuffer != 0)
  211266. {
  211267. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211268. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211269. if (doJitter
  211270. && overlapBuffer->startFrame > 0
  211271. && overlapBuffer->numFrames > 0
  211272. && overlapBuffer->dataLength > 0)
  211273. {
  211274. const int numFrames = rb->numFrames;
  211275. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  211276. {
  211277. rb->startFrame -= framesOverlap;
  211278. if (framesToCheck < framesOverlap
  211279. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  211280. rb->numFrames += framesOverlap;
  211281. }
  211282. else
  211283. {
  211284. overlapBuffer->dataLength = 0;
  211285. overlapBuffer->startFrame = 0;
  211286. overlapBuffer->numFrames = 0;
  211287. }
  211288. }
  211289. if (! read (rb))
  211290. return false;
  211291. if (doJitter)
  211292. {
  211293. const int checkLen = framesToCheck * 2352;
  211294. const int maxToCheck = rb->dataLength - checkLen;
  211295. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211296. return true;
  211297. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211298. bool found = false;
  211299. for (int i = 0; i < maxToCheck; ++i)
  211300. {
  211301. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  211302. {
  211303. i += checkLen;
  211304. rb->dataStartOffset = i;
  211305. rb->dataLength -= i;
  211306. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  211307. found = true;
  211308. break;
  211309. }
  211310. }
  211311. rb->numFrames = rb->dataLength / 2352;
  211312. rb->dataLength = 2352 * rb->numFrames;
  211313. if (!found)
  211314. return false;
  211315. }
  211316. if (canDoJitter)
  211317. {
  211318. memcpy (overlapBuffer->buffer,
  211319. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  211320. 2352 * framesToCheck);
  211321. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  211322. overlapBuffer->numFrames = framesToCheck;
  211323. overlapBuffer->dataLength = 2352 * framesToCheck;
  211324. overlapBuffer->dataStartOffset = 0;
  211325. }
  211326. else
  211327. {
  211328. overlapBuffer->startFrame = 0;
  211329. overlapBuffer->numFrames = 0;
  211330. overlapBuffer->dataLength = 0;
  211331. }
  211332. return true;
  211333. }
  211334. else
  211335. {
  211336. return read (rb);
  211337. }
  211338. }
  211339. int CDController::getLastIndex()
  211340. {
  211341. char qdata[100];
  211342. SRB_ExecSCSICmd s;
  211343. prepare (s);
  211344. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211345. s.SRB_BufLen = sizeof (qdata);
  211346. s.SRB_BufPointer = (BYTE*)qdata;
  211347. s.SRB_CDBLen = 12;
  211348. s.CDBByte[0] = 0x42;
  211349. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211350. s.CDBByte[2] = 64;
  211351. s.CDBByte[3] = 1; // get current position
  211352. s.CDBByte[7] = 0;
  211353. s.CDBByte[8] = (BYTE)sizeof (qdata);
  211354. perform (s);
  211355. if (s.SRB_Status == SS_COMP)
  211356. return qdata[7];
  211357. return 0;
  211358. }
  211359. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211360. {
  211361. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211362. SRB_ExecSCSICmd s;
  211363. zerostruct (s);
  211364. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211365. s.SRB_HaID = info.ha;
  211366. s.SRB_Target = info.tgt;
  211367. s.SRB_Lun = info.lun;
  211368. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211369. s.SRB_BufLen = 0x324;
  211370. s.SRB_BufPointer = (BYTE*)lpToc;
  211371. s.SRB_SenseLen = 0x0E;
  211372. s.SRB_CDBLen = 0x0A;
  211373. s.SRB_PostProc = event;
  211374. s.CDBByte[0] = 0x43;
  211375. s.CDBByte[1] = 0x00;
  211376. s.CDBByte[7] = 0x03;
  211377. s.CDBByte[8] = 0x24;
  211378. ResetEvent (event);
  211379. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211380. : fSendASPI32Command ((LPSRB)&s);
  211381. if (status == SS_PENDING)
  211382. WaitForSingleObject (event, 4000);
  211383. CloseHandle (event);
  211384. return (s.SRB_Status == SS_COMP);
  211385. }
  211386. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  211387. CDReadBuffer* const overlapBuffer)
  211388. {
  211389. if (controller == 0)
  211390. {
  211391. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211392. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211393. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211394. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211395. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211396. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211397. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211398. }
  211399. buffer->index = 0;
  211400. if ((controller != 0)
  211401. && controller->readAudio (buffer, overlapBuffer))
  211402. {
  211403. if (buffer->wantsIndex)
  211404. buffer->index = controller->getLastIndex();
  211405. return true;
  211406. }
  211407. return false;
  211408. }
  211409. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211410. {
  211411. if (shouldBeOpen)
  211412. {
  211413. if (controller != 0)
  211414. {
  211415. controller->shutDown();
  211416. controller = 0;
  211417. }
  211418. if (scsiHandle != 0)
  211419. {
  211420. CloseHandle (scsiHandle);
  211421. scsiHandle = 0;
  211422. }
  211423. }
  211424. SRB_ExecSCSICmd s;
  211425. zerostruct (s);
  211426. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211427. s.SRB_HaID = info.ha;
  211428. s.SRB_Target = info.tgt;
  211429. s.SRB_Lun = info.lun;
  211430. s.SRB_SenseLen = SENSE_LEN;
  211431. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211432. s.SRB_BufLen = 0;
  211433. s.SRB_BufPointer = 0;
  211434. s.SRB_CDBLen = 12;
  211435. s.CDBByte[0] = 0x1b;
  211436. s.CDBByte[1] = (BYTE)(info.lun << 5);
  211437. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  211438. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211439. s.SRB_PostProc = event;
  211440. ResetEvent (event);
  211441. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211442. : fSendASPI32Command ((LPSRB)&s);
  211443. if (status == SS_PENDING)
  211444. WaitForSingleObject (event, 4000);
  211445. CloseHandle (event);
  211446. }
  211447. bool CDDeviceHandle::testController (const int type,
  211448. CDController* const newController,
  211449. CDReadBuffer* const rb)
  211450. {
  211451. controller = newController;
  211452. readType = (BYTE)type;
  211453. controller->deviceInfo = this;
  211454. controller->framesToCheck = 1;
  211455. controller->framesOverlap = 3;
  211456. bool passed = false;
  211457. memset (rb->buffer, 0xcd, rb->bufferSize);
  211458. if (controller->read (rb))
  211459. {
  211460. passed = true;
  211461. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  211462. int wrong = 0;
  211463. for (int i = rb->dataLength / 4; --i >= 0;)
  211464. {
  211465. if (*p++ == (int) 0xcdcdcdcd)
  211466. {
  211467. if (++wrong == 4)
  211468. {
  211469. passed = false;
  211470. break;
  211471. }
  211472. }
  211473. else
  211474. {
  211475. wrong = 0;
  211476. }
  211477. }
  211478. }
  211479. if (! passed)
  211480. {
  211481. controller->shutDown();
  211482. controller = 0;
  211483. }
  211484. return passed;
  211485. }
  211486. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  211487. {
  211488. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211489. const int bufSize = 128;
  211490. BYTE buffer[bufSize];
  211491. zeromem (buffer, bufSize);
  211492. SRB_ExecSCSICmd s;
  211493. zerostruct (s);
  211494. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211495. s.SRB_HaID = ha;
  211496. s.SRB_Target = tgt;
  211497. s.SRB_Lun = lun;
  211498. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211499. s.SRB_BufLen = bufSize;
  211500. s.SRB_BufPointer = buffer;
  211501. s.SRB_SenseLen = SENSE_LEN;
  211502. s.SRB_CDBLen = 6;
  211503. s.SRB_PostProc = event;
  211504. s.CDBByte[0] = SCSI_INQUIRY;
  211505. s.CDBByte[4] = 100;
  211506. ResetEvent (event);
  211507. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  211508. WaitForSingleObject (event, 4000);
  211509. CloseHandle (event);
  211510. if (s.SRB_Status == SS_COMP)
  211511. {
  211512. memcpy (dev->vendor, &buffer[8], 8);
  211513. memcpy (dev->productId, &buffer[16], 16);
  211514. memcpy (dev->rev, &buffer[32], 4);
  211515. memcpy (dev->vendorSpec, &buffer[36], 20);
  211516. }
  211517. }
  211518. static int FindCDDevices (CDDeviceInfo* const list,
  211519. int maxItems)
  211520. {
  211521. int count = 0;
  211522. if (usingScsi)
  211523. {
  211524. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  211525. {
  211526. TCHAR drivePath[8];
  211527. drivePath[0] = driveLetter;
  211528. drivePath[1] = ':';
  211529. drivePath[2] = '\\';
  211530. drivePath[3] = 0;
  211531. if (GetDriveType (drivePath) == DRIVE_CDROM)
  211532. {
  211533. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  211534. if (h != INVALID_HANDLE_VALUE)
  211535. {
  211536. BYTE buffer[100], passThroughStruct[1024];
  211537. zeromem (buffer, sizeof (buffer));
  211538. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211539. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  211540. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  211541. p->spt.CdbLength = 6;
  211542. p->spt.SenseInfoLength = 24;
  211543. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  211544. p->spt.DataTransferLength = 100;
  211545. p->spt.TimeOutValue = 2;
  211546. p->spt.DataBuffer = buffer;
  211547. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211548. p->spt.Cdb[0] = 0x12;
  211549. p->spt.Cdb[4] = 100;
  211550. DWORD bytesReturned = 0;
  211551. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211552. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211553. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211554. &bytesReturned, 0) != 0)
  211555. {
  211556. zeromem (&list[count], sizeof (CDDeviceInfo));
  211557. list[count].scsiDriveLetter = driveLetter;
  211558. memcpy (list[count].vendor, &buffer[8], 8);
  211559. memcpy (list[count].productId, &buffer[16], 16);
  211560. memcpy (list[count].rev, &buffer[32], 4);
  211561. memcpy (list[count].vendorSpec, &buffer[36], 20);
  211562. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211563. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  211564. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  211565. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  211566. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  211567. &bytesReturned, 0) != 0)
  211568. {
  211569. list[count].ha = scsiAddr->PortNumber;
  211570. list[count].tgt = scsiAddr->TargetId;
  211571. list[count].lun = scsiAddr->Lun;
  211572. ++count;
  211573. }
  211574. }
  211575. CloseHandle (h);
  211576. }
  211577. }
  211578. }
  211579. }
  211580. else
  211581. {
  211582. const DWORD d = fGetASPI32SupportInfo();
  211583. BYTE status = HIBYTE (LOWORD (d));
  211584. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  211585. return 0;
  211586. const int numAdapters = LOBYTE (LOWORD (d));
  211587. for (BYTE ha = 0; ha < numAdapters; ++ha)
  211588. {
  211589. SRB_HAInquiry s;
  211590. zerostruct (s);
  211591. s.SRB_Cmd = SC_HA_INQUIRY;
  211592. s.SRB_HaID = ha;
  211593. fSendASPI32Command ((LPSRB)&s);
  211594. if (s.SRB_Status == SS_COMP)
  211595. {
  211596. maxItems = (int)s.HA_Unique[3];
  211597. if (maxItems == 0)
  211598. maxItems = 8;
  211599. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  211600. {
  211601. for (BYTE lun = 0; lun < 8; ++lun)
  211602. {
  211603. SRB_GDEVBlock sb;
  211604. zerostruct (sb);
  211605. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  211606. sb.SRB_HaID = ha;
  211607. sb.SRB_Target = tgt;
  211608. sb.SRB_Lun = lun;
  211609. fSendASPI32Command ((LPSRB) &sb);
  211610. if (sb.SRB_Status == SS_COMP
  211611. && sb.SRB_DeviceType == DTYPE_CROM)
  211612. {
  211613. zeromem (&list[count], sizeof (CDDeviceInfo));
  211614. list[count].ha = ha;
  211615. list[count].tgt = tgt;
  211616. list[count].lun = lun;
  211617. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  211618. ++count;
  211619. }
  211620. }
  211621. }
  211622. }
  211623. }
  211624. }
  211625. return count;
  211626. }
  211627. static int ripperUsers = 0;
  211628. static bool initialisedOk = false;
  211629. class DeinitialiseTimer : private Timer,
  211630. private DeletedAtShutdown
  211631. {
  211632. DeinitialiseTimer (const DeinitialiseTimer&);
  211633. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  211634. public:
  211635. DeinitialiseTimer()
  211636. {
  211637. startTimer (4000);
  211638. }
  211639. ~DeinitialiseTimer()
  211640. {
  211641. if (--ripperUsers == 0)
  211642. DeinitialiseCDRipper();
  211643. }
  211644. void timerCallback()
  211645. {
  211646. delete this;
  211647. }
  211648. juce_UseDebuggingNewOperator
  211649. };
  211650. static void incUserCount()
  211651. {
  211652. if (ripperUsers++ == 0)
  211653. initialisedOk = InitialiseCDRipper();
  211654. }
  211655. static void decUserCount()
  211656. {
  211657. new DeinitialiseTimer();
  211658. }
  211659. struct CDDeviceWrapper
  211660. {
  211661. ScopedPointer<CDDeviceHandle> cdH;
  211662. ScopedPointer<CDReadBuffer> overlapBuffer;
  211663. bool jitter;
  211664. };
  211665. static int getAddressOf (const TOCTRACK* const t)
  211666. {
  211667. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  211668. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  211669. }
  211670. static const int samplesPerFrame = 44100 / 75;
  211671. static const int bytesPerFrame = samplesPerFrame * 4;
  211672. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  211673. {
  211674. SRB_GDEVBlock s;
  211675. zerostruct (s);
  211676. s.SRB_Cmd = SC_GET_DEV_TYPE;
  211677. s.SRB_HaID = device->ha;
  211678. s.SRB_Target = device->tgt;
  211679. s.SRB_Lun = device->lun;
  211680. if (usingScsi)
  211681. {
  211682. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  211683. if (h != INVALID_HANDLE_VALUE)
  211684. {
  211685. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  211686. cdh->scsiHandle = h;
  211687. return cdh;
  211688. }
  211689. }
  211690. else
  211691. {
  211692. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  211693. && s.SRB_DeviceType == DTYPE_CROM)
  211694. {
  211695. return new CDDeviceHandle (device);
  211696. }
  211697. }
  211698. return 0;
  211699. }
  211700. }
  211701. const StringArray AudioCDReader::getAvailableCDNames()
  211702. {
  211703. using namespace CDReaderHelpers;
  211704. StringArray results;
  211705. incUserCount();
  211706. if (initialisedOk)
  211707. {
  211708. CDDeviceInfo list[8];
  211709. const int num = FindCDDevices (list, 8);
  211710. decUserCount();
  211711. for (int i = 0; i < num; ++i)
  211712. {
  211713. String s;
  211714. if (list[i].scsiDriveLetter > 0)
  211715. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211716. s << String (list[i].vendor).trim()
  211717. << ' ' << String (list[i].productId).trim()
  211718. << ' ' << String (list[i].rev).trim();
  211719. results.add (s);
  211720. }
  211721. }
  211722. return results;
  211723. }
  211724. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211725. {
  211726. using namespace CDReaderHelpers;
  211727. incUserCount();
  211728. if (initialisedOk)
  211729. {
  211730. CDDeviceInfo list[8];
  211731. const int num = FindCDDevices (list, 8);
  211732. if (((unsigned int) deviceIndex) < (unsigned int) num)
  211733. {
  211734. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  211735. if (handle != 0)
  211736. {
  211737. CDDeviceWrapper* const d = new CDDeviceWrapper();
  211738. d->cdH = handle;
  211739. d->overlapBuffer = new CDReadBuffer(3);
  211740. return new AudioCDReader (d);
  211741. }
  211742. }
  211743. }
  211744. decUserCount();
  211745. return 0;
  211746. }
  211747. AudioCDReader::AudioCDReader (void* handle_)
  211748. : AudioFormatReader (0, "CD Audio"),
  211749. handle (handle_),
  211750. indexingEnabled (false),
  211751. lastIndex (0),
  211752. firstFrameInBuffer (0),
  211753. samplesInBuffer (0)
  211754. {
  211755. using namespace CDReaderHelpers;
  211756. jassert (handle_ != 0);
  211757. refreshTrackLengths();
  211758. sampleRate = 44100.0;
  211759. bitsPerSample = 16;
  211760. numChannels = 2;
  211761. usesFloatingPointData = false;
  211762. buffer.setSize (4 * bytesPerFrame, true);
  211763. }
  211764. AudioCDReader::~AudioCDReader()
  211765. {
  211766. using namespace CDReaderHelpers;
  211767. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211768. delete device;
  211769. decUserCount();
  211770. }
  211771. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211772. int64 startSampleInFile, int numSamples)
  211773. {
  211774. using namespace CDReaderHelpers;
  211775. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211776. bool ok = true;
  211777. while (numSamples > 0)
  211778. {
  211779. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211780. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211781. if (startSampleInFile >= bufferStartSample
  211782. && startSampleInFile < bufferEndSample)
  211783. {
  211784. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211785. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211786. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211787. const short* src = (const short*) buffer.getData();
  211788. src += 2 * (startSampleInFile - bufferStartSample);
  211789. for (int i = 0; i < toDo; ++i)
  211790. {
  211791. l[i] = src [i << 1] << 16;
  211792. if (r != 0)
  211793. r[i] = src [(i << 1) + 1] << 16;
  211794. }
  211795. startOffsetInDestBuffer += toDo;
  211796. startSampleInFile += toDo;
  211797. numSamples -= toDo;
  211798. }
  211799. else
  211800. {
  211801. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211802. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211803. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211804. {
  211805. device->overlapBuffer->dataLength = 0;
  211806. device->overlapBuffer->startFrame = 0;
  211807. device->overlapBuffer->numFrames = 0;
  211808. device->jitter = false;
  211809. }
  211810. firstFrameInBuffer = frameNeeded;
  211811. lastIndex = 0;
  211812. CDReadBuffer readBuffer (framesInBuffer + 4);
  211813. readBuffer.wantsIndex = indexingEnabled;
  211814. int i;
  211815. for (i = 5; --i >= 0;)
  211816. {
  211817. readBuffer.startFrame = frameNeeded;
  211818. readBuffer.numFrames = framesInBuffer;
  211819. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  211820. break;
  211821. else
  211822. device->overlapBuffer->dataLength = 0;
  211823. }
  211824. if (i >= 0)
  211825. {
  211826. memcpy ((char*) buffer.getData(),
  211827. readBuffer.buffer + readBuffer.dataStartOffset,
  211828. readBuffer.dataLength);
  211829. samplesInBuffer = readBuffer.dataLength >> 2;
  211830. lastIndex = readBuffer.index;
  211831. }
  211832. else
  211833. {
  211834. int* l = destSamples[0] + startOffsetInDestBuffer;
  211835. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211836. while (--numSamples >= 0)
  211837. {
  211838. *l++ = 0;
  211839. if (r != 0)
  211840. *r++ = 0;
  211841. }
  211842. // sometimes the read fails for just the very last couple of blocks, so
  211843. // we'll ignore and errors in the last half-second of the disk..
  211844. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211845. break;
  211846. }
  211847. }
  211848. }
  211849. return ok;
  211850. }
  211851. bool AudioCDReader::isCDStillPresent() const
  211852. {
  211853. using namespace CDReaderHelpers;
  211854. TOC toc;
  211855. zerostruct (toc);
  211856. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc);
  211857. }
  211858. void AudioCDReader::refreshTrackLengths()
  211859. {
  211860. using namespace CDReaderHelpers;
  211861. trackStartSamples.clear();
  211862. zeromem (audioTracks, sizeof (audioTracks));
  211863. TOC toc;
  211864. zerostruct (toc);
  211865. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc))
  211866. {
  211867. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211868. for (int i = 0; i <= numTracks; ++i)
  211869. {
  211870. trackStartSamples.add (samplesPerFrame * getAddressOf (&toc.tracks [i]));
  211871. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211872. }
  211873. }
  211874. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211875. }
  211876. bool AudioCDReader::isTrackAudio (int trackNum) const
  211877. {
  211878. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211879. }
  211880. void AudioCDReader::enableIndexScanning (bool b)
  211881. {
  211882. indexingEnabled = b;
  211883. }
  211884. int AudioCDReader::getLastIndex() const
  211885. {
  211886. return lastIndex;
  211887. }
  211888. const int framesPerIndexRead = 4;
  211889. int AudioCDReader::getIndexAt (int samplePos)
  211890. {
  211891. using namespace CDReaderHelpers;
  211892. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211893. const int frameNeeded = samplePos / samplesPerFrame;
  211894. device->overlapBuffer->dataLength = 0;
  211895. device->overlapBuffer->startFrame = 0;
  211896. device->overlapBuffer->numFrames = 0;
  211897. device->jitter = false;
  211898. firstFrameInBuffer = 0;
  211899. lastIndex = 0;
  211900. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211901. readBuffer.wantsIndex = true;
  211902. int i;
  211903. for (i = 5; --i >= 0;)
  211904. {
  211905. readBuffer.startFrame = frameNeeded;
  211906. readBuffer.numFrames = framesPerIndexRead;
  211907. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  211908. break;
  211909. }
  211910. if (i >= 0)
  211911. return readBuffer.index;
  211912. return -1;
  211913. }
  211914. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211915. {
  211916. using namespace CDReaderHelpers;
  211917. Array <int> indexes;
  211918. const int trackStart = getPositionOfTrackStart (trackNumber);
  211919. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211920. bool needToScan = true;
  211921. if (trackEnd - trackStart > 20 * 44100)
  211922. {
  211923. // check the end of the track for indexes before scanning the whole thing
  211924. needToScan = false;
  211925. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211926. bool seenAnIndex = false;
  211927. while (pos <= trackEnd - samplesPerFrame)
  211928. {
  211929. const int index = getIndexAt (pos);
  211930. if (index == 0)
  211931. {
  211932. // lead-out, so skip back a bit if we've not found any indexes yet..
  211933. if (seenAnIndex)
  211934. break;
  211935. pos -= 44100 * 5;
  211936. if (pos < trackStart)
  211937. break;
  211938. }
  211939. else
  211940. {
  211941. if (index > 0)
  211942. seenAnIndex = true;
  211943. if (index > 1)
  211944. {
  211945. needToScan = true;
  211946. break;
  211947. }
  211948. pos += samplesPerFrame * framesPerIndexRead;
  211949. }
  211950. }
  211951. }
  211952. if (needToScan)
  211953. {
  211954. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211955. int pos = trackStart;
  211956. int last = -1;
  211957. while (pos < trackEnd - samplesPerFrame * 10)
  211958. {
  211959. const int frameNeeded = pos / samplesPerFrame;
  211960. device->overlapBuffer->dataLength = 0;
  211961. device->overlapBuffer->startFrame = 0;
  211962. device->overlapBuffer->numFrames = 0;
  211963. device->jitter = false;
  211964. firstFrameInBuffer = 0;
  211965. CDReadBuffer readBuffer (4);
  211966. readBuffer.wantsIndex = true;
  211967. int i;
  211968. for (i = 5; --i >= 0;)
  211969. {
  211970. readBuffer.startFrame = frameNeeded;
  211971. readBuffer.numFrames = framesPerIndexRead;
  211972. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  211973. break;
  211974. }
  211975. if (i < 0)
  211976. break;
  211977. if (readBuffer.index > last && readBuffer.index > 1)
  211978. {
  211979. last = readBuffer.index;
  211980. indexes.add (pos);
  211981. }
  211982. pos += samplesPerFrame * framesPerIndexRead;
  211983. }
  211984. indexes.removeValue (trackStart);
  211985. }
  211986. return indexes;
  211987. }
  211988. void AudioCDReader::ejectDisk()
  211989. {
  211990. using namespace CDReaderHelpers;
  211991. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  211992. }
  211993. #endif
  211994. #if JUCE_USE_CDBURNER
  211995. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211996. {
  211997. CoInitialize (0);
  211998. IDiscMaster* dm;
  211999. IDiscRecorder* result = 0;
  212000. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  212001. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  212002. IID_IDiscMaster,
  212003. (void**) &dm)))
  212004. {
  212005. if (SUCCEEDED (dm->Open()))
  212006. {
  212007. IEnumDiscRecorders* drEnum = 0;
  212008. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  212009. {
  212010. IDiscRecorder* dr = 0;
  212011. DWORD dummy;
  212012. int index = 0;
  212013. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  212014. {
  212015. if (indexToOpen == index)
  212016. {
  212017. result = dr;
  212018. break;
  212019. }
  212020. else if (list != 0)
  212021. {
  212022. BSTR path;
  212023. if (SUCCEEDED (dr->GetPath (&path)))
  212024. list->add ((const WCHAR*) path);
  212025. }
  212026. ++index;
  212027. dr->Release();
  212028. }
  212029. drEnum->Release();
  212030. }
  212031. if (master == 0)
  212032. dm->Close();
  212033. }
  212034. if (master != 0)
  212035. *master = dm;
  212036. else
  212037. dm->Release();
  212038. }
  212039. return result;
  212040. }
  212041. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  212042. public Timer
  212043. {
  212044. public:
  212045. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  212046. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  212047. listener (0), progress (0), shouldCancel (false)
  212048. {
  212049. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  212050. jassert (SUCCEEDED (hr));
  212051. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  212052. //jassert (SUCCEEDED (hr));
  212053. lastState = getDiskState();
  212054. startTimer (2000);
  212055. }
  212056. ~Pimpl() {}
  212057. void releaseObjects()
  212058. {
  212059. discRecorder->Close();
  212060. if (redbook != 0)
  212061. redbook->Release();
  212062. discRecorder->Release();
  212063. discMaster->Release();
  212064. Release();
  212065. }
  212066. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  212067. {
  212068. if (listener != 0 && ! shouldCancel)
  212069. shouldCancel = listener->audioCDBurnProgress (progress);
  212070. *pbCancel = shouldCancel;
  212071. return S_OK;
  212072. }
  212073. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  212074. {
  212075. progress = nCompleted / (float) nTotal;
  212076. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  212077. return E_NOTIMPL;
  212078. }
  212079. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  212080. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  212081. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  212082. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212083. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212084. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212085. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212086. class ScopedDiscOpener
  212087. {
  212088. public:
  212089. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  212090. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  212091. private:
  212092. Pimpl& pimpl;
  212093. ScopedDiscOpener (const ScopedDiscOpener&);
  212094. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  212095. };
  212096. DiskState getDiskState()
  212097. {
  212098. const ScopedDiscOpener opener (*this);
  212099. long type, flags;
  212100. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  212101. if (FAILED (hr))
  212102. return unknown;
  212103. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  212104. return writableDiskPresent;
  212105. if (type == 0)
  212106. return noDisc;
  212107. else
  212108. return readOnlyDiskPresent;
  212109. }
  212110. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  212111. {
  212112. ComSmartPtr<IPropertyStorage> prop;
  212113. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212114. return defaultReturn;
  212115. PROPSPEC iPropSpec;
  212116. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212117. iPropSpec.lpwstr = name;
  212118. PROPVARIANT iPropVariant;
  212119. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  212120. ? defaultReturn : (int) iPropVariant.lVal;
  212121. }
  212122. bool setIntProperty (const LPOLESTR name, const int value) const
  212123. {
  212124. ComSmartPtr<IPropertyStorage> prop;
  212125. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212126. return false;
  212127. PROPSPEC iPropSpec;
  212128. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212129. iPropSpec.lpwstr = name;
  212130. PROPVARIANT iPropVariant;
  212131. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  212132. return false;
  212133. iPropVariant.lVal = (long) value;
  212134. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  212135. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  212136. }
  212137. void timerCallback()
  212138. {
  212139. const DiskState state = getDiskState();
  212140. if (state != lastState)
  212141. {
  212142. lastState = state;
  212143. owner.sendChangeMessage (&owner);
  212144. }
  212145. }
  212146. AudioCDBurner& owner;
  212147. DiskState lastState;
  212148. IDiscMaster* discMaster;
  212149. IDiscRecorder* discRecorder;
  212150. IRedbookDiscMaster* redbook;
  212151. AudioCDBurner::BurnProgressListener* listener;
  212152. float progress;
  212153. bool shouldCancel;
  212154. };
  212155. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  212156. {
  212157. IDiscMaster* discMaster = 0;
  212158. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  212159. if (discRecorder != 0)
  212160. pimpl = new Pimpl (*this, discMaster, discRecorder);
  212161. }
  212162. AudioCDBurner::~AudioCDBurner()
  212163. {
  212164. if (pimpl != 0)
  212165. pimpl.release()->releaseObjects();
  212166. }
  212167. const StringArray AudioCDBurner::findAvailableDevices()
  212168. {
  212169. StringArray devs;
  212170. enumCDBurners (&devs, -1, 0);
  212171. return devs;
  212172. }
  212173. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  212174. {
  212175. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  212176. if (b->pimpl == 0)
  212177. b = 0;
  212178. return b.release();
  212179. }
  212180. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  212181. {
  212182. return pimpl->getDiskState();
  212183. }
  212184. bool AudioCDBurner::isDiskPresent() const
  212185. {
  212186. return getDiskState() == writableDiskPresent;
  212187. }
  212188. bool AudioCDBurner::openTray()
  212189. {
  212190. const Pimpl::ScopedDiscOpener opener (*pimpl);
  212191. return SUCCEEDED (pimpl->discRecorder->Eject());
  212192. }
  212193. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  212194. {
  212195. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  212196. DiskState oldState = getDiskState();
  212197. DiskState newState = oldState;
  212198. while (newState == oldState && Time::currentTimeMillis() < timeout)
  212199. {
  212200. newState = getDiskState();
  212201. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  212202. }
  212203. return newState;
  212204. }
  212205. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  212206. {
  212207. Array<int> results;
  212208. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  212209. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  212210. for (int i = 0; i < numElementsInArray (speeds); ++i)
  212211. if (speeds[i] <= maxSpeed)
  212212. results.add (speeds[i]);
  212213. results.addIfNotAlreadyThere (maxSpeed);
  212214. return results;
  212215. }
  212216. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  212217. {
  212218. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  212219. return false;
  212220. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  212221. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  212222. }
  212223. int AudioCDBurner::getNumAvailableAudioBlocks() const
  212224. {
  212225. long blocksFree = 0;
  212226. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  212227. return blocksFree;
  212228. }
  212229. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  212230. bool performFakeBurnForTesting, int writeSpeed)
  212231. {
  212232. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  212233. pimpl->listener = listener;
  212234. pimpl->progress = 0;
  212235. pimpl->shouldCancel = false;
  212236. UINT_PTR cookie;
  212237. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  212238. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  212239. ejectDiscAfterwards);
  212240. String error;
  212241. if (hr != S_OK)
  212242. {
  212243. const char* e = "Couldn't open or write to the CD device";
  212244. if (hr == IMAPI_E_USERABORT)
  212245. e = "User cancelled the write operation";
  212246. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  212247. e = "No Disk present";
  212248. error = e;
  212249. }
  212250. pimpl->discMaster->ProgressUnadvise (cookie);
  212251. pimpl->listener = 0;
  212252. return error;
  212253. }
  212254. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  212255. {
  212256. if (audioSource == 0)
  212257. return false;
  212258. ScopedPointer<AudioSource> source (audioSource);
  212259. long bytesPerBlock;
  212260. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  212261. const int samplesPerBlock = bytesPerBlock / 4;
  212262. bool ok = true;
  212263. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  212264. HeapBlock <byte> buffer (bytesPerBlock);
  212265. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  212266. int samplesDone = 0;
  212267. source->prepareToPlay (samplesPerBlock, 44100.0);
  212268. while (ok)
  212269. {
  212270. {
  212271. AudioSourceChannelInfo info;
  212272. info.buffer = &sourceBuffer;
  212273. info.numSamples = samplesPerBlock;
  212274. info.startSample = 0;
  212275. sourceBuffer.clear();
  212276. source->getNextAudioBlock (info);
  212277. }
  212278. zeromem (buffer, bytesPerBlock);
  212279. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  212280. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  212281. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  212282. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  212283. CDSampleFormat left (buffer, 2);
  212284. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  212285. CDSampleFormat right (buffer + 2, 2);
  212286. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  212287. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212288. if (FAILED (hr))
  212289. ok = false;
  212290. samplesDone += samplesPerBlock;
  212291. if (samplesDone >= numSamples)
  212292. break;
  212293. }
  212294. hr = pimpl->redbook->CloseAudioTrack();
  212295. return ok && hr == S_OK;
  212296. }
  212297. #endif
  212298. #endif
  212299. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212300. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212301. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212302. // compiled on its own).
  212303. #if JUCE_INCLUDED_FILE
  212304. class MidiInCollector
  212305. {
  212306. public:
  212307. MidiInCollector (MidiInput* const input_,
  212308. MidiInputCallback& callback_)
  212309. : deviceHandle (0),
  212310. input (input_),
  212311. callback (callback_),
  212312. concatenator (4096),
  212313. isStarted (false),
  212314. startTime (0)
  212315. {
  212316. }
  212317. ~MidiInCollector()
  212318. {
  212319. stop();
  212320. if (deviceHandle != 0)
  212321. {
  212322. int count = 5;
  212323. while (--count >= 0)
  212324. {
  212325. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  212326. break;
  212327. Sleep (20);
  212328. }
  212329. }
  212330. }
  212331. void handleMessage (const uint32 message, const uint32 timeStamp)
  212332. {
  212333. if ((message & 0xff) >= 0x80 && isStarted)
  212334. {
  212335. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  212336. writeFinishedBlocks();
  212337. }
  212338. }
  212339. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212340. {
  212341. if (isStarted)
  212342. {
  212343. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  212344. writeFinishedBlocks();
  212345. }
  212346. }
  212347. void start()
  212348. {
  212349. jassert (deviceHandle != 0);
  212350. if (deviceHandle != 0 && ! isStarted)
  212351. {
  212352. activeMidiCollectors.addIfNotAlreadyThere (this);
  212353. for (int i = 0; i < (int) numHeaders; ++i)
  212354. headers[i].write (deviceHandle);
  212355. startTime = Time::getMillisecondCounter();
  212356. MMRESULT res = midiInStart (deviceHandle);
  212357. if (res == MMSYSERR_NOERROR)
  212358. {
  212359. concatenator.reset();
  212360. isStarted = true;
  212361. }
  212362. else
  212363. {
  212364. unprepareAllHeaders();
  212365. }
  212366. }
  212367. }
  212368. void stop()
  212369. {
  212370. if (isStarted)
  212371. {
  212372. isStarted = false;
  212373. midiInReset (deviceHandle);
  212374. midiInStop (deviceHandle);
  212375. activeMidiCollectors.removeValue (this);
  212376. unprepareAllHeaders();
  212377. concatenator.reset();
  212378. }
  212379. }
  212380. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212381. {
  212382. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  212383. if (activeMidiCollectors.contains (collector))
  212384. {
  212385. if (uMsg == MIM_DATA)
  212386. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  212387. else if (uMsg == MIM_LONGDATA)
  212388. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212389. }
  212390. }
  212391. juce_UseDebuggingNewOperator
  212392. HMIDIIN deviceHandle;
  212393. private:
  212394. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  212395. MidiInput* input;
  212396. MidiInputCallback& callback;
  212397. MidiDataConcatenator concatenator;
  212398. bool volatile isStarted;
  212399. uint32 startTime;
  212400. class MidiHeader
  212401. {
  212402. public:
  212403. MidiHeader()
  212404. {
  212405. zerostruct (hdr);
  212406. hdr.lpData = data;
  212407. hdr.dwBufferLength = numElementsInArray (data);
  212408. }
  212409. void write (HMIDIIN deviceHandle)
  212410. {
  212411. hdr.dwBytesRecorded = 0;
  212412. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212413. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  212414. }
  212415. void writeIfFinished (HMIDIIN deviceHandle)
  212416. {
  212417. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212418. {
  212419. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212420. (void) res;
  212421. write (deviceHandle);
  212422. }
  212423. }
  212424. void unprepare (HMIDIIN deviceHandle)
  212425. {
  212426. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212427. {
  212428. int c = 10;
  212429. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  212430. Thread::sleep (20);
  212431. jassert (c >= 0);
  212432. }
  212433. }
  212434. private:
  212435. MIDIHDR hdr;
  212436. char data [256];
  212437. MidiHeader (const MidiHeader&);
  212438. MidiHeader& operator= (const MidiHeader&);
  212439. };
  212440. enum { numHeaders = 32 };
  212441. MidiHeader headers [numHeaders];
  212442. void writeFinishedBlocks()
  212443. {
  212444. for (int i = 0; i < (int) numHeaders; ++i)
  212445. headers[i].writeIfFinished (deviceHandle);
  212446. }
  212447. void unprepareAllHeaders()
  212448. {
  212449. for (int i = 0; i < (int) numHeaders; ++i)
  212450. headers[i].unprepare (deviceHandle);
  212451. }
  212452. double convertTimeStamp (uint32 timeStamp)
  212453. {
  212454. timeStamp += startTime;
  212455. const uint32 now = Time::getMillisecondCounter();
  212456. if (timeStamp > now)
  212457. {
  212458. if (timeStamp > now + 2)
  212459. --startTime;
  212460. timeStamp = now;
  212461. }
  212462. return timeStamp * 0.001;
  212463. }
  212464. MidiInCollector (const MidiInCollector&);
  212465. MidiInCollector& operator= (const MidiInCollector&);
  212466. };
  212467. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  212468. const StringArray MidiInput::getDevices()
  212469. {
  212470. StringArray s;
  212471. const int num = midiInGetNumDevs();
  212472. for (int i = 0; i < num; ++i)
  212473. {
  212474. MIDIINCAPS mc;
  212475. zerostruct (mc);
  212476. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212477. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212478. }
  212479. return s;
  212480. }
  212481. int MidiInput::getDefaultDeviceIndex()
  212482. {
  212483. return 0;
  212484. }
  212485. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212486. {
  212487. if (callback == 0)
  212488. return 0;
  212489. UINT deviceId = MIDI_MAPPER;
  212490. int n = 0;
  212491. String name;
  212492. const int num = midiInGetNumDevs();
  212493. for (int i = 0; i < num; ++i)
  212494. {
  212495. MIDIINCAPS mc;
  212496. zerostruct (mc);
  212497. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212498. {
  212499. if (index == n)
  212500. {
  212501. deviceId = i;
  212502. name = String (mc.szPname, numElementsInArray (mc.szPname));
  212503. break;
  212504. }
  212505. ++n;
  212506. }
  212507. }
  212508. ScopedPointer <MidiInput> in (new MidiInput (name));
  212509. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  212510. HMIDIIN h;
  212511. HRESULT err = midiInOpen (&h, deviceId,
  212512. (DWORD_PTR) &MidiInCollector::midiInCallback,
  212513. (DWORD_PTR) (MidiInCollector*) collector,
  212514. CALLBACK_FUNCTION);
  212515. if (err == MMSYSERR_NOERROR)
  212516. {
  212517. collector->deviceHandle = h;
  212518. in->internal = collector.release();
  212519. return in.release();
  212520. }
  212521. return 0;
  212522. }
  212523. MidiInput::MidiInput (const String& name_)
  212524. : name (name_),
  212525. internal (0)
  212526. {
  212527. }
  212528. MidiInput::~MidiInput()
  212529. {
  212530. delete static_cast <MidiInCollector*> (internal);
  212531. }
  212532. void MidiInput::start()
  212533. {
  212534. static_cast <MidiInCollector*> (internal)->start();
  212535. }
  212536. void MidiInput::stop()
  212537. {
  212538. static_cast <MidiInCollector*> (internal)->stop();
  212539. }
  212540. struct MidiOutHandle
  212541. {
  212542. int refCount;
  212543. UINT deviceId;
  212544. HMIDIOUT handle;
  212545. static Array<MidiOutHandle*> activeHandles;
  212546. juce_UseDebuggingNewOperator
  212547. };
  212548. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212549. const StringArray MidiOutput::getDevices()
  212550. {
  212551. StringArray s;
  212552. const int num = midiOutGetNumDevs();
  212553. for (int i = 0; i < num; ++i)
  212554. {
  212555. MIDIOUTCAPS mc;
  212556. zerostruct (mc);
  212557. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212558. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212559. }
  212560. return s;
  212561. }
  212562. int MidiOutput::getDefaultDeviceIndex()
  212563. {
  212564. const int num = midiOutGetNumDevs();
  212565. int n = 0;
  212566. for (int i = 0; i < num; ++i)
  212567. {
  212568. MIDIOUTCAPS mc;
  212569. zerostruct (mc);
  212570. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212571. {
  212572. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212573. return n;
  212574. ++n;
  212575. }
  212576. }
  212577. return 0;
  212578. }
  212579. MidiOutput* MidiOutput::openDevice (int index)
  212580. {
  212581. UINT deviceId = MIDI_MAPPER;
  212582. const int num = midiOutGetNumDevs();
  212583. int i, n = 0;
  212584. for (i = 0; i < num; ++i)
  212585. {
  212586. MIDIOUTCAPS mc;
  212587. zerostruct (mc);
  212588. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212589. {
  212590. // use the microsoft sw synth as a default - best not to allow deviceId
  212591. // to be MIDI_MAPPER, or else device sharing breaks
  212592. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212593. deviceId = i;
  212594. if (index == n)
  212595. {
  212596. deviceId = i;
  212597. break;
  212598. }
  212599. ++n;
  212600. }
  212601. }
  212602. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212603. {
  212604. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212605. if (han != 0 && han->deviceId == deviceId)
  212606. {
  212607. han->refCount++;
  212608. MidiOutput* const out = new MidiOutput();
  212609. out->internal = han;
  212610. return out;
  212611. }
  212612. }
  212613. for (i = 4; --i >= 0;)
  212614. {
  212615. HMIDIOUT h = 0;
  212616. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212617. if (res == MMSYSERR_NOERROR)
  212618. {
  212619. MidiOutHandle* const han = new MidiOutHandle();
  212620. han->deviceId = deviceId;
  212621. han->refCount = 1;
  212622. han->handle = h;
  212623. MidiOutHandle::activeHandles.add (han);
  212624. MidiOutput* const out = new MidiOutput();
  212625. out->internal = han;
  212626. return out;
  212627. }
  212628. else if (res == MMSYSERR_ALLOCATED)
  212629. {
  212630. Sleep (100);
  212631. }
  212632. else
  212633. {
  212634. break;
  212635. }
  212636. }
  212637. return 0;
  212638. }
  212639. MidiOutput::~MidiOutput()
  212640. {
  212641. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212642. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212643. {
  212644. midiOutClose (h->handle);
  212645. MidiOutHandle::activeHandles.removeValue (h);
  212646. delete h;
  212647. }
  212648. }
  212649. void MidiOutput::reset()
  212650. {
  212651. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212652. midiOutReset (h->handle);
  212653. }
  212654. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212655. {
  212656. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212657. DWORD n;
  212658. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212659. {
  212660. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212661. rightVol = nn[0] / (float) 0xffff;
  212662. leftVol = nn[1] / (float) 0xffff;
  212663. return true;
  212664. }
  212665. else
  212666. {
  212667. rightVol = leftVol = 1.0f;
  212668. return false;
  212669. }
  212670. }
  212671. void MidiOutput::setVolume (float leftVol, float rightVol)
  212672. {
  212673. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212674. DWORD n;
  212675. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212676. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212677. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212678. midiOutSetVolume (handle->handle, n);
  212679. }
  212680. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212681. {
  212682. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212683. if (message.getRawDataSize() > 3
  212684. || message.isSysEx())
  212685. {
  212686. MIDIHDR h;
  212687. zerostruct (h);
  212688. h.lpData = (char*) message.getRawData();
  212689. h.dwBufferLength = message.getRawDataSize();
  212690. h.dwBytesRecorded = message.getRawDataSize();
  212691. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212692. {
  212693. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212694. if (res == MMSYSERR_NOERROR)
  212695. {
  212696. while ((h.dwFlags & MHDR_DONE) == 0)
  212697. Sleep (1);
  212698. int count = 500; // 1 sec timeout
  212699. while (--count >= 0)
  212700. {
  212701. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212702. if (res == MIDIERR_STILLPLAYING)
  212703. Sleep (2);
  212704. else
  212705. break;
  212706. }
  212707. }
  212708. }
  212709. }
  212710. else
  212711. {
  212712. midiOutShortMsg (handle->handle,
  212713. *(unsigned int*) message.getRawData());
  212714. }
  212715. }
  212716. #endif
  212717. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212718. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212719. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212720. // compiled on its own).
  212721. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212722. #undef WINDOWS
  212723. // #define ASIO_DEBUGGING 1
  212724. #if ASIO_DEBUGGING
  212725. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212726. #else
  212727. #define log(a) {}
  212728. #endif
  212729. #if ASIO_DEBUGGING
  212730. static void logError (const String& context, long error)
  212731. {
  212732. String err ("unknown error");
  212733. if (error == ASE_NotPresent) err = "Not Present";
  212734. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212735. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212736. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212737. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212738. else if (error == ASE_NoClock) err = "No Clock";
  212739. else if (error == ASE_NoMemory) err = "Out of memory";
  212740. log ("!!error: " + context + " - " + err);
  212741. }
  212742. #else
  212743. #define logError(a, b) {}
  212744. #endif
  212745. class ASIOAudioIODevice;
  212746. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212747. static const int maxASIOChannels = 160;
  212748. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212749. private Timer
  212750. {
  212751. public:
  212752. Component ourWindow;
  212753. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212754. const String& optionalDllForDirectLoading_)
  212755. : AudioIODevice (name_, "ASIO"),
  212756. asioObject (0),
  212757. classId (classId_),
  212758. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212759. currentBitDepth (16),
  212760. currentSampleRate (0),
  212761. isOpen_ (false),
  212762. isStarted (false),
  212763. postOutput (true),
  212764. insideControlPanelModalLoop (false),
  212765. shouldUsePreferredSize (false)
  212766. {
  212767. name = name_;
  212768. ourWindow.addToDesktop (0);
  212769. windowHandle = ourWindow.getWindowHandle();
  212770. jassert (currentASIODev [slotNumber] == 0);
  212771. currentASIODev [slotNumber] = this;
  212772. openDevice();
  212773. }
  212774. ~ASIOAudioIODevice()
  212775. {
  212776. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212777. if (currentASIODev[i] == this)
  212778. currentASIODev[i] = 0;
  212779. close();
  212780. log ("ASIO - exiting");
  212781. removeCurrentDriver();
  212782. }
  212783. void updateSampleRates()
  212784. {
  212785. // find a list of sample rates..
  212786. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212787. sampleRates.clear();
  212788. if (asioObject != 0)
  212789. {
  212790. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212791. {
  212792. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212793. if (err == 0)
  212794. {
  212795. sampleRates.add ((int) possibleSampleRates[index]);
  212796. log ("rate: " + String ((int) possibleSampleRates[index]));
  212797. }
  212798. else if (err != ASE_NoClock)
  212799. {
  212800. logError ("CanSampleRate", err);
  212801. }
  212802. }
  212803. if (sampleRates.size() == 0)
  212804. {
  212805. double cr = 0;
  212806. const long err = asioObject->getSampleRate (&cr);
  212807. log ("No sample rates supported - current rate: " + String ((int) cr));
  212808. if (err == 0)
  212809. sampleRates.add ((int) cr);
  212810. }
  212811. }
  212812. }
  212813. const StringArray getOutputChannelNames()
  212814. {
  212815. return outputChannelNames;
  212816. }
  212817. const StringArray getInputChannelNames()
  212818. {
  212819. return inputChannelNames;
  212820. }
  212821. int getNumSampleRates()
  212822. {
  212823. return sampleRates.size();
  212824. }
  212825. double getSampleRate (int index)
  212826. {
  212827. return sampleRates [index];
  212828. }
  212829. int getNumBufferSizesAvailable()
  212830. {
  212831. return bufferSizes.size();
  212832. }
  212833. int getBufferSizeSamples (int index)
  212834. {
  212835. return bufferSizes [index];
  212836. }
  212837. int getDefaultBufferSize()
  212838. {
  212839. return preferredSize;
  212840. }
  212841. const String open (const BigInteger& inputChannels,
  212842. const BigInteger& outputChannels,
  212843. double sr,
  212844. int bufferSizeSamples)
  212845. {
  212846. close();
  212847. currentCallback = 0;
  212848. if (bufferSizeSamples <= 0)
  212849. shouldUsePreferredSize = true;
  212850. if (asioObject == 0 || ! isASIOOpen)
  212851. {
  212852. log ("Warning: device not open");
  212853. const String err (openDevice());
  212854. if (asioObject == 0 || ! isASIOOpen)
  212855. return err;
  212856. }
  212857. isStarted = false;
  212858. bufferIndex = -1;
  212859. long err = 0;
  212860. long newPreferredSize = 0;
  212861. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212862. minSize = 0;
  212863. maxSize = 0;
  212864. newPreferredSize = 0;
  212865. granularity = 0;
  212866. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212867. {
  212868. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212869. shouldUsePreferredSize = true;
  212870. preferredSize = newPreferredSize;
  212871. }
  212872. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212873. // dynamic changes to the buffer size...
  212874. shouldUsePreferredSize = shouldUsePreferredSize
  212875. || getName().containsIgnoreCase ("Digidesign");
  212876. if (shouldUsePreferredSize)
  212877. {
  212878. log ("Using preferred size for buffer..");
  212879. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212880. {
  212881. bufferSizeSamples = preferredSize;
  212882. }
  212883. else
  212884. {
  212885. bufferSizeSamples = 1024;
  212886. logError ("GetBufferSize1", err);
  212887. }
  212888. shouldUsePreferredSize = false;
  212889. }
  212890. int sampleRate = roundDoubleToInt (sr);
  212891. currentSampleRate = sampleRate;
  212892. currentBlockSizeSamples = bufferSizeSamples;
  212893. currentChansOut.clear();
  212894. currentChansIn.clear();
  212895. zeromem (inBuffers, sizeof (inBuffers));
  212896. zeromem (outBuffers, sizeof (outBuffers));
  212897. updateSampleRates();
  212898. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212899. sampleRate = sampleRates[0];
  212900. jassert (sampleRate != 0);
  212901. if (sampleRate == 0)
  212902. sampleRate = 44100;
  212903. long numSources = 32;
  212904. ASIOClockSource clocks[32];
  212905. zeromem (clocks, sizeof (clocks));
  212906. asioObject->getClockSources (clocks, &numSources);
  212907. bool isSourceSet = false;
  212908. // careful not to remove this loop because it does more than just logging!
  212909. int i;
  212910. for (i = 0; i < numSources; ++i)
  212911. {
  212912. String s ("clock: ");
  212913. s += clocks[i].name;
  212914. if (clocks[i].isCurrentSource)
  212915. {
  212916. isSourceSet = true;
  212917. s << " (cur)";
  212918. }
  212919. log (s);
  212920. }
  212921. if (numSources > 1 && ! isSourceSet)
  212922. {
  212923. log ("setting clock source");
  212924. asioObject->setClockSource (clocks[0].index);
  212925. Thread::sleep (20);
  212926. }
  212927. else
  212928. {
  212929. if (numSources == 0)
  212930. {
  212931. log ("ASIO - no clock sources!");
  212932. }
  212933. }
  212934. double cr = 0;
  212935. err = asioObject->getSampleRate (&cr);
  212936. if (err == 0)
  212937. {
  212938. currentSampleRate = cr;
  212939. }
  212940. else
  212941. {
  212942. logError ("GetSampleRate", err);
  212943. currentSampleRate = 0;
  212944. }
  212945. error = String::empty;
  212946. needToReset = false;
  212947. isReSync = false;
  212948. err = 0;
  212949. bool buffersCreated = false;
  212950. if (currentSampleRate != sampleRate)
  212951. {
  212952. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212953. err = asioObject->setSampleRate (sampleRate);
  212954. if (err == ASE_NoClock && numSources > 0)
  212955. {
  212956. log ("trying to set a clock source..");
  212957. Thread::sleep (10);
  212958. err = asioObject->setClockSource (clocks[0].index);
  212959. if (err != 0)
  212960. {
  212961. logError ("SetClock", err);
  212962. }
  212963. Thread::sleep (10);
  212964. err = asioObject->setSampleRate (sampleRate);
  212965. }
  212966. }
  212967. if (err == 0)
  212968. {
  212969. currentSampleRate = sampleRate;
  212970. if (needToReset)
  212971. {
  212972. if (isReSync)
  212973. {
  212974. log ("Resync request");
  212975. }
  212976. log ("! Resetting ASIO after sample rate change");
  212977. removeCurrentDriver();
  212978. loadDriver();
  212979. const String error (initDriver());
  212980. if (error.isNotEmpty())
  212981. {
  212982. log ("ASIOInit: " + error);
  212983. }
  212984. needToReset = false;
  212985. isReSync = false;
  212986. }
  212987. numActiveInputChans = 0;
  212988. numActiveOutputChans = 0;
  212989. ASIOBufferInfo* info = bufferInfos;
  212990. int i;
  212991. for (i = 0; i < totalNumInputChans; ++i)
  212992. {
  212993. if (inputChannels[i])
  212994. {
  212995. currentChansIn.setBit (i);
  212996. info->isInput = 1;
  212997. info->channelNum = i;
  212998. info->buffers[0] = info->buffers[1] = 0;
  212999. ++info;
  213000. ++numActiveInputChans;
  213001. }
  213002. }
  213003. for (i = 0; i < totalNumOutputChans; ++i)
  213004. {
  213005. if (outputChannels[i])
  213006. {
  213007. currentChansOut.setBit (i);
  213008. info->isInput = 0;
  213009. info->channelNum = i;
  213010. info->buffers[0] = info->buffers[1] = 0;
  213011. ++info;
  213012. ++numActiveOutputChans;
  213013. }
  213014. }
  213015. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  213016. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213017. if (currentASIODev[0] == this)
  213018. {
  213019. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213020. callbacks.asioMessage = &asioMessagesCallback0;
  213021. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213022. }
  213023. else if (currentASIODev[1] == this)
  213024. {
  213025. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213026. callbacks.asioMessage = &asioMessagesCallback1;
  213027. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213028. }
  213029. else if (currentASIODev[2] == this)
  213030. {
  213031. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213032. callbacks.asioMessage = &asioMessagesCallback2;
  213033. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213034. }
  213035. else
  213036. {
  213037. jassertfalse;
  213038. }
  213039. log ("disposing buffers");
  213040. err = asioObject->disposeBuffers();
  213041. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  213042. err = asioObject->createBuffers (bufferInfos,
  213043. totalBuffers,
  213044. currentBlockSizeSamples,
  213045. &callbacks);
  213046. if (err != 0)
  213047. {
  213048. currentBlockSizeSamples = preferredSize;
  213049. logError ("create buffers 2", err);
  213050. asioObject->disposeBuffers();
  213051. err = asioObject->createBuffers (bufferInfos,
  213052. totalBuffers,
  213053. currentBlockSizeSamples,
  213054. &callbacks);
  213055. }
  213056. if (err == 0)
  213057. {
  213058. buffersCreated = true;
  213059. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  213060. int n = 0;
  213061. Array <int> types;
  213062. currentBitDepth = 16;
  213063. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  213064. {
  213065. if (inputChannels[i])
  213066. {
  213067. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  213068. ASIOChannelInfo channelInfo;
  213069. zerostruct (channelInfo);
  213070. channelInfo.channel = i;
  213071. channelInfo.isInput = 1;
  213072. asioObject->getChannelInfo (&channelInfo);
  213073. types.addIfNotAlreadyThere (channelInfo.type);
  213074. typeToFormatParameters (channelInfo.type,
  213075. inputChannelBitDepths[n],
  213076. inputChannelBytesPerSample[n],
  213077. inputChannelIsFloat[n],
  213078. inputChannelLittleEndian[n]);
  213079. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  213080. ++n;
  213081. }
  213082. }
  213083. jassert (numActiveInputChans == n);
  213084. n = 0;
  213085. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  213086. {
  213087. if (outputChannels[i])
  213088. {
  213089. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  213090. ASIOChannelInfo channelInfo;
  213091. zerostruct (channelInfo);
  213092. channelInfo.channel = i;
  213093. channelInfo.isInput = 0;
  213094. asioObject->getChannelInfo (&channelInfo);
  213095. types.addIfNotAlreadyThere (channelInfo.type);
  213096. typeToFormatParameters (channelInfo.type,
  213097. outputChannelBitDepths[n],
  213098. outputChannelBytesPerSample[n],
  213099. outputChannelIsFloat[n],
  213100. outputChannelLittleEndian[n]);
  213101. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  213102. ++n;
  213103. }
  213104. }
  213105. jassert (numActiveOutputChans == n);
  213106. for (i = types.size(); --i >= 0;)
  213107. {
  213108. log ("channel format: " + String (types[i]));
  213109. }
  213110. jassert (n <= totalBuffers);
  213111. for (i = 0; i < numActiveOutputChans; ++i)
  213112. {
  213113. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  213114. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  213115. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  213116. {
  213117. log ("!! Null buffers");
  213118. }
  213119. else
  213120. {
  213121. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  213122. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  213123. }
  213124. }
  213125. inputLatency = outputLatency = 0;
  213126. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213127. {
  213128. log ("ASIO - no latencies");
  213129. }
  213130. else
  213131. {
  213132. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  213133. }
  213134. isOpen_ = true;
  213135. log ("starting ASIO");
  213136. calledback = false;
  213137. err = asioObject->start();
  213138. if (err != 0)
  213139. {
  213140. isOpen_ = false;
  213141. log ("ASIO - stop on failure");
  213142. Thread::sleep (10);
  213143. asioObject->stop();
  213144. error = "Can't start device";
  213145. Thread::sleep (10);
  213146. }
  213147. else
  213148. {
  213149. int count = 300;
  213150. while (--count > 0 && ! calledback)
  213151. Thread::sleep (10);
  213152. isStarted = true;
  213153. if (! calledback)
  213154. {
  213155. error = "Device didn't start correctly";
  213156. log ("ASIO didn't callback - stopping..");
  213157. asioObject->stop();
  213158. }
  213159. }
  213160. }
  213161. else
  213162. {
  213163. error = "Can't create i/o buffers";
  213164. }
  213165. }
  213166. else
  213167. {
  213168. error = "Can't set sample rate: ";
  213169. error << sampleRate;
  213170. }
  213171. if (error.isNotEmpty())
  213172. {
  213173. logError (error, err);
  213174. if (asioObject != 0 && buffersCreated)
  213175. asioObject->disposeBuffers();
  213176. Thread::sleep (20);
  213177. isStarted = false;
  213178. isOpen_ = false;
  213179. const String errorCopy (error);
  213180. close(); // (this resets the error string)
  213181. error = errorCopy;
  213182. }
  213183. needToReset = false;
  213184. isReSync = false;
  213185. return error;
  213186. }
  213187. void close()
  213188. {
  213189. error = String::empty;
  213190. stopTimer();
  213191. stop();
  213192. if (isASIOOpen && isOpen_)
  213193. {
  213194. const ScopedLock sl (callbackLock);
  213195. isOpen_ = false;
  213196. isStarted = false;
  213197. needToReset = false;
  213198. isReSync = false;
  213199. log ("ASIO - stopping");
  213200. if (asioObject != 0)
  213201. {
  213202. Thread::sleep (20);
  213203. asioObject->stop();
  213204. Thread::sleep (10);
  213205. asioObject->disposeBuffers();
  213206. }
  213207. Thread::sleep (10);
  213208. }
  213209. }
  213210. bool isOpen()
  213211. {
  213212. return isOpen_ || insideControlPanelModalLoop;
  213213. }
  213214. int getCurrentBufferSizeSamples()
  213215. {
  213216. return currentBlockSizeSamples;
  213217. }
  213218. double getCurrentSampleRate()
  213219. {
  213220. return currentSampleRate;
  213221. }
  213222. const BigInteger getActiveOutputChannels() const
  213223. {
  213224. return currentChansOut;
  213225. }
  213226. const BigInteger getActiveInputChannels() const
  213227. {
  213228. return currentChansIn;
  213229. }
  213230. int getCurrentBitDepth()
  213231. {
  213232. return currentBitDepth;
  213233. }
  213234. int getOutputLatencyInSamples()
  213235. {
  213236. return outputLatency + currentBlockSizeSamples / 4;
  213237. }
  213238. int getInputLatencyInSamples()
  213239. {
  213240. return inputLatency + currentBlockSizeSamples / 4;
  213241. }
  213242. void start (AudioIODeviceCallback* callback)
  213243. {
  213244. if (callback != 0)
  213245. {
  213246. callback->audioDeviceAboutToStart (this);
  213247. const ScopedLock sl (callbackLock);
  213248. currentCallback = callback;
  213249. }
  213250. }
  213251. void stop()
  213252. {
  213253. AudioIODeviceCallback* const lastCallback = currentCallback;
  213254. {
  213255. const ScopedLock sl (callbackLock);
  213256. currentCallback = 0;
  213257. }
  213258. if (lastCallback != 0)
  213259. lastCallback->audioDeviceStopped();
  213260. }
  213261. bool isPlaying()
  213262. {
  213263. return isASIOOpen && (currentCallback != 0);
  213264. }
  213265. const String getLastError()
  213266. {
  213267. return error;
  213268. }
  213269. bool hasControlPanel() const
  213270. {
  213271. return true;
  213272. }
  213273. bool showControlPanel()
  213274. {
  213275. log ("ASIO - showing control panel");
  213276. Component modalWindow (String::empty);
  213277. modalWindow.setOpaque (true);
  213278. modalWindow.addToDesktop (0);
  213279. modalWindow.enterModalState();
  213280. bool done = false;
  213281. JUCE_TRY
  213282. {
  213283. // are there are devices that need to be closed before showing their control panel?
  213284. // close();
  213285. insideControlPanelModalLoop = true;
  213286. const uint32 started = Time::getMillisecondCounter();
  213287. if (asioObject != 0)
  213288. {
  213289. asioObject->controlPanel();
  213290. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  213291. log ("spent: " + String (spent));
  213292. if (spent > 300)
  213293. {
  213294. shouldUsePreferredSize = true;
  213295. done = true;
  213296. }
  213297. }
  213298. }
  213299. JUCE_CATCH_ALL
  213300. insideControlPanelModalLoop = false;
  213301. return done;
  213302. }
  213303. void resetRequest() throw()
  213304. {
  213305. needToReset = true;
  213306. }
  213307. void resyncRequest() throw()
  213308. {
  213309. needToReset = true;
  213310. isReSync = true;
  213311. }
  213312. void timerCallback()
  213313. {
  213314. if (! insideControlPanelModalLoop)
  213315. {
  213316. stopTimer();
  213317. // used to cause a reset
  213318. log ("! ASIO restart request!");
  213319. if (isOpen_)
  213320. {
  213321. AudioIODeviceCallback* const oldCallback = currentCallback;
  213322. close();
  213323. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213324. currentSampleRate, currentBlockSizeSamples);
  213325. if (oldCallback != 0)
  213326. start (oldCallback);
  213327. }
  213328. }
  213329. else
  213330. {
  213331. startTimer (100);
  213332. }
  213333. }
  213334. juce_UseDebuggingNewOperator
  213335. private:
  213336. IASIO* volatile asioObject;
  213337. ASIOCallbacks callbacks;
  213338. void* windowHandle;
  213339. CLSID classId;
  213340. const String optionalDllForDirectLoading;
  213341. String error;
  213342. long totalNumInputChans, totalNumOutputChans;
  213343. StringArray inputChannelNames, outputChannelNames;
  213344. Array<int> sampleRates, bufferSizes;
  213345. long inputLatency, outputLatency;
  213346. long minSize, maxSize, preferredSize, granularity;
  213347. int volatile currentBlockSizeSamples;
  213348. int volatile currentBitDepth;
  213349. double volatile currentSampleRate;
  213350. BigInteger currentChansOut, currentChansIn;
  213351. AudioIODeviceCallback* volatile currentCallback;
  213352. CriticalSection callbackLock;
  213353. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213354. float* inBuffers [maxASIOChannels];
  213355. float* outBuffers [maxASIOChannels];
  213356. int inputChannelBitDepths [maxASIOChannels];
  213357. int outputChannelBitDepths [maxASIOChannels];
  213358. int inputChannelBytesPerSample [maxASIOChannels];
  213359. int outputChannelBytesPerSample [maxASIOChannels];
  213360. bool inputChannelIsFloat [maxASIOChannels];
  213361. bool outputChannelIsFloat [maxASIOChannels];
  213362. bool inputChannelLittleEndian [maxASIOChannels];
  213363. bool outputChannelLittleEndian [maxASIOChannels];
  213364. WaitableEvent event1;
  213365. HeapBlock <float> tempBuffer;
  213366. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213367. bool isOpen_, isStarted;
  213368. bool volatile isASIOOpen;
  213369. bool volatile calledback;
  213370. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213371. bool volatile insideControlPanelModalLoop;
  213372. bool volatile shouldUsePreferredSize;
  213373. void removeCurrentDriver()
  213374. {
  213375. if (asioObject != 0)
  213376. {
  213377. asioObject->Release();
  213378. asioObject = 0;
  213379. }
  213380. }
  213381. bool loadDriver()
  213382. {
  213383. removeCurrentDriver();
  213384. JUCE_TRY
  213385. {
  213386. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213387. classId, (void**) &asioObject) == S_OK)
  213388. {
  213389. return true;
  213390. }
  213391. // If a class isn't registered but we have a path for it, we can fallback to
  213392. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213393. if (optionalDllForDirectLoading.isNotEmpty())
  213394. {
  213395. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  213396. if (h != 0)
  213397. {
  213398. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213399. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213400. if (dllGetClassObject != 0)
  213401. {
  213402. IClassFactory* classFactory = 0;
  213403. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213404. if (classFactory != 0)
  213405. {
  213406. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213407. classFactory->Release();
  213408. }
  213409. return asioObject != 0;
  213410. }
  213411. }
  213412. }
  213413. }
  213414. JUCE_CATCH_ALL
  213415. asioObject = 0;
  213416. return false;
  213417. }
  213418. const String initDriver()
  213419. {
  213420. if (asioObject != 0)
  213421. {
  213422. char buffer [256];
  213423. zeromem (buffer, sizeof (buffer));
  213424. if (! asioObject->init (windowHandle))
  213425. {
  213426. asioObject->getErrorMessage (buffer);
  213427. return String (buffer, sizeof (buffer) - 1);
  213428. }
  213429. // just in case any daft drivers expect this to be called..
  213430. asioObject->getDriverName (buffer);
  213431. return String::empty;
  213432. }
  213433. return "No Driver";
  213434. }
  213435. const String openDevice()
  213436. {
  213437. // use this in case the driver starts opening dialog boxes..
  213438. Component modalWindow (String::empty);
  213439. modalWindow.setOpaque (true);
  213440. modalWindow.addToDesktop (0);
  213441. modalWindow.enterModalState();
  213442. // open the device and get its info..
  213443. log ("opening ASIO device: " + getName());
  213444. needToReset = false;
  213445. isReSync = false;
  213446. outputChannelNames.clear();
  213447. inputChannelNames.clear();
  213448. bufferSizes.clear();
  213449. sampleRates.clear();
  213450. isASIOOpen = false;
  213451. isOpen_ = false;
  213452. totalNumInputChans = 0;
  213453. totalNumOutputChans = 0;
  213454. numActiveInputChans = 0;
  213455. numActiveOutputChans = 0;
  213456. currentCallback = 0;
  213457. error = String::empty;
  213458. if (getName().isEmpty())
  213459. return error;
  213460. long err = 0;
  213461. if (loadDriver())
  213462. {
  213463. if ((error = initDriver()).isEmpty())
  213464. {
  213465. numActiveInputChans = 0;
  213466. numActiveOutputChans = 0;
  213467. totalNumInputChans = 0;
  213468. totalNumOutputChans = 0;
  213469. if (asioObject != 0
  213470. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213471. {
  213472. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213473. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213474. {
  213475. // find a list of buffer sizes..
  213476. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213477. if (granularity >= 0)
  213478. {
  213479. granularity = jmax (1, (int) granularity);
  213480. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213481. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213482. }
  213483. else if (granularity < 0)
  213484. {
  213485. for (int i = 0; i < 18; ++i)
  213486. {
  213487. const int s = (1 << i);
  213488. if (s >= minSize && s <= maxSize)
  213489. bufferSizes.add (s);
  213490. }
  213491. }
  213492. if (! bufferSizes.contains (preferredSize))
  213493. bufferSizes.insert (0, preferredSize);
  213494. double currentRate = 0;
  213495. asioObject->getSampleRate (&currentRate);
  213496. if (currentRate <= 0.0 || currentRate > 192001.0)
  213497. {
  213498. log ("setting sample rate");
  213499. err = asioObject->setSampleRate (44100.0);
  213500. if (err != 0)
  213501. {
  213502. logError ("setting sample rate", err);
  213503. }
  213504. asioObject->getSampleRate (&currentRate);
  213505. }
  213506. currentSampleRate = currentRate;
  213507. postOutput = (asioObject->outputReady() == 0);
  213508. if (postOutput)
  213509. {
  213510. log ("ASIO outputReady = ok");
  213511. }
  213512. updateSampleRates();
  213513. // ..because cubase does it at this point
  213514. inputLatency = outputLatency = 0;
  213515. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213516. {
  213517. log ("ASIO - no latencies");
  213518. }
  213519. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213520. // create some dummy buffers now.. because cubase does..
  213521. numActiveInputChans = 0;
  213522. numActiveOutputChans = 0;
  213523. ASIOBufferInfo* info = bufferInfos;
  213524. int i, numChans = 0;
  213525. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213526. {
  213527. info->isInput = 1;
  213528. info->channelNum = i;
  213529. info->buffers[0] = info->buffers[1] = 0;
  213530. ++info;
  213531. ++numChans;
  213532. }
  213533. const int outputBufferIndex = numChans;
  213534. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213535. {
  213536. info->isInput = 0;
  213537. info->channelNum = i;
  213538. info->buffers[0] = info->buffers[1] = 0;
  213539. ++info;
  213540. ++numChans;
  213541. }
  213542. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213543. if (currentASIODev[0] == this)
  213544. {
  213545. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213546. callbacks.asioMessage = &asioMessagesCallback0;
  213547. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213548. }
  213549. else if (currentASIODev[1] == this)
  213550. {
  213551. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213552. callbacks.asioMessage = &asioMessagesCallback1;
  213553. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213554. }
  213555. else if (currentASIODev[2] == this)
  213556. {
  213557. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213558. callbacks.asioMessage = &asioMessagesCallback2;
  213559. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213560. }
  213561. else
  213562. {
  213563. jassertfalse;
  213564. }
  213565. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213566. if (preferredSize > 0)
  213567. {
  213568. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213569. if (err != 0)
  213570. {
  213571. logError ("dummy buffers", err);
  213572. }
  213573. }
  213574. long newInps = 0, newOuts = 0;
  213575. asioObject->getChannels (&newInps, &newOuts);
  213576. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213577. {
  213578. totalNumInputChans = newInps;
  213579. totalNumOutputChans = newOuts;
  213580. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213581. }
  213582. updateSampleRates();
  213583. ASIOChannelInfo channelInfo;
  213584. channelInfo.type = 0;
  213585. for (i = 0; i < totalNumInputChans; ++i)
  213586. {
  213587. zerostruct (channelInfo);
  213588. channelInfo.channel = i;
  213589. channelInfo.isInput = 1;
  213590. asioObject->getChannelInfo (&channelInfo);
  213591. inputChannelNames.add (String (channelInfo.name));
  213592. }
  213593. for (i = 0; i < totalNumOutputChans; ++i)
  213594. {
  213595. zerostruct (channelInfo);
  213596. channelInfo.channel = i;
  213597. channelInfo.isInput = 0;
  213598. asioObject->getChannelInfo (&channelInfo);
  213599. outputChannelNames.add (String (channelInfo.name));
  213600. typeToFormatParameters (channelInfo.type,
  213601. outputChannelBitDepths[i],
  213602. outputChannelBytesPerSample[i],
  213603. outputChannelIsFloat[i],
  213604. outputChannelLittleEndian[i]);
  213605. if (i < 2)
  213606. {
  213607. // clear the channels that are used with the dummy stuff
  213608. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213609. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213610. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213611. }
  213612. }
  213613. outputChannelNames.trim();
  213614. inputChannelNames.trim();
  213615. outputChannelNames.appendNumbersToDuplicates (false, true);
  213616. inputChannelNames.appendNumbersToDuplicates (false, true);
  213617. // start and stop because cubase does it..
  213618. asioObject->getLatencies (&inputLatency, &outputLatency);
  213619. if ((err = asioObject->start()) != 0)
  213620. {
  213621. // ignore an error here, as it might start later after setting other stuff up
  213622. logError ("ASIO start", err);
  213623. }
  213624. Thread::sleep (100);
  213625. asioObject->stop();
  213626. }
  213627. else
  213628. {
  213629. error = "Can't detect buffer sizes";
  213630. }
  213631. }
  213632. else
  213633. {
  213634. error = "Can't detect asio channels";
  213635. }
  213636. }
  213637. }
  213638. else
  213639. {
  213640. error = "No such device";
  213641. }
  213642. if (error.isNotEmpty())
  213643. {
  213644. logError (error, err);
  213645. if (asioObject != 0)
  213646. asioObject->disposeBuffers();
  213647. removeCurrentDriver();
  213648. isASIOOpen = false;
  213649. }
  213650. else
  213651. {
  213652. isASIOOpen = true;
  213653. log ("ASIO device open");
  213654. }
  213655. isOpen_ = false;
  213656. needToReset = false;
  213657. isReSync = false;
  213658. return error;
  213659. }
  213660. void callback (const long index)
  213661. {
  213662. if (isStarted)
  213663. {
  213664. bufferIndex = index;
  213665. processBuffer();
  213666. }
  213667. else
  213668. {
  213669. if (postOutput && (asioObject != 0))
  213670. asioObject->outputReady();
  213671. }
  213672. calledback = true;
  213673. }
  213674. void processBuffer()
  213675. {
  213676. const ASIOBufferInfo* const infos = bufferInfos;
  213677. const int bi = bufferIndex;
  213678. const ScopedLock sl (callbackLock);
  213679. if (needToReset)
  213680. {
  213681. needToReset = false;
  213682. if (isReSync)
  213683. {
  213684. log ("! ASIO resync");
  213685. isReSync = false;
  213686. }
  213687. else
  213688. {
  213689. startTimer (20);
  213690. }
  213691. }
  213692. if (bi >= 0)
  213693. {
  213694. const int samps = currentBlockSizeSamples;
  213695. if (currentCallback != 0)
  213696. {
  213697. int i;
  213698. for (i = 0; i < numActiveInputChans; ++i)
  213699. {
  213700. float* const dst = inBuffers[i];
  213701. jassert (dst != 0);
  213702. const char* const src = (const char*) (infos[i].buffers[bi]);
  213703. if (inputChannelIsFloat[i])
  213704. {
  213705. memcpy (dst, src, samps * sizeof (float));
  213706. }
  213707. else
  213708. {
  213709. jassert (dst == tempBuffer + (samps * i));
  213710. switch (inputChannelBitDepths[i])
  213711. {
  213712. case 16:
  213713. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213714. samps, inputChannelLittleEndian[i]);
  213715. break;
  213716. case 24:
  213717. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213718. samps, inputChannelLittleEndian[i]);
  213719. break;
  213720. case 32:
  213721. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213722. samps, inputChannelLittleEndian[i]);
  213723. break;
  213724. case 64:
  213725. jassertfalse;
  213726. break;
  213727. }
  213728. }
  213729. }
  213730. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  213731. numActiveInputChans,
  213732. outBuffers,
  213733. numActiveOutputChans,
  213734. samps);
  213735. for (i = 0; i < numActiveOutputChans; ++i)
  213736. {
  213737. float* const src = outBuffers[i];
  213738. jassert (src != 0);
  213739. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213740. if (outputChannelIsFloat[i])
  213741. {
  213742. memcpy (dst, src, samps * sizeof (float));
  213743. }
  213744. else
  213745. {
  213746. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213747. switch (outputChannelBitDepths[i])
  213748. {
  213749. case 16:
  213750. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213751. samps, outputChannelLittleEndian[i]);
  213752. break;
  213753. case 24:
  213754. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213755. samps, outputChannelLittleEndian[i]);
  213756. break;
  213757. case 32:
  213758. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213759. samps, outputChannelLittleEndian[i]);
  213760. break;
  213761. case 64:
  213762. jassertfalse;
  213763. break;
  213764. }
  213765. }
  213766. }
  213767. }
  213768. else
  213769. {
  213770. for (int i = 0; i < numActiveOutputChans; ++i)
  213771. {
  213772. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213773. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213774. }
  213775. }
  213776. }
  213777. if (postOutput)
  213778. asioObject->outputReady();
  213779. }
  213780. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213781. {
  213782. if (currentASIODev[0] != 0)
  213783. currentASIODev[0]->callback (index);
  213784. return 0;
  213785. }
  213786. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213787. {
  213788. if (currentASIODev[1] != 0)
  213789. currentASIODev[1]->callback (index);
  213790. return 0;
  213791. }
  213792. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213793. {
  213794. if (currentASIODev[2] != 0)
  213795. currentASIODev[2]->callback (index);
  213796. return 0;
  213797. }
  213798. static void bufferSwitchCallback0 (long index, long)
  213799. {
  213800. if (currentASIODev[0] != 0)
  213801. currentASIODev[0]->callback (index);
  213802. }
  213803. static void bufferSwitchCallback1 (long index, long)
  213804. {
  213805. if (currentASIODev[1] != 0)
  213806. currentASIODev[1]->callback (index);
  213807. }
  213808. static void bufferSwitchCallback2 (long index, long)
  213809. {
  213810. if (currentASIODev[2] != 0)
  213811. currentASIODev[2]->callback (index);
  213812. }
  213813. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  213814. {
  213815. return asioMessagesCallback (selector, value, 0);
  213816. }
  213817. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  213818. {
  213819. return asioMessagesCallback (selector, value, 1);
  213820. }
  213821. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  213822. {
  213823. return asioMessagesCallback (selector, value, 2);
  213824. }
  213825. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  213826. {
  213827. switch (selector)
  213828. {
  213829. case kAsioSelectorSupported:
  213830. if (value == kAsioResetRequest
  213831. || value == kAsioEngineVersion
  213832. || value == kAsioResyncRequest
  213833. || value == kAsioLatenciesChanged
  213834. || value == kAsioSupportsInputMonitor)
  213835. return 1;
  213836. break;
  213837. case kAsioBufferSizeChange:
  213838. break;
  213839. case kAsioResetRequest:
  213840. if (currentASIODev[deviceIndex] != 0)
  213841. currentASIODev[deviceIndex]->resetRequest();
  213842. return 1;
  213843. case kAsioResyncRequest:
  213844. if (currentASIODev[deviceIndex] != 0)
  213845. currentASIODev[deviceIndex]->resyncRequest();
  213846. return 1;
  213847. case kAsioLatenciesChanged:
  213848. return 1;
  213849. case kAsioEngineVersion:
  213850. return 2;
  213851. case kAsioSupportsTimeInfo:
  213852. case kAsioSupportsTimeCode:
  213853. return 0;
  213854. }
  213855. return 0;
  213856. }
  213857. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  213858. {
  213859. }
  213860. static void convertInt16ToFloat (const char* src,
  213861. float* dest,
  213862. const int srcStrideBytes,
  213863. int numSamples,
  213864. const bool littleEndian) throw()
  213865. {
  213866. const double g = 1.0 / 32768.0;
  213867. if (littleEndian)
  213868. {
  213869. while (--numSamples >= 0)
  213870. {
  213871. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213872. src += srcStrideBytes;
  213873. }
  213874. }
  213875. else
  213876. {
  213877. while (--numSamples >= 0)
  213878. {
  213879. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213880. src += srcStrideBytes;
  213881. }
  213882. }
  213883. }
  213884. static void convertFloatToInt16 (const float* src,
  213885. char* dest,
  213886. const int dstStrideBytes,
  213887. int numSamples,
  213888. const bool littleEndian) throw()
  213889. {
  213890. const double maxVal = (double) 0x7fff;
  213891. if (littleEndian)
  213892. {
  213893. while (--numSamples >= 0)
  213894. {
  213895. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213896. dest += dstStrideBytes;
  213897. }
  213898. }
  213899. else
  213900. {
  213901. while (--numSamples >= 0)
  213902. {
  213903. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213904. dest += dstStrideBytes;
  213905. }
  213906. }
  213907. }
  213908. static void convertInt24ToFloat (const char* src,
  213909. float* dest,
  213910. const int srcStrideBytes,
  213911. int numSamples,
  213912. const bool littleEndian) throw()
  213913. {
  213914. const double g = 1.0 / 0x7fffff;
  213915. if (littleEndian)
  213916. {
  213917. while (--numSamples >= 0)
  213918. {
  213919. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213920. src += srcStrideBytes;
  213921. }
  213922. }
  213923. else
  213924. {
  213925. while (--numSamples >= 0)
  213926. {
  213927. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213928. src += srcStrideBytes;
  213929. }
  213930. }
  213931. }
  213932. static void convertFloatToInt24 (const float* src,
  213933. char* dest,
  213934. const int dstStrideBytes,
  213935. int numSamples,
  213936. const bool littleEndian) throw()
  213937. {
  213938. const double maxVal = (double) 0x7fffff;
  213939. if (littleEndian)
  213940. {
  213941. while (--numSamples >= 0)
  213942. {
  213943. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213944. dest += dstStrideBytes;
  213945. }
  213946. }
  213947. else
  213948. {
  213949. while (--numSamples >= 0)
  213950. {
  213951. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213952. dest += dstStrideBytes;
  213953. }
  213954. }
  213955. }
  213956. static void convertInt32ToFloat (const char* src,
  213957. float* dest,
  213958. const int srcStrideBytes,
  213959. int numSamples,
  213960. const bool littleEndian) throw()
  213961. {
  213962. const double g = 1.0 / 0x7fffffff;
  213963. if (littleEndian)
  213964. {
  213965. while (--numSamples >= 0)
  213966. {
  213967. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213968. src += srcStrideBytes;
  213969. }
  213970. }
  213971. else
  213972. {
  213973. while (--numSamples >= 0)
  213974. {
  213975. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213976. src += srcStrideBytes;
  213977. }
  213978. }
  213979. }
  213980. static void convertFloatToInt32 (const float* src,
  213981. char* dest,
  213982. const int dstStrideBytes,
  213983. int numSamples,
  213984. const bool littleEndian) throw()
  213985. {
  213986. const double maxVal = (double) 0x7fffffff;
  213987. if (littleEndian)
  213988. {
  213989. while (--numSamples >= 0)
  213990. {
  213991. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213992. dest += dstStrideBytes;
  213993. }
  213994. }
  213995. else
  213996. {
  213997. while (--numSamples >= 0)
  213998. {
  213999. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214000. dest += dstStrideBytes;
  214001. }
  214002. }
  214003. }
  214004. static void typeToFormatParameters (const long type,
  214005. int& bitDepth,
  214006. int& byteStride,
  214007. bool& formatIsFloat,
  214008. bool& littleEndian) throw()
  214009. {
  214010. bitDepth = 0;
  214011. littleEndian = false;
  214012. formatIsFloat = false;
  214013. switch (type)
  214014. {
  214015. case ASIOSTInt16MSB:
  214016. case ASIOSTInt16LSB:
  214017. case ASIOSTInt32MSB16:
  214018. case ASIOSTInt32LSB16:
  214019. bitDepth = 16; break;
  214020. case ASIOSTFloat32MSB:
  214021. case ASIOSTFloat32LSB:
  214022. formatIsFloat = true;
  214023. bitDepth = 32; break;
  214024. case ASIOSTInt32MSB:
  214025. case ASIOSTInt32LSB:
  214026. bitDepth = 32; break;
  214027. case ASIOSTInt24MSB:
  214028. case ASIOSTInt24LSB:
  214029. case ASIOSTInt32MSB24:
  214030. case ASIOSTInt32LSB24:
  214031. case ASIOSTInt32MSB18:
  214032. case ASIOSTInt32MSB20:
  214033. case ASIOSTInt32LSB18:
  214034. case ASIOSTInt32LSB20:
  214035. bitDepth = 24; break;
  214036. case ASIOSTFloat64MSB:
  214037. case ASIOSTFloat64LSB:
  214038. default:
  214039. bitDepth = 64;
  214040. break;
  214041. }
  214042. switch (type)
  214043. {
  214044. case ASIOSTInt16MSB:
  214045. case ASIOSTInt32MSB16:
  214046. case ASIOSTFloat32MSB:
  214047. case ASIOSTFloat64MSB:
  214048. case ASIOSTInt32MSB:
  214049. case ASIOSTInt32MSB18:
  214050. case ASIOSTInt32MSB20:
  214051. case ASIOSTInt32MSB24:
  214052. case ASIOSTInt24MSB:
  214053. littleEndian = false; break;
  214054. case ASIOSTInt16LSB:
  214055. case ASIOSTInt32LSB16:
  214056. case ASIOSTFloat32LSB:
  214057. case ASIOSTFloat64LSB:
  214058. case ASIOSTInt32LSB:
  214059. case ASIOSTInt32LSB18:
  214060. case ASIOSTInt32LSB20:
  214061. case ASIOSTInt32LSB24:
  214062. case ASIOSTInt24LSB:
  214063. littleEndian = true; break;
  214064. default:
  214065. break;
  214066. }
  214067. switch (type)
  214068. {
  214069. case ASIOSTInt16LSB:
  214070. case ASIOSTInt16MSB:
  214071. byteStride = 2; break;
  214072. case ASIOSTInt24LSB:
  214073. case ASIOSTInt24MSB:
  214074. byteStride = 3; break;
  214075. case ASIOSTInt32MSB16:
  214076. case ASIOSTInt32LSB16:
  214077. case ASIOSTInt32MSB:
  214078. case ASIOSTInt32MSB18:
  214079. case ASIOSTInt32MSB20:
  214080. case ASIOSTInt32MSB24:
  214081. case ASIOSTInt32LSB:
  214082. case ASIOSTInt32LSB18:
  214083. case ASIOSTInt32LSB20:
  214084. case ASIOSTInt32LSB24:
  214085. case ASIOSTFloat32LSB:
  214086. case ASIOSTFloat32MSB:
  214087. byteStride = 4; break;
  214088. case ASIOSTFloat64MSB:
  214089. case ASIOSTFloat64LSB:
  214090. byteStride = 8; break;
  214091. default:
  214092. break;
  214093. }
  214094. }
  214095. };
  214096. class ASIOAudioIODeviceType : public AudioIODeviceType
  214097. {
  214098. public:
  214099. ASIOAudioIODeviceType()
  214100. : AudioIODeviceType ("ASIO"),
  214101. hasScanned (false)
  214102. {
  214103. CoInitialize (0);
  214104. }
  214105. ~ASIOAudioIODeviceType()
  214106. {
  214107. }
  214108. void scanForDevices()
  214109. {
  214110. hasScanned = true;
  214111. deviceNames.clear();
  214112. classIds.clear();
  214113. HKEY hk = 0;
  214114. int index = 0;
  214115. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  214116. {
  214117. for (;;)
  214118. {
  214119. char name [256];
  214120. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  214121. {
  214122. addDriverInfo (name, hk);
  214123. }
  214124. else
  214125. {
  214126. break;
  214127. }
  214128. }
  214129. RegCloseKey (hk);
  214130. }
  214131. }
  214132. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  214133. {
  214134. jassert (hasScanned); // need to call scanForDevices() before doing this
  214135. return deviceNames;
  214136. }
  214137. int getDefaultDeviceIndex (bool) const
  214138. {
  214139. jassert (hasScanned); // need to call scanForDevices() before doing this
  214140. for (int i = deviceNames.size(); --i >= 0;)
  214141. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  214142. return i; // asio4all is a safe choice for a default..
  214143. #if JUCE_DEBUG
  214144. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  214145. return 1; // (the digi m-box driver crashes the app when you run
  214146. // it in the debugger, which can be a bit annoying)
  214147. #endif
  214148. return 0;
  214149. }
  214150. static int findFreeSlot()
  214151. {
  214152. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  214153. if (currentASIODev[i] == 0)
  214154. return i;
  214155. jassertfalse; // unfortunately you can only have a finite number
  214156. // of ASIO devices open at the same time..
  214157. return -1;
  214158. }
  214159. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  214160. {
  214161. jassert (hasScanned); // need to call scanForDevices() before doing this
  214162. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  214163. }
  214164. bool hasSeparateInputsAndOutputs() const { return false; }
  214165. AudioIODevice* createDevice (const String& outputDeviceName,
  214166. const String& inputDeviceName)
  214167. {
  214168. // ASIO can't open two different devices for input and output - they must be the same one.
  214169. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  214170. jassert (hasScanned); // need to call scanForDevices() before doing this
  214171. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  214172. : inputDeviceName);
  214173. if (index >= 0)
  214174. {
  214175. const int freeSlot = findFreeSlot();
  214176. if (freeSlot >= 0)
  214177. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  214178. }
  214179. return 0;
  214180. }
  214181. juce_UseDebuggingNewOperator
  214182. private:
  214183. StringArray deviceNames;
  214184. OwnedArray <CLSID> classIds;
  214185. bool hasScanned;
  214186. static bool checkClassIsOk (const String& classId)
  214187. {
  214188. HKEY hk = 0;
  214189. bool ok = false;
  214190. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  214191. {
  214192. int index = 0;
  214193. for (;;)
  214194. {
  214195. WCHAR buf [512];
  214196. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  214197. {
  214198. if (classId.equalsIgnoreCase (buf))
  214199. {
  214200. HKEY subKey, pathKey;
  214201. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214202. {
  214203. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  214204. {
  214205. WCHAR pathName [1024];
  214206. DWORD dtype = REG_SZ;
  214207. DWORD dsize = sizeof (pathName);
  214208. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  214209. ok = File (pathName).exists();
  214210. RegCloseKey (pathKey);
  214211. }
  214212. RegCloseKey (subKey);
  214213. }
  214214. break;
  214215. }
  214216. }
  214217. else
  214218. {
  214219. break;
  214220. }
  214221. }
  214222. RegCloseKey (hk);
  214223. }
  214224. return ok;
  214225. }
  214226. void addDriverInfo (const String& keyName, HKEY hk)
  214227. {
  214228. HKEY subKey;
  214229. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214230. {
  214231. WCHAR buf [256];
  214232. zerostruct (buf);
  214233. DWORD dtype = REG_SZ;
  214234. DWORD dsize = sizeof (buf);
  214235. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214236. {
  214237. if (dsize > 0 && checkClassIsOk (buf))
  214238. {
  214239. CLSID classId;
  214240. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  214241. {
  214242. dtype = REG_SZ;
  214243. dsize = sizeof (buf);
  214244. String deviceName;
  214245. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214246. deviceName = buf;
  214247. else
  214248. deviceName = keyName;
  214249. log ("found " + deviceName);
  214250. deviceNames.add (deviceName);
  214251. classIds.add (new CLSID (classId));
  214252. }
  214253. }
  214254. RegCloseKey (subKey);
  214255. }
  214256. }
  214257. }
  214258. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  214259. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  214260. };
  214261. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  214262. {
  214263. return new ASIOAudioIODeviceType();
  214264. }
  214265. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  214266. void* guid,
  214267. const String& optionalDllForDirectLoading)
  214268. {
  214269. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  214270. if (freeSlot < 0)
  214271. return 0;
  214272. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  214273. }
  214274. #undef log
  214275. #endif
  214276. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  214277. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  214278. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214279. // compiled on its own).
  214280. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  214281. END_JUCE_NAMESPACE
  214282. extern "C"
  214283. {
  214284. // Declare just the minimum number of interfaces for the DSound objects that we need..
  214285. typedef struct typeDSBUFFERDESC
  214286. {
  214287. DWORD dwSize;
  214288. DWORD dwFlags;
  214289. DWORD dwBufferBytes;
  214290. DWORD dwReserved;
  214291. LPWAVEFORMATEX lpwfxFormat;
  214292. GUID guid3DAlgorithm;
  214293. } DSBUFFERDESC;
  214294. struct IDirectSoundBuffer;
  214295. #undef INTERFACE
  214296. #define INTERFACE IDirectSound
  214297. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  214298. {
  214299. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214300. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214301. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214302. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  214303. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214304. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  214305. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  214306. STDMETHOD(Compact) (THIS) PURE;
  214307. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  214308. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  214309. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214310. };
  214311. #undef INTERFACE
  214312. #define INTERFACE IDirectSoundBuffer
  214313. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  214314. {
  214315. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214316. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214317. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214318. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214319. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214320. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214321. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214322. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214323. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214324. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214325. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214326. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214327. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214328. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214329. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214330. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214331. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214332. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214333. STDMETHOD(Stop) (THIS) PURE;
  214334. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214335. STDMETHOD(Restore) (THIS) PURE;
  214336. };
  214337. typedef struct typeDSCBUFFERDESC
  214338. {
  214339. DWORD dwSize;
  214340. DWORD dwFlags;
  214341. DWORD dwBufferBytes;
  214342. DWORD dwReserved;
  214343. LPWAVEFORMATEX lpwfxFormat;
  214344. } DSCBUFFERDESC;
  214345. struct IDirectSoundCaptureBuffer;
  214346. #undef INTERFACE
  214347. #define INTERFACE IDirectSoundCapture
  214348. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214349. {
  214350. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214351. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214352. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214353. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214354. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214355. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214356. };
  214357. #undef INTERFACE
  214358. #define INTERFACE IDirectSoundCaptureBuffer
  214359. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214360. {
  214361. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214362. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214363. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214364. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214365. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214366. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214367. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214368. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214369. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214370. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214371. STDMETHOD(Stop) (THIS) PURE;
  214372. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214373. };
  214374. };
  214375. BEGIN_JUCE_NAMESPACE
  214376. static const String getDSErrorMessage (HRESULT hr)
  214377. {
  214378. const char* result = 0;
  214379. switch (hr)
  214380. {
  214381. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214382. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214383. case E_INVALIDARG: result = "Invalid parameter"; break;
  214384. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214385. case E_FAIL: result = "Generic error"; break;
  214386. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214387. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214388. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214389. case E_NOTIMPL: result = "Unsupported function"; break;
  214390. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214391. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214392. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214393. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214394. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214395. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214396. case E_NOINTERFACE: result = "No interface"; break;
  214397. case S_OK: result = "No error"; break;
  214398. default: return "Unknown error: " + String ((int) hr);
  214399. }
  214400. return result;
  214401. }
  214402. #define DS_DEBUGGING 1
  214403. #ifdef DS_DEBUGGING
  214404. #define CATCH JUCE_CATCH_EXCEPTION
  214405. #undef log
  214406. #define log(a) Logger::writeToLog(a);
  214407. #undef logError
  214408. #define logError(a) logDSError(a, __LINE__);
  214409. static void logDSError (HRESULT hr, int lineNum)
  214410. {
  214411. if (hr != S_OK)
  214412. {
  214413. String error ("DS error at line ");
  214414. error << lineNum << " - " << getDSErrorMessage (hr);
  214415. log (error);
  214416. }
  214417. }
  214418. #else
  214419. #define CATCH JUCE_CATCH_ALL
  214420. #define log(a)
  214421. #define logError(a)
  214422. #endif
  214423. #define DSOUND_FUNCTION(functionName, params) \
  214424. typedef HRESULT (WINAPI *type##functionName) params; \
  214425. static type##functionName ds##functionName = 0;
  214426. #define DSOUND_FUNCTION_LOAD(functionName) \
  214427. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214428. jassert (ds##functionName != 0);
  214429. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214430. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214431. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214432. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214433. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214434. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214435. static void initialiseDSoundFunctions()
  214436. {
  214437. if (dsDirectSoundCreate == 0)
  214438. {
  214439. HMODULE h = LoadLibraryA ("dsound.dll");
  214440. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214441. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214442. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214443. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214444. }
  214445. }
  214446. class DSoundInternalOutChannel
  214447. {
  214448. String name;
  214449. LPGUID guid;
  214450. int sampleRate, bufferSizeSamples;
  214451. float* leftBuffer;
  214452. float* rightBuffer;
  214453. IDirectSound* pDirectSound;
  214454. IDirectSoundBuffer* pOutputBuffer;
  214455. DWORD writeOffset;
  214456. int totalBytesPerBuffer;
  214457. int bytesPerBuffer;
  214458. unsigned int lastPlayCursor;
  214459. public:
  214460. int bitDepth;
  214461. bool doneFlag;
  214462. DSoundInternalOutChannel (const String& name_,
  214463. LPGUID guid_,
  214464. int rate,
  214465. int bufferSize,
  214466. float* left,
  214467. float* right)
  214468. : name (name_),
  214469. guid (guid_),
  214470. sampleRate (rate),
  214471. bufferSizeSamples (bufferSize),
  214472. leftBuffer (left),
  214473. rightBuffer (right),
  214474. pDirectSound (0),
  214475. pOutputBuffer (0),
  214476. bitDepth (16)
  214477. {
  214478. }
  214479. ~DSoundInternalOutChannel()
  214480. {
  214481. close();
  214482. }
  214483. void close()
  214484. {
  214485. HRESULT hr;
  214486. if (pOutputBuffer != 0)
  214487. {
  214488. JUCE_TRY
  214489. {
  214490. log ("closing dsound out: " + name);
  214491. hr = pOutputBuffer->Stop();
  214492. logError (hr);
  214493. }
  214494. CATCH
  214495. JUCE_TRY
  214496. {
  214497. hr = pOutputBuffer->Release();
  214498. logError (hr);
  214499. }
  214500. CATCH
  214501. pOutputBuffer = 0;
  214502. }
  214503. if (pDirectSound != 0)
  214504. {
  214505. JUCE_TRY
  214506. {
  214507. hr = pDirectSound->Release();
  214508. logError (hr);
  214509. }
  214510. CATCH
  214511. pDirectSound = 0;
  214512. }
  214513. }
  214514. const String open()
  214515. {
  214516. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214517. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214518. pDirectSound = 0;
  214519. pOutputBuffer = 0;
  214520. writeOffset = 0;
  214521. String error;
  214522. HRESULT hr = E_NOINTERFACE;
  214523. if (dsDirectSoundCreate != 0)
  214524. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214525. if (hr == S_OK)
  214526. {
  214527. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214528. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214529. const int numChannels = 2;
  214530. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214531. logError (hr);
  214532. if (hr == S_OK)
  214533. {
  214534. IDirectSoundBuffer* pPrimaryBuffer;
  214535. DSBUFFERDESC primaryDesc;
  214536. zerostruct (primaryDesc);
  214537. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214538. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214539. primaryDesc.dwBufferBytes = 0;
  214540. primaryDesc.lpwfxFormat = 0;
  214541. log ("opening dsound out step 2");
  214542. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214543. logError (hr);
  214544. if (hr == S_OK)
  214545. {
  214546. WAVEFORMATEX wfFormat;
  214547. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214548. wfFormat.nChannels = (unsigned short) numChannels;
  214549. wfFormat.nSamplesPerSec = sampleRate;
  214550. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214551. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214552. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214553. wfFormat.cbSize = 0;
  214554. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214555. logError (hr);
  214556. if (hr == S_OK)
  214557. {
  214558. DSBUFFERDESC secondaryDesc;
  214559. zerostruct (secondaryDesc);
  214560. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214561. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214562. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214563. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214564. secondaryDesc.lpwfxFormat = &wfFormat;
  214565. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214566. logError (hr);
  214567. if (hr == S_OK)
  214568. {
  214569. log ("opening dsound out step 3");
  214570. DWORD dwDataLen;
  214571. unsigned char* pDSBuffData;
  214572. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214573. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214574. logError (hr);
  214575. if (hr == S_OK)
  214576. {
  214577. zeromem (pDSBuffData, dwDataLen);
  214578. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214579. if (hr == S_OK)
  214580. {
  214581. hr = pOutputBuffer->SetCurrentPosition (0);
  214582. if (hr == S_OK)
  214583. {
  214584. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214585. if (hr == S_OK)
  214586. return String::empty;
  214587. }
  214588. }
  214589. }
  214590. }
  214591. }
  214592. }
  214593. }
  214594. }
  214595. error = getDSErrorMessage (hr);
  214596. close();
  214597. return error;
  214598. }
  214599. void synchronisePosition()
  214600. {
  214601. if (pOutputBuffer != 0)
  214602. {
  214603. DWORD playCursor;
  214604. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214605. }
  214606. }
  214607. bool service()
  214608. {
  214609. if (pOutputBuffer == 0)
  214610. return true;
  214611. DWORD playCursor, writeCursor;
  214612. for (;;)
  214613. {
  214614. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214615. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214616. {
  214617. pOutputBuffer->Restore();
  214618. continue;
  214619. }
  214620. if (hr == S_OK)
  214621. break;
  214622. logError (hr);
  214623. jassertfalse;
  214624. return true;
  214625. }
  214626. int playWriteGap = writeCursor - playCursor;
  214627. if (playWriteGap < 0)
  214628. playWriteGap += totalBytesPerBuffer;
  214629. int bytesEmpty = playCursor - writeOffset;
  214630. if (bytesEmpty < 0)
  214631. bytesEmpty += totalBytesPerBuffer;
  214632. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214633. {
  214634. writeOffset = writeCursor;
  214635. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214636. }
  214637. if (bytesEmpty >= bytesPerBuffer)
  214638. {
  214639. void* lpbuf1 = 0;
  214640. void* lpbuf2 = 0;
  214641. DWORD dwSize1 = 0;
  214642. DWORD dwSize2 = 0;
  214643. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  214644. bytesPerBuffer,
  214645. &lpbuf1, &dwSize1,
  214646. &lpbuf2, &dwSize2, 0);
  214647. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214648. {
  214649. pOutputBuffer->Restore();
  214650. hr = pOutputBuffer->Lock (writeOffset,
  214651. bytesPerBuffer,
  214652. &lpbuf1, &dwSize1,
  214653. &lpbuf2, &dwSize2, 0);
  214654. }
  214655. if (hr == S_OK)
  214656. {
  214657. if (bitDepth == 16)
  214658. {
  214659. const float gainL = 32767.0f;
  214660. const float gainR = 32767.0f;
  214661. int* dest = static_cast<int*> (lpbuf1);
  214662. const float* left = leftBuffer;
  214663. const float* right = rightBuffer;
  214664. int samples1 = dwSize1 >> 2;
  214665. int samples2 = dwSize2 >> 2;
  214666. if (left == 0)
  214667. {
  214668. while (--samples1 >= 0)
  214669. {
  214670. int r = roundToInt (gainR * *right++);
  214671. if (r < -32768)
  214672. r = -32768;
  214673. else if (r > 32767)
  214674. r = 32767;
  214675. *dest++ = (r << 16);
  214676. }
  214677. dest = static_cast<int*> (lpbuf2);
  214678. while (--samples2 >= 0)
  214679. {
  214680. int r = roundToInt (gainR * *right++);
  214681. if (r < -32768)
  214682. r = -32768;
  214683. else if (r > 32767)
  214684. r = 32767;
  214685. *dest++ = (r << 16);
  214686. }
  214687. }
  214688. else if (right == 0)
  214689. {
  214690. while (--samples1 >= 0)
  214691. {
  214692. int l = roundToInt (gainL * *left++);
  214693. if (l < -32768)
  214694. l = -32768;
  214695. else if (l > 32767)
  214696. l = 32767;
  214697. l &= 0xffff;
  214698. *dest++ = l;
  214699. }
  214700. dest = static_cast<int*> (lpbuf2);
  214701. while (--samples2 >= 0)
  214702. {
  214703. int l = roundToInt (gainL * *left++);
  214704. if (l < -32768)
  214705. l = -32768;
  214706. else if (l > 32767)
  214707. l = 32767;
  214708. l &= 0xffff;
  214709. *dest++ = l;
  214710. }
  214711. }
  214712. else
  214713. {
  214714. while (--samples1 >= 0)
  214715. {
  214716. int l = roundToInt (gainL * *left++);
  214717. if (l < -32768)
  214718. l = -32768;
  214719. else if (l > 32767)
  214720. l = 32767;
  214721. l &= 0xffff;
  214722. int r = roundToInt (gainR * *right++);
  214723. if (r < -32768)
  214724. r = -32768;
  214725. else if (r > 32767)
  214726. r = 32767;
  214727. *dest++ = (r << 16) | l;
  214728. }
  214729. dest = static_cast<int*> (lpbuf2);
  214730. while (--samples2 >= 0)
  214731. {
  214732. int l = roundToInt (gainL * *left++);
  214733. if (l < -32768)
  214734. l = -32768;
  214735. else if (l > 32767)
  214736. l = 32767;
  214737. l &= 0xffff;
  214738. int r = roundToInt (gainR * *right++);
  214739. if (r < -32768)
  214740. r = -32768;
  214741. else if (r > 32767)
  214742. r = 32767;
  214743. *dest++ = (r << 16) | l;
  214744. }
  214745. }
  214746. }
  214747. else
  214748. {
  214749. jassertfalse;
  214750. }
  214751. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214752. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214753. }
  214754. else
  214755. {
  214756. jassertfalse;
  214757. logError (hr);
  214758. }
  214759. bytesEmpty -= bytesPerBuffer;
  214760. return true;
  214761. }
  214762. else
  214763. {
  214764. return false;
  214765. }
  214766. }
  214767. };
  214768. struct DSoundInternalInChannel
  214769. {
  214770. String name;
  214771. LPGUID guid;
  214772. int sampleRate, bufferSizeSamples;
  214773. float* leftBuffer;
  214774. float* rightBuffer;
  214775. IDirectSound* pDirectSound;
  214776. IDirectSoundCapture* pDirectSoundCapture;
  214777. IDirectSoundCaptureBuffer* pInputBuffer;
  214778. public:
  214779. unsigned int readOffset;
  214780. int bytesPerBuffer, totalBytesPerBuffer;
  214781. int bitDepth;
  214782. bool doneFlag;
  214783. DSoundInternalInChannel (const String& name_,
  214784. LPGUID guid_,
  214785. int rate,
  214786. int bufferSize,
  214787. float* left,
  214788. float* right)
  214789. : name (name_),
  214790. guid (guid_),
  214791. sampleRate (rate),
  214792. bufferSizeSamples (bufferSize),
  214793. leftBuffer (left),
  214794. rightBuffer (right),
  214795. pDirectSound (0),
  214796. pDirectSoundCapture (0),
  214797. pInputBuffer (0),
  214798. bitDepth (16)
  214799. {
  214800. }
  214801. ~DSoundInternalInChannel()
  214802. {
  214803. close();
  214804. }
  214805. void close()
  214806. {
  214807. HRESULT hr;
  214808. if (pInputBuffer != 0)
  214809. {
  214810. JUCE_TRY
  214811. {
  214812. log ("closing dsound in: " + name);
  214813. hr = pInputBuffer->Stop();
  214814. logError (hr);
  214815. }
  214816. CATCH
  214817. JUCE_TRY
  214818. {
  214819. hr = pInputBuffer->Release();
  214820. logError (hr);
  214821. }
  214822. CATCH
  214823. pInputBuffer = 0;
  214824. }
  214825. if (pDirectSoundCapture != 0)
  214826. {
  214827. JUCE_TRY
  214828. {
  214829. hr = pDirectSoundCapture->Release();
  214830. logError (hr);
  214831. }
  214832. CATCH
  214833. pDirectSoundCapture = 0;
  214834. }
  214835. if (pDirectSound != 0)
  214836. {
  214837. JUCE_TRY
  214838. {
  214839. hr = pDirectSound->Release();
  214840. logError (hr);
  214841. }
  214842. CATCH
  214843. pDirectSound = 0;
  214844. }
  214845. }
  214846. const String open()
  214847. {
  214848. log ("opening dsound in device: " + name
  214849. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214850. pDirectSound = 0;
  214851. pDirectSoundCapture = 0;
  214852. pInputBuffer = 0;
  214853. readOffset = 0;
  214854. totalBytesPerBuffer = 0;
  214855. String error;
  214856. HRESULT hr = E_NOINTERFACE;
  214857. if (dsDirectSoundCaptureCreate != 0)
  214858. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214859. logError (hr);
  214860. if (hr == S_OK)
  214861. {
  214862. const int numChannels = 2;
  214863. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214864. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214865. WAVEFORMATEX wfFormat;
  214866. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214867. wfFormat.nChannels = (unsigned short)numChannels;
  214868. wfFormat.nSamplesPerSec = sampleRate;
  214869. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214870. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214871. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214872. wfFormat.cbSize = 0;
  214873. DSCBUFFERDESC captureDesc;
  214874. zerostruct (captureDesc);
  214875. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214876. captureDesc.dwFlags = 0;
  214877. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214878. captureDesc.lpwfxFormat = &wfFormat;
  214879. log ("opening dsound in step 2");
  214880. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214881. logError (hr);
  214882. if (hr == S_OK)
  214883. {
  214884. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214885. logError (hr);
  214886. if (hr == S_OK)
  214887. return String::empty;
  214888. }
  214889. }
  214890. error = getDSErrorMessage (hr);
  214891. close();
  214892. return error;
  214893. }
  214894. void synchronisePosition()
  214895. {
  214896. if (pInputBuffer != 0)
  214897. {
  214898. DWORD capturePos;
  214899. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214900. }
  214901. }
  214902. bool service()
  214903. {
  214904. if (pInputBuffer == 0)
  214905. return true;
  214906. DWORD capturePos, readPos;
  214907. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  214908. logError (hr);
  214909. if (hr != S_OK)
  214910. return true;
  214911. int bytesFilled = readPos - readOffset;
  214912. if (bytesFilled < 0)
  214913. bytesFilled += totalBytesPerBuffer;
  214914. if (bytesFilled >= bytesPerBuffer)
  214915. {
  214916. LPBYTE lpbuf1 = 0;
  214917. LPBYTE lpbuf2 = 0;
  214918. DWORD dwsize1 = 0;
  214919. DWORD dwsize2 = 0;
  214920. HRESULT hr = pInputBuffer->Lock (readOffset,
  214921. bytesPerBuffer,
  214922. (void**) &lpbuf1, &dwsize1,
  214923. (void**) &lpbuf2, &dwsize2, 0);
  214924. if (hr == S_OK)
  214925. {
  214926. if (bitDepth == 16)
  214927. {
  214928. const float g = 1.0f / 32768.0f;
  214929. float* destL = leftBuffer;
  214930. float* destR = rightBuffer;
  214931. int samples1 = dwsize1 >> 2;
  214932. int samples2 = dwsize2 >> 2;
  214933. const short* src = (const short*)lpbuf1;
  214934. if (destL == 0)
  214935. {
  214936. while (--samples1 >= 0)
  214937. {
  214938. ++src;
  214939. *destR++ = *src++ * g;
  214940. }
  214941. src = (const short*)lpbuf2;
  214942. while (--samples2 >= 0)
  214943. {
  214944. ++src;
  214945. *destR++ = *src++ * g;
  214946. }
  214947. }
  214948. else if (destR == 0)
  214949. {
  214950. while (--samples1 >= 0)
  214951. {
  214952. *destL++ = *src++ * g;
  214953. ++src;
  214954. }
  214955. src = (const short*)lpbuf2;
  214956. while (--samples2 >= 0)
  214957. {
  214958. *destL++ = *src++ * g;
  214959. ++src;
  214960. }
  214961. }
  214962. else
  214963. {
  214964. while (--samples1 >= 0)
  214965. {
  214966. *destL++ = *src++ * g;
  214967. *destR++ = *src++ * g;
  214968. }
  214969. src = (const short*)lpbuf2;
  214970. while (--samples2 >= 0)
  214971. {
  214972. *destL++ = *src++ * g;
  214973. *destR++ = *src++ * g;
  214974. }
  214975. }
  214976. }
  214977. else
  214978. {
  214979. jassertfalse;
  214980. }
  214981. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214982. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214983. }
  214984. else
  214985. {
  214986. logError (hr);
  214987. jassertfalse;
  214988. }
  214989. bytesFilled -= bytesPerBuffer;
  214990. return true;
  214991. }
  214992. else
  214993. {
  214994. return false;
  214995. }
  214996. }
  214997. };
  214998. class DSoundAudioIODevice : public AudioIODevice,
  214999. public Thread
  215000. {
  215001. public:
  215002. DSoundAudioIODevice (const String& deviceName,
  215003. const int outputDeviceIndex_,
  215004. const int inputDeviceIndex_)
  215005. : AudioIODevice (deviceName, "DirectSound"),
  215006. Thread ("Juce DSound"),
  215007. isOpen_ (false),
  215008. isStarted (false),
  215009. outputDeviceIndex (outputDeviceIndex_),
  215010. inputDeviceIndex (inputDeviceIndex_),
  215011. totalSamplesOut (0),
  215012. sampleRate (0.0),
  215013. inputBuffers (1, 1),
  215014. outputBuffers (1, 1),
  215015. callback (0),
  215016. bufferSizeSamples (0)
  215017. {
  215018. if (outputDeviceIndex_ >= 0)
  215019. {
  215020. outChannels.add (TRANS("Left"));
  215021. outChannels.add (TRANS("Right"));
  215022. }
  215023. if (inputDeviceIndex_ >= 0)
  215024. {
  215025. inChannels.add (TRANS("Left"));
  215026. inChannels.add (TRANS("Right"));
  215027. }
  215028. }
  215029. ~DSoundAudioIODevice()
  215030. {
  215031. close();
  215032. }
  215033. const StringArray getOutputChannelNames()
  215034. {
  215035. return outChannels;
  215036. }
  215037. const StringArray getInputChannelNames()
  215038. {
  215039. return inChannels;
  215040. }
  215041. int getNumSampleRates()
  215042. {
  215043. return 4;
  215044. }
  215045. double getSampleRate (int index)
  215046. {
  215047. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215048. return samps [jlimit (0, 3, index)];
  215049. }
  215050. int getNumBufferSizesAvailable()
  215051. {
  215052. return 50;
  215053. }
  215054. int getBufferSizeSamples (int index)
  215055. {
  215056. int n = 64;
  215057. for (int i = 0; i < index; ++i)
  215058. n += (n < 512) ? 32
  215059. : ((n < 1024) ? 64
  215060. : ((n < 2048) ? 128 : 256));
  215061. return n;
  215062. }
  215063. int getDefaultBufferSize()
  215064. {
  215065. return 2560;
  215066. }
  215067. const String open (const BigInteger& inputChannels,
  215068. const BigInteger& outputChannels,
  215069. double sampleRate,
  215070. int bufferSizeSamples)
  215071. {
  215072. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  215073. isOpen_ = lastError.isEmpty();
  215074. return lastError;
  215075. }
  215076. void close()
  215077. {
  215078. stop();
  215079. if (isOpen_)
  215080. {
  215081. closeDevice();
  215082. isOpen_ = false;
  215083. }
  215084. }
  215085. bool isOpen()
  215086. {
  215087. return isOpen_ && isThreadRunning();
  215088. }
  215089. int getCurrentBufferSizeSamples()
  215090. {
  215091. return bufferSizeSamples;
  215092. }
  215093. double getCurrentSampleRate()
  215094. {
  215095. return sampleRate;
  215096. }
  215097. int getCurrentBitDepth()
  215098. {
  215099. int i, bits = 256;
  215100. for (i = inChans.size(); --i >= 0;)
  215101. bits = jmin (bits, inChans[i]->bitDepth);
  215102. for (i = outChans.size(); --i >= 0;)
  215103. bits = jmin (bits, outChans[i]->bitDepth);
  215104. if (bits > 32)
  215105. bits = 16;
  215106. return bits;
  215107. }
  215108. const BigInteger getActiveOutputChannels() const
  215109. {
  215110. return enabledOutputs;
  215111. }
  215112. const BigInteger getActiveInputChannels() const
  215113. {
  215114. return enabledInputs;
  215115. }
  215116. int getOutputLatencyInSamples()
  215117. {
  215118. return (int) (getCurrentBufferSizeSamples() * 1.5);
  215119. }
  215120. int getInputLatencyInSamples()
  215121. {
  215122. return getOutputLatencyInSamples();
  215123. }
  215124. void start (AudioIODeviceCallback* call)
  215125. {
  215126. if (isOpen_ && call != 0 && ! isStarted)
  215127. {
  215128. if (! isThreadRunning())
  215129. {
  215130. // something gone wrong and the thread's stopped..
  215131. isOpen_ = false;
  215132. return;
  215133. }
  215134. call->audioDeviceAboutToStart (this);
  215135. const ScopedLock sl (startStopLock);
  215136. callback = call;
  215137. isStarted = true;
  215138. }
  215139. }
  215140. void stop()
  215141. {
  215142. if (isStarted)
  215143. {
  215144. AudioIODeviceCallback* const callbackLocal = callback;
  215145. {
  215146. const ScopedLock sl (startStopLock);
  215147. isStarted = false;
  215148. }
  215149. if (callbackLocal != 0)
  215150. callbackLocal->audioDeviceStopped();
  215151. }
  215152. }
  215153. bool isPlaying()
  215154. {
  215155. return isStarted && isOpen_ && isThreadRunning();
  215156. }
  215157. const String getLastError()
  215158. {
  215159. return lastError;
  215160. }
  215161. juce_UseDebuggingNewOperator
  215162. StringArray inChannels, outChannels;
  215163. int outputDeviceIndex, inputDeviceIndex;
  215164. private:
  215165. bool isOpen_;
  215166. bool isStarted;
  215167. String lastError;
  215168. OwnedArray <DSoundInternalInChannel> inChans;
  215169. OwnedArray <DSoundInternalOutChannel> outChans;
  215170. WaitableEvent startEvent;
  215171. int bufferSizeSamples;
  215172. int volatile totalSamplesOut;
  215173. int64 volatile lastBlockTime;
  215174. double sampleRate;
  215175. BigInteger enabledInputs, enabledOutputs;
  215176. AudioSampleBuffer inputBuffers, outputBuffers;
  215177. AudioIODeviceCallback* callback;
  215178. CriticalSection startStopLock;
  215179. DSoundAudioIODevice (const DSoundAudioIODevice&);
  215180. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  215181. const String openDevice (const BigInteger& inputChannels,
  215182. const BigInteger& outputChannels,
  215183. double sampleRate_,
  215184. int bufferSizeSamples_);
  215185. void closeDevice()
  215186. {
  215187. isStarted = false;
  215188. stopThread (5000);
  215189. inChans.clear();
  215190. outChans.clear();
  215191. inputBuffers.setSize (1, 1);
  215192. outputBuffers.setSize (1, 1);
  215193. }
  215194. void resync()
  215195. {
  215196. if (! threadShouldExit())
  215197. {
  215198. sleep (5);
  215199. int i;
  215200. for (i = 0; i < outChans.size(); ++i)
  215201. outChans.getUnchecked(i)->synchronisePosition();
  215202. for (i = 0; i < inChans.size(); ++i)
  215203. inChans.getUnchecked(i)->synchronisePosition();
  215204. }
  215205. }
  215206. public:
  215207. void run()
  215208. {
  215209. while (! threadShouldExit())
  215210. {
  215211. if (wait (100))
  215212. break;
  215213. }
  215214. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  215215. const int maxTimeMS = jmax (5, 3 * latencyMs);
  215216. while (! threadShouldExit())
  215217. {
  215218. int numToDo = 0;
  215219. uint32 startTime = Time::getMillisecondCounter();
  215220. int i;
  215221. for (i = inChans.size(); --i >= 0;)
  215222. {
  215223. inChans.getUnchecked(i)->doneFlag = false;
  215224. ++numToDo;
  215225. }
  215226. for (i = outChans.size(); --i >= 0;)
  215227. {
  215228. outChans.getUnchecked(i)->doneFlag = false;
  215229. ++numToDo;
  215230. }
  215231. if (numToDo > 0)
  215232. {
  215233. const int maxCount = 3;
  215234. int count = maxCount;
  215235. for (;;)
  215236. {
  215237. for (i = inChans.size(); --i >= 0;)
  215238. {
  215239. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  215240. if ((! in->doneFlag) && in->service())
  215241. {
  215242. in->doneFlag = true;
  215243. --numToDo;
  215244. }
  215245. }
  215246. for (i = outChans.size(); --i >= 0;)
  215247. {
  215248. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  215249. if ((! out->doneFlag) && out->service())
  215250. {
  215251. out->doneFlag = true;
  215252. --numToDo;
  215253. }
  215254. }
  215255. if (numToDo <= 0)
  215256. break;
  215257. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  215258. {
  215259. resync();
  215260. break;
  215261. }
  215262. if (--count <= 0)
  215263. {
  215264. Sleep (1);
  215265. count = maxCount;
  215266. }
  215267. if (threadShouldExit())
  215268. return;
  215269. }
  215270. }
  215271. else
  215272. {
  215273. sleep (1);
  215274. }
  215275. const ScopedLock sl (startStopLock);
  215276. if (isStarted)
  215277. {
  215278. JUCE_TRY
  215279. {
  215280. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  215281. inputBuffers.getNumChannels(),
  215282. outputBuffers.getArrayOfChannels(),
  215283. outputBuffers.getNumChannels(),
  215284. bufferSizeSamples);
  215285. }
  215286. JUCE_CATCH_EXCEPTION
  215287. totalSamplesOut += bufferSizeSamples;
  215288. }
  215289. else
  215290. {
  215291. outputBuffers.clear();
  215292. totalSamplesOut = 0;
  215293. sleep (1);
  215294. }
  215295. }
  215296. }
  215297. };
  215298. class DSoundAudioIODeviceType : public AudioIODeviceType
  215299. {
  215300. public:
  215301. DSoundAudioIODeviceType()
  215302. : AudioIODeviceType ("DirectSound"),
  215303. hasScanned (false)
  215304. {
  215305. initialiseDSoundFunctions();
  215306. }
  215307. ~DSoundAudioIODeviceType()
  215308. {
  215309. }
  215310. void scanForDevices()
  215311. {
  215312. hasScanned = true;
  215313. outputDeviceNames.clear();
  215314. outputGuids.clear();
  215315. inputDeviceNames.clear();
  215316. inputGuids.clear();
  215317. if (dsDirectSoundEnumerateW != 0)
  215318. {
  215319. dsDirectSoundEnumerateW (outputEnumProcW, this);
  215320. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  215321. }
  215322. }
  215323. const StringArray getDeviceNames (bool wantInputNames) const
  215324. {
  215325. jassert (hasScanned); // need to call scanForDevices() before doing this
  215326. return wantInputNames ? inputDeviceNames
  215327. : outputDeviceNames;
  215328. }
  215329. int getDefaultDeviceIndex (bool /*forInput*/) const
  215330. {
  215331. jassert (hasScanned); // need to call scanForDevices() before doing this
  215332. return 0;
  215333. }
  215334. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215335. {
  215336. jassert (hasScanned); // need to call scanForDevices() before doing this
  215337. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  215338. if (d == 0)
  215339. return -1;
  215340. return asInput ? d->inputDeviceIndex
  215341. : d->outputDeviceIndex;
  215342. }
  215343. bool hasSeparateInputsAndOutputs() const { return true; }
  215344. AudioIODevice* createDevice (const String& outputDeviceName,
  215345. const String& inputDeviceName)
  215346. {
  215347. jassert (hasScanned); // need to call scanForDevices() before doing this
  215348. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215349. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215350. if (outputIndex >= 0 || inputIndex >= 0)
  215351. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215352. : inputDeviceName,
  215353. outputIndex, inputIndex);
  215354. return 0;
  215355. }
  215356. juce_UseDebuggingNewOperator
  215357. StringArray outputDeviceNames;
  215358. OwnedArray <GUID> outputGuids;
  215359. StringArray inputDeviceNames;
  215360. OwnedArray <GUID> inputGuids;
  215361. private:
  215362. bool hasScanned;
  215363. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  215364. {
  215365. desc = desc.trim();
  215366. if (desc.isNotEmpty())
  215367. {
  215368. const String origDesc (desc);
  215369. int n = 2;
  215370. while (outputDeviceNames.contains (desc))
  215371. desc = origDesc + " (" + String (n++) + ")";
  215372. outputDeviceNames.add (desc);
  215373. if (lpGUID != 0)
  215374. outputGuids.add (new GUID (*lpGUID));
  215375. else
  215376. outputGuids.add (0);
  215377. }
  215378. return TRUE;
  215379. }
  215380. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215381. {
  215382. return ((DSoundAudioIODeviceType*) object)
  215383. ->outputEnumProc (lpGUID, String (description));
  215384. }
  215385. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215386. {
  215387. return ((DSoundAudioIODeviceType*) object)
  215388. ->outputEnumProc (lpGUID, String (description));
  215389. }
  215390. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  215391. {
  215392. desc = desc.trim();
  215393. if (desc.isNotEmpty())
  215394. {
  215395. const String origDesc (desc);
  215396. int n = 2;
  215397. while (inputDeviceNames.contains (desc))
  215398. desc = origDesc + " (" + String (n++) + ")";
  215399. inputDeviceNames.add (desc);
  215400. if (lpGUID != 0)
  215401. inputGuids.add (new GUID (*lpGUID));
  215402. else
  215403. inputGuids.add (0);
  215404. }
  215405. return TRUE;
  215406. }
  215407. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215408. {
  215409. return ((DSoundAudioIODeviceType*) object)
  215410. ->inputEnumProc (lpGUID, String (description));
  215411. }
  215412. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215413. {
  215414. return ((DSoundAudioIODeviceType*) object)
  215415. ->inputEnumProc (lpGUID, String (description));
  215416. }
  215417. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  215418. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  215419. };
  215420. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  215421. const BigInteger& outputChannels,
  215422. double sampleRate_,
  215423. int bufferSizeSamples_)
  215424. {
  215425. closeDevice();
  215426. totalSamplesOut = 0;
  215427. sampleRate = sampleRate_;
  215428. if (bufferSizeSamples_ <= 0)
  215429. bufferSizeSamples_ = 960; // use as a default size if none is set.
  215430. bufferSizeSamples = bufferSizeSamples_ & ~7;
  215431. DSoundAudioIODeviceType dlh;
  215432. dlh.scanForDevices();
  215433. enabledInputs = inputChannels;
  215434. enabledInputs.setRange (inChannels.size(),
  215435. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  215436. false);
  215437. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  215438. inputBuffers.clear();
  215439. int i, numIns = 0;
  215440. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  215441. {
  215442. float* left = 0;
  215443. if (enabledInputs[i])
  215444. left = inputBuffers.getSampleData (numIns++);
  215445. float* right = 0;
  215446. if (enabledInputs[i + 1])
  215447. right = inputBuffers.getSampleData (numIns++);
  215448. if (left != 0 || right != 0)
  215449. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  215450. dlh.inputGuids [inputDeviceIndex],
  215451. (int) sampleRate, bufferSizeSamples,
  215452. left, right));
  215453. }
  215454. enabledOutputs = outputChannels;
  215455. enabledOutputs.setRange (outChannels.size(),
  215456. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  215457. false);
  215458. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  215459. outputBuffers.clear();
  215460. int numOuts = 0;
  215461. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215462. {
  215463. float* left = 0;
  215464. if (enabledOutputs[i])
  215465. left = outputBuffers.getSampleData (numOuts++);
  215466. float* right = 0;
  215467. if (enabledOutputs[i + 1])
  215468. right = outputBuffers.getSampleData (numOuts++);
  215469. if (left != 0 || right != 0)
  215470. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215471. dlh.outputGuids [outputDeviceIndex],
  215472. (int) sampleRate, bufferSizeSamples,
  215473. left, right));
  215474. }
  215475. String error;
  215476. // boost our priority while opening the devices to try to get better sync between them
  215477. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215478. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215479. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215480. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215481. for (i = 0; i < outChans.size(); ++i)
  215482. {
  215483. error = outChans[i]->open();
  215484. if (error.isNotEmpty())
  215485. {
  215486. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215487. break;
  215488. }
  215489. }
  215490. if (error.isEmpty())
  215491. {
  215492. for (i = 0; i < inChans.size(); ++i)
  215493. {
  215494. error = inChans[i]->open();
  215495. if (error.isNotEmpty())
  215496. {
  215497. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215498. break;
  215499. }
  215500. }
  215501. }
  215502. if (error.isEmpty())
  215503. {
  215504. totalSamplesOut = 0;
  215505. for (i = 0; i < outChans.size(); ++i)
  215506. outChans.getUnchecked(i)->synchronisePosition();
  215507. for (i = 0; i < inChans.size(); ++i)
  215508. inChans.getUnchecked(i)->synchronisePosition();
  215509. startThread (9);
  215510. sleep (10);
  215511. notify();
  215512. }
  215513. else
  215514. {
  215515. log (error);
  215516. }
  215517. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215518. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215519. return error;
  215520. }
  215521. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  215522. {
  215523. return new DSoundAudioIODeviceType();
  215524. }
  215525. #undef log
  215526. #endif
  215527. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215528. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215529. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215530. // compiled on its own).
  215531. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215532. #ifndef WASAPI_ENABLE_LOGGING
  215533. #define WASAPI_ENABLE_LOGGING 1
  215534. #endif
  215535. namespace WasapiClasses
  215536. {
  215537. static void logFailure (HRESULT hr)
  215538. {
  215539. (void) hr;
  215540. #if WASAPI_ENABLE_LOGGING
  215541. if (FAILED (hr))
  215542. {
  215543. String e;
  215544. e << Time::getCurrentTime().toString (true, true, true, true)
  215545. << " -- WASAPI error: ";
  215546. switch (hr)
  215547. {
  215548. case E_POINTER: e << "E_POINTER"; break;
  215549. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  215550. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  215551. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215552. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215553. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215554. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  215555. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215556. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  215557. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215558. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  215559. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  215560. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215561. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215562. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215563. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215564. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215565. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215566. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215567. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215568. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215569. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215570. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215571. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  215572. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215573. default: e << String::toHexString ((int) hr); break;
  215574. }
  215575. DBG (e);
  215576. jassertfalse;
  215577. }
  215578. #endif
  215579. }
  215580. static bool check (HRESULT hr)
  215581. {
  215582. logFailure (hr);
  215583. return SUCCEEDED (hr);
  215584. }
  215585. static const String getDeviceID (IMMDevice* const device)
  215586. {
  215587. String s;
  215588. WCHAR* deviceId = 0;
  215589. if (check (device->GetId (&deviceId)))
  215590. {
  215591. s = String (deviceId);
  215592. CoTaskMemFree (deviceId);
  215593. }
  215594. return s;
  215595. }
  215596. static EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  215597. {
  215598. EDataFlow flow = eRender;
  215599. ComSmartPtr <IMMEndpoint> endPoint;
  215600. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  215601. (void) check (endPoint->GetDataFlow (&flow));
  215602. return flow;
  215603. }
  215604. static int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215605. {
  215606. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215607. }
  215608. static void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215609. {
  215610. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215611. : sizeof (WAVEFORMATEX));
  215612. }
  215613. class WASAPIDeviceBase
  215614. {
  215615. public:
  215616. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215617. : device (device_),
  215618. sampleRate (0),
  215619. numChannels (0),
  215620. actualNumChannels (0),
  215621. defaultSampleRate (0),
  215622. minBufferSize (0),
  215623. defaultBufferSize (0),
  215624. latencySamples (0),
  215625. useExclusiveMode (useExclusiveMode_)
  215626. {
  215627. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215628. ComSmartPtr <IAudioClient> tempClient (createClient());
  215629. if (tempClient == 0)
  215630. return;
  215631. REFERENCE_TIME defaultPeriod, minPeriod;
  215632. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215633. return;
  215634. WAVEFORMATEX* mixFormat = 0;
  215635. if (! check (tempClient->GetMixFormat (&mixFormat)))
  215636. return;
  215637. WAVEFORMATEXTENSIBLE format;
  215638. copyWavFormat (format, mixFormat);
  215639. CoTaskMemFree (mixFormat);
  215640. actualNumChannels = numChannels = format.Format.nChannels;
  215641. defaultSampleRate = format.Format.nSamplesPerSec;
  215642. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  215643. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  215644. rates.addUsingDefaultSort (defaultSampleRate);
  215645. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215646. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215647. {
  215648. if (ratesToTest[i] == defaultSampleRate)
  215649. continue;
  215650. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215651. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215652. (WAVEFORMATEX*) &format, 0)))
  215653. if (! rates.contains (ratesToTest[i]))
  215654. rates.addUsingDefaultSort (ratesToTest[i]);
  215655. }
  215656. }
  215657. ~WASAPIDeviceBase()
  215658. {
  215659. device = 0;
  215660. CloseHandle (clientEvent);
  215661. }
  215662. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215663. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215664. {
  215665. sampleRate = newSampleRate;
  215666. channels = newChannels;
  215667. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215668. numChannels = channels.getHighestBit() + 1;
  215669. if (numChannels == 0)
  215670. return true;
  215671. client = createClient();
  215672. if (client != 0
  215673. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215674. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215675. {
  215676. channelMaps.clear();
  215677. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215678. if (channels[i])
  215679. channelMaps.add (i);
  215680. REFERENCE_TIME latency;
  215681. if (check (client->GetStreamLatency (&latency)))
  215682. latencySamples = refTimeToSamples (latency, sampleRate);
  215683. (void) check (client->GetBufferSize (&actualBufferSize));
  215684. return check (client->SetEventHandle (clientEvent));
  215685. }
  215686. return false;
  215687. }
  215688. void closeClient()
  215689. {
  215690. if (client != 0)
  215691. client->Stop();
  215692. client = 0;
  215693. ResetEvent (clientEvent);
  215694. }
  215695. ComSmartPtr <IMMDevice> device;
  215696. ComSmartPtr <IAudioClient> client;
  215697. double sampleRate, defaultSampleRate;
  215698. int numChannels, actualNumChannels;
  215699. int minBufferSize, defaultBufferSize, latencySamples;
  215700. const bool useExclusiveMode;
  215701. Array <double> rates;
  215702. HANDLE clientEvent;
  215703. BigInteger channels;
  215704. Array <int> channelMaps;
  215705. UINT32 actualBufferSize;
  215706. int bytesPerSample;
  215707. virtual void updateFormat (bool isFloat) = 0;
  215708. private:
  215709. const ComSmartPtr <IAudioClient> createClient()
  215710. {
  215711. ComSmartPtr <IAudioClient> client;
  215712. if (device != 0)
  215713. {
  215714. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  215715. logFailure (hr);
  215716. }
  215717. return client;
  215718. }
  215719. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215720. {
  215721. WAVEFORMATEXTENSIBLE format;
  215722. zerostruct (format);
  215723. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215724. {
  215725. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215726. }
  215727. else
  215728. {
  215729. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215730. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215731. }
  215732. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215733. format.Format.nChannels = (WORD) numChannels;
  215734. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215735. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215736. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215737. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215738. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215739. switch (numChannels)
  215740. {
  215741. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215742. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215743. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215744. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215745. 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;
  215746. default: break;
  215747. }
  215748. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215749. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215750. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215751. logFailure (hr);
  215752. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215753. {
  215754. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215755. hr = S_OK;
  215756. }
  215757. CoTaskMemFree (nearestFormat);
  215758. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215759. if (useExclusiveMode)
  215760. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215761. GUID session;
  215762. if (hr == S_OK
  215763. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215764. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215765. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215766. {
  215767. actualNumChannels = format.Format.nChannels;
  215768. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215769. bytesPerSample = format.Format.wBitsPerSample / 8;
  215770. updateFormat (isFloat);
  215771. return true;
  215772. }
  215773. return false;
  215774. }
  215775. WASAPIDeviceBase (const WASAPIDeviceBase&);
  215776. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  215777. };
  215778. class WASAPIInputDevice : public WASAPIDeviceBase
  215779. {
  215780. public:
  215781. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215782. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215783. reservoir (1, 1)
  215784. {
  215785. }
  215786. ~WASAPIInputDevice()
  215787. {
  215788. close();
  215789. }
  215790. bool open (const double newSampleRate, const BigInteger& newChannels)
  215791. {
  215792. reservoirSize = 0;
  215793. reservoirCapacity = 16384;
  215794. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215795. return openClient (newSampleRate, newChannels)
  215796. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient), (void**) captureClient.resetAndGetPointerAddress())));
  215797. }
  215798. void close()
  215799. {
  215800. closeClient();
  215801. captureClient = 0;
  215802. reservoir.setSize (0);
  215803. }
  215804. void updateFormat (bool isFloat)
  215805. {
  215806. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  215807. if (isFloat)
  215808. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215809. else if (bytesPerSample == 4)
  215810. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215811. else if (bytesPerSample == 3)
  215812. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215813. else
  215814. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215815. }
  215816. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215817. {
  215818. if (numChannels <= 0)
  215819. return;
  215820. int offset = 0;
  215821. while (bufferSize > 0)
  215822. {
  215823. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215824. {
  215825. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215826. for (int i = 0; i < numDestBuffers; ++i)
  215827. converter->convertSamples (destBuffers[i], offset, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  215828. bufferSize -= samplesToDo;
  215829. offset += samplesToDo;
  215830. reservoirSize -= samplesToDo;
  215831. }
  215832. else
  215833. {
  215834. UINT32 packetLength = 0;
  215835. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  215836. break;
  215837. if (packetLength == 0)
  215838. {
  215839. if (thread.threadShouldExit())
  215840. break;
  215841. Thread::sleep (1);
  215842. continue;
  215843. }
  215844. uint8* inputData = 0;
  215845. UINT32 numSamplesAvailable;
  215846. DWORD flags;
  215847. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  215848. {
  215849. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  215850. for (int i = 0; i < numDestBuffers; ++i)
  215851. converter->convertSamples (destBuffers[i], offset, inputData, channelMaps.getUnchecked(i), samplesToDo);
  215852. bufferSize -= samplesToDo;
  215853. offset += samplesToDo;
  215854. if (samplesToDo < (int) numSamplesAvailable)
  215855. {
  215856. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  215857. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  215858. bytesPerSample * actualNumChannels * reservoirSize);
  215859. }
  215860. captureClient->ReleaseBuffer (numSamplesAvailable);
  215861. }
  215862. }
  215863. }
  215864. }
  215865. ComSmartPtr <IAudioCaptureClient> captureClient;
  215866. MemoryBlock reservoir;
  215867. int reservoirSize, reservoirCapacity;
  215868. ScopedPointer <AudioData::Converter> converter;
  215869. private:
  215870. WASAPIInputDevice (const WASAPIInputDevice&);
  215871. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  215872. };
  215873. class WASAPIOutputDevice : public WASAPIDeviceBase
  215874. {
  215875. public:
  215876. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215877. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215878. {
  215879. }
  215880. ~WASAPIOutputDevice()
  215881. {
  215882. close();
  215883. }
  215884. bool open (const double newSampleRate, const BigInteger& newChannels)
  215885. {
  215886. return openClient (newSampleRate, newChannels)
  215887. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  215888. }
  215889. void close()
  215890. {
  215891. closeClient();
  215892. renderClient = 0;
  215893. }
  215894. void updateFormat (bool isFloat)
  215895. {
  215896. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  215897. if (isFloat)
  215898. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215899. else if (bytesPerSample == 4)
  215900. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215901. else if (bytesPerSample == 3)
  215902. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215903. else
  215904. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215905. }
  215906. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  215907. {
  215908. if (numChannels <= 0)
  215909. return;
  215910. int offset = 0;
  215911. while (bufferSize > 0)
  215912. {
  215913. UINT32 padding = 0;
  215914. if (! check (client->GetCurrentPadding (&padding)))
  215915. return;
  215916. int samplesToDo = useExclusiveMode ? bufferSize
  215917. : jmin ((int) (actualBufferSize - padding), bufferSize);
  215918. if (samplesToDo <= 0)
  215919. {
  215920. if (thread.threadShouldExit())
  215921. break;
  215922. Thread::sleep (0);
  215923. continue;
  215924. }
  215925. uint8* outputData = 0;
  215926. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  215927. {
  215928. for (int i = 0; i < numSrcBuffers; ++i)
  215929. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i], offset, samplesToDo);
  215930. renderClient->ReleaseBuffer (samplesToDo, 0);
  215931. offset += samplesToDo;
  215932. bufferSize -= samplesToDo;
  215933. }
  215934. }
  215935. }
  215936. ComSmartPtr <IAudioRenderClient> renderClient;
  215937. ScopedPointer <AudioData::Converter> converter;
  215938. private:
  215939. WASAPIOutputDevice (const WASAPIOutputDevice&);
  215940. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  215941. };
  215942. class WASAPIAudioIODevice : public AudioIODevice,
  215943. public Thread
  215944. {
  215945. public:
  215946. WASAPIAudioIODevice (const String& deviceName,
  215947. const String& outputDeviceId_,
  215948. const String& inputDeviceId_,
  215949. const bool useExclusiveMode_)
  215950. : AudioIODevice (deviceName, "Windows Audio"),
  215951. Thread ("Juce WASAPI"),
  215952. isOpen_ (false),
  215953. isStarted (false),
  215954. outputDeviceId (outputDeviceId_),
  215955. inputDeviceId (inputDeviceId_),
  215956. useExclusiveMode (useExclusiveMode_),
  215957. currentBufferSizeSamples (0),
  215958. currentSampleRate (0),
  215959. callback (0)
  215960. {
  215961. }
  215962. ~WASAPIAudioIODevice()
  215963. {
  215964. close();
  215965. }
  215966. bool initialise()
  215967. {
  215968. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  215969. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  215970. latencyIn = latencyOut = 0;
  215971. Array <double> ratesIn, ratesOut;
  215972. if (createDevices())
  215973. {
  215974. jassert (inputDevice != 0 || outputDevice != 0);
  215975. if (inputDevice != 0 && outputDevice != 0)
  215976. {
  215977. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  215978. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  215979. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  215980. sampleRates = inputDevice->rates;
  215981. sampleRates.removeValuesNotIn (outputDevice->rates);
  215982. }
  215983. else
  215984. {
  215985. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  215986. : static_cast<WASAPIDeviceBase*> (outputDevice);
  215987. defaultSampleRate = d->defaultSampleRate;
  215988. minBufferSize = d->minBufferSize;
  215989. defaultBufferSize = d->defaultBufferSize;
  215990. sampleRates = d->rates;
  215991. }
  215992. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215993. if (minBufferSize != defaultBufferSize)
  215994. bufferSizes.addUsingDefaultSort (minBufferSize);
  215995. int n = 64;
  215996. for (int i = 0; i < 40; ++i)
  215997. {
  215998. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  215999. bufferSizes.addUsingDefaultSort (n);
  216000. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  216001. }
  216002. return true;
  216003. }
  216004. return false;
  216005. }
  216006. const StringArray getOutputChannelNames()
  216007. {
  216008. StringArray outChannels;
  216009. if (outputDevice != 0)
  216010. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  216011. outChannels.add ("Output channel " + String (i));
  216012. return outChannels;
  216013. }
  216014. const StringArray getInputChannelNames()
  216015. {
  216016. StringArray inChannels;
  216017. if (inputDevice != 0)
  216018. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  216019. inChannels.add ("Input channel " + String (i));
  216020. return inChannels;
  216021. }
  216022. int getNumSampleRates() { return sampleRates.size(); }
  216023. double getSampleRate (int index) { return sampleRates [index]; }
  216024. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  216025. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  216026. int getDefaultBufferSize() { return defaultBufferSize; }
  216027. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  216028. double getCurrentSampleRate() { return currentSampleRate; }
  216029. int getCurrentBitDepth() { return 32; }
  216030. int getOutputLatencyInSamples() { return latencyOut; }
  216031. int getInputLatencyInSamples() { return latencyIn; }
  216032. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  216033. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  216034. const String getLastError() { return lastError; }
  216035. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  216036. double sampleRate, int bufferSizeSamples)
  216037. {
  216038. close();
  216039. lastError = String::empty;
  216040. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  216041. {
  216042. lastError = "The input and output devices don't share a common sample rate!";
  216043. return lastError;
  216044. }
  216045. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  216046. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  216047. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  216048. {
  216049. lastError = "Couldn't open the input device!";
  216050. return lastError;
  216051. }
  216052. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  216053. {
  216054. close();
  216055. lastError = "Couldn't open the output device!";
  216056. return lastError;
  216057. }
  216058. if (inputDevice != 0)
  216059. ResetEvent (inputDevice->clientEvent);
  216060. if (outputDevice != 0)
  216061. ResetEvent (outputDevice->clientEvent);
  216062. startThread (8);
  216063. Thread::sleep (5);
  216064. if (inputDevice != 0 && inputDevice->client != 0)
  216065. {
  216066. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  216067. HRESULT hr = inputDevice->client->Start();
  216068. logFailure (hr); //xxx handle this
  216069. }
  216070. if (outputDevice != 0 && outputDevice->client != 0)
  216071. {
  216072. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  216073. HRESULT hr = outputDevice->client->Start();
  216074. logFailure (hr); //xxx handle this
  216075. }
  216076. isOpen_ = true;
  216077. return lastError;
  216078. }
  216079. void close()
  216080. {
  216081. stop();
  216082. if (inputDevice != 0)
  216083. SetEvent (inputDevice->clientEvent);
  216084. if (outputDevice != 0)
  216085. SetEvent (outputDevice->clientEvent);
  216086. stopThread (5000);
  216087. if (inputDevice != 0)
  216088. inputDevice->close();
  216089. if (outputDevice != 0)
  216090. outputDevice->close();
  216091. isOpen_ = false;
  216092. }
  216093. bool isOpen() { return isOpen_ && isThreadRunning(); }
  216094. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  216095. void start (AudioIODeviceCallback* call)
  216096. {
  216097. if (isOpen_ && call != 0 && ! isStarted)
  216098. {
  216099. if (! isThreadRunning())
  216100. {
  216101. // something's gone wrong and the thread's stopped..
  216102. isOpen_ = false;
  216103. return;
  216104. }
  216105. call->audioDeviceAboutToStart (this);
  216106. const ScopedLock sl (startStopLock);
  216107. callback = call;
  216108. isStarted = true;
  216109. }
  216110. }
  216111. void stop()
  216112. {
  216113. if (isStarted)
  216114. {
  216115. AudioIODeviceCallback* const callbackLocal = callback;
  216116. {
  216117. const ScopedLock sl (startStopLock);
  216118. isStarted = false;
  216119. }
  216120. if (callbackLocal != 0)
  216121. callbackLocal->audioDeviceStopped();
  216122. }
  216123. }
  216124. void setMMThreadPriority()
  216125. {
  216126. DynamicLibraryLoader dll ("avrt.dll");
  216127. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  216128. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  216129. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  216130. {
  216131. DWORD dummy = 0;
  216132. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  216133. if (h != 0)
  216134. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  216135. }
  216136. }
  216137. void run()
  216138. {
  216139. setMMThreadPriority();
  216140. const int bufferSize = currentBufferSizeSamples;
  216141. HANDLE events[2];
  216142. int numEvents = 0;
  216143. if (inputDevice != 0)
  216144. events [numEvents++] = inputDevice->clientEvent;
  216145. if (outputDevice != 0)
  216146. events [numEvents++] = outputDevice->clientEvent;
  216147. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  216148. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  216149. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  216150. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  216151. float** const inputBuffers = ins.getArrayOfChannels();
  216152. float** const outputBuffers = outs.getArrayOfChannels();
  216153. ins.clear();
  216154. while (! threadShouldExit())
  216155. {
  216156. const DWORD result = useExclusiveMode ? (inputDevice != 0 ? WaitForSingleObject (inputDevice->clientEvent, 1000) : S_OK)
  216157. : WaitForMultipleObjects (numEvents, events, true, 1000);
  216158. if (result == WAIT_TIMEOUT)
  216159. continue;
  216160. if (threadShouldExit())
  216161. break;
  216162. if (inputDevice != 0)
  216163. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  216164. // Make the callback..
  216165. {
  216166. const ScopedLock sl (startStopLock);
  216167. if (isStarted)
  216168. {
  216169. JUCE_TRY
  216170. {
  216171. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  216172. numInputBuffers,
  216173. outputBuffers,
  216174. numOutputBuffers,
  216175. bufferSize);
  216176. }
  216177. JUCE_CATCH_EXCEPTION
  216178. }
  216179. else
  216180. {
  216181. outs.clear();
  216182. }
  216183. }
  216184. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  216185. continue;
  216186. if (outputDevice != 0)
  216187. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  216188. }
  216189. }
  216190. juce_UseDebuggingNewOperator
  216191. String outputDeviceId, inputDeviceId;
  216192. String lastError;
  216193. private:
  216194. // Device stats...
  216195. ScopedPointer<WASAPIInputDevice> inputDevice;
  216196. ScopedPointer<WASAPIOutputDevice> outputDevice;
  216197. const bool useExclusiveMode;
  216198. double defaultSampleRate;
  216199. int minBufferSize, defaultBufferSize;
  216200. int latencyIn, latencyOut;
  216201. Array <double> sampleRates;
  216202. Array <int> bufferSizes;
  216203. // Active state...
  216204. bool isOpen_, isStarted;
  216205. int currentBufferSizeSamples;
  216206. double currentSampleRate;
  216207. AudioIODeviceCallback* callback;
  216208. CriticalSection startStopLock;
  216209. bool createDevices()
  216210. {
  216211. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216212. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216213. return false;
  216214. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216215. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  216216. return false;
  216217. UINT32 numDevices = 0;
  216218. if (! check (deviceCollection->GetCount (&numDevices)))
  216219. return false;
  216220. for (UINT32 i = 0; i < numDevices; ++i)
  216221. {
  216222. ComSmartPtr <IMMDevice> device;
  216223. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216224. continue;
  216225. const String deviceId (getDeviceID (device));
  216226. if (deviceId.isEmpty())
  216227. continue;
  216228. const EDataFlow flow = getDataFlow (device);
  216229. if (deviceId == inputDeviceId && flow == eCapture)
  216230. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  216231. else if (deviceId == outputDeviceId && flow == eRender)
  216232. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  216233. }
  216234. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  216235. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  216236. }
  216237. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  216238. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  216239. };
  216240. class WASAPIAudioIODeviceType : public AudioIODeviceType
  216241. {
  216242. public:
  216243. WASAPIAudioIODeviceType()
  216244. : AudioIODeviceType ("Windows Audio"),
  216245. hasScanned (false)
  216246. {
  216247. }
  216248. ~WASAPIAudioIODeviceType()
  216249. {
  216250. }
  216251. void scanForDevices()
  216252. {
  216253. hasScanned = true;
  216254. outputDeviceNames.clear();
  216255. inputDeviceNames.clear();
  216256. outputDeviceIds.clear();
  216257. inputDeviceIds.clear();
  216258. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216259. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216260. return;
  216261. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  216262. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  216263. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216264. UINT32 numDevices = 0;
  216265. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  216266. && check (deviceCollection->GetCount (&numDevices))))
  216267. return;
  216268. for (UINT32 i = 0; i < numDevices; ++i)
  216269. {
  216270. ComSmartPtr <IMMDevice> device;
  216271. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216272. continue;
  216273. const String deviceId (getDeviceID (device));
  216274. DWORD state = 0;
  216275. if (! check (device->GetState (&state)))
  216276. continue;
  216277. if (state != DEVICE_STATE_ACTIVE)
  216278. continue;
  216279. String name;
  216280. {
  216281. ComSmartPtr <IPropertyStore> properties;
  216282. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  216283. continue;
  216284. PROPVARIANT value;
  216285. PropVariantInit (&value);
  216286. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  216287. name = value.pwszVal;
  216288. PropVariantClear (&value);
  216289. }
  216290. const EDataFlow flow = getDataFlow (device);
  216291. if (flow == eRender)
  216292. {
  216293. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  216294. outputDeviceIds.insert (index, deviceId);
  216295. outputDeviceNames.insert (index, name);
  216296. }
  216297. else if (flow == eCapture)
  216298. {
  216299. const int index = (deviceId == defaultCapture) ? 0 : -1;
  216300. inputDeviceIds.insert (index, deviceId);
  216301. inputDeviceNames.insert (index, name);
  216302. }
  216303. }
  216304. inputDeviceNames.appendNumbersToDuplicates (false, false);
  216305. outputDeviceNames.appendNumbersToDuplicates (false, false);
  216306. }
  216307. const StringArray getDeviceNames (bool wantInputNames) const
  216308. {
  216309. jassert (hasScanned); // need to call scanForDevices() before doing this
  216310. return wantInputNames ? inputDeviceNames
  216311. : outputDeviceNames;
  216312. }
  216313. int getDefaultDeviceIndex (bool /*forInput*/) const
  216314. {
  216315. jassert (hasScanned); // need to call scanForDevices() before doing this
  216316. return 0;
  216317. }
  216318. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  216319. {
  216320. jassert (hasScanned); // need to call scanForDevices() before doing this
  216321. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  216322. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  216323. : outputDeviceIds.indexOf (d->outputDeviceId));
  216324. }
  216325. bool hasSeparateInputsAndOutputs() const { return true; }
  216326. AudioIODevice* createDevice (const String& outputDeviceName,
  216327. const String& inputDeviceName)
  216328. {
  216329. jassert (hasScanned); // need to call scanForDevices() before doing this
  216330. const bool useExclusiveMode = false;
  216331. ScopedPointer<WASAPIAudioIODevice> device;
  216332. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  216333. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  216334. if (outputIndex >= 0 || inputIndex >= 0)
  216335. {
  216336. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  216337. : inputDeviceName,
  216338. outputDeviceIds [outputIndex],
  216339. inputDeviceIds [inputIndex],
  216340. useExclusiveMode);
  216341. if (! device->initialise())
  216342. device = 0;
  216343. }
  216344. return device.release();
  216345. }
  216346. juce_UseDebuggingNewOperator
  216347. StringArray outputDeviceNames, outputDeviceIds;
  216348. StringArray inputDeviceNames, inputDeviceIds;
  216349. private:
  216350. bool hasScanned;
  216351. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  216352. {
  216353. String s;
  216354. IMMDevice* dev = 0;
  216355. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  216356. eMultimedia, &dev)))
  216357. {
  216358. WCHAR* deviceId = 0;
  216359. if (check (dev->GetId (&deviceId)))
  216360. {
  216361. s = String (deviceId);
  216362. CoTaskMemFree (deviceId);
  216363. }
  216364. dev->Release();
  216365. }
  216366. return s;
  216367. }
  216368. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  216369. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  216370. };
  216371. }
  216372. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  216373. {
  216374. return new WasapiClasses::WASAPIAudioIODeviceType();
  216375. }
  216376. #endif
  216377. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  216378. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  216379. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  216380. // compiled on its own).
  216381. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  216382. class DShowCameraDeviceInteral : public ChangeBroadcaster
  216383. {
  216384. public:
  216385. DShowCameraDeviceInteral (CameraDevice* const owner_,
  216386. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  216387. const ComSmartPtr <IBaseFilter>& filter_,
  216388. int minWidth, int minHeight,
  216389. int maxWidth, int maxHeight)
  216390. : owner (owner_),
  216391. captureGraphBuilder (captureGraphBuilder_),
  216392. filter (filter_),
  216393. ok (false),
  216394. imageNeedsFlipping (false),
  216395. width (0),
  216396. height (0),
  216397. activeUsers (0),
  216398. recordNextFrameTime (false)
  216399. {
  216400. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  216401. if (FAILED (hr))
  216402. return;
  216403. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  216404. if (FAILED (hr))
  216405. return;
  216406. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  216407. if (FAILED (hr))
  216408. return;
  216409. {
  216410. ComSmartPtr <IAMStreamConfig> streamConfig;
  216411. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  216412. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  216413. if (streamConfig != 0)
  216414. {
  216415. getVideoSizes (streamConfig);
  216416. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  216417. return;
  216418. }
  216419. }
  216420. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  216421. if (FAILED (hr))
  216422. return;
  216423. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  216424. if (FAILED (hr))
  216425. return;
  216426. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  216427. if (FAILED (hr))
  216428. return;
  216429. if (! connectFilters (filter, smartTee))
  216430. return;
  216431. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  216432. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  216433. if (FAILED (hr))
  216434. return;
  216435. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  216436. if (FAILED (hr))
  216437. return;
  216438. AM_MEDIA_TYPE mt;
  216439. zerostruct (mt);
  216440. mt.majortype = MEDIATYPE_Video;
  216441. mt.subtype = MEDIASUBTYPE_RGB24;
  216442. mt.formattype = FORMAT_VideoInfo;
  216443. sampleGrabber->SetMediaType (&mt);
  216444. callback = new GrabberCallback (*this);
  216445. hr = sampleGrabber->SetCallback (callback, 1);
  216446. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  216447. if (FAILED (hr))
  216448. return;
  216449. ComSmartPtr <IPin> grabberInputPin;
  216450. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  216451. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  216452. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  216453. return;
  216454. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  216455. if (FAILED (hr))
  216456. return;
  216457. zerostruct (mt);
  216458. hr = sampleGrabber->GetConnectedMediaType (&mt);
  216459. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  216460. width = pVih->bmiHeader.biWidth;
  216461. height = pVih->bmiHeader.biHeight;
  216462. ComSmartPtr <IBaseFilter> nullFilter;
  216463. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  216464. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  216465. if (connectFilters (sampleGrabberBase, nullFilter)
  216466. && addGraphToRot())
  216467. {
  216468. activeImage = Image (Image::RGB, width, height, true);
  216469. loadingImage = Image (Image::RGB, width, height, true);
  216470. ok = true;
  216471. }
  216472. }
  216473. ~DShowCameraDeviceInteral()
  216474. {
  216475. if (mediaControl != 0)
  216476. mediaControl->Stop();
  216477. removeGraphFromRot();
  216478. for (int i = viewerComps.size(); --i >= 0;)
  216479. viewerComps.getUnchecked(i)->ownerDeleted();
  216480. callback = 0;
  216481. graphBuilder = 0;
  216482. sampleGrabber = 0;
  216483. mediaControl = 0;
  216484. filter = 0;
  216485. captureGraphBuilder = 0;
  216486. smartTee = 0;
  216487. smartTeePreviewOutputPin = 0;
  216488. smartTeeCaptureOutputPin = 0;
  216489. asfWriter = 0;
  216490. }
  216491. void addUser()
  216492. {
  216493. if (ok && activeUsers++ == 0)
  216494. mediaControl->Run();
  216495. }
  216496. void removeUser()
  216497. {
  216498. if (ok && --activeUsers == 0)
  216499. mediaControl->Stop();
  216500. }
  216501. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216502. {
  216503. if (recordNextFrameTime)
  216504. {
  216505. const double defaultCameraLatency = 0.1;
  216506. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216507. recordNextFrameTime = false;
  216508. ComSmartPtr <IPin> pin;
  216509. if (getPin (filter, PINDIR_OUTPUT, pin))
  216510. {
  216511. ComSmartPtr <IAMPushSource> pushSource;
  216512. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  216513. if (pushSource != 0)
  216514. {
  216515. REFERENCE_TIME latency = 0;
  216516. hr = pushSource->GetLatency (&latency);
  216517. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216518. }
  216519. }
  216520. }
  216521. {
  216522. const int lineStride = width * 3;
  216523. const ScopedLock sl (imageSwapLock);
  216524. {
  216525. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  216526. for (int i = 0; i < height; ++i)
  216527. memcpy (destData.getLinePointer ((height - 1) - i),
  216528. buffer + lineStride * i,
  216529. lineStride);
  216530. }
  216531. imageNeedsFlipping = true;
  216532. }
  216533. if (listeners.size() > 0)
  216534. callListeners (loadingImage);
  216535. sendChangeMessage (this);
  216536. }
  216537. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216538. {
  216539. if (imageNeedsFlipping)
  216540. {
  216541. const ScopedLock sl (imageSwapLock);
  216542. swapVariables (loadingImage, activeImage);
  216543. imageNeedsFlipping = false;
  216544. }
  216545. RectanglePlacement rp (RectanglePlacement::centred);
  216546. double dx = 0, dy = 0, dw = width, dh = height;
  216547. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216548. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216549. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216550. g.saveState();
  216551. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216552. g.fillAll (Colours::black);
  216553. g.restoreState();
  216554. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216555. }
  216556. bool createFileCaptureFilter (const File& file)
  216557. {
  216558. removeFileCaptureFilter();
  216559. file.deleteFile();
  216560. mediaControl->Stop();
  216561. firstRecordedTime = Time();
  216562. recordNextFrameTime = true;
  216563. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216564. if (SUCCEEDED (hr))
  216565. {
  216566. ComSmartPtr <IFileSinkFilter> fileSink;
  216567. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  216568. if (SUCCEEDED (hr))
  216569. {
  216570. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  216571. if (SUCCEEDED (hr))
  216572. {
  216573. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216574. if (SUCCEEDED (hr))
  216575. {
  216576. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216577. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  216578. asfConfig->SetIndexMode (true);
  216579. ComSmartPtr <IWMProfileManager> profileManager;
  216580. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  216581. // This gibberish is the DirectShow profile for a video-only wmv file.
  216582. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  216583. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  216584. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216585. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  216586. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  216587. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  216588. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  216589. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  216590. prof = prof.replace ("$WIDTH", String (width))
  216591. .replace ("$HEIGHT", String (height));
  216592. ComSmartPtr <IWMProfile> currentProfile;
  216593. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, currentProfile.resetAndGetPointerAddress());
  216594. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216595. if (SUCCEEDED (hr))
  216596. {
  216597. ComSmartPtr <IPin> asfWriterInputPin;
  216598. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  216599. {
  216600. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216601. if (SUCCEEDED (hr)
  216602. && ok && activeUsers > 0
  216603. && SUCCEEDED (mediaControl->Run()))
  216604. {
  216605. return true;
  216606. }
  216607. }
  216608. }
  216609. }
  216610. }
  216611. }
  216612. }
  216613. removeFileCaptureFilter();
  216614. if (ok && activeUsers > 0)
  216615. mediaControl->Run();
  216616. return false;
  216617. }
  216618. void removeFileCaptureFilter()
  216619. {
  216620. mediaControl->Stop();
  216621. if (asfWriter != 0)
  216622. {
  216623. graphBuilder->RemoveFilter (asfWriter);
  216624. asfWriter = 0;
  216625. }
  216626. if (ok && activeUsers > 0)
  216627. mediaControl->Run();
  216628. }
  216629. void addListener (CameraDevice::Listener* listenerToAdd)
  216630. {
  216631. const ScopedLock sl (listenerLock);
  216632. if (listeners.size() == 0)
  216633. addUser();
  216634. listeners.addIfNotAlreadyThere (listenerToAdd);
  216635. }
  216636. void removeListener (CameraDevice::Listener* listenerToRemove)
  216637. {
  216638. const ScopedLock sl (listenerLock);
  216639. listeners.removeValue (listenerToRemove);
  216640. if (listeners.size() == 0)
  216641. removeUser();
  216642. }
  216643. void callListeners (const Image& image)
  216644. {
  216645. const ScopedLock sl (listenerLock);
  216646. for (int i = listeners.size(); --i >= 0;)
  216647. {
  216648. CameraDevice::Listener* const l = listeners[i];
  216649. if (l != 0)
  216650. l->imageReceived (image);
  216651. }
  216652. }
  216653. class DShowCaptureViewerComp : public Component,
  216654. public ChangeListener
  216655. {
  216656. public:
  216657. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216658. : owner (owner_)
  216659. {
  216660. setOpaque (true);
  216661. owner->addChangeListener (this);
  216662. owner->addUser();
  216663. owner->viewerComps.add (this);
  216664. setSize (owner->width, owner->height);
  216665. }
  216666. ~DShowCaptureViewerComp()
  216667. {
  216668. if (owner != 0)
  216669. {
  216670. owner->viewerComps.removeValue (this);
  216671. owner->removeUser();
  216672. owner->removeChangeListener (this);
  216673. }
  216674. }
  216675. void ownerDeleted()
  216676. {
  216677. owner = 0;
  216678. }
  216679. void paint (Graphics& g)
  216680. {
  216681. g.setColour (Colours::black);
  216682. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216683. if (owner != 0)
  216684. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216685. else
  216686. g.fillAll (Colours::black);
  216687. }
  216688. void changeListenerCallback (void*)
  216689. {
  216690. repaint();
  216691. }
  216692. private:
  216693. DShowCameraDeviceInteral* owner;
  216694. };
  216695. bool ok;
  216696. int width, height;
  216697. Time firstRecordedTime;
  216698. Array <DShowCaptureViewerComp*> viewerComps;
  216699. private:
  216700. CameraDevice* const owner;
  216701. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216702. ComSmartPtr <IBaseFilter> filter;
  216703. ComSmartPtr <IBaseFilter> smartTee;
  216704. ComSmartPtr <IGraphBuilder> graphBuilder;
  216705. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216706. ComSmartPtr <IMediaControl> mediaControl;
  216707. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216708. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216709. ComSmartPtr <IBaseFilter> asfWriter;
  216710. int activeUsers;
  216711. Array <int> widths, heights;
  216712. DWORD graphRegistrationID;
  216713. CriticalSection imageSwapLock;
  216714. bool imageNeedsFlipping;
  216715. Image loadingImage;
  216716. Image activeImage;
  216717. bool recordNextFrameTime;
  216718. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216719. {
  216720. widths.clear();
  216721. heights.clear();
  216722. int count = 0, size = 0;
  216723. streamConfig->GetNumberOfCapabilities (&count, &size);
  216724. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216725. {
  216726. for (int i = 0; i < count; ++i)
  216727. {
  216728. VIDEO_STREAM_CONFIG_CAPS scc;
  216729. AM_MEDIA_TYPE* config;
  216730. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216731. if (SUCCEEDED (hr))
  216732. {
  216733. const int w = scc.InputSize.cx;
  216734. const int h = scc.InputSize.cy;
  216735. bool duplicate = false;
  216736. for (int j = widths.size(); --j >= 0;)
  216737. {
  216738. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216739. {
  216740. duplicate = true;
  216741. break;
  216742. }
  216743. }
  216744. if (! duplicate)
  216745. {
  216746. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216747. widths.add (w);
  216748. heights.add (h);
  216749. }
  216750. deleteMediaType (config);
  216751. }
  216752. }
  216753. }
  216754. }
  216755. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216756. const int minWidth, const int minHeight,
  216757. const int maxWidth, const int maxHeight)
  216758. {
  216759. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216760. streamConfig->GetNumberOfCapabilities (&count, &size);
  216761. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216762. {
  216763. AM_MEDIA_TYPE* config;
  216764. VIDEO_STREAM_CONFIG_CAPS scc;
  216765. for (int i = 0; i < count; ++i)
  216766. {
  216767. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216768. if (SUCCEEDED (hr))
  216769. {
  216770. if (scc.InputSize.cx >= minWidth
  216771. && scc.InputSize.cy >= minHeight
  216772. && scc.InputSize.cx <= maxWidth
  216773. && scc.InputSize.cy <= maxHeight)
  216774. {
  216775. int area = scc.InputSize.cx * scc.InputSize.cy;
  216776. if (area > bestArea)
  216777. {
  216778. bestIndex = i;
  216779. bestArea = area;
  216780. }
  216781. }
  216782. deleteMediaType (config);
  216783. }
  216784. }
  216785. if (bestIndex >= 0)
  216786. {
  216787. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216788. hr = streamConfig->SetFormat (config);
  216789. deleteMediaType (config);
  216790. return SUCCEEDED (hr);
  216791. }
  216792. }
  216793. return false;
  216794. }
  216795. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  216796. {
  216797. ComSmartPtr <IEnumPins> enumerator;
  216798. ComSmartPtr <IPin> pin;
  216799. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  216800. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  216801. {
  216802. PIN_DIRECTION dir;
  216803. pin->QueryDirection (&dir);
  216804. if (wantedDirection == dir)
  216805. {
  216806. PIN_INFO info;
  216807. zerostruct (info);
  216808. pin->QueryPinInfo (&info);
  216809. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  216810. {
  216811. result = pin;
  216812. return true;
  216813. }
  216814. }
  216815. }
  216816. return false;
  216817. }
  216818. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  216819. {
  216820. ComSmartPtr <IPin> in, out;
  216821. return getPin (first, PINDIR_OUTPUT, out)
  216822. && getPin (second, PINDIR_INPUT, in)
  216823. && SUCCEEDED (graphBuilder->Connect (out, in));
  216824. }
  216825. bool addGraphToRot()
  216826. {
  216827. ComSmartPtr <IRunningObjectTable> rot;
  216828. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216829. return false;
  216830. ComSmartPtr <IMoniker> moniker;
  216831. WCHAR buffer[128];
  216832. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  216833. if (FAILED (hr))
  216834. return false;
  216835. graphRegistrationID = 0;
  216836. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  216837. }
  216838. void removeGraphFromRot()
  216839. {
  216840. ComSmartPtr <IRunningObjectTable> rot;
  216841. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216842. rot->Revoke (graphRegistrationID);
  216843. }
  216844. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  216845. {
  216846. if (pmt->cbFormat != 0)
  216847. CoTaskMemFree ((PVOID) pmt->pbFormat);
  216848. if (pmt->pUnk != 0)
  216849. pmt->pUnk->Release();
  216850. CoTaskMemFree (pmt);
  216851. }
  216852. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  216853. {
  216854. public:
  216855. GrabberCallback (DShowCameraDeviceInteral& owner_)
  216856. : owner (owner_)
  216857. {
  216858. }
  216859. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  216860. {
  216861. return E_FAIL;
  216862. }
  216863. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  216864. {
  216865. owner.handleFrame (time, buffer, bufferSize);
  216866. return S_OK;
  216867. }
  216868. private:
  216869. DShowCameraDeviceInteral& owner;
  216870. GrabberCallback (const GrabberCallback&);
  216871. GrabberCallback& operator= (const GrabberCallback&);
  216872. };
  216873. ComSmartPtr <GrabberCallback> callback;
  216874. Array <CameraDevice::Listener*> listeners;
  216875. CriticalSection listenerLock;
  216876. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  216877. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  216878. };
  216879. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  216880. : name (name_)
  216881. {
  216882. isRecording = false;
  216883. }
  216884. CameraDevice::~CameraDevice()
  216885. {
  216886. stopRecording();
  216887. delete static_cast <DShowCameraDeviceInteral*> (internal);
  216888. internal = 0;
  216889. }
  216890. Component* CameraDevice::createViewerComponent()
  216891. {
  216892. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  216893. }
  216894. const String CameraDevice::getFileExtension()
  216895. {
  216896. return ".wmv";
  216897. }
  216898. void CameraDevice::startRecordingToFile (const File& file, int quality)
  216899. {
  216900. stopRecording();
  216901. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216902. d->addUser();
  216903. isRecording = d->createFileCaptureFilter (file);
  216904. }
  216905. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  216906. {
  216907. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216908. return d->firstRecordedTime;
  216909. }
  216910. void CameraDevice::stopRecording()
  216911. {
  216912. if (isRecording)
  216913. {
  216914. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216915. d->removeFileCaptureFilter();
  216916. d->removeUser();
  216917. isRecording = false;
  216918. }
  216919. }
  216920. void CameraDevice::addListener (Listener* listenerToAdd)
  216921. {
  216922. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216923. if (listenerToAdd != 0)
  216924. d->addListener (listenerToAdd);
  216925. }
  216926. void CameraDevice::removeListener (Listener* listenerToRemove)
  216927. {
  216928. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216929. if (listenerToRemove != 0)
  216930. d->removeListener (listenerToRemove);
  216931. }
  216932. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  216933. const int deviceIndexToOpen,
  216934. String& name)
  216935. {
  216936. int index = 0;
  216937. ComSmartPtr <IBaseFilter> result;
  216938. ComSmartPtr <ICreateDevEnum> pDevEnum;
  216939. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  216940. if (SUCCEEDED (hr))
  216941. {
  216942. ComSmartPtr <IEnumMoniker> enumerator;
  216943. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  216944. if (SUCCEEDED (hr) && enumerator != 0)
  216945. {
  216946. ComSmartPtr <IMoniker> moniker;
  216947. ULONG fetched;
  216948. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  216949. {
  216950. ComSmartPtr <IBaseFilter> captureFilter;
  216951. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  216952. if (SUCCEEDED (hr))
  216953. {
  216954. ComSmartPtr <IPropertyBag> propertyBag;
  216955. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  216956. if (SUCCEEDED (hr))
  216957. {
  216958. VARIANT var;
  216959. var.vt = VT_BSTR;
  216960. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  216961. propertyBag = 0;
  216962. if (SUCCEEDED (hr))
  216963. {
  216964. if (names != 0)
  216965. names->add (var.bstrVal);
  216966. if (index == deviceIndexToOpen)
  216967. {
  216968. name = var.bstrVal;
  216969. result = captureFilter;
  216970. break;
  216971. }
  216972. ++index;
  216973. }
  216974. }
  216975. }
  216976. }
  216977. }
  216978. }
  216979. return result;
  216980. }
  216981. const StringArray CameraDevice::getAvailableDevices()
  216982. {
  216983. StringArray devs;
  216984. String dummy;
  216985. enumerateCameras (&devs, -1, dummy);
  216986. return devs;
  216987. }
  216988. CameraDevice* CameraDevice::openDevice (int index,
  216989. int minWidth, int minHeight,
  216990. int maxWidth, int maxHeight)
  216991. {
  216992. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216993. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  216994. if (SUCCEEDED (hr))
  216995. {
  216996. String name;
  216997. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  216998. if (filter != 0)
  216999. {
  217000. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  217001. DShowCameraDeviceInteral* const intern
  217002. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  217003. minWidth, minHeight, maxWidth, maxHeight);
  217004. cam->internal = intern;
  217005. if (intern->ok)
  217006. return cam.release();
  217007. }
  217008. }
  217009. return 0;
  217010. }
  217011. #endif
  217012. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  217013. #endif
  217014. // Auto-link the other win32 libs that are needed by library calls..
  217015. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  217016. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217017. // Auto-links to various win32 libs that are needed by library calls..
  217018. #pragma comment(lib, "kernel32.lib")
  217019. #pragma comment(lib, "user32.lib")
  217020. #pragma comment(lib, "shell32.lib")
  217021. #pragma comment(lib, "gdi32.lib")
  217022. #pragma comment(lib, "vfw32.lib")
  217023. #pragma comment(lib, "comdlg32.lib")
  217024. #pragma comment(lib, "winmm.lib")
  217025. #pragma comment(lib, "wininet.lib")
  217026. #pragma comment(lib, "ole32.lib")
  217027. #pragma comment(lib, "oleaut32.lib")
  217028. #pragma comment(lib, "advapi32.lib")
  217029. #pragma comment(lib, "ws2_32.lib")
  217030. #pragma comment(lib, "version.lib")
  217031. #ifdef _NATIVE_WCHAR_T_DEFINED
  217032. #ifdef _DEBUG
  217033. #pragma comment(lib, "comsuppwd.lib")
  217034. #else
  217035. #pragma comment(lib, "comsuppw.lib")
  217036. #endif
  217037. #else
  217038. #ifdef _DEBUG
  217039. #pragma comment(lib, "comsuppd.lib")
  217040. #else
  217041. #pragma comment(lib, "comsupp.lib")
  217042. #endif
  217043. #endif
  217044. #if JUCE_OPENGL
  217045. #pragma comment(lib, "OpenGL32.Lib")
  217046. #pragma comment(lib, "GlU32.Lib")
  217047. #endif
  217048. #if JUCE_QUICKTIME
  217049. #pragma comment (lib, "QTMLClient.lib")
  217050. #endif
  217051. #if JUCE_USE_CAMERA
  217052. #pragma comment (lib, "Strmiids.lib")
  217053. #pragma comment (lib, "wmvcore.lib")
  217054. #endif
  217055. #if JUCE_DIRECT2D
  217056. #pragma comment (lib, "Dwrite.lib")
  217057. #pragma comment (lib, "D2d1.lib")
  217058. #endif
  217059. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217060. #endif
  217061. END_JUCE_NAMESPACE
  217062. #endif
  217063. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  217064. #endif
  217065. #if JUCE_LINUX
  217066. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  217067. /*
  217068. This file wraps together all the mac-specific code, so that
  217069. we can include all the native headers just once, and compile all our
  217070. platform-specific stuff in one big lump, keeping it out of the way of
  217071. the rest of the codebase.
  217072. */
  217073. #if JUCE_LINUX
  217074. BEGIN_JUCE_NAMESPACE
  217075. #define JUCE_INCLUDED_FILE 1
  217076. // Now include the actual code files..
  217077. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  217078. /*
  217079. This file contains posix routines that are common to both the Linux and Mac builds.
  217080. It gets included directly in the cpp files for these platforms.
  217081. */
  217082. CriticalSection::CriticalSection() throw()
  217083. {
  217084. pthread_mutexattr_t atts;
  217085. pthread_mutexattr_init (&atts);
  217086. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  217087. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217088. pthread_mutex_init (&internal, &atts);
  217089. }
  217090. CriticalSection::~CriticalSection() throw()
  217091. {
  217092. pthread_mutex_destroy (&internal);
  217093. }
  217094. void CriticalSection::enter() const throw()
  217095. {
  217096. pthread_mutex_lock (&internal);
  217097. }
  217098. bool CriticalSection::tryEnter() const throw()
  217099. {
  217100. return pthread_mutex_trylock (&internal) == 0;
  217101. }
  217102. void CriticalSection::exit() const throw()
  217103. {
  217104. pthread_mutex_unlock (&internal);
  217105. }
  217106. class WaitableEventImpl
  217107. {
  217108. public:
  217109. WaitableEventImpl (const bool manualReset_)
  217110. : triggered (false),
  217111. manualReset (manualReset_)
  217112. {
  217113. pthread_cond_init (&condition, 0);
  217114. pthread_mutexattr_t atts;
  217115. pthread_mutexattr_init (&atts);
  217116. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217117. pthread_mutex_init (&mutex, &atts);
  217118. }
  217119. ~WaitableEventImpl()
  217120. {
  217121. pthread_cond_destroy (&condition);
  217122. pthread_mutex_destroy (&mutex);
  217123. }
  217124. bool wait (const int timeOutMillisecs) throw()
  217125. {
  217126. pthread_mutex_lock (&mutex);
  217127. if (! triggered)
  217128. {
  217129. if (timeOutMillisecs < 0)
  217130. {
  217131. do
  217132. {
  217133. pthread_cond_wait (&condition, &mutex);
  217134. }
  217135. while (! triggered);
  217136. }
  217137. else
  217138. {
  217139. struct timeval now;
  217140. gettimeofday (&now, 0);
  217141. struct timespec time;
  217142. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  217143. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  217144. if (time.tv_nsec >= 1000000000)
  217145. {
  217146. time.tv_nsec -= 1000000000;
  217147. time.tv_sec++;
  217148. }
  217149. do
  217150. {
  217151. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  217152. {
  217153. pthread_mutex_unlock (&mutex);
  217154. return false;
  217155. }
  217156. }
  217157. while (! triggered);
  217158. }
  217159. }
  217160. if (! manualReset)
  217161. triggered = false;
  217162. pthread_mutex_unlock (&mutex);
  217163. return true;
  217164. }
  217165. void signal() throw()
  217166. {
  217167. pthread_mutex_lock (&mutex);
  217168. triggered = true;
  217169. pthread_cond_broadcast (&condition);
  217170. pthread_mutex_unlock (&mutex);
  217171. }
  217172. void reset() throw()
  217173. {
  217174. pthread_mutex_lock (&mutex);
  217175. triggered = false;
  217176. pthread_mutex_unlock (&mutex);
  217177. }
  217178. private:
  217179. pthread_cond_t condition;
  217180. pthread_mutex_t mutex;
  217181. bool triggered;
  217182. const bool manualReset;
  217183. WaitableEventImpl (const WaitableEventImpl&);
  217184. WaitableEventImpl& operator= (const WaitableEventImpl&);
  217185. };
  217186. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  217187. : internal (new WaitableEventImpl (manualReset))
  217188. {
  217189. }
  217190. WaitableEvent::~WaitableEvent() throw()
  217191. {
  217192. delete static_cast <WaitableEventImpl*> (internal);
  217193. }
  217194. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  217195. {
  217196. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  217197. }
  217198. void WaitableEvent::signal() const throw()
  217199. {
  217200. static_cast <WaitableEventImpl*> (internal)->signal();
  217201. }
  217202. void WaitableEvent::reset() const throw()
  217203. {
  217204. static_cast <WaitableEventImpl*> (internal)->reset();
  217205. }
  217206. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  217207. {
  217208. struct timespec time;
  217209. time.tv_sec = millisecs / 1000;
  217210. time.tv_nsec = (millisecs % 1000) * 1000000;
  217211. nanosleep (&time, 0);
  217212. }
  217213. const juce_wchar File::separator = '/';
  217214. const String File::separatorString ("/");
  217215. const File File::getCurrentWorkingDirectory()
  217216. {
  217217. HeapBlock<char> heapBuffer;
  217218. char localBuffer [1024];
  217219. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  217220. int bufferSize = 4096;
  217221. while (cwd == 0 && errno == ERANGE)
  217222. {
  217223. heapBuffer.malloc (bufferSize);
  217224. cwd = getcwd (heapBuffer, bufferSize - 1);
  217225. bufferSize += 1024;
  217226. }
  217227. return File (String::fromUTF8 (cwd));
  217228. }
  217229. bool File::setAsCurrentWorkingDirectory() const
  217230. {
  217231. return chdir (getFullPathName().toUTF8()) == 0;
  217232. }
  217233. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217234. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  217235. #else
  217236. typedef struct stat juce_statStruct;
  217237. #endif
  217238. static bool juce_stat (const String& fileName, juce_statStruct& info)
  217239. {
  217240. return fileName.isNotEmpty()
  217241. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217242. && (stat64 (fileName.toUTF8(), &info) == 0);
  217243. #else
  217244. && (stat (fileName.toUTF8(), &info) == 0);
  217245. #endif
  217246. }
  217247. bool File::isDirectory() const
  217248. {
  217249. juce_statStruct info;
  217250. return fullPath.isEmpty()
  217251. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  217252. }
  217253. bool File::exists() const
  217254. {
  217255. juce_statStruct info;
  217256. return fullPath.isNotEmpty()
  217257. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217258. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  217259. #else
  217260. && (lstat (fullPath.toUTF8(), &info) == 0);
  217261. #endif
  217262. }
  217263. bool File::existsAsFile() const
  217264. {
  217265. return exists() && ! isDirectory();
  217266. }
  217267. int64 File::getSize() const
  217268. {
  217269. juce_statStruct info;
  217270. return juce_stat (fullPath, info) ? info.st_size : 0;
  217271. }
  217272. bool File::hasWriteAccess() const
  217273. {
  217274. if (exists())
  217275. return access (fullPath.toUTF8(), W_OK) == 0;
  217276. if ((! isDirectory()) && fullPath.containsChar (separator))
  217277. return getParentDirectory().hasWriteAccess();
  217278. return false;
  217279. }
  217280. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  217281. {
  217282. juce_statStruct info;
  217283. if (! juce_stat (fullPath, info))
  217284. return false;
  217285. info.st_mode &= 0777; // Just permissions
  217286. if (shouldBeReadOnly)
  217287. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  217288. else
  217289. // Give everybody write permission?
  217290. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  217291. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  217292. }
  217293. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  217294. {
  217295. modificationTime = 0;
  217296. accessTime = 0;
  217297. creationTime = 0;
  217298. juce_statStruct info;
  217299. if (juce_stat (fullPath, info))
  217300. {
  217301. modificationTime = (int64) info.st_mtime * 1000;
  217302. accessTime = (int64) info.st_atime * 1000;
  217303. creationTime = (int64) info.st_ctime * 1000;
  217304. }
  217305. }
  217306. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  217307. {
  217308. struct utimbuf times;
  217309. times.actime = (time_t) (accessTime / 1000);
  217310. times.modtime = (time_t) (modificationTime / 1000);
  217311. return utime (fullPath.toUTF8(), &times) == 0;
  217312. }
  217313. bool File::deleteFile() const
  217314. {
  217315. if (! exists())
  217316. return true;
  217317. else if (isDirectory())
  217318. return rmdir (fullPath.toUTF8()) == 0;
  217319. else
  217320. return remove (fullPath.toUTF8()) == 0;
  217321. }
  217322. bool File::moveInternal (const File& dest) const
  217323. {
  217324. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  217325. return true;
  217326. if (hasWriteAccess() && copyInternal (dest))
  217327. {
  217328. if (deleteFile())
  217329. return true;
  217330. dest.deleteFile();
  217331. }
  217332. return false;
  217333. }
  217334. void File::createDirectoryInternal (const String& fileName) const
  217335. {
  217336. mkdir (fileName.toUTF8(), 0777);
  217337. }
  217338. int64 juce_fileSetPosition (void* handle, int64 pos)
  217339. {
  217340. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  217341. return pos;
  217342. return -1;
  217343. }
  217344. void FileInputStream::openHandle()
  217345. {
  217346. totalSize = file.getSize();
  217347. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  217348. if (f != -1)
  217349. fileHandle = (void*) f;
  217350. }
  217351. void FileInputStream::closeHandle()
  217352. {
  217353. if (fileHandle != 0)
  217354. {
  217355. close ((int) (pointer_sized_int) fileHandle);
  217356. fileHandle = 0;
  217357. }
  217358. }
  217359. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  217360. {
  217361. if (fileHandle != 0)
  217362. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  217363. return 0;
  217364. }
  217365. void FileOutputStream::openHandle()
  217366. {
  217367. if (file.exists())
  217368. {
  217369. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  217370. if (f != -1)
  217371. {
  217372. currentPosition = lseek (f, 0, SEEK_END);
  217373. if (currentPosition >= 0)
  217374. fileHandle = (void*) f;
  217375. else
  217376. close (f);
  217377. }
  217378. }
  217379. else
  217380. {
  217381. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  217382. if (f != -1)
  217383. fileHandle = (void*) f;
  217384. }
  217385. }
  217386. void FileOutputStream::closeHandle()
  217387. {
  217388. if (fileHandle != 0)
  217389. {
  217390. close ((int) (pointer_sized_int) fileHandle);
  217391. fileHandle = 0;
  217392. }
  217393. }
  217394. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  217395. {
  217396. if (fileHandle != 0)
  217397. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  217398. return 0;
  217399. }
  217400. void FileOutputStream::flushInternal()
  217401. {
  217402. if (fileHandle != 0)
  217403. fsync ((int) (pointer_sized_int) fileHandle);
  217404. }
  217405. const File juce_getExecutableFile()
  217406. {
  217407. Dl_info exeInfo;
  217408. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  217409. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  217410. }
  217411. // if this file doesn't exist, find a parent of it that does..
  217412. static bool juce_doStatFS (File f, struct statfs& result)
  217413. {
  217414. for (int i = 5; --i >= 0;)
  217415. {
  217416. if (f.exists())
  217417. break;
  217418. f = f.getParentDirectory();
  217419. }
  217420. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  217421. }
  217422. int64 File::getBytesFreeOnVolume() const
  217423. {
  217424. struct statfs buf;
  217425. if (juce_doStatFS (*this, buf))
  217426. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  217427. return 0;
  217428. }
  217429. int64 File::getVolumeTotalSize() const
  217430. {
  217431. struct statfs buf;
  217432. if (juce_doStatFS (*this, buf))
  217433. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  217434. return 0;
  217435. }
  217436. const String File::getVolumeLabel() const
  217437. {
  217438. #if JUCE_MAC
  217439. struct VolAttrBuf
  217440. {
  217441. u_int32_t length;
  217442. attrreference_t mountPointRef;
  217443. char mountPointSpace [MAXPATHLEN];
  217444. } attrBuf;
  217445. struct attrlist attrList;
  217446. zerostruct (attrList);
  217447. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217448. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217449. File f (*this);
  217450. for (;;)
  217451. {
  217452. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217453. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217454. (int) attrBuf.mountPointRef.attr_length);
  217455. const File parent (f.getParentDirectory());
  217456. if (f == parent)
  217457. break;
  217458. f = parent;
  217459. }
  217460. #endif
  217461. return String::empty;
  217462. }
  217463. int File::getVolumeSerialNumber() const
  217464. {
  217465. return 0; // xxx
  217466. }
  217467. void juce_runSystemCommand (const String& command)
  217468. {
  217469. int result = system (command.toUTF8());
  217470. (void) result;
  217471. }
  217472. const String juce_getOutputFromCommand (const String& command)
  217473. {
  217474. // slight bodge here, as we just pipe the output into a temp file and read it...
  217475. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217476. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217477. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217478. String result (tempFile.loadFileAsString());
  217479. tempFile.deleteFile();
  217480. return result;
  217481. }
  217482. class InterProcessLock::Pimpl
  217483. {
  217484. public:
  217485. Pimpl (const String& name, const int timeOutMillisecs)
  217486. : handle (0), refCount (1)
  217487. {
  217488. #if JUCE_MAC
  217489. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217490. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217491. #else
  217492. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217493. #endif
  217494. temp.create();
  217495. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217496. if (handle != 0)
  217497. {
  217498. struct flock fl;
  217499. zerostruct (fl);
  217500. fl.l_whence = SEEK_SET;
  217501. fl.l_type = F_WRLCK;
  217502. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217503. for (;;)
  217504. {
  217505. const int result = fcntl (handle, F_SETLK, &fl);
  217506. if (result >= 0)
  217507. return;
  217508. if (errno != EINTR)
  217509. {
  217510. if (timeOutMillisecs == 0
  217511. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217512. break;
  217513. Thread::sleep (10);
  217514. }
  217515. }
  217516. }
  217517. closeFile();
  217518. }
  217519. ~Pimpl()
  217520. {
  217521. closeFile();
  217522. }
  217523. void closeFile()
  217524. {
  217525. if (handle != 0)
  217526. {
  217527. struct flock fl;
  217528. zerostruct (fl);
  217529. fl.l_whence = SEEK_SET;
  217530. fl.l_type = F_UNLCK;
  217531. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217532. {}
  217533. close (handle);
  217534. handle = 0;
  217535. }
  217536. }
  217537. int handle, refCount;
  217538. };
  217539. InterProcessLock::InterProcessLock (const String& name_)
  217540. : name (name_)
  217541. {
  217542. }
  217543. InterProcessLock::~InterProcessLock()
  217544. {
  217545. }
  217546. bool InterProcessLock::enter (const int timeOutMillisecs)
  217547. {
  217548. const ScopedLock sl (lock);
  217549. if (pimpl == 0)
  217550. {
  217551. pimpl = new Pimpl (name, timeOutMillisecs);
  217552. if (pimpl->handle == 0)
  217553. pimpl = 0;
  217554. }
  217555. else
  217556. {
  217557. pimpl->refCount++;
  217558. }
  217559. return pimpl != 0;
  217560. }
  217561. void InterProcessLock::exit()
  217562. {
  217563. const ScopedLock sl (lock);
  217564. // Trying to release the lock too many times!
  217565. jassert (pimpl != 0);
  217566. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217567. pimpl = 0;
  217568. }
  217569. void JUCE_API juce_threadEntryPoint (void*);
  217570. void* threadEntryProc (void* userData)
  217571. {
  217572. JUCE_AUTORELEASEPOOL
  217573. juce_threadEntryPoint (userData);
  217574. return 0;
  217575. }
  217576. void* juce_createThread (void* userData)
  217577. {
  217578. pthread_t handle = 0;
  217579. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217580. {
  217581. pthread_detach (handle);
  217582. return (void*) handle;
  217583. }
  217584. return 0;
  217585. }
  217586. void juce_killThread (void* handle)
  217587. {
  217588. if (handle != 0)
  217589. pthread_cancel ((pthread_t) handle);
  217590. }
  217591. void juce_setCurrentThreadName (const String& /*name*/)
  217592. {
  217593. }
  217594. bool juce_setThreadPriority (void* handle, int priority)
  217595. {
  217596. struct sched_param param;
  217597. int policy;
  217598. priority = jlimit (0, 10, priority);
  217599. if (handle == 0)
  217600. handle = (void*) pthread_self();
  217601. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217602. return false;
  217603. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217604. const int minPriority = sched_get_priority_min (policy);
  217605. const int maxPriority = sched_get_priority_max (policy);
  217606. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217607. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217608. }
  217609. Thread::ThreadID Thread::getCurrentThreadId()
  217610. {
  217611. return (ThreadID) pthread_self();
  217612. }
  217613. void Thread::yield()
  217614. {
  217615. sched_yield();
  217616. }
  217617. /* Remove this macro if you're having problems compiling the cpu affinity
  217618. calls (the API for these has changed about quite a bit in various Linux
  217619. versions, and a lot of distros seem to ship with obsolete versions)
  217620. */
  217621. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217622. #define SUPPORT_AFFINITIES 1
  217623. #endif
  217624. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217625. {
  217626. #if SUPPORT_AFFINITIES
  217627. cpu_set_t affinity;
  217628. CPU_ZERO (&affinity);
  217629. for (int i = 0; i < 32; ++i)
  217630. if ((affinityMask & (1 << i)) != 0)
  217631. CPU_SET (i, &affinity);
  217632. /*
  217633. N.B. If this line causes a compile error, then you've probably not got the latest
  217634. version of glibc installed.
  217635. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217636. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217637. */
  217638. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217639. sched_yield();
  217640. #else
  217641. /* affinities aren't supported because either the appropriate header files weren't found,
  217642. or the SUPPORT_AFFINITIES macro was turned off
  217643. */
  217644. jassertfalse;
  217645. #endif
  217646. }
  217647. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217648. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217649. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217650. // compiled on its own).
  217651. #if JUCE_INCLUDED_FILE
  217652. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  217653. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  217654. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  217655. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  217656. bool File::copyInternal (const File& dest) const
  217657. {
  217658. FileInputStream in (*this);
  217659. if (dest.deleteFile())
  217660. {
  217661. {
  217662. FileOutputStream out (dest);
  217663. if (out.failedToOpen())
  217664. return false;
  217665. if (out.writeFromInputStream (in, -1) == getSize())
  217666. return true;
  217667. }
  217668. dest.deleteFile();
  217669. }
  217670. return false;
  217671. }
  217672. void File::findFileSystemRoots (Array<File>& destArray)
  217673. {
  217674. destArray.add (File ("/"));
  217675. }
  217676. bool File::isOnCDRomDrive() const
  217677. {
  217678. struct statfs buf;
  217679. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217680. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  217681. }
  217682. bool File::isOnHardDisk() const
  217683. {
  217684. struct statfs buf;
  217685. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217686. {
  217687. switch (buf.f_type)
  217688. {
  217689. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217690. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217691. case U_NFS_SUPER_MAGIC: // Network NFS
  217692. case U_SMB_SUPER_MAGIC: // Network Samba
  217693. return false;
  217694. default:
  217695. // Assume anything else is a hard-disk (but note it could
  217696. // be a RAM disk. There isn't a good way of determining
  217697. // this for sure)
  217698. return true;
  217699. }
  217700. }
  217701. // Assume so if this fails for some reason
  217702. return true;
  217703. }
  217704. bool File::isOnRemovableDrive() const
  217705. {
  217706. jassertfalse; // xxx not implemented for linux!
  217707. return false;
  217708. }
  217709. bool File::isHidden() const
  217710. {
  217711. return getFileName().startsWithChar ('.');
  217712. }
  217713. static const File juce_readlink (const String& file, const File& defaultFile)
  217714. {
  217715. const int size = 8192;
  217716. HeapBlock<char> buffer;
  217717. buffer.malloc (size + 4);
  217718. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  217719. if (numBytes > 0 && numBytes <= size)
  217720. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  217721. return defaultFile;
  217722. }
  217723. const File File::getLinkedTarget() const
  217724. {
  217725. return juce_readlink (getFullPathName().toUTF8(), *this);
  217726. }
  217727. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217728. const File File::getSpecialLocation (const SpecialLocationType type)
  217729. {
  217730. switch (type)
  217731. {
  217732. case userHomeDirectory:
  217733. {
  217734. const char* homeDir = getenv ("HOME");
  217735. if (homeDir == 0)
  217736. {
  217737. struct passwd* const pw = getpwuid (getuid());
  217738. if (pw != 0)
  217739. homeDir = pw->pw_dir;
  217740. }
  217741. return File (String::fromUTF8 (homeDir));
  217742. }
  217743. case userDocumentsDirectory:
  217744. case userMusicDirectory:
  217745. case userMoviesDirectory:
  217746. case userApplicationDataDirectory:
  217747. return File ("~");
  217748. case userDesktopDirectory:
  217749. return File ("~/Desktop");
  217750. case commonApplicationDataDirectory:
  217751. return File ("/var");
  217752. case globalApplicationsDirectory:
  217753. return File ("/usr");
  217754. case tempDirectory:
  217755. {
  217756. File tmp ("/var/tmp");
  217757. if (! tmp.isDirectory())
  217758. {
  217759. tmp = "/tmp";
  217760. if (! tmp.isDirectory())
  217761. tmp = File::getCurrentWorkingDirectory();
  217762. }
  217763. return tmp;
  217764. }
  217765. case invokedExecutableFile:
  217766. if (juce_Argv0 != 0)
  217767. return File (String::fromUTF8 (juce_Argv0));
  217768. // deliberate fall-through...
  217769. case currentExecutableFile:
  217770. case currentApplicationFile:
  217771. return juce_getExecutableFile();
  217772. case hostApplicationPath:
  217773. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217774. default:
  217775. jassertfalse; // unknown type?
  217776. break;
  217777. }
  217778. return File::nonexistent;
  217779. }
  217780. const String File::getVersion() const
  217781. {
  217782. return String::empty; // xxx not yet implemented
  217783. }
  217784. bool File::moveToTrash() const
  217785. {
  217786. if (! exists())
  217787. return true;
  217788. File trashCan ("~/.Trash");
  217789. if (! trashCan.isDirectory())
  217790. trashCan = "~/.local/share/Trash/files";
  217791. if (! trashCan.isDirectory())
  217792. return false;
  217793. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217794. getFileExtension()));
  217795. }
  217796. class DirectoryIterator::NativeIterator::Pimpl
  217797. {
  217798. public:
  217799. Pimpl (const File& directory, const String& wildCard_)
  217800. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217801. wildCard (wildCard_),
  217802. dir (opendir (directory.getFullPathName().toUTF8()))
  217803. {
  217804. if (wildCard == "*.*")
  217805. wildCard = "*";
  217806. wildcardUTF8 = wildCard.toUTF8();
  217807. }
  217808. ~Pimpl()
  217809. {
  217810. if (dir != 0)
  217811. closedir (dir);
  217812. }
  217813. bool next (String& filenameFound,
  217814. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217815. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217816. {
  217817. if (dir == 0)
  217818. return false;
  217819. for (;;)
  217820. {
  217821. struct dirent* const de = readdir (dir);
  217822. if (de == 0)
  217823. return false;
  217824. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  217825. {
  217826. filenameFound = String::fromUTF8 (de->d_name);
  217827. const String path (parentDir + filenameFound);
  217828. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  217829. {
  217830. struct stat info;
  217831. const bool statOk = juce_stat (path, info);
  217832. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  217833. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  217834. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  217835. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  217836. }
  217837. if (isHidden != 0)
  217838. *isHidden = filenameFound.startsWithChar ('.');
  217839. if (isReadOnly != 0)
  217840. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  217841. return true;
  217842. }
  217843. }
  217844. }
  217845. private:
  217846. String parentDir, wildCard;
  217847. const char* wildcardUTF8;
  217848. DIR* dir;
  217849. Pimpl (const Pimpl&);
  217850. Pimpl& operator= (const Pimpl&);
  217851. };
  217852. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217853. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217854. {
  217855. }
  217856. DirectoryIterator::NativeIterator::~NativeIterator()
  217857. {
  217858. }
  217859. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217860. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217861. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217862. {
  217863. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  217864. }
  217865. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  217866. {
  217867. String cmdString (fileName.replace (" ", "\\ ",false));
  217868. cmdString << " " << parameters;
  217869. if (URL::isProbablyAWebsiteURL (fileName)
  217870. || cmdString.startsWithIgnoreCase ("file:")
  217871. || URL::isProbablyAnEmailAddress (fileName))
  217872. {
  217873. // create a command that tries to launch a bunch of likely browsers
  217874. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  217875. StringArray cmdLines;
  217876. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  217877. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  217878. cmdString = cmdLines.joinIntoString (" || ");
  217879. }
  217880. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  217881. const int cpid = fork();
  217882. if (cpid == 0)
  217883. {
  217884. setsid();
  217885. // Child process
  217886. execve (argv[0], (char**) argv, environ);
  217887. exit (0);
  217888. }
  217889. return cpid >= 0;
  217890. }
  217891. void File::revealToUser() const
  217892. {
  217893. if (isDirectory())
  217894. startAsProcess();
  217895. else if (getParentDirectory().exists())
  217896. getParentDirectory().startAsProcess();
  217897. }
  217898. #endif
  217899. /*** End of inlined file: juce_linux_Files.cpp ***/
  217900. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  217901. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217902. // compiled on its own).
  217903. #if JUCE_INCLUDED_FILE
  217904. struct NamedPipeInternal
  217905. {
  217906. String pipeInName, pipeOutName;
  217907. int pipeIn, pipeOut;
  217908. bool volatile createdPipe, blocked, stopReadOperation;
  217909. static void signalHandler (int) {}
  217910. };
  217911. void NamedPipe::cancelPendingReads()
  217912. {
  217913. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  217914. {
  217915. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217916. intern->stopReadOperation = true;
  217917. char buffer [1] = { 0 };
  217918. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  217919. (void) bytesWritten;
  217920. int timeout = 2000;
  217921. while (intern->blocked && --timeout >= 0)
  217922. Thread::sleep (2);
  217923. intern->stopReadOperation = false;
  217924. }
  217925. }
  217926. void NamedPipe::close()
  217927. {
  217928. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217929. if (intern != 0)
  217930. {
  217931. internal = 0;
  217932. if (intern->pipeIn != -1)
  217933. ::close (intern->pipeIn);
  217934. if (intern->pipeOut != -1)
  217935. ::close (intern->pipeOut);
  217936. if (intern->createdPipe)
  217937. {
  217938. unlink (intern->pipeInName.toUTF8());
  217939. unlink (intern->pipeOutName.toUTF8());
  217940. }
  217941. delete intern;
  217942. }
  217943. }
  217944. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217945. {
  217946. close();
  217947. NamedPipeInternal* const intern = new NamedPipeInternal();
  217948. internal = intern;
  217949. intern->createdPipe = createPipe;
  217950. intern->blocked = false;
  217951. intern->stopReadOperation = false;
  217952. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217953. siginterrupt (SIGPIPE, 1);
  217954. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217955. intern->pipeInName = pipePath + "_in";
  217956. intern->pipeOutName = pipePath + "_out";
  217957. intern->pipeIn = -1;
  217958. intern->pipeOut = -1;
  217959. if (createPipe)
  217960. {
  217961. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217962. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217963. {
  217964. delete intern;
  217965. internal = 0;
  217966. return false;
  217967. }
  217968. }
  217969. return true;
  217970. }
  217971. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217972. {
  217973. int bytesRead = -1;
  217974. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217975. if (intern != 0)
  217976. {
  217977. intern->blocked = true;
  217978. if (intern->pipeIn == -1)
  217979. {
  217980. if (intern->createdPipe)
  217981. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217982. else
  217983. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217984. if (intern->pipeIn == -1)
  217985. {
  217986. intern->blocked = false;
  217987. return -1;
  217988. }
  217989. }
  217990. bytesRead = 0;
  217991. char* p = static_cast<char*> (destBuffer);
  217992. while (bytesRead < maxBytesToRead)
  217993. {
  217994. const int bytesThisTime = maxBytesToRead - bytesRead;
  217995. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  217996. if (numRead <= 0 || intern->stopReadOperation)
  217997. {
  217998. bytesRead = -1;
  217999. break;
  218000. }
  218001. bytesRead += numRead;
  218002. p += bytesRead;
  218003. }
  218004. intern->blocked = false;
  218005. }
  218006. return bytesRead;
  218007. }
  218008. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  218009. {
  218010. int bytesWritten = -1;
  218011. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218012. if (intern != 0)
  218013. {
  218014. if (intern->pipeOut == -1)
  218015. {
  218016. if (intern->createdPipe)
  218017. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  218018. else
  218019. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  218020. if (intern->pipeOut == -1)
  218021. {
  218022. return -1;
  218023. }
  218024. }
  218025. const char* p = static_cast<const char*> (sourceBuffer);
  218026. bytesWritten = 0;
  218027. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  218028. while (bytesWritten < numBytesToWrite
  218029. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  218030. {
  218031. const int bytesThisTime = numBytesToWrite - bytesWritten;
  218032. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  218033. if (numWritten <= 0)
  218034. {
  218035. bytesWritten = -1;
  218036. break;
  218037. }
  218038. bytesWritten += numWritten;
  218039. p += bytesWritten;
  218040. }
  218041. }
  218042. return bytesWritten;
  218043. }
  218044. #endif
  218045. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  218046. /*** Start of inlined file: juce_linux_Network.cpp ***/
  218047. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218048. // compiled on its own).
  218049. #if JUCE_INCLUDED_FILE
  218050. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  218051. {
  218052. int numResults = 0;
  218053. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  218054. if (s != -1)
  218055. {
  218056. char buf [1024];
  218057. struct ifconf ifc;
  218058. ifc.ifc_len = sizeof (buf);
  218059. ifc.ifc_buf = buf;
  218060. ioctl (s, SIOCGIFCONF, &ifc);
  218061. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  218062. {
  218063. struct ifreq ifr;
  218064. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  218065. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  218066. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  218067. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  218068. && numResults < maxNum)
  218069. {
  218070. int64 a = 0;
  218071. for (int j = 6; --j >= 0;)
  218072. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  218073. *addresses++ = a;
  218074. ++numResults;
  218075. }
  218076. }
  218077. close (s);
  218078. }
  218079. return numResults;
  218080. }
  218081. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  218082. const String& emailSubject,
  218083. const String& bodyText,
  218084. const StringArray& filesToAttach)
  218085. {
  218086. jassertfalse; // xxx todo
  218087. return false;
  218088. }
  218089. /** A HTTP input stream that uses sockets.
  218090. */
  218091. class JUCE_HTTPSocketStream
  218092. {
  218093. public:
  218094. JUCE_HTTPSocketStream()
  218095. : readPosition (0),
  218096. socketHandle (-1),
  218097. levelsOfRedirection (0),
  218098. timeoutSeconds (15)
  218099. {
  218100. }
  218101. ~JUCE_HTTPSocketStream()
  218102. {
  218103. closeSocket();
  218104. }
  218105. bool open (const String& url,
  218106. const String& headers,
  218107. const MemoryBlock& postData,
  218108. const bool isPost,
  218109. URL::OpenStreamProgressCallback* callback,
  218110. void* callbackContext,
  218111. int timeOutMs)
  218112. {
  218113. closeSocket();
  218114. uint32 timeOutTime = Time::getMillisecondCounter();
  218115. if (timeOutMs == 0)
  218116. timeOutTime += 60000;
  218117. else if (timeOutMs < 0)
  218118. timeOutTime = 0xffffffff;
  218119. else
  218120. timeOutTime += timeOutMs;
  218121. String hostName, hostPath;
  218122. int hostPort;
  218123. if (! decomposeURL (url, hostName, hostPath, hostPort))
  218124. return false;
  218125. const struct hostent* host = 0;
  218126. int port = 0;
  218127. String proxyName, proxyPath;
  218128. int proxyPort = 0;
  218129. String proxyURL (getenv ("http_proxy"));
  218130. if (proxyURL.startsWithIgnoreCase ("http://"))
  218131. {
  218132. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  218133. return false;
  218134. host = gethostbyname (proxyName.toUTF8());
  218135. port = proxyPort;
  218136. }
  218137. else
  218138. {
  218139. host = gethostbyname (hostName.toUTF8());
  218140. port = hostPort;
  218141. }
  218142. if (host == 0)
  218143. return false;
  218144. struct sockaddr_in address;
  218145. zerostruct (address);
  218146. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  218147. address.sin_family = host->h_addrtype;
  218148. address.sin_port = htons (port);
  218149. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  218150. if (socketHandle == -1)
  218151. return false;
  218152. int receiveBufferSize = 16384;
  218153. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  218154. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  218155. #if JUCE_MAC
  218156. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  218157. #endif
  218158. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  218159. {
  218160. closeSocket();
  218161. return false;
  218162. }
  218163. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  218164. proxyName, proxyPort,
  218165. hostPath, url,
  218166. headers, postData,
  218167. isPost));
  218168. size_t totalHeaderSent = 0;
  218169. while (totalHeaderSent < requestHeader.getSize())
  218170. {
  218171. if (Time::getMillisecondCounter() > timeOutTime)
  218172. {
  218173. closeSocket();
  218174. return false;
  218175. }
  218176. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  218177. if (send (socketHandle,
  218178. ((const char*) requestHeader.getData()) + totalHeaderSent,
  218179. numToSend, 0)
  218180. != numToSend)
  218181. {
  218182. closeSocket();
  218183. return false;
  218184. }
  218185. totalHeaderSent += numToSend;
  218186. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  218187. {
  218188. closeSocket();
  218189. return false;
  218190. }
  218191. }
  218192. const String responseHeader (readResponse (timeOutTime));
  218193. if (responseHeader.isNotEmpty())
  218194. {
  218195. //DBG (responseHeader);
  218196. headerLines.clear();
  218197. headerLines.addLines (responseHeader);
  218198. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  218199. .substring (0, 3).getIntValue();
  218200. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  218201. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  218202. String location (findHeaderItem (headerLines, "Location:"));
  218203. if (statusCode >= 300 && statusCode < 400
  218204. && location.isNotEmpty())
  218205. {
  218206. if (! location.startsWithIgnoreCase ("http://"))
  218207. location = "http://" + location;
  218208. if (levelsOfRedirection++ < 3)
  218209. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  218210. }
  218211. else
  218212. {
  218213. levelsOfRedirection = 0;
  218214. return true;
  218215. }
  218216. }
  218217. closeSocket();
  218218. return false;
  218219. }
  218220. int read (void* buffer, int bytesToRead)
  218221. {
  218222. fd_set readbits;
  218223. FD_ZERO (&readbits);
  218224. FD_SET (socketHandle, &readbits);
  218225. struct timeval tv;
  218226. tv.tv_sec = timeoutSeconds;
  218227. tv.tv_usec = 0;
  218228. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218229. return 0; // (timeout)
  218230. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  218231. readPosition += bytesRead;
  218232. return bytesRead;
  218233. }
  218234. int readPosition;
  218235. StringArray headerLines;
  218236. juce_UseDebuggingNewOperator
  218237. private:
  218238. int socketHandle, levelsOfRedirection;
  218239. const int timeoutSeconds;
  218240. void closeSocket()
  218241. {
  218242. if (socketHandle >= 0)
  218243. close (socketHandle);
  218244. socketHandle = -1;
  218245. }
  218246. const MemoryBlock createRequestHeader (const String& hostName,
  218247. const int hostPort,
  218248. const String& proxyName,
  218249. const int proxyPort,
  218250. const String& hostPath,
  218251. const String& originalURL,
  218252. const String& headers,
  218253. const MemoryBlock& postData,
  218254. const bool isPost)
  218255. {
  218256. String header (isPost ? "POST " : "GET ");
  218257. if (proxyName.isEmpty())
  218258. {
  218259. header << hostPath << " HTTP/1.0\r\nHost: "
  218260. << hostName << ':' << hostPort;
  218261. }
  218262. else
  218263. {
  218264. header << originalURL << " HTTP/1.0\r\nHost: "
  218265. << proxyName << ':' << proxyPort;
  218266. }
  218267. header << "\r\nUser-Agent: JUCE/"
  218268. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  218269. << "\r\nConnection: Close\r\nContent-Length: "
  218270. << postData.getSize() << "\r\n"
  218271. << headers << "\r\n";
  218272. MemoryBlock mb;
  218273. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  218274. mb.append (postData.getData(), postData.getSize());
  218275. return mb;
  218276. }
  218277. const String readResponse (const uint32 timeOutTime)
  218278. {
  218279. int bytesRead = 0, numConsecutiveLFs = 0;
  218280. MemoryBlock buffer (1024, true);
  218281. while (numConsecutiveLFs < 2 && bytesRead < 32768
  218282. && Time::getMillisecondCounter() <= timeOutTime)
  218283. {
  218284. fd_set readbits;
  218285. FD_ZERO (&readbits);
  218286. FD_SET (socketHandle, &readbits);
  218287. struct timeval tv;
  218288. tv.tv_sec = timeoutSeconds;
  218289. tv.tv_usec = 0;
  218290. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218291. return String::empty; // (timeout)
  218292. buffer.ensureSize (bytesRead + 8, true);
  218293. char* const dest = (char*) buffer.getData() + bytesRead;
  218294. if (recv (socketHandle, dest, 1, 0) == -1)
  218295. return String::empty;
  218296. const char lastByte = *dest;
  218297. ++bytesRead;
  218298. if (lastByte == '\n')
  218299. ++numConsecutiveLFs;
  218300. else if (lastByte != '\r')
  218301. numConsecutiveLFs = 0;
  218302. }
  218303. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  218304. if (header.startsWithIgnoreCase ("HTTP/"))
  218305. return header.trimEnd();
  218306. return String::empty;
  218307. }
  218308. static bool decomposeURL (const String& url,
  218309. String& host, String& path, int& port)
  218310. {
  218311. if (! url.startsWithIgnoreCase ("http://"))
  218312. return false;
  218313. const int nextSlash = url.indexOfChar (7, '/');
  218314. int nextColon = url.indexOfChar (7, ':');
  218315. if (nextColon > nextSlash && nextSlash > 0)
  218316. nextColon = -1;
  218317. if (nextColon >= 0)
  218318. {
  218319. host = url.substring (7, nextColon);
  218320. if (nextSlash >= 0)
  218321. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  218322. else
  218323. port = url.substring (nextColon + 1).getIntValue();
  218324. }
  218325. else
  218326. {
  218327. port = 80;
  218328. if (nextSlash >= 0)
  218329. host = url.substring (7, nextSlash);
  218330. else
  218331. host = url.substring (7);
  218332. }
  218333. if (nextSlash >= 0)
  218334. path = url.substring (nextSlash);
  218335. else
  218336. path = "/";
  218337. return true;
  218338. }
  218339. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  218340. {
  218341. for (int i = 0; i < lines.size(); ++i)
  218342. if (lines[i].startsWithIgnoreCase (itemName))
  218343. return lines[i].substring (itemName.length()).trim();
  218344. return String::empty;
  218345. }
  218346. };
  218347. void* juce_openInternetFile (const String& url,
  218348. const String& headers,
  218349. const MemoryBlock& postData,
  218350. const bool isPost,
  218351. URL::OpenStreamProgressCallback* callback,
  218352. void* callbackContext,
  218353. int timeOutMs)
  218354. {
  218355. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  218356. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  218357. return s.release();
  218358. return 0;
  218359. }
  218360. void juce_closeInternetFile (void* handle)
  218361. {
  218362. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  218363. }
  218364. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  218365. {
  218366. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218367. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  218368. }
  218369. int64 juce_getInternetFileContentLength (void* handle)
  218370. {
  218371. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218372. if (s != 0)
  218373. {
  218374. //xxx todo
  218375. jassertfalse
  218376. }
  218377. return -1;
  218378. }
  218379. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  218380. {
  218381. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218382. if (s != 0)
  218383. {
  218384. for (int i = 0; i < s->headerLines.size(); ++i)
  218385. {
  218386. const String& headersEntry = s->headerLines[i];
  218387. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  218388. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  218389. const String previousValue (headers [key]);
  218390. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  218391. }
  218392. }
  218393. }
  218394. int juce_seekInInternetFile (void* handle, int newPosition)
  218395. {
  218396. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218397. return s != 0 ? s->readPosition : 0;
  218398. }
  218399. #endif
  218400. /*** End of inlined file: juce_linux_Network.cpp ***/
  218401. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  218402. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218403. // compiled on its own).
  218404. #if JUCE_INCLUDED_FILE
  218405. void Logger::outputDebugString (const String& text)
  218406. {
  218407. std::cerr << text << std::endl;
  218408. }
  218409. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  218410. {
  218411. return Linux;
  218412. }
  218413. const String SystemStats::getOperatingSystemName()
  218414. {
  218415. return "Linux";
  218416. }
  218417. bool SystemStats::isOperatingSystem64Bit()
  218418. {
  218419. #if JUCE_64BIT
  218420. return true;
  218421. #else
  218422. //xxx not sure how to find this out?..
  218423. return false;
  218424. #endif
  218425. }
  218426. static const String juce_getCpuInfo (const char* const key)
  218427. {
  218428. StringArray lines;
  218429. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  218430. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  218431. if (lines[i].startsWithIgnoreCase (key))
  218432. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  218433. return String::empty;
  218434. }
  218435. const String SystemStats::getCpuVendor()
  218436. {
  218437. return juce_getCpuInfo ("vendor_id");
  218438. }
  218439. int SystemStats::getCpuSpeedInMegaherz()
  218440. {
  218441. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  218442. }
  218443. int SystemStats::getMemorySizeInMegabytes()
  218444. {
  218445. struct sysinfo sysi;
  218446. if (sysinfo (&sysi) == 0)
  218447. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218448. return 0;
  218449. }
  218450. int SystemStats::getPageSize()
  218451. {
  218452. return sysconf (_SC_PAGESIZE);
  218453. }
  218454. const String SystemStats::getLogonName()
  218455. {
  218456. const char* user = getenv ("USER");
  218457. if (user == 0)
  218458. {
  218459. struct passwd* const pw = getpwuid (getuid());
  218460. if (pw != 0)
  218461. user = pw->pw_name;
  218462. }
  218463. return String::fromUTF8 (user);
  218464. }
  218465. const String SystemStats::getFullUserName()
  218466. {
  218467. return getLogonName();
  218468. }
  218469. void SystemStats::initialiseStats()
  218470. {
  218471. const String flags (juce_getCpuInfo ("flags"));
  218472. cpuFlags.hasMMX = flags.contains ("mmx");
  218473. cpuFlags.hasSSE = flags.contains ("sse");
  218474. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218475. cpuFlags.has3DNow = flags.contains ("3dnow");
  218476. cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1;
  218477. }
  218478. void PlatformUtilities::fpuReset()
  218479. {
  218480. }
  218481. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  218482. {
  218483. if (gettimeofday (t, 0) != 0)
  218484. return false;
  218485. static unsigned int calibrate = 0;
  218486. static bool calibrated = false;
  218487. if (! calibrated)
  218488. {
  218489. calibrated = true;
  218490. struct sysinfo sysi;
  218491. if (sysinfo (&sysi) == 0)
  218492. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  218493. }
  218494. t->tv_sec -= calibrate;
  218495. return true;
  218496. }
  218497. uint32 juce_millisecondsSinceStartup() throw()
  218498. {
  218499. timeval t;
  218500. if (juce_getTimeSinceStartup (&t))
  218501. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  218502. return 0;
  218503. }
  218504. int64 Time::getHighResolutionTicks() throw()
  218505. {
  218506. timeval t;
  218507. if (juce_getTimeSinceStartup (&t))
  218508. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  218509. return 0;
  218510. }
  218511. int64 Time::getHighResolutionTicksPerSecond() throw()
  218512. {
  218513. return 1000000; // (microseconds)
  218514. }
  218515. double Time::getMillisecondCounterHiRes() throw()
  218516. {
  218517. return getHighResolutionTicks() * 0.001;
  218518. }
  218519. bool Time::setSystemTimeToThisTime() const
  218520. {
  218521. timeval t;
  218522. t.tv_sec = millisSinceEpoch % 1000000;
  218523. t.tv_usec = millisSinceEpoch - t.tv_sec;
  218524. return settimeofday (&t, 0) ? false : true;
  218525. }
  218526. #endif
  218527. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218528. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218529. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218530. // compiled on its own).
  218531. #if JUCE_INCLUDED_FILE
  218532. /*
  218533. Note that a lot of methods that you'd expect to find in this file actually
  218534. live in juce_posix_SharedCode.h!
  218535. */
  218536. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218537. void Process::setPriority (ProcessPriority prior)
  218538. {
  218539. struct sched_param param;
  218540. int policy, maxp, minp;
  218541. const int p = (int) prior;
  218542. if (p <= 1)
  218543. policy = SCHED_OTHER;
  218544. else
  218545. policy = SCHED_RR;
  218546. minp = sched_get_priority_min (policy);
  218547. maxp = sched_get_priority_max (policy);
  218548. if (p < 2)
  218549. param.sched_priority = 0;
  218550. else if (p == 2 )
  218551. // Set to middle of lower realtime priority range
  218552. param.sched_priority = minp + (maxp - minp) / 4;
  218553. else
  218554. // Set to middle of higher realtime priority range
  218555. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218556. pthread_setschedparam (pthread_self(), policy, &param);
  218557. }
  218558. void Process::terminate()
  218559. {
  218560. exit (0);
  218561. }
  218562. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  218563. {
  218564. static char testResult = 0;
  218565. if (testResult == 0)
  218566. {
  218567. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218568. if (testResult >= 0)
  218569. {
  218570. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218571. testResult = 1;
  218572. }
  218573. }
  218574. return testResult < 0;
  218575. }
  218576. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218577. {
  218578. return juce_isRunningUnderDebugger();
  218579. }
  218580. void Process::raisePrivilege()
  218581. {
  218582. // If running suid root, change effective user
  218583. // to root
  218584. if (geteuid() != 0 && getuid() == 0)
  218585. {
  218586. setreuid (geteuid(), getuid());
  218587. setregid (getegid(), getgid());
  218588. }
  218589. }
  218590. void Process::lowerPrivilege()
  218591. {
  218592. // If runing suid root, change effective user
  218593. // back to real user
  218594. if (geteuid() == 0 && getuid() != 0)
  218595. {
  218596. setreuid (geteuid(), getuid());
  218597. setregid (getegid(), getgid());
  218598. }
  218599. }
  218600. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218601. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218602. {
  218603. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218604. }
  218605. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218606. {
  218607. dlclose(handle);
  218608. }
  218609. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218610. {
  218611. return dlsym (libraryHandle, procedureName.toCString());
  218612. }
  218613. #endif
  218614. #endif
  218615. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218616. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218617. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218618. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218619. // compiled on its own).
  218620. #if JUCE_INCLUDED_FILE
  218621. extern Display* display;
  218622. extern Window juce_messageWindowHandle;
  218623. namespace ClipboardHelpers
  218624. {
  218625. static String localClipboardContent;
  218626. static Atom atom_UTF8_STRING;
  218627. static Atom atom_CLIPBOARD;
  218628. static Atom atom_TARGETS;
  218629. static void initSelectionAtoms()
  218630. {
  218631. static bool isInitialised = false;
  218632. if (! isInitialised)
  218633. {
  218634. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218635. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218636. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218637. }
  218638. }
  218639. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218640. // works only for strings shorter than 1000000 bytes
  218641. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218642. {
  218643. String returnData;
  218644. char* clipData;
  218645. Atom actualType;
  218646. int actualFormat;
  218647. unsigned long numItems, bytesLeft;
  218648. if (XGetWindowProperty (display, window, prop,
  218649. 0L /* offset */, 1000000 /* length (max) */, False,
  218650. AnyPropertyType /* format */,
  218651. &actualType, &actualFormat, &numItems, &bytesLeft,
  218652. (unsigned char**) &clipData) == Success)
  218653. {
  218654. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218655. returnData = String::fromUTF8 (clipData, numItems);
  218656. else if (actualType == XA_STRING && actualFormat == 8)
  218657. returnData = String (clipData, numItems);
  218658. if (clipData != 0)
  218659. XFree (clipData);
  218660. jassert (bytesLeft == 0 || numItems == 1000000);
  218661. }
  218662. XDeleteProperty (display, window, prop);
  218663. return returnData;
  218664. }
  218665. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218666. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218667. {
  218668. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218669. // The selection owner will be asked to set the JUCE_SEL property on the
  218670. // juce_messageWindowHandle with the selection content
  218671. XConvertSelection (display, selection, requestedFormat, property_name,
  218672. juce_messageWindowHandle, CurrentTime);
  218673. int count = 50; // will wait at most for 200 ms
  218674. while (--count >= 0)
  218675. {
  218676. XEvent event;
  218677. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218678. {
  218679. if (event.xselection.property == property_name)
  218680. {
  218681. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218682. selectionContent = readWindowProperty (event.xselection.requestor,
  218683. event.xselection.property,
  218684. requestedFormat);
  218685. return true;
  218686. }
  218687. else
  218688. {
  218689. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218690. }
  218691. }
  218692. // not very elegant.. we could do a select() or something like that...
  218693. // however clipboard content requesting is inherently slow on x11, it
  218694. // often takes 50ms or more so...
  218695. Thread::sleep (4);
  218696. }
  218697. return false;
  218698. }
  218699. }
  218700. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218701. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218702. {
  218703. ClipboardHelpers::initSelectionAtoms();
  218704. // the selection content is sent to the target window as a window property
  218705. XSelectionEvent reply;
  218706. reply.type = SelectionNotify;
  218707. reply.display = evt.display;
  218708. reply.requestor = evt.requestor;
  218709. reply.selection = evt.selection;
  218710. reply.target = evt.target;
  218711. reply.property = None; // == "fail"
  218712. reply.time = evt.time;
  218713. HeapBlock <char> data;
  218714. int propertyFormat = 0, numDataItems = 0;
  218715. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218716. {
  218717. if (evt.target == XA_STRING)
  218718. {
  218719. // format data according to system locale
  218720. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218721. data.calloc (numDataItems + 1);
  218722. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218723. propertyFormat = 8; // bits/item
  218724. }
  218725. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218726. {
  218727. // translate to utf8
  218728. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218729. data.calloc (numDataItems + 1);
  218730. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218731. propertyFormat = 8; // bits/item
  218732. }
  218733. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218734. {
  218735. // another application wants to know what we are able to send
  218736. numDataItems = 2;
  218737. propertyFormat = 32; // atoms are 32-bit
  218738. data.calloc (numDataItems * 4);
  218739. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218740. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218741. atoms[1] = XA_STRING;
  218742. }
  218743. }
  218744. else
  218745. {
  218746. DBG ("requested unsupported clipboard");
  218747. }
  218748. if (data != 0)
  218749. {
  218750. const int maxReasonableSelectionSize = 1000000;
  218751. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218752. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218753. {
  218754. XChangeProperty (evt.display, evt.requestor,
  218755. evt.property, evt.target,
  218756. propertyFormat /* 8 or 32 */, PropModeReplace,
  218757. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218758. reply.property = evt.property; // " == success"
  218759. }
  218760. }
  218761. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218762. }
  218763. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218764. {
  218765. ClipboardHelpers::initSelectionAtoms();
  218766. ClipboardHelpers::localClipboardContent = clipText;
  218767. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218768. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218769. }
  218770. const String SystemClipboard::getTextFromClipboard()
  218771. {
  218772. ClipboardHelpers::initSelectionAtoms();
  218773. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218774. level" clipboard that is supposed to be filled by ctrl-C
  218775. etc). When a clipboard manager is running, the content of this
  218776. selection is preserved even when the original selection owner
  218777. exits.
  218778. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218779. filled by good old x11 apps such as xterm)
  218780. */
  218781. String content;
  218782. Atom selection = XA_PRIMARY;
  218783. Window selectionOwner = None;
  218784. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218785. {
  218786. selection = ClipboardHelpers::atom_CLIPBOARD;
  218787. selectionOwner = XGetSelectionOwner (display, selection);
  218788. }
  218789. if (selectionOwner != None)
  218790. {
  218791. if (selectionOwner == juce_messageWindowHandle)
  218792. {
  218793. content = ClipboardHelpers::localClipboardContent;
  218794. }
  218795. else
  218796. {
  218797. // first try: we want an utf8 string
  218798. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218799. if (! ok)
  218800. {
  218801. // second chance, ask for a good old locale-dependent string ..
  218802. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218803. }
  218804. }
  218805. }
  218806. return content;
  218807. }
  218808. #endif
  218809. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218810. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218811. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218812. // compiled on its own).
  218813. #if JUCE_INCLUDED_FILE
  218814. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  218815. #define JUCE_DEBUG_XERRORS 1
  218816. #endif
  218817. Display* display = 0;
  218818. Window juce_messageWindowHandle = None;
  218819. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  218820. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  218821. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  218822. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  218823. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  218824. class InternalMessageQueue
  218825. {
  218826. public:
  218827. InternalMessageQueue()
  218828. : bytesInSocket (0),
  218829. totalEventCount (0)
  218830. {
  218831. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  218832. (void) ret; jassert (ret == 0);
  218833. //setNonBlocking (fd[0]);
  218834. //setNonBlocking (fd[1]);
  218835. }
  218836. ~InternalMessageQueue()
  218837. {
  218838. close (fd[0]);
  218839. close (fd[1]);
  218840. clearSingletonInstance();
  218841. }
  218842. void postMessage (Message* msg)
  218843. {
  218844. const int maxBytesInSocketQueue = 128;
  218845. ScopedLock sl (lock);
  218846. queue.add (msg);
  218847. if (bytesInSocket < maxBytesInSocketQueue)
  218848. {
  218849. ++bytesInSocket;
  218850. ScopedUnlock ul (lock);
  218851. const unsigned char x = 0xff;
  218852. size_t bytesWritten = write (fd[0], &x, 1);
  218853. (void) bytesWritten;
  218854. }
  218855. }
  218856. bool isEmpty() const
  218857. {
  218858. ScopedLock sl (lock);
  218859. return queue.size() == 0;
  218860. }
  218861. bool dispatchNextEvent()
  218862. {
  218863. // This alternates between giving priority to XEvents or internal messages,
  218864. // to keep everything running smoothly..
  218865. if ((++totalEventCount & 1) != 0)
  218866. return dispatchNextXEvent() || dispatchNextInternalMessage();
  218867. else
  218868. return dispatchNextInternalMessage() || dispatchNextXEvent();
  218869. }
  218870. // Wait for an event (either XEvent, or an internal Message)
  218871. bool sleepUntilEvent (const int timeoutMs)
  218872. {
  218873. if (! isEmpty())
  218874. return true;
  218875. if (display != 0)
  218876. {
  218877. ScopedXLock xlock;
  218878. if (XPending (display))
  218879. return true;
  218880. }
  218881. struct timeval tv;
  218882. tv.tv_sec = 0;
  218883. tv.tv_usec = timeoutMs * 1000;
  218884. int fd0 = getWaitHandle();
  218885. int fdmax = fd0;
  218886. fd_set readset;
  218887. FD_ZERO (&readset);
  218888. FD_SET (fd0, &readset);
  218889. if (display != 0)
  218890. {
  218891. ScopedXLock xlock;
  218892. int fd1 = XConnectionNumber (display);
  218893. FD_SET (fd1, &readset);
  218894. fdmax = jmax (fd0, fd1);
  218895. }
  218896. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  218897. return (ret > 0); // ret <= 0 if error or timeout
  218898. }
  218899. struct MessageThreadFuncCall
  218900. {
  218901. enum { uniqueID = 0x73774623 };
  218902. MessageCallbackFunction* func;
  218903. void* parameter;
  218904. void* result;
  218905. CriticalSection lock;
  218906. WaitableEvent event;
  218907. };
  218908. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  218909. private:
  218910. CriticalSection lock;
  218911. OwnedArray <Message> queue;
  218912. int fd[2];
  218913. int bytesInSocket;
  218914. int totalEventCount;
  218915. int getWaitHandle() const throw() { return fd[1]; }
  218916. static bool setNonBlocking (int handle)
  218917. {
  218918. int socketFlags = fcntl (handle, F_GETFL, 0);
  218919. if (socketFlags == -1)
  218920. return false;
  218921. socketFlags |= O_NONBLOCK;
  218922. return fcntl (handle, F_SETFL, socketFlags) == 0;
  218923. }
  218924. static bool dispatchNextXEvent()
  218925. {
  218926. if (display == 0)
  218927. return false;
  218928. XEvent evt;
  218929. {
  218930. ScopedXLock xlock;
  218931. if (! XPending (display))
  218932. return false;
  218933. XNextEvent (display, &evt);
  218934. }
  218935. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  218936. juce_handleSelectionRequest (evt.xselectionrequest);
  218937. else if (evt.xany.window != juce_messageWindowHandle)
  218938. juce_windowMessageReceive (&evt);
  218939. return true;
  218940. }
  218941. Message* popNextMessage()
  218942. {
  218943. ScopedLock sl (lock);
  218944. if (bytesInSocket > 0)
  218945. {
  218946. --bytesInSocket;
  218947. ScopedUnlock ul (lock);
  218948. unsigned char x;
  218949. size_t numBytes = read (fd[1], &x, 1);
  218950. (void) numBytes;
  218951. }
  218952. return queue.removeAndReturn (0);
  218953. }
  218954. bool dispatchNextInternalMessage()
  218955. {
  218956. ScopedPointer <Message> msg (popNextMessage());
  218957. if (msg == 0)
  218958. return false;
  218959. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  218960. {
  218961. // Handle callback message
  218962. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  218963. call->result = (*(call->func)) (call->parameter);
  218964. call->event.signal();
  218965. }
  218966. else
  218967. {
  218968. // Handle "normal" messages
  218969. MessageManager::getInstance()->deliverMessage (msg.release());
  218970. }
  218971. return true;
  218972. }
  218973. };
  218974. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  218975. namespace LinuxErrorHandling
  218976. {
  218977. static bool errorOccurred = false;
  218978. static bool keyboardBreakOccurred = false;
  218979. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218980. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218981. // Usually happens when client-server connection is broken
  218982. static int ioErrorHandler (Display* display)
  218983. {
  218984. DBG ("ERROR: connection to X server broken.. terminating.");
  218985. if (JUCEApplication::isStandaloneApp())
  218986. MessageManager::getInstance()->stopDispatchLoop();
  218987. errorOccurred = true;
  218988. return 0;
  218989. }
  218990. // A protocol error has occurred
  218991. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218992. {
  218993. #if JUCE_DEBUG_XERRORS
  218994. char errorStr[64] = { 0 };
  218995. char requestStr[64] = { 0 };
  218996. XGetErrorText (display, event->error_code, errorStr, 64);
  218997. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  218998. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  218999. #endif
  219000. return 0;
  219001. }
  219002. static void installXErrorHandlers()
  219003. {
  219004. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  219005. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  219006. }
  219007. static void removeXErrorHandlers()
  219008. {
  219009. XSetIOErrorHandler (oldIOErrorHandler);
  219010. oldIOErrorHandler = 0;
  219011. XSetErrorHandler (oldErrorHandler);
  219012. oldErrorHandler = 0;
  219013. }
  219014. static void keyboardBreakSignalHandler (int sig)
  219015. {
  219016. if (sig == SIGINT)
  219017. keyboardBreakOccurred = true;
  219018. }
  219019. static void installKeyboardBreakHandler()
  219020. {
  219021. struct sigaction saction;
  219022. sigset_t maskSet;
  219023. sigemptyset (&maskSet);
  219024. saction.sa_handler = keyboardBreakSignalHandler;
  219025. saction.sa_mask = maskSet;
  219026. saction.sa_flags = 0;
  219027. sigaction (SIGINT, &saction, 0);
  219028. }
  219029. }
  219030. void MessageManager::doPlatformSpecificInitialisation()
  219031. {
  219032. // Initialise xlib for multiple thread support
  219033. static bool initThreadCalled = false;
  219034. if (! initThreadCalled)
  219035. {
  219036. if (! XInitThreads())
  219037. {
  219038. // This is fatal! Print error and closedown
  219039. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  219040. if (JUCEApplication::isStandaloneApp())
  219041. Process::terminate();
  219042. return;
  219043. }
  219044. initThreadCalled = true;
  219045. }
  219046. LinuxErrorHandling::installXErrorHandlers();
  219047. LinuxErrorHandling::installKeyboardBreakHandler();
  219048. // Create the internal message queue
  219049. InternalMessageQueue::getInstance();
  219050. // Try to connect to a display
  219051. String displayName (getenv ("DISPLAY"));
  219052. if (displayName.isEmpty())
  219053. displayName = ":0.0";
  219054. display = XOpenDisplay (displayName.toCString());
  219055. if (display != 0) // This is not fatal! we can run headless.
  219056. {
  219057. // Create a context to store user data associated with Windows we create in WindowDriver
  219058. windowHandleXContext = XUniqueContext();
  219059. // We're only interested in client messages for this window, which are always sent
  219060. XSetWindowAttributes swa;
  219061. swa.event_mask = NoEventMask;
  219062. // Create our message window (this will never be mapped)
  219063. const int screen = DefaultScreen (display);
  219064. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  219065. 0, 0, 1, 1, 0, 0, InputOnly,
  219066. DefaultVisual (display, screen),
  219067. CWEventMask, &swa);
  219068. }
  219069. }
  219070. void MessageManager::doPlatformSpecificShutdown()
  219071. {
  219072. InternalMessageQueue::deleteInstance();
  219073. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  219074. {
  219075. XDestroyWindow (display, juce_messageWindowHandle);
  219076. XCloseDisplay (display);
  219077. juce_messageWindowHandle = 0;
  219078. display = 0;
  219079. LinuxErrorHandling::removeXErrorHandlers();
  219080. }
  219081. }
  219082. bool juce_postMessageToSystemQueue (Message* message)
  219083. {
  219084. if (LinuxErrorHandling::errorOccurred)
  219085. return false;
  219086. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  219087. return true;
  219088. }
  219089. void MessageManager::broadcastMessage (const String& value)
  219090. {
  219091. /* TODO */
  219092. }
  219093. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  219094. {
  219095. if (LinuxErrorHandling::errorOccurred)
  219096. return 0;
  219097. if (isThisTheMessageThread())
  219098. return func (parameter);
  219099. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  219100. messageCallContext.func = func;
  219101. messageCallContext.parameter = parameter;
  219102. InternalMessageQueue::getInstanceWithoutCreating()
  219103. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  219104. 0, 0, &messageCallContext));
  219105. // Wait for it to complete before continuing
  219106. messageCallContext.event.wait();
  219107. return messageCallContext.result;
  219108. }
  219109. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  219110. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  219111. {
  219112. while (! LinuxErrorHandling::errorOccurred)
  219113. {
  219114. if (LinuxErrorHandling::keyboardBreakOccurred)
  219115. {
  219116. LinuxErrorHandling::errorOccurred = true;
  219117. if (JUCEApplication::isStandaloneApp())
  219118. Process::terminate();
  219119. break;
  219120. }
  219121. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  219122. return true;
  219123. if (returnIfNoPendingMessages)
  219124. break;
  219125. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  219126. }
  219127. return false;
  219128. }
  219129. #endif
  219130. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  219131. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  219132. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219133. // compiled on its own).
  219134. #if JUCE_INCLUDED_FILE
  219135. class FreeTypeFontFace
  219136. {
  219137. public:
  219138. enum FontStyle
  219139. {
  219140. Plain = 0,
  219141. Bold = 1,
  219142. Italic = 2
  219143. };
  219144. FreeTypeFontFace (const String& familyName)
  219145. : hasSerif (false),
  219146. monospaced (false)
  219147. {
  219148. family = familyName;
  219149. }
  219150. void setFileName (const String& name, const int faceIndex, FontStyle style)
  219151. {
  219152. if (names [(int) style].fileName.isEmpty())
  219153. {
  219154. names [(int) style].fileName = name;
  219155. names [(int) style].faceIndex = faceIndex;
  219156. }
  219157. }
  219158. const String& getFamilyName() const throw() { return family; }
  219159. const String& getFileName (const int style, int& faceIndex) const throw()
  219160. {
  219161. faceIndex = names[style].faceIndex;
  219162. return names[style].fileName;
  219163. }
  219164. void setMonospaced (bool mono) throw() { monospaced = mono; }
  219165. bool getMonospaced() const throw() { return monospaced; }
  219166. void setSerif (const bool serif) throw() { hasSerif = serif; }
  219167. bool getSerif() const throw() { return hasSerif; }
  219168. private:
  219169. String family;
  219170. struct FontNameIndex
  219171. {
  219172. String fileName;
  219173. int faceIndex;
  219174. };
  219175. FontNameIndex names[4];
  219176. bool hasSerif, monospaced;
  219177. };
  219178. class FreeTypeInterface : public DeletedAtShutdown
  219179. {
  219180. public:
  219181. FreeTypeInterface()
  219182. : ftLib (0),
  219183. lastFace (0),
  219184. lastBold (false),
  219185. lastItalic (false)
  219186. {
  219187. if (FT_Init_FreeType (&ftLib) != 0)
  219188. {
  219189. ftLib = 0;
  219190. DBG ("Failed to initialize FreeType");
  219191. }
  219192. StringArray fontDirs;
  219193. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  219194. fontDirs.removeEmptyStrings (true);
  219195. if (fontDirs.size() == 0)
  219196. {
  219197. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  219198. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  219199. if (fontsInfo != 0)
  219200. {
  219201. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  219202. {
  219203. fontDirs.add (e->getAllSubText().trim());
  219204. }
  219205. }
  219206. }
  219207. if (fontDirs.size() == 0)
  219208. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  219209. for (int i = 0; i < fontDirs.size(); ++i)
  219210. enumerateFaces (fontDirs[i]);
  219211. }
  219212. ~FreeTypeInterface()
  219213. {
  219214. if (lastFace != 0)
  219215. FT_Done_Face (lastFace);
  219216. if (ftLib != 0)
  219217. FT_Done_FreeType (ftLib);
  219218. clearSingletonInstance();
  219219. }
  219220. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  219221. {
  219222. for (int i = 0; i < faces.size(); i++)
  219223. if (faces[i]->getFamilyName() == familyName)
  219224. return faces[i];
  219225. if (! create)
  219226. return 0;
  219227. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  219228. faces.add (newFace);
  219229. return newFace;
  219230. }
  219231. // Enumerate all font faces available in a given directory
  219232. void enumerateFaces (const String& path)
  219233. {
  219234. File dirPath (path);
  219235. if (path.isEmpty() || ! dirPath.isDirectory())
  219236. return;
  219237. DirectoryIterator di (dirPath, true);
  219238. while (di.next())
  219239. {
  219240. File possible (di.getFile());
  219241. if (possible.hasFileExtension ("ttf")
  219242. || possible.hasFileExtension ("pfb")
  219243. || possible.hasFileExtension ("pcf"))
  219244. {
  219245. FT_Face face;
  219246. int faceIndex = 0;
  219247. int numFaces = 0;
  219248. do
  219249. {
  219250. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  219251. faceIndex, &face) == 0)
  219252. {
  219253. if (faceIndex == 0)
  219254. numFaces = face->num_faces;
  219255. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  219256. {
  219257. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  219258. int style = (int) FreeTypeFontFace::Plain;
  219259. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  219260. style |= (int) FreeTypeFontFace::Bold;
  219261. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  219262. style |= (int) FreeTypeFontFace::Italic;
  219263. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  219264. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  219265. // Surely there must be a better way to do this?
  219266. const String name (face->family_name);
  219267. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  219268. || name.containsIgnoreCase ("Verdana")
  219269. || name.containsIgnoreCase ("Arial")));
  219270. }
  219271. FT_Done_Face (face);
  219272. }
  219273. ++faceIndex;
  219274. }
  219275. while (faceIndex < numFaces);
  219276. }
  219277. }
  219278. }
  219279. // Create a FreeType face object for a given font
  219280. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  219281. {
  219282. FT_Face face = 0;
  219283. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  219284. {
  219285. face = lastFace;
  219286. }
  219287. else
  219288. {
  219289. if (lastFace != 0)
  219290. {
  219291. FT_Done_Face (lastFace);
  219292. lastFace = 0;
  219293. }
  219294. lastFontName = fontName;
  219295. lastBold = bold;
  219296. lastItalic = italic;
  219297. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  219298. if (ftFace != 0)
  219299. {
  219300. int style = (int) FreeTypeFontFace::Plain;
  219301. if (bold)
  219302. style |= (int) FreeTypeFontFace::Bold;
  219303. if (italic)
  219304. style |= (int) FreeTypeFontFace::Italic;
  219305. int faceIndex;
  219306. String fileName (ftFace->getFileName (style, faceIndex));
  219307. if (fileName.isEmpty())
  219308. {
  219309. style ^= (int) FreeTypeFontFace::Bold;
  219310. fileName = ftFace->getFileName (style, faceIndex);
  219311. if (fileName.isEmpty())
  219312. {
  219313. style ^= (int) FreeTypeFontFace::Bold;
  219314. style ^= (int) FreeTypeFontFace::Italic;
  219315. fileName = ftFace->getFileName (style, faceIndex);
  219316. if (! fileName.length())
  219317. {
  219318. style ^= (int) FreeTypeFontFace::Bold;
  219319. fileName = ftFace->getFileName (style, faceIndex);
  219320. }
  219321. }
  219322. }
  219323. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  219324. {
  219325. face = lastFace;
  219326. // If there isn't a unicode charmap then select the first one.
  219327. if (FT_Select_Charmap (face, ft_encoding_unicode))
  219328. FT_Set_Charmap (face, face->charmaps[0]);
  219329. }
  219330. }
  219331. }
  219332. return face;
  219333. }
  219334. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  219335. {
  219336. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  219337. const float height = (float) (face->ascender - face->descender);
  219338. const float scaleX = 1.0f / height;
  219339. const float scaleY = -1.0f / height;
  219340. Path destShape;
  219341. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  219342. || face->glyph->format != ft_glyph_format_outline)
  219343. {
  219344. return false;
  219345. }
  219346. const FT_Outline* const outline = &face->glyph->outline;
  219347. const short* const contours = outline->contours;
  219348. const char* const tags = outline->tags;
  219349. FT_Vector* const points = outline->points;
  219350. for (int c = 0; c < outline->n_contours; c++)
  219351. {
  219352. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  219353. const int endPoint = contours[c];
  219354. for (int p = startPoint; p <= endPoint; p++)
  219355. {
  219356. const float x = scaleX * points[p].x;
  219357. const float y = scaleY * points[p].y;
  219358. if (p == startPoint)
  219359. {
  219360. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219361. {
  219362. float x2 = scaleX * points [endPoint].x;
  219363. float y2 = scaleY * points [endPoint].y;
  219364. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  219365. {
  219366. x2 = (x + x2) * 0.5f;
  219367. y2 = (y + y2) * 0.5f;
  219368. }
  219369. destShape.startNewSubPath (x2, y2);
  219370. }
  219371. else
  219372. {
  219373. destShape.startNewSubPath (x, y);
  219374. }
  219375. }
  219376. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  219377. {
  219378. if (p != startPoint)
  219379. destShape.lineTo (x, y);
  219380. }
  219381. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219382. {
  219383. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  219384. float x2 = scaleX * points [nextIndex].x;
  219385. float y2 = scaleY * points [nextIndex].y;
  219386. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  219387. {
  219388. x2 = (x + x2) * 0.5f;
  219389. y2 = (y + y2) * 0.5f;
  219390. }
  219391. else
  219392. {
  219393. ++p;
  219394. }
  219395. destShape.quadraticTo (x, y, x2, y2);
  219396. }
  219397. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  219398. {
  219399. if (p >= endPoint)
  219400. return false;
  219401. const int next1 = p + 1;
  219402. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  219403. const float x2 = scaleX * points [next1].x;
  219404. const float y2 = scaleY * points [next1].y;
  219405. const float x3 = scaleX * points [next2].x;
  219406. const float y3 = scaleY * points [next2].y;
  219407. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  219408. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  219409. return false;
  219410. destShape.cubicTo (x, y, x2, y2, x3, y3);
  219411. p += 2;
  219412. }
  219413. }
  219414. destShape.closeSubPath();
  219415. }
  219416. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  219417. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  219418. addKerning (face, dest, character, glyphIndex);
  219419. return true;
  219420. }
  219421. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  219422. {
  219423. const float height = (float) (face->ascender - face->descender);
  219424. uint32 rightGlyphIndex;
  219425. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  219426. while (rightGlyphIndex != 0)
  219427. {
  219428. FT_Vector kerning;
  219429. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  219430. {
  219431. if (kerning.x != 0)
  219432. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  219433. }
  219434. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  219435. }
  219436. }
  219437. // Add a glyph to a font
  219438. bool addGlyphToFont (const uint32 character, const String& fontName,
  219439. bool bold, bool italic, CustomTypeface& dest)
  219440. {
  219441. FT_Face face = createFT_Face (fontName, bold, italic);
  219442. return face != 0 && addGlyph (face, dest, character);
  219443. }
  219444. void getFamilyNames (StringArray& familyNames) const
  219445. {
  219446. for (int i = 0; i < faces.size(); i++)
  219447. familyNames.add (faces[i]->getFamilyName());
  219448. }
  219449. void getMonospacedNames (StringArray& monoSpaced) const
  219450. {
  219451. for (int i = 0; i < faces.size(); i++)
  219452. if (faces[i]->getMonospaced())
  219453. monoSpaced.add (faces[i]->getFamilyName());
  219454. }
  219455. void getSerifNames (StringArray& serif) const
  219456. {
  219457. for (int i = 0; i < faces.size(); i++)
  219458. if (faces[i]->getSerif())
  219459. serif.add (faces[i]->getFamilyName());
  219460. }
  219461. void getSansSerifNames (StringArray& sansSerif) const
  219462. {
  219463. for (int i = 0; i < faces.size(); i++)
  219464. if (! faces[i]->getSerif())
  219465. sansSerif.add (faces[i]->getFamilyName());
  219466. }
  219467. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219468. private:
  219469. FT_Library ftLib;
  219470. FT_Face lastFace;
  219471. String lastFontName;
  219472. bool lastBold, lastItalic;
  219473. OwnedArray<FreeTypeFontFace> faces;
  219474. };
  219475. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219476. class FreetypeTypeface : public CustomTypeface
  219477. {
  219478. public:
  219479. FreetypeTypeface (const Font& font)
  219480. {
  219481. FT_Face face = FreeTypeInterface::getInstance()
  219482. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219483. if (face == 0)
  219484. {
  219485. #if JUCE_DEBUG
  219486. String msg ("Failed to create typeface: ");
  219487. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219488. DBG (msg);
  219489. #endif
  219490. }
  219491. else
  219492. {
  219493. setCharacteristics (font.getTypefaceName(),
  219494. face->ascender / (float) (face->ascender - face->descender),
  219495. font.isBold(), font.isItalic(),
  219496. L' ');
  219497. }
  219498. }
  219499. bool loadGlyphIfPossible (juce_wchar character)
  219500. {
  219501. return FreeTypeInterface::getInstance()
  219502. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219503. }
  219504. };
  219505. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219506. {
  219507. return new FreetypeTypeface (font);
  219508. }
  219509. const StringArray Font::findAllTypefaceNames()
  219510. {
  219511. StringArray s;
  219512. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219513. s.sort (true);
  219514. return s;
  219515. }
  219516. static const String pickBestFont (const StringArray& names,
  219517. const char* const choicesString)
  219518. {
  219519. StringArray choices;
  219520. choices.addTokens (String (choicesString), ",", String::empty);
  219521. choices.trim();
  219522. choices.removeEmptyStrings();
  219523. int i, j;
  219524. for (j = 0; j < choices.size(); ++j)
  219525. if (names.contains (choices[j], true))
  219526. return choices[j];
  219527. for (j = 0; j < choices.size(); ++j)
  219528. for (i = 0; i < names.size(); i++)
  219529. if (names[i].startsWithIgnoreCase (choices[j]))
  219530. return names[i];
  219531. for (j = 0; j < choices.size(); ++j)
  219532. for (i = 0; i < names.size(); i++)
  219533. if (names[i].containsIgnoreCase (choices[j]))
  219534. return names[i];
  219535. return names[0];
  219536. }
  219537. static const String linux_getDefaultSansSerifFontName()
  219538. {
  219539. StringArray allFonts;
  219540. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219541. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219542. }
  219543. static const String linux_getDefaultSerifFontName()
  219544. {
  219545. StringArray allFonts;
  219546. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219547. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219548. }
  219549. static const String linux_getDefaultMonospacedFontName()
  219550. {
  219551. StringArray allFonts;
  219552. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219553. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219554. }
  219555. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  219556. {
  219557. defaultSans = linux_getDefaultSansSerifFontName();
  219558. defaultSerif = linux_getDefaultSerifFontName();
  219559. defaultFixed = linux_getDefaultMonospacedFontName();
  219560. }
  219561. #endif
  219562. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219563. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219564. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219565. // compiled on its own).
  219566. #if JUCE_INCLUDED_FILE
  219567. // These are defined in juce_linux_Messaging.cpp
  219568. extern Display* display;
  219569. extern XContext windowHandleXContext;
  219570. namespace Atoms
  219571. {
  219572. enum ProtocolItems
  219573. {
  219574. TAKE_FOCUS = 0,
  219575. DELETE_WINDOW = 1,
  219576. PING = 2
  219577. };
  219578. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219579. ActiveWin, Pid, WindowType, WindowState,
  219580. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219581. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219582. XdndActionDescription, XdndActionCopy,
  219583. allowedActions[5],
  219584. allowedMimeTypes[2];
  219585. const unsigned long DndVersion = 3;
  219586. static void initialiseAtoms()
  219587. {
  219588. static bool atomsInitialised = false;
  219589. if (! atomsInitialised)
  219590. {
  219591. atomsInitialised = true;
  219592. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219593. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219594. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219595. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219596. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219597. State = XInternAtom (display, "WM_STATE", True);
  219598. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219599. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219600. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219601. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219602. XdndAware = XInternAtom (display, "XdndAware", False);
  219603. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219604. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219605. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219606. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219607. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219608. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219609. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219610. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219611. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219612. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219613. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219614. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219615. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219616. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219617. allowedActions[1] = XdndActionCopy;
  219618. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219619. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219620. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219621. }
  219622. }
  219623. }
  219624. namespace Keys
  219625. {
  219626. enum MouseButtons
  219627. {
  219628. NoButton = 0,
  219629. LeftButton = 1,
  219630. MiddleButton = 2,
  219631. RightButton = 3,
  219632. WheelUp = 4,
  219633. WheelDown = 5
  219634. };
  219635. static int AltMask = 0;
  219636. static int NumLockMask = 0;
  219637. static bool numLock = false;
  219638. static bool capsLock = false;
  219639. static char keyStates [32];
  219640. static const int extendedKeyModifier = 0x10000000;
  219641. }
  219642. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219643. {
  219644. int keysym;
  219645. if (keyCode & Keys::extendedKeyModifier)
  219646. {
  219647. keysym = 0xff00 | (keyCode & 0xff);
  219648. }
  219649. else
  219650. {
  219651. keysym = keyCode;
  219652. if (keysym == (XK_Tab & 0xff)
  219653. || keysym == (XK_Return & 0xff)
  219654. || keysym == (XK_Escape & 0xff)
  219655. || keysym == (XK_BackSpace & 0xff))
  219656. {
  219657. keysym |= 0xff00;
  219658. }
  219659. }
  219660. ScopedXLock xlock;
  219661. const int keycode = XKeysymToKeycode (display, keysym);
  219662. const int keybyte = keycode >> 3;
  219663. const int keybit = (1 << (keycode & 7));
  219664. return (Keys::keyStates [keybyte] & keybit) != 0;
  219665. }
  219666. #if JUCE_USE_XSHM
  219667. namespace XSHMHelpers
  219668. {
  219669. static int trappedErrorCode = 0;
  219670. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219671. {
  219672. trappedErrorCode = err->error_code;
  219673. return 0;
  219674. }
  219675. static bool isShmAvailable() throw()
  219676. {
  219677. static bool isChecked = false;
  219678. static bool isAvailable = false;
  219679. if (! isChecked)
  219680. {
  219681. isChecked = true;
  219682. int major, minor;
  219683. Bool pixmaps;
  219684. ScopedXLock xlock;
  219685. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219686. {
  219687. trappedErrorCode = 0;
  219688. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219689. XShmSegmentInfo segmentInfo;
  219690. zerostruct (segmentInfo);
  219691. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219692. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219693. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219694. xImage->bytes_per_line * xImage->height,
  219695. IPC_CREAT | 0777)) >= 0)
  219696. {
  219697. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219698. if (segmentInfo.shmaddr != (void*) -1)
  219699. {
  219700. segmentInfo.readOnly = False;
  219701. xImage->data = segmentInfo.shmaddr;
  219702. XSync (display, False);
  219703. if (XShmAttach (display, &segmentInfo) != 0)
  219704. {
  219705. XSync (display, False);
  219706. XShmDetach (display, &segmentInfo);
  219707. isAvailable = true;
  219708. }
  219709. }
  219710. XFlush (display);
  219711. XDestroyImage (xImage);
  219712. shmdt (segmentInfo.shmaddr);
  219713. }
  219714. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219715. XSetErrorHandler (oldHandler);
  219716. if (trappedErrorCode != 0)
  219717. isAvailable = false;
  219718. }
  219719. }
  219720. return isAvailable;
  219721. }
  219722. }
  219723. #endif
  219724. #if JUCE_USE_XRENDER
  219725. namespace XRender
  219726. {
  219727. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219728. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219729. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219730. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219731. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219732. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219733. static tXRenderFindFormat xRenderFindFormat = 0;
  219734. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219735. static bool isAvailable()
  219736. {
  219737. static bool hasLoaded = false;
  219738. if (! hasLoaded)
  219739. {
  219740. ScopedXLock xlock;
  219741. hasLoaded = true;
  219742. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219743. if (h != 0)
  219744. {
  219745. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219746. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219747. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219748. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219749. }
  219750. if (xRenderQueryVersion != 0
  219751. && xRenderFindStandardFormat != 0
  219752. && xRenderFindFormat != 0
  219753. && xRenderFindVisualFormat != 0)
  219754. {
  219755. int major, minor;
  219756. if (xRenderQueryVersion (display, &major, &minor))
  219757. return true;
  219758. }
  219759. xRenderQueryVersion = 0;
  219760. }
  219761. return xRenderQueryVersion != 0;
  219762. }
  219763. static XRenderPictFormat* findPictureFormat()
  219764. {
  219765. ScopedXLock xlock;
  219766. XRenderPictFormat* pictFormat = 0;
  219767. if (isAvailable())
  219768. {
  219769. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219770. if (pictFormat == 0)
  219771. {
  219772. XRenderPictFormat desiredFormat;
  219773. desiredFormat.type = PictTypeDirect;
  219774. desiredFormat.depth = 32;
  219775. desiredFormat.direct.alphaMask = 0xff;
  219776. desiredFormat.direct.redMask = 0xff;
  219777. desiredFormat.direct.greenMask = 0xff;
  219778. desiredFormat.direct.blueMask = 0xff;
  219779. desiredFormat.direct.alpha = 24;
  219780. desiredFormat.direct.red = 16;
  219781. desiredFormat.direct.green = 8;
  219782. desiredFormat.direct.blue = 0;
  219783. pictFormat = xRenderFindFormat (display,
  219784. PictFormatType | PictFormatDepth
  219785. | PictFormatRedMask | PictFormatRed
  219786. | PictFormatGreenMask | PictFormatGreen
  219787. | PictFormatBlueMask | PictFormatBlue
  219788. | PictFormatAlphaMask | PictFormatAlpha,
  219789. &desiredFormat,
  219790. 0);
  219791. }
  219792. }
  219793. return pictFormat;
  219794. }
  219795. }
  219796. #endif
  219797. namespace Visuals
  219798. {
  219799. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219800. {
  219801. ScopedXLock xlock;
  219802. Visual* visual = 0;
  219803. int numVisuals = 0;
  219804. long desiredMask = VisualNoMask;
  219805. XVisualInfo desiredVisual;
  219806. desiredVisual.screen = DefaultScreen (display);
  219807. desiredVisual.depth = desiredDepth;
  219808. desiredMask = VisualScreenMask | VisualDepthMask;
  219809. if (desiredDepth == 32)
  219810. {
  219811. desiredVisual.c_class = TrueColor;
  219812. desiredVisual.red_mask = 0x00FF0000;
  219813. desiredVisual.green_mask = 0x0000FF00;
  219814. desiredVisual.blue_mask = 0x000000FF;
  219815. desiredVisual.bits_per_rgb = 8;
  219816. desiredMask |= VisualClassMask;
  219817. desiredMask |= VisualRedMaskMask;
  219818. desiredMask |= VisualGreenMaskMask;
  219819. desiredMask |= VisualBlueMaskMask;
  219820. desiredMask |= VisualBitsPerRGBMask;
  219821. }
  219822. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219823. desiredMask,
  219824. &desiredVisual,
  219825. &numVisuals);
  219826. if (xvinfos != 0)
  219827. {
  219828. for (int i = 0; i < numVisuals; i++)
  219829. {
  219830. if (xvinfos[i].depth == desiredDepth)
  219831. {
  219832. visual = xvinfos[i].visual;
  219833. break;
  219834. }
  219835. }
  219836. XFree (xvinfos);
  219837. }
  219838. return visual;
  219839. }
  219840. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  219841. {
  219842. Visual* visual = 0;
  219843. if (desiredDepth == 32)
  219844. {
  219845. #if JUCE_USE_XSHM
  219846. if (XSHMHelpers::isShmAvailable())
  219847. {
  219848. #if JUCE_USE_XRENDER
  219849. if (XRender::isAvailable())
  219850. {
  219851. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  219852. if (pictFormat != 0)
  219853. {
  219854. int numVisuals = 0;
  219855. XVisualInfo desiredVisual;
  219856. desiredVisual.screen = DefaultScreen (display);
  219857. desiredVisual.depth = 32;
  219858. desiredVisual.bits_per_rgb = 8;
  219859. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219860. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  219861. &desiredVisual, &numVisuals);
  219862. if (xvinfos != 0)
  219863. {
  219864. for (int i = 0; i < numVisuals; ++i)
  219865. {
  219866. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  219867. if (pictVisualFormat != 0
  219868. && pictVisualFormat->type == PictTypeDirect
  219869. && pictVisualFormat->direct.alphaMask)
  219870. {
  219871. visual = xvinfos[i].visual;
  219872. matchedDepth = 32;
  219873. break;
  219874. }
  219875. }
  219876. XFree (xvinfos);
  219877. }
  219878. }
  219879. }
  219880. #endif
  219881. if (visual == 0)
  219882. {
  219883. visual = findVisualWithDepth (32);
  219884. if (visual != 0)
  219885. matchedDepth = 32;
  219886. }
  219887. }
  219888. #endif
  219889. }
  219890. if (visual == 0 && desiredDepth >= 24)
  219891. {
  219892. visual = findVisualWithDepth (24);
  219893. if (visual != 0)
  219894. matchedDepth = 24;
  219895. }
  219896. if (visual == 0 && desiredDepth >= 16)
  219897. {
  219898. visual = findVisualWithDepth (16);
  219899. if (visual != 0)
  219900. matchedDepth = 16;
  219901. }
  219902. return visual;
  219903. }
  219904. }
  219905. class XBitmapImage : public Image::SharedImage
  219906. {
  219907. public:
  219908. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  219909. const bool clearImage, const int imageDepth_, Visual* visual)
  219910. : Image::SharedImage (format_, w, h),
  219911. imageDepth (imageDepth_),
  219912. gc (None)
  219913. {
  219914. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  219915. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  219916. lineStride = ((w * pixelStride + 3) & ~3);
  219917. ScopedXLock xlock;
  219918. #if JUCE_USE_XSHM
  219919. usingXShm = false;
  219920. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  219921. {
  219922. zerostruct (segmentInfo);
  219923. segmentInfo.shmid = -1;
  219924. segmentInfo.shmaddr = (char *) -1;
  219925. segmentInfo.readOnly = False;
  219926. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  219927. if (xImage != 0)
  219928. {
  219929. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219930. xImage->bytes_per_line * xImage->height,
  219931. IPC_CREAT | 0777)) >= 0)
  219932. {
  219933. if (segmentInfo.shmid != -1)
  219934. {
  219935. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219936. if (segmentInfo.shmaddr != (void*) -1)
  219937. {
  219938. segmentInfo.readOnly = False;
  219939. xImage->data = segmentInfo.shmaddr;
  219940. imageData = (uint8*) segmentInfo.shmaddr;
  219941. if (XShmAttach (display, &segmentInfo) != 0)
  219942. usingXShm = true;
  219943. else
  219944. jassertfalse;
  219945. }
  219946. else
  219947. {
  219948. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219949. }
  219950. }
  219951. }
  219952. }
  219953. }
  219954. if (! usingXShm)
  219955. #endif
  219956. {
  219957. imageDataAllocated.malloc (lineStride * h);
  219958. imageData = imageDataAllocated;
  219959. if (format_ == Image::ARGB && clearImage)
  219960. zeromem (imageData, h * lineStride);
  219961. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219962. xImage->width = w;
  219963. xImage->height = h;
  219964. xImage->xoffset = 0;
  219965. xImage->format = ZPixmap;
  219966. xImage->data = (char*) imageData;
  219967. xImage->byte_order = ImageByteOrder (display);
  219968. xImage->bitmap_unit = BitmapUnit (display);
  219969. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219970. xImage->bitmap_pad = 32;
  219971. xImage->depth = pixelStride * 8;
  219972. xImage->bytes_per_line = lineStride;
  219973. xImage->bits_per_pixel = pixelStride * 8;
  219974. xImage->red_mask = 0x00FF0000;
  219975. xImage->green_mask = 0x0000FF00;
  219976. xImage->blue_mask = 0x000000FF;
  219977. if (imageDepth == 16)
  219978. {
  219979. const int pixelStride = 2;
  219980. const int lineStride = ((w * pixelStride + 3) & ~3);
  219981. imageData16Bit.malloc (lineStride * h);
  219982. xImage->data = imageData16Bit;
  219983. xImage->bitmap_pad = 16;
  219984. xImage->depth = pixelStride * 8;
  219985. xImage->bytes_per_line = lineStride;
  219986. xImage->bits_per_pixel = pixelStride * 8;
  219987. xImage->red_mask = visual->red_mask;
  219988. xImage->green_mask = visual->green_mask;
  219989. xImage->blue_mask = visual->blue_mask;
  219990. }
  219991. if (! XInitImage (xImage))
  219992. jassertfalse;
  219993. }
  219994. }
  219995. ~XBitmapImage()
  219996. {
  219997. ScopedXLock xlock;
  219998. if (gc != None)
  219999. XFreeGC (display, gc);
  220000. #if JUCE_USE_XSHM
  220001. if (usingXShm)
  220002. {
  220003. XShmDetach (display, &segmentInfo);
  220004. XFlush (display);
  220005. XDestroyImage (xImage);
  220006. shmdt (segmentInfo.shmaddr);
  220007. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220008. }
  220009. else
  220010. #endif
  220011. {
  220012. xImage->data = 0;
  220013. XDestroyImage (xImage);
  220014. }
  220015. }
  220016. Image::ImageType getType() const { return Image::NativeImage; }
  220017. LowLevelGraphicsContext* createLowLevelContext()
  220018. {
  220019. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  220020. }
  220021. SharedImage* clone()
  220022. {
  220023. jassertfalse;
  220024. return 0;
  220025. }
  220026. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  220027. {
  220028. ScopedXLock xlock;
  220029. if (gc == None)
  220030. {
  220031. XGCValues gcvalues;
  220032. gcvalues.foreground = None;
  220033. gcvalues.background = None;
  220034. gcvalues.function = GXcopy;
  220035. gcvalues.plane_mask = AllPlanes;
  220036. gcvalues.clip_mask = None;
  220037. gcvalues.graphics_exposures = False;
  220038. gc = XCreateGC (display, window,
  220039. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  220040. &gcvalues);
  220041. }
  220042. if (imageDepth == 16)
  220043. {
  220044. const uint32 rMask = xImage->red_mask;
  220045. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  220046. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  220047. const uint32 gMask = xImage->green_mask;
  220048. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  220049. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  220050. const uint32 bMask = xImage->blue_mask;
  220051. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  220052. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  220053. const Image::BitmapData srcData (Image (this), false);
  220054. for (int y = sy; y < sy + dh; ++y)
  220055. {
  220056. const uint8* p = srcData.getPixelPointer (sx, y);
  220057. for (int x = sx; x < sx + dw; ++x)
  220058. {
  220059. const PixelRGB* const pixel = (const PixelRGB*) p;
  220060. p += srcData.pixelStride;
  220061. XPutPixel (xImage, x, y,
  220062. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  220063. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  220064. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  220065. }
  220066. }
  220067. }
  220068. // blit results to screen.
  220069. #if JUCE_USE_XSHM
  220070. if (usingXShm)
  220071. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  220072. else
  220073. #endif
  220074. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  220075. }
  220076. juce_UseDebuggingNewOperator
  220077. private:
  220078. XImage* xImage;
  220079. const int imageDepth;
  220080. HeapBlock <uint8> imageDataAllocated;
  220081. HeapBlock <char> imageData16Bit;
  220082. GC gc;
  220083. #if JUCE_USE_XSHM
  220084. XShmSegmentInfo segmentInfo;
  220085. bool usingXShm;
  220086. #endif
  220087. static int getShiftNeeded (const uint32 mask) throw()
  220088. {
  220089. for (int i = 32; --i >= 0;)
  220090. if (((mask >> i) & 1) != 0)
  220091. return i - 7;
  220092. jassertfalse;
  220093. return 0;
  220094. }
  220095. };
  220096. class LinuxComponentPeer : public ComponentPeer
  220097. {
  220098. public:
  220099. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  220100. : ComponentPeer (component, windowStyleFlags),
  220101. windowH (0),
  220102. parentWindow (0),
  220103. wx (0),
  220104. wy (0),
  220105. ww (0),
  220106. wh (0),
  220107. fullScreen (false),
  220108. mapped (false),
  220109. visual (0),
  220110. depth (0)
  220111. {
  220112. // it's dangerous to create a window on a thread other than the message thread..
  220113. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220114. repainter = new LinuxRepaintManager (this);
  220115. createWindow();
  220116. setTitle (component->getName());
  220117. }
  220118. ~LinuxComponentPeer()
  220119. {
  220120. // it's dangerous to delete a window on a thread other than the message thread..
  220121. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220122. deleteIconPixmaps();
  220123. destroyWindow();
  220124. windowH = 0;
  220125. }
  220126. void* getNativeHandle() const
  220127. {
  220128. return (void*) windowH;
  220129. }
  220130. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  220131. {
  220132. XPointer peer = 0;
  220133. ScopedXLock xlock;
  220134. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  220135. {
  220136. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  220137. peer = 0;
  220138. }
  220139. return (LinuxComponentPeer*) peer;
  220140. }
  220141. void setVisible (bool shouldBeVisible)
  220142. {
  220143. ScopedXLock xlock;
  220144. if (shouldBeVisible)
  220145. XMapWindow (display, windowH);
  220146. else
  220147. XUnmapWindow (display, windowH);
  220148. }
  220149. void setTitle (const String& title)
  220150. {
  220151. setWindowTitle (windowH, title);
  220152. }
  220153. void setPosition (int x, int y)
  220154. {
  220155. setBounds (x, y, ww, wh, false);
  220156. }
  220157. void setSize (int w, int h)
  220158. {
  220159. setBounds (wx, wy, w, h, false);
  220160. }
  220161. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  220162. {
  220163. fullScreen = isNowFullScreen;
  220164. if (windowH != 0)
  220165. {
  220166. Component::SafePointer<Component> deletionChecker (component);
  220167. wx = x;
  220168. wy = y;
  220169. ww = jmax (1, w);
  220170. wh = jmax (1, h);
  220171. ScopedXLock xlock;
  220172. // Make sure the Window manager does what we want
  220173. XSizeHints* hints = XAllocSizeHints();
  220174. hints->flags = USSize | USPosition;
  220175. hints->width = ww;
  220176. hints->height = wh;
  220177. hints->x = wx;
  220178. hints->y = wy;
  220179. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  220180. {
  220181. hints->min_width = hints->max_width = hints->width;
  220182. hints->min_height = hints->max_height = hints->height;
  220183. hints->flags |= PMinSize | PMaxSize;
  220184. }
  220185. XSetWMNormalHints (display, windowH, hints);
  220186. XFree (hints);
  220187. XMoveResizeWindow (display, windowH,
  220188. wx - windowBorder.getLeft(),
  220189. wy - windowBorder.getTop(), ww, wh);
  220190. if (deletionChecker != 0)
  220191. {
  220192. updateBorderSize();
  220193. handleMovedOrResized();
  220194. }
  220195. }
  220196. }
  220197. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  220198. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  220199. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  220200. {
  220201. return relativePosition + getScreenPosition();
  220202. }
  220203. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  220204. {
  220205. return screenPosition - getScreenPosition();
  220206. }
  220207. void setMinimised (bool shouldBeMinimised)
  220208. {
  220209. if (shouldBeMinimised)
  220210. {
  220211. Window root = RootWindow (display, DefaultScreen (display));
  220212. XClientMessageEvent clientMsg;
  220213. clientMsg.display = display;
  220214. clientMsg.window = windowH;
  220215. clientMsg.type = ClientMessage;
  220216. clientMsg.format = 32;
  220217. clientMsg.message_type = Atoms::ChangeState;
  220218. clientMsg.data.l[0] = IconicState;
  220219. ScopedXLock xlock;
  220220. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  220221. }
  220222. else
  220223. {
  220224. setVisible (true);
  220225. }
  220226. }
  220227. bool isMinimised() const
  220228. {
  220229. bool minimised = false;
  220230. unsigned char* stateProp;
  220231. unsigned long nitems, bytesLeft;
  220232. Atom actualType;
  220233. int actualFormat;
  220234. ScopedXLock xlock;
  220235. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  220236. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  220237. &stateProp) == Success
  220238. && actualType == Atoms::State
  220239. && actualFormat == 32
  220240. && nitems > 0)
  220241. {
  220242. if (((unsigned long*) stateProp)[0] == IconicState)
  220243. minimised = true;
  220244. XFree (stateProp);
  220245. }
  220246. return minimised;
  220247. }
  220248. void setFullScreen (const bool shouldBeFullScreen)
  220249. {
  220250. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  220251. setMinimised (false);
  220252. if (fullScreen != shouldBeFullScreen)
  220253. {
  220254. if (shouldBeFullScreen)
  220255. r = Desktop::getInstance().getMainMonitorArea();
  220256. if (! r.isEmpty())
  220257. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220258. getComponent()->repaint();
  220259. }
  220260. }
  220261. bool isFullScreen() const
  220262. {
  220263. return fullScreen;
  220264. }
  220265. bool isChildWindowOf (Window possibleParent) const
  220266. {
  220267. Window* windowList = 0;
  220268. uint32 windowListSize = 0;
  220269. Window parent, root;
  220270. ScopedXLock xlock;
  220271. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  220272. {
  220273. if (windowList != 0)
  220274. XFree (windowList);
  220275. return parent == possibleParent;
  220276. }
  220277. return false;
  220278. }
  220279. bool isFrontWindow() const
  220280. {
  220281. Window* windowList = 0;
  220282. uint32 windowListSize = 0;
  220283. bool result = false;
  220284. ScopedXLock xlock;
  220285. Window parent, root = RootWindow (display, DefaultScreen (display));
  220286. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  220287. {
  220288. for (int i = windowListSize; --i >= 0;)
  220289. {
  220290. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  220291. if (peer != 0)
  220292. {
  220293. result = (peer == this);
  220294. break;
  220295. }
  220296. }
  220297. }
  220298. if (windowList != 0)
  220299. XFree (windowList);
  220300. return result;
  220301. }
  220302. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  220303. {
  220304. int x = position.getX();
  220305. int y = position.getY();
  220306. if (((unsigned int) x) >= (unsigned int) ww
  220307. || ((unsigned int) y) >= (unsigned int) wh)
  220308. return false;
  220309. bool inFront = false;
  220310. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  220311. {
  220312. Component* const c = Desktop::getInstance().getComponent (i);
  220313. if (inFront)
  220314. {
  220315. if (c->contains (x + wx - c->getScreenX(),
  220316. y + wy - c->getScreenY()))
  220317. {
  220318. return false;
  220319. }
  220320. }
  220321. else if (c == getComponent())
  220322. {
  220323. inFront = true;
  220324. }
  220325. }
  220326. if (trueIfInAChildWindow)
  220327. return true;
  220328. ::Window root, child;
  220329. unsigned int bw, depth;
  220330. int wx, wy, w, h;
  220331. ScopedXLock xlock;
  220332. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220333. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  220334. &bw, &depth))
  220335. {
  220336. return false;
  220337. }
  220338. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  220339. return false;
  220340. return child == None;
  220341. }
  220342. const BorderSize getFrameSize() const
  220343. {
  220344. return BorderSize();
  220345. }
  220346. bool setAlwaysOnTop (bool alwaysOnTop)
  220347. {
  220348. return false;
  220349. }
  220350. void toFront (bool makeActive)
  220351. {
  220352. if (makeActive)
  220353. {
  220354. setVisible (true);
  220355. grabFocus();
  220356. }
  220357. XEvent ev;
  220358. ev.xclient.type = ClientMessage;
  220359. ev.xclient.serial = 0;
  220360. ev.xclient.send_event = True;
  220361. ev.xclient.message_type = Atoms::ActiveWin;
  220362. ev.xclient.window = windowH;
  220363. ev.xclient.format = 32;
  220364. ev.xclient.data.l[0] = 2;
  220365. ev.xclient.data.l[1] = CurrentTime;
  220366. ev.xclient.data.l[2] = 0;
  220367. ev.xclient.data.l[3] = 0;
  220368. ev.xclient.data.l[4] = 0;
  220369. {
  220370. ScopedXLock xlock;
  220371. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  220372. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  220373. XWindowAttributes attr;
  220374. XGetWindowAttributes (display, windowH, &attr);
  220375. if (component->isAlwaysOnTop())
  220376. XRaiseWindow (display, windowH);
  220377. XSync (display, False);
  220378. }
  220379. handleBroughtToFront();
  220380. }
  220381. void toBehind (ComponentPeer* other)
  220382. {
  220383. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  220384. jassert (otherPeer != 0); // wrong type of window?
  220385. if (otherPeer != 0)
  220386. {
  220387. setMinimised (false);
  220388. Window newStack[] = { otherPeer->windowH, windowH };
  220389. ScopedXLock xlock;
  220390. XRestackWindows (display, newStack, 2);
  220391. }
  220392. }
  220393. bool isFocused() const
  220394. {
  220395. int revert = 0;
  220396. Window focusedWindow = 0;
  220397. ScopedXLock xlock;
  220398. XGetInputFocus (display, &focusedWindow, &revert);
  220399. return focusedWindow == windowH;
  220400. }
  220401. void grabFocus()
  220402. {
  220403. XWindowAttributes atts;
  220404. ScopedXLock xlock;
  220405. if (windowH != 0
  220406. && XGetWindowAttributes (display, windowH, &atts)
  220407. && atts.map_state == IsViewable
  220408. && ! isFocused())
  220409. {
  220410. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  220411. isActiveApplication = true;
  220412. }
  220413. }
  220414. void textInputRequired (const Point<int>&)
  220415. {
  220416. }
  220417. void repaint (const Rectangle<int>& area)
  220418. {
  220419. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220420. }
  220421. void performAnyPendingRepaintsNow()
  220422. {
  220423. repainter->performAnyPendingRepaintsNow();
  220424. }
  220425. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  220426. {
  220427. ScopedXLock xlock;
  220428. const int width = image.getWidth();
  220429. const int height = image.getHeight();
  220430. HeapBlock <char> colour (width * height);
  220431. int index = 0;
  220432. for (int y = 0; y < height; ++y)
  220433. for (int x = 0; x < width; ++x)
  220434. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  220435. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  220436. 0, colour.getData(),
  220437. width, height, 32, 0);
  220438. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  220439. width, height, 24);
  220440. GC gc = XCreateGC (display, pixmap, 0, 0);
  220441. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  220442. XFreeGC (display, gc);
  220443. return pixmap;
  220444. }
  220445. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  220446. {
  220447. ScopedXLock xlock;
  220448. const int width = image.getWidth();
  220449. const int height = image.getHeight();
  220450. const int stride = (width + 7) >> 3;
  220451. HeapBlock <char> mask;
  220452. mask.calloc (stride * height);
  220453. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220454. for (int y = 0; y < height; ++y)
  220455. {
  220456. for (int x = 0; x < width; ++x)
  220457. {
  220458. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220459. const int offset = y * stride + (x >> 3);
  220460. if (image.getPixelAt (x, y).getAlpha() >= 128)
  220461. mask[offset] |= bit;
  220462. }
  220463. }
  220464. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  220465. mask.getData(), width, height, 1, 0, 1);
  220466. }
  220467. void setIcon (const Image& newIcon)
  220468. {
  220469. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220470. HeapBlock <unsigned long> data (dataSize);
  220471. int index = 0;
  220472. data[index++] = newIcon.getWidth();
  220473. data[index++] = newIcon.getHeight();
  220474. for (int y = 0; y < newIcon.getHeight(); ++y)
  220475. for (int x = 0; x < newIcon.getWidth(); ++x)
  220476. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220477. ScopedXLock xlock;
  220478. XChangeProperty (display, windowH,
  220479. XInternAtom (display, "_NET_WM_ICON", False),
  220480. XA_CARDINAL, 32, PropModeReplace,
  220481. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220482. deleteIconPixmaps();
  220483. XWMHints* wmHints = XGetWMHints (display, windowH);
  220484. if (wmHints == 0)
  220485. wmHints = XAllocWMHints();
  220486. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220487. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  220488. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  220489. XSetWMHints (display, windowH, wmHints);
  220490. XFree (wmHints);
  220491. XSync (display, False);
  220492. }
  220493. void deleteIconPixmaps()
  220494. {
  220495. ScopedXLock xlock;
  220496. XWMHints* wmHints = XGetWMHints (display, windowH);
  220497. if (wmHints != 0)
  220498. {
  220499. if ((wmHints->flags & IconPixmapHint) != 0)
  220500. {
  220501. wmHints->flags &= ~IconPixmapHint;
  220502. XFreePixmap (display, wmHints->icon_pixmap);
  220503. }
  220504. if ((wmHints->flags & IconMaskHint) != 0)
  220505. {
  220506. wmHints->flags &= ~IconMaskHint;
  220507. XFreePixmap (display, wmHints->icon_mask);
  220508. }
  220509. XSetWMHints (display, windowH, wmHints);
  220510. XFree (wmHints);
  220511. }
  220512. }
  220513. void handleWindowMessage (XEvent* event)
  220514. {
  220515. switch (event->xany.type)
  220516. {
  220517. case 2: // 'KeyPress'
  220518. {
  220519. ScopedXLock xlock;
  220520. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  220521. updateKeyStates (keyEvent->keycode, true);
  220522. char utf8 [64];
  220523. zeromem (utf8, sizeof (utf8));
  220524. KeySym sym;
  220525. {
  220526. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220527. ::setlocale (LC_ALL, "");
  220528. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220529. ::setlocale (LC_ALL, oldLocale);
  220530. }
  220531. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220532. int keyCode = (int) unicodeChar;
  220533. if (keyCode < 0x20)
  220534. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220535. const ModifierKeys oldMods (currentModifiers);
  220536. bool keyPressed = false;
  220537. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220538. if ((sym & 0xff00) == 0xff00)
  220539. {
  220540. // Translate keypad
  220541. if (sym == XK_KP_Divide)
  220542. keyCode = XK_slash;
  220543. else if (sym == XK_KP_Multiply)
  220544. keyCode = XK_asterisk;
  220545. else if (sym == XK_KP_Subtract)
  220546. keyCode = XK_hyphen;
  220547. else if (sym == XK_KP_Add)
  220548. keyCode = XK_plus;
  220549. else if (sym == XK_KP_Enter)
  220550. keyCode = XK_Return;
  220551. else if (sym == XK_KP_Decimal)
  220552. keyCode = Keys::numLock ? XK_period : XK_Delete;
  220553. else if (sym == XK_KP_0)
  220554. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  220555. else if (sym == XK_KP_1)
  220556. keyCode = Keys::numLock ? XK_1 : XK_End;
  220557. else if (sym == XK_KP_2)
  220558. keyCode = Keys::numLock ? XK_2 : XK_Down;
  220559. else if (sym == XK_KP_3)
  220560. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  220561. else if (sym == XK_KP_4)
  220562. keyCode = Keys::numLock ? XK_4 : XK_Left;
  220563. else if (sym == XK_KP_5)
  220564. keyCode = XK_5;
  220565. else if (sym == XK_KP_6)
  220566. keyCode = Keys::numLock ? XK_6 : XK_Right;
  220567. else if (sym == XK_KP_7)
  220568. keyCode = Keys::numLock ? XK_7 : XK_Home;
  220569. else if (sym == XK_KP_8)
  220570. keyCode = Keys::numLock ? XK_8 : XK_Up;
  220571. else if (sym == XK_KP_9)
  220572. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  220573. switch (sym)
  220574. {
  220575. case XK_Left:
  220576. case XK_Right:
  220577. case XK_Up:
  220578. case XK_Down:
  220579. case XK_Page_Up:
  220580. case XK_Page_Down:
  220581. case XK_End:
  220582. case XK_Home:
  220583. case XK_Delete:
  220584. case XK_Insert:
  220585. keyPressed = true;
  220586. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220587. break;
  220588. case XK_Tab:
  220589. case XK_Return:
  220590. case XK_Escape:
  220591. case XK_BackSpace:
  220592. keyPressed = true;
  220593. keyCode &= 0xff;
  220594. break;
  220595. default:
  220596. {
  220597. if (sym >= XK_F1 && sym <= XK_F16)
  220598. {
  220599. keyPressed = true;
  220600. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220601. }
  220602. break;
  220603. }
  220604. }
  220605. }
  220606. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220607. keyPressed = true;
  220608. if (oldMods != currentModifiers)
  220609. handleModifierKeysChange();
  220610. if (keyDownChange)
  220611. handleKeyUpOrDown (true);
  220612. if (keyPressed)
  220613. handleKeyPress (keyCode, unicodeChar);
  220614. break;
  220615. }
  220616. case KeyRelease:
  220617. {
  220618. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  220619. updateKeyStates (keyEvent->keycode, false);
  220620. KeySym sym;
  220621. {
  220622. ScopedXLock xlock;
  220623. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220624. }
  220625. const ModifierKeys oldMods (currentModifiers);
  220626. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220627. if (oldMods != currentModifiers)
  220628. handleModifierKeysChange();
  220629. if (keyDownChange)
  220630. handleKeyUpOrDown (false);
  220631. break;
  220632. }
  220633. case ButtonPress:
  220634. {
  220635. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  220636. updateKeyModifiers (buttonPressEvent->state);
  220637. bool buttonMsg = false;
  220638. const int map = pointerMap [buttonPressEvent->button - Button1];
  220639. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220640. {
  220641. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220642. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220643. }
  220644. if (map == Keys::LeftButton)
  220645. {
  220646. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220647. buttonMsg = true;
  220648. }
  220649. else if (map == Keys::RightButton)
  220650. {
  220651. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220652. buttonMsg = true;
  220653. }
  220654. else if (map == Keys::MiddleButton)
  220655. {
  220656. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220657. buttonMsg = true;
  220658. }
  220659. if (buttonMsg)
  220660. {
  220661. toFront (true);
  220662. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220663. getEventTime (buttonPressEvent->time));
  220664. }
  220665. clearLastMousePos();
  220666. break;
  220667. }
  220668. case ButtonRelease:
  220669. {
  220670. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  220671. updateKeyModifiers (buttonRelEvent->state);
  220672. const int map = pointerMap [buttonRelEvent->button - Button1];
  220673. if (map == Keys::LeftButton)
  220674. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220675. else if (map == Keys::RightButton)
  220676. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220677. else if (map == Keys::MiddleButton)
  220678. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220679. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220680. getEventTime (buttonRelEvent->time));
  220681. clearLastMousePos();
  220682. break;
  220683. }
  220684. case MotionNotify:
  220685. {
  220686. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  220687. updateKeyModifiers (movedEvent->state);
  220688. const Point<int> mousePos (Desktop::getMousePosition());
  220689. if (lastMousePos != mousePos)
  220690. {
  220691. lastMousePos = mousePos;
  220692. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220693. {
  220694. Window wRoot = 0, wParent = 0;
  220695. {
  220696. ScopedXLock xlock;
  220697. unsigned int numChildren;
  220698. Window* wChild = 0;
  220699. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220700. }
  220701. if (wParent != 0
  220702. && wParent != windowH
  220703. && wParent != wRoot)
  220704. {
  220705. parentWindow = wParent;
  220706. updateBounds();
  220707. }
  220708. else
  220709. {
  220710. parentWindow = 0;
  220711. }
  220712. }
  220713. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220714. }
  220715. break;
  220716. }
  220717. case EnterNotify:
  220718. {
  220719. clearLastMousePos();
  220720. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  220721. if (! currentModifiers.isAnyMouseButtonDown())
  220722. {
  220723. updateKeyModifiers (enterEvent->state);
  220724. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220725. }
  220726. break;
  220727. }
  220728. case LeaveNotify:
  220729. {
  220730. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  220731. // Suppress the normal leave if we've got a pointer grab, or if
  220732. // it's a bogus one caused by clicking a mouse button when running
  220733. // in a Window manager
  220734. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220735. || leaveEvent->mode == NotifyUngrab)
  220736. {
  220737. updateKeyModifiers (leaveEvent->state);
  220738. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220739. }
  220740. break;
  220741. }
  220742. case FocusIn:
  220743. {
  220744. isActiveApplication = true;
  220745. if (isFocused())
  220746. handleFocusGain();
  220747. break;
  220748. }
  220749. case FocusOut:
  220750. {
  220751. isActiveApplication = false;
  220752. if (! isFocused())
  220753. handleFocusLoss();
  220754. break;
  220755. }
  220756. case Expose:
  220757. {
  220758. // Batch together all pending expose events
  220759. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  220760. XEvent nextEvent;
  220761. ScopedXLock xlock;
  220762. if (exposeEvent->window != windowH)
  220763. {
  220764. Window child;
  220765. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220766. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220767. &child);
  220768. }
  220769. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220770. exposeEvent->width, exposeEvent->height));
  220771. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220772. {
  220773. XPeekEvent (display, (XEvent*) &nextEvent);
  220774. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  220775. break;
  220776. XNextEvent (display, (XEvent*) &nextEvent);
  220777. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220778. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220779. nextExposeEvent->width, nextExposeEvent->height));
  220780. }
  220781. break;
  220782. }
  220783. case CirculateNotify:
  220784. case CreateNotify:
  220785. case DestroyNotify:
  220786. // Think we can ignore these
  220787. break;
  220788. case ConfigureNotify:
  220789. {
  220790. updateBounds();
  220791. updateBorderSize();
  220792. handleMovedOrResized();
  220793. // if the native title bar is dragged, need to tell any active menus, etc.
  220794. if ((styleFlags & windowHasTitleBar) != 0
  220795. && component->isCurrentlyBlockedByAnotherModalComponent())
  220796. {
  220797. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220798. if (currentModalComp != 0)
  220799. currentModalComp->inputAttemptWhenModal();
  220800. }
  220801. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  220802. if (confEvent->window == windowH
  220803. && confEvent->above != 0
  220804. && isFrontWindow())
  220805. {
  220806. handleBroughtToFront();
  220807. }
  220808. break;
  220809. }
  220810. case ReparentNotify:
  220811. {
  220812. parentWindow = 0;
  220813. Window wRoot = 0;
  220814. Window* wChild = 0;
  220815. unsigned int numChildren;
  220816. {
  220817. ScopedXLock xlock;
  220818. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  220819. }
  220820. if (parentWindow == windowH || parentWindow == wRoot)
  220821. parentWindow = 0;
  220822. updateBounds();
  220823. updateBorderSize();
  220824. handleMovedOrResized();
  220825. break;
  220826. }
  220827. case GravityNotify:
  220828. {
  220829. updateBounds();
  220830. updateBorderSize();
  220831. handleMovedOrResized();
  220832. break;
  220833. }
  220834. case MapNotify:
  220835. mapped = true;
  220836. handleBroughtToFront();
  220837. break;
  220838. case UnmapNotify:
  220839. mapped = false;
  220840. break;
  220841. case MappingNotify:
  220842. {
  220843. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  220844. if (mappingEvent->request != MappingPointer)
  220845. {
  220846. // Deal with modifier/keyboard mapping
  220847. ScopedXLock xlock;
  220848. XRefreshKeyboardMapping (mappingEvent);
  220849. updateModifierMappings();
  220850. }
  220851. break;
  220852. }
  220853. case ClientMessage:
  220854. {
  220855. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  220856. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  220857. {
  220858. const Atom atom = (Atom) clientMsg->data.l[0];
  220859. if (atom == Atoms::ProtocolList [Atoms::PING])
  220860. {
  220861. Window root = RootWindow (display, DefaultScreen (display));
  220862. event->xclient.window = root;
  220863. XSendEvent (display, root, False, NoEventMask, event);
  220864. XFlush (display);
  220865. }
  220866. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  220867. {
  220868. XWindowAttributes atts;
  220869. ScopedXLock xlock;
  220870. if (clientMsg->window != 0
  220871. && XGetWindowAttributes (display, clientMsg->window, &atts))
  220872. {
  220873. if (atts.map_state == IsViewable)
  220874. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  220875. }
  220876. }
  220877. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  220878. {
  220879. handleUserClosingWindow();
  220880. }
  220881. }
  220882. else if (clientMsg->message_type == Atoms::XdndEnter)
  220883. {
  220884. handleDragAndDropEnter (clientMsg);
  220885. }
  220886. else if (clientMsg->message_type == Atoms::XdndLeave)
  220887. {
  220888. resetDragAndDrop();
  220889. }
  220890. else if (clientMsg->message_type == Atoms::XdndPosition)
  220891. {
  220892. handleDragAndDropPosition (clientMsg);
  220893. }
  220894. else if (clientMsg->message_type == Atoms::XdndDrop)
  220895. {
  220896. handleDragAndDropDrop (clientMsg);
  220897. }
  220898. else if (clientMsg->message_type == Atoms::XdndStatus)
  220899. {
  220900. handleDragAndDropStatus (clientMsg);
  220901. }
  220902. else if (clientMsg->message_type == Atoms::XdndFinished)
  220903. {
  220904. resetDragAndDrop();
  220905. }
  220906. break;
  220907. }
  220908. case SelectionNotify:
  220909. handleDragAndDropSelection (event);
  220910. break;
  220911. case SelectionClear:
  220912. case SelectionRequest:
  220913. break;
  220914. default:
  220915. #if JUCE_USE_XSHM
  220916. {
  220917. ScopedXLock xlock;
  220918. if (event->xany.type == XShmGetEventBase (display))
  220919. repainter->notifyPaintCompleted();
  220920. }
  220921. #endif
  220922. break;
  220923. }
  220924. }
  220925. void showMouseCursor (Cursor cursor) throw()
  220926. {
  220927. ScopedXLock xlock;
  220928. XDefineCursor (display, windowH, cursor);
  220929. }
  220930. void setTaskBarIcon (const Image& image)
  220931. {
  220932. ScopedXLock xlock;
  220933. taskbarImage = image;
  220934. Screen* const screen = XDefaultScreenOfDisplay (display);
  220935. const int screenNumber = XScreenNumberOfScreen (screen);
  220936. String screenAtom ("_NET_SYSTEM_TRAY_S");
  220937. screenAtom << screenNumber;
  220938. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  220939. XGrabServer (display);
  220940. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  220941. if (managerWin != None)
  220942. XSelectInput (display, managerWin, StructureNotifyMask);
  220943. XUngrabServer (display);
  220944. XFlush (display);
  220945. if (managerWin != None)
  220946. {
  220947. XEvent ev;
  220948. zerostruct (ev);
  220949. ev.xclient.type = ClientMessage;
  220950. ev.xclient.window = managerWin;
  220951. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  220952. ev.xclient.format = 32;
  220953. ev.xclient.data.l[0] = CurrentTime;
  220954. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  220955. ev.xclient.data.l[2] = windowH;
  220956. ev.xclient.data.l[3] = 0;
  220957. ev.xclient.data.l[4] = 0;
  220958. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  220959. XSync (display, False);
  220960. }
  220961. // For older KDE's ...
  220962. long atomData = 1;
  220963. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  220964. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  220965. // For more recent KDE's...
  220966. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  220967. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  220968. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  220969. XSizeHints* hints = XAllocSizeHints();
  220970. hints->flags = PMinSize;
  220971. hints->min_width = 22;
  220972. hints->min_height = 22;
  220973. XSetWMNormalHints (display, windowH, hints);
  220974. XFree (hints);
  220975. }
  220976. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  220977. juce_UseDebuggingNewOperator
  220978. bool dontRepaint;
  220979. static ModifierKeys currentModifiers;
  220980. static bool isActiveApplication;
  220981. private:
  220982. class LinuxRepaintManager : public Timer
  220983. {
  220984. public:
  220985. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  220986. : peer (peer_),
  220987. lastTimeImageUsed (0)
  220988. {
  220989. #if JUCE_USE_XSHM
  220990. shmCompletedDrawing = true;
  220991. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220992. if (useARGBImagesForRendering)
  220993. {
  220994. ScopedXLock xlock;
  220995. XShmSegmentInfo segmentinfo;
  220996. XImage* const testImage
  220997. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220998. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  220999. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  221000. XDestroyImage (testImage);
  221001. }
  221002. #endif
  221003. }
  221004. ~LinuxRepaintManager()
  221005. {
  221006. }
  221007. void timerCallback()
  221008. {
  221009. #if JUCE_USE_XSHM
  221010. if (! shmCompletedDrawing)
  221011. return;
  221012. #endif
  221013. if (! regionsNeedingRepaint.isEmpty())
  221014. {
  221015. stopTimer();
  221016. performAnyPendingRepaintsNow();
  221017. }
  221018. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  221019. {
  221020. stopTimer();
  221021. image = Image::null;
  221022. }
  221023. }
  221024. void repaint (const Rectangle<int>& area)
  221025. {
  221026. if (! isTimerRunning())
  221027. startTimer (repaintTimerPeriod);
  221028. regionsNeedingRepaint.add (area);
  221029. }
  221030. void performAnyPendingRepaintsNow()
  221031. {
  221032. #if JUCE_USE_XSHM
  221033. if (! shmCompletedDrawing)
  221034. {
  221035. startTimer (repaintTimerPeriod);
  221036. return;
  221037. }
  221038. #endif
  221039. peer->clearMaskedRegion();
  221040. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  221041. regionsNeedingRepaint.clear();
  221042. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  221043. if (! totalArea.isEmpty())
  221044. {
  221045. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  221046. || image.getHeight() < totalArea.getHeight())
  221047. {
  221048. #if JUCE_USE_XSHM
  221049. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  221050. : Image::RGB,
  221051. #else
  221052. image = Image (new XBitmapImage (Image::RGB,
  221053. #endif
  221054. (totalArea.getWidth() + 31) & ~31,
  221055. (totalArea.getHeight() + 31) & ~31,
  221056. false, peer->depth, peer->visual));
  221057. }
  221058. startTimer (repaintTimerPeriod);
  221059. RectangleList adjustedList (originalRepaintRegion);
  221060. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  221061. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  221062. if (peer->depth == 32)
  221063. {
  221064. RectangleList::Iterator i (originalRepaintRegion);
  221065. while (i.next())
  221066. image.clear (*i.getRectangle() - totalArea.getPosition());
  221067. }
  221068. peer->handlePaint (context);
  221069. if (! peer->maskedRegion.isEmpty())
  221070. originalRepaintRegion.subtract (peer->maskedRegion);
  221071. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  221072. {
  221073. #if JUCE_USE_XSHM
  221074. shmCompletedDrawing = false;
  221075. #endif
  221076. const Rectangle<int>& r = *i.getRectangle();
  221077. static_cast<XBitmapImage*> (image.getSharedImage())
  221078. ->blitToWindow (peer->windowH,
  221079. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  221080. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  221081. }
  221082. }
  221083. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  221084. startTimer (repaintTimerPeriod);
  221085. }
  221086. #if JUCE_USE_XSHM
  221087. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  221088. #endif
  221089. private:
  221090. enum { repaintTimerPeriod = 1000 / 100 };
  221091. LinuxComponentPeer* const peer;
  221092. Image image;
  221093. uint32 lastTimeImageUsed;
  221094. RectangleList regionsNeedingRepaint;
  221095. #if JUCE_USE_XSHM
  221096. bool useARGBImagesForRendering, shmCompletedDrawing;
  221097. #endif
  221098. LinuxRepaintManager (const LinuxRepaintManager&);
  221099. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  221100. };
  221101. ScopedPointer <LinuxRepaintManager> repainter;
  221102. friend class LinuxRepaintManager;
  221103. Window windowH, parentWindow;
  221104. int wx, wy, ww, wh;
  221105. Image taskbarImage;
  221106. bool fullScreen, mapped;
  221107. Visual* visual;
  221108. int depth;
  221109. BorderSize windowBorder;
  221110. struct MotifWmHints
  221111. {
  221112. unsigned long flags;
  221113. unsigned long functions;
  221114. unsigned long decorations;
  221115. long input_mode;
  221116. unsigned long status;
  221117. };
  221118. static void updateKeyStates (const int keycode, const bool press) throw()
  221119. {
  221120. const int keybyte = keycode >> 3;
  221121. const int keybit = (1 << (keycode & 7));
  221122. if (press)
  221123. Keys::keyStates [keybyte] |= keybit;
  221124. else
  221125. Keys::keyStates [keybyte] &= ~keybit;
  221126. }
  221127. static void updateKeyModifiers (const int status) throw()
  221128. {
  221129. int keyMods = 0;
  221130. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  221131. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  221132. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  221133. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  221134. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  221135. Keys::capsLock = ((status & LockMask) != 0);
  221136. }
  221137. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  221138. {
  221139. int modifier = 0;
  221140. bool isModifier = true;
  221141. switch (sym)
  221142. {
  221143. case XK_Shift_L:
  221144. case XK_Shift_R:
  221145. modifier = ModifierKeys::shiftModifier;
  221146. break;
  221147. case XK_Control_L:
  221148. case XK_Control_R:
  221149. modifier = ModifierKeys::ctrlModifier;
  221150. break;
  221151. case XK_Alt_L:
  221152. case XK_Alt_R:
  221153. modifier = ModifierKeys::altModifier;
  221154. break;
  221155. case XK_Num_Lock:
  221156. if (press)
  221157. Keys::numLock = ! Keys::numLock;
  221158. break;
  221159. case XK_Caps_Lock:
  221160. if (press)
  221161. Keys::capsLock = ! Keys::capsLock;
  221162. break;
  221163. case XK_Scroll_Lock:
  221164. break;
  221165. default:
  221166. isModifier = false;
  221167. break;
  221168. }
  221169. if (modifier != 0)
  221170. {
  221171. if (press)
  221172. currentModifiers = currentModifiers.withFlags (modifier);
  221173. else
  221174. currentModifiers = currentModifiers.withoutFlags (modifier);
  221175. }
  221176. return isModifier;
  221177. }
  221178. // Alt and Num lock are not defined by standard X
  221179. // modifier constants: check what they're mapped to
  221180. static void updateModifierMappings() throw()
  221181. {
  221182. ScopedXLock xlock;
  221183. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  221184. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  221185. Keys::AltMask = 0;
  221186. Keys::NumLockMask = 0;
  221187. XModifierKeymap* mapping = XGetModifierMapping (display);
  221188. if (mapping)
  221189. {
  221190. for (int i = 0; i < 8; i++)
  221191. {
  221192. if (mapping->modifiermap [i << 1] == altLeftCode)
  221193. Keys::AltMask = 1 << i;
  221194. else if (mapping->modifiermap [i << 1] == numLockCode)
  221195. Keys::NumLockMask = 1 << i;
  221196. }
  221197. XFreeModifiermap (mapping);
  221198. }
  221199. }
  221200. void removeWindowDecorations (Window wndH)
  221201. {
  221202. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221203. if (hints != None)
  221204. {
  221205. MotifWmHints motifHints;
  221206. zerostruct (motifHints);
  221207. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  221208. motifHints.decorations = 0;
  221209. ScopedXLock xlock;
  221210. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221211. (unsigned char*) &motifHints, 4);
  221212. }
  221213. hints = XInternAtom (display, "_WIN_HINTS", True);
  221214. if (hints != None)
  221215. {
  221216. long gnomeHints = 0;
  221217. ScopedXLock xlock;
  221218. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221219. (unsigned char*) &gnomeHints, 1);
  221220. }
  221221. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  221222. if (hints != None)
  221223. {
  221224. long kwmHints = 2; /*KDE_tinyDecoration*/
  221225. ScopedXLock xlock;
  221226. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221227. (unsigned char*) &kwmHints, 1);
  221228. }
  221229. }
  221230. void addWindowButtons (Window wndH)
  221231. {
  221232. ScopedXLock xlock;
  221233. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221234. if (hints != None)
  221235. {
  221236. MotifWmHints motifHints;
  221237. zerostruct (motifHints);
  221238. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  221239. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  221240. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  221241. if ((styleFlags & windowHasCloseButton) != 0)
  221242. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  221243. if ((styleFlags & windowHasMinimiseButton) != 0)
  221244. {
  221245. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  221246. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  221247. }
  221248. if ((styleFlags & windowHasMaximiseButton) != 0)
  221249. {
  221250. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  221251. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  221252. }
  221253. if ((styleFlags & windowIsResizable) != 0)
  221254. {
  221255. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  221256. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  221257. }
  221258. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  221259. }
  221260. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  221261. if (hints != None)
  221262. {
  221263. int netHints [6];
  221264. int num = 0;
  221265. if ((styleFlags & windowIsResizable) != 0)
  221266. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  221267. if ((styleFlags & windowHasMaximiseButton) != 0)
  221268. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  221269. if ((styleFlags & windowHasMinimiseButton) != 0)
  221270. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  221271. if ((styleFlags & windowHasCloseButton) != 0)
  221272. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  221273. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  221274. }
  221275. }
  221276. void setWindowType()
  221277. {
  221278. int netHints [2];
  221279. int numHints = 0;
  221280. if ((styleFlags & windowIsTemporary) != 0
  221281. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  221282. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  221283. else
  221284. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  221285. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  221286. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  221287. (unsigned char*) &netHints, numHints);
  221288. numHints = 0;
  221289. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  221290. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  221291. if (component->isAlwaysOnTop())
  221292. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  221293. if (numHints > 0)
  221294. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  221295. (unsigned char*) &netHints, numHints);
  221296. }
  221297. void createWindow()
  221298. {
  221299. ScopedXLock xlock;
  221300. Atoms::initialiseAtoms();
  221301. resetDragAndDrop();
  221302. // Get defaults for various properties
  221303. const int screen = DefaultScreen (display);
  221304. Window root = RootWindow (display, screen);
  221305. // Try to obtain a 32-bit visual or fallback to 24 or 16
  221306. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  221307. if (visual == 0)
  221308. {
  221309. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  221310. Process::terminate();
  221311. }
  221312. // Create and install a colormap suitable fr our visual
  221313. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  221314. XInstallColormap (display, colormap);
  221315. // Set up the window attributes
  221316. XSetWindowAttributes swa;
  221317. swa.border_pixel = 0;
  221318. swa.background_pixmap = None;
  221319. swa.colormap = colormap;
  221320. swa.event_mask = getAllEventsMask();
  221321. windowH = XCreateWindow (display, root,
  221322. 0, 0, 1, 1,
  221323. 0, depth, InputOutput, visual,
  221324. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  221325. &swa);
  221326. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  221327. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  221328. GrabModeAsync, GrabModeAsync, None, None);
  221329. // Set the window context to identify the window handle object
  221330. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  221331. {
  221332. // Failed
  221333. jassertfalse;
  221334. Logger::outputDebugString ("Failed to create context information for window.\n");
  221335. XDestroyWindow (display, windowH);
  221336. windowH = 0;
  221337. return;
  221338. }
  221339. // Set window manager hints
  221340. XWMHints* wmHints = XAllocWMHints();
  221341. wmHints->flags = InputHint | StateHint;
  221342. wmHints->input = True; // Locally active input model
  221343. wmHints->initial_state = NormalState;
  221344. XSetWMHints (display, windowH, wmHints);
  221345. XFree (wmHints);
  221346. // Set the window type
  221347. setWindowType();
  221348. // Define decoration
  221349. if ((styleFlags & windowHasTitleBar) == 0)
  221350. removeWindowDecorations (windowH);
  221351. else
  221352. addWindowButtons (windowH);
  221353. // Set window name
  221354. setWindowTitle (windowH, getComponent()->getName());
  221355. // Associate the PID, allowing to be shut down when something goes wrong
  221356. unsigned long pid = getpid();
  221357. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  221358. (unsigned char*) &pid, 1);
  221359. // Set window manager protocols
  221360. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  221361. (unsigned char*) Atoms::ProtocolList, 2);
  221362. // Set drag and drop flags
  221363. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  221364. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  221365. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  221366. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  221367. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  221368. (const unsigned char*) "", 0);
  221369. unsigned long dndVersion = Atoms::DndVersion;
  221370. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  221371. (const unsigned char*) &dndVersion, 1);
  221372. // Initialise the pointer and keyboard mapping
  221373. // This is not the same as the logical pointer mapping the X server uses:
  221374. // we don't mess with this.
  221375. static bool mappingInitialised = false;
  221376. if (! mappingInitialised)
  221377. {
  221378. mappingInitialised = true;
  221379. const int numButtons = XGetPointerMapping (display, 0, 0);
  221380. if (numButtons == 2)
  221381. {
  221382. pointerMap[0] = Keys::LeftButton;
  221383. pointerMap[1] = Keys::RightButton;
  221384. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  221385. }
  221386. else if (numButtons >= 3)
  221387. {
  221388. pointerMap[0] = Keys::LeftButton;
  221389. pointerMap[1] = Keys::MiddleButton;
  221390. pointerMap[2] = Keys::RightButton;
  221391. if (numButtons >= 5)
  221392. {
  221393. pointerMap[3] = Keys::WheelUp;
  221394. pointerMap[4] = Keys::WheelDown;
  221395. }
  221396. }
  221397. updateModifierMappings();
  221398. }
  221399. }
  221400. void destroyWindow()
  221401. {
  221402. ScopedXLock xlock;
  221403. XPointer handlePointer;
  221404. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  221405. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  221406. XDestroyWindow (display, windowH);
  221407. // Wait for it to complete and then remove any events for this
  221408. // window from the event queue.
  221409. XSync (display, false);
  221410. XEvent event;
  221411. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  221412. {}
  221413. }
  221414. static int getAllEventsMask() throw()
  221415. {
  221416. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  221417. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  221418. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  221419. }
  221420. static int64 getEventTime (::Time t)
  221421. {
  221422. static int64 eventTimeOffset = 0x12345678;
  221423. const int64 thisMessageTime = t;
  221424. if (eventTimeOffset == 0x12345678)
  221425. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  221426. return eventTimeOffset + thisMessageTime;
  221427. }
  221428. static void setWindowTitle (Window xwin, const String& title)
  221429. {
  221430. XTextProperty nameProperty;
  221431. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  221432. ScopedXLock xlock;
  221433. if (XStringListToTextProperty (strings, 1, &nameProperty))
  221434. {
  221435. XSetWMName (display, xwin, &nameProperty);
  221436. XSetWMIconName (display, xwin, &nameProperty);
  221437. XFree (nameProperty.value);
  221438. }
  221439. }
  221440. void updateBorderSize()
  221441. {
  221442. if ((styleFlags & windowHasTitleBar) == 0)
  221443. {
  221444. windowBorder = BorderSize (0);
  221445. }
  221446. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  221447. {
  221448. ScopedXLock xlock;
  221449. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  221450. if (hints != None)
  221451. {
  221452. unsigned char* data = 0;
  221453. unsigned long nitems, bytesLeft;
  221454. Atom actualType;
  221455. int actualFormat;
  221456. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  221457. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221458. &data) == Success)
  221459. {
  221460. const unsigned long* const sizes = (const unsigned long*) data;
  221461. if (actualFormat == 32)
  221462. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  221463. (int) sizes[3], (int) sizes[1]);
  221464. XFree (data);
  221465. }
  221466. }
  221467. }
  221468. }
  221469. void updateBounds()
  221470. {
  221471. jassert (windowH != 0);
  221472. if (windowH != 0)
  221473. {
  221474. Window root, child;
  221475. unsigned int bw, depth;
  221476. ScopedXLock xlock;
  221477. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221478. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  221479. &bw, &depth))
  221480. {
  221481. wx = wy = ww = wh = 0;
  221482. }
  221483. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  221484. {
  221485. wx = wy = 0;
  221486. }
  221487. }
  221488. }
  221489. void resetDragAndDrop()
  221490. {
  221491. dragAndDropFiles.clear();
  221492. lastDropPos = Point<int> (-1, -1);
  221493. dragAndDropCurrentMimeType = 0;
  221494. dragAndDropSourceWindow = 0;
  221495. srcMimeTypeAtomList.clear();
  221496. }
  221497. void sendDragAndDropMessage (XClientMessageEvent& msg)
  221498. {
  221499. msg.type = ClientMessage;
  221500. msg.display = display;
  221501. msg.window = dragAndDropSourceWindow;
  221502. msg.format = 32;
  221503. msg.data.l[0] = windowH;
  221504. ScopedXLock xlock;
  221505. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221506. }
  221507. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221508. {
  221509. XClientMessageEvent msg;
  221510. zerostruct (msg);
  221511. msg.message_type = Atoms::XdndStatus;
  221512. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221513. msg.data.l[4] = dropAction;
  221514. sendDragAndDropMessage (msg);
  221515. }
  221516. void sendDragAndDropLeave()
  221517. {
  221518. XClientMessageEvent msg;
  221519. zerostruct (msg);
  221520. msg.message_type = Atoms::XdndLeave;
  221521. sendDragAndDropMessage (msg);
  221522. }
  221523. void sendDragAndDropFinish()
  221524. {
  221525. XClientMessageEvent msg;
  221526. zerostruct (msg);
  221527. msg.message_type = Atoms::XdndFinished;
  221528. sendDragAndDropMessage (msg);
  221529. }
  221530. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221531. {
  221532. if ((clientMsg->data.l[1] & 1) == 0)
  221533. {
  221534. sendDragAndDropLeave();
  221535. if (dragAndDropFiles.size() > 0)
  221536. handleFileDragExit (dragAndDropFiles);
  221537. dragAndDropFiles.clear();
  221538. }
  221539. }
  221540. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221541. {
  221542. if (dragAndDropSourceWindow == 0)
  221543. return;
  221544. dragAndDropSourceWindow = clientMsg->data.l[0];
  221545. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221546. (int) clientMsg->data.l[2] & 0xffff);
  221547. dropPos -= getScreenPosition();
  221548. if (lastDropPos != dropPos)
  221549. {
  221550. lastDropPos = dropPos;
  221551. dragAndDropTimestamp = clientMsg->data.l[3];
  221552. Atom targetAction = Atoms::XdndActionCopy;
  221553. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221554. {
  221555. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221556. {
  221557. targetAction = Atoms::allowedActions[i];
  221558. break;
  221559. }
  221560. }
  221561. sendDragAndDropStatus (true, targetAction);
  221562. if (dragAndDropFiles.size() == 0)
  221563. updateDraggedFileList (clientMsg);
  221564. if (dragAndDropFiles.size() > 0)
  221565. handleFileDragMove (dragAndDropFiles, dropPos);
  221566. }
  221567. }
  221568. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221569. {
  221570. if (dragAndDropFiles.size() == 0)
  221571. updateDraggedFileList (clientMsg);
  221572. const StringArray files (dragAndDropFiles);
  221573. const Point<int> lastPos (lastDropPos);
  221574. sendDragAndDropFinish();
  221575. resetDragAndDrop();
  221576. if (files.size() > 0)
  221577. handleFileDragDrop (files, lastPos);
  221578. }
  221579. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221580. {
  221581. dragAndDropFiles.clear();
  221582. srcMimeTypeAtomList.clear();
  221583. dragAndDropCurrentMimeType = 0;
  221584. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221585. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221586. {
  221587. dragAndDropSourceWindow = 0;
  221588. return;
  221589. }
  221590. dragAndDropSourceWindow = clientMsg->data.l[0];
  221591. if ((clientMsg->data.l[1] & 1) != 0)
  221592. {
  221593. Atom actual;
  221594. int format;
  221595. unsigned long count = 0, remaining = 0;
  221596. unsigned char* data = 0;
  221597. ScopedXLock xlock;
  221598. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221599. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221600. &count, &remaining, &data);
  221601. if (data != 0)
  221602. {
  221603. if (actual == XA_ATOM && format == 32 && count != 0)
  221604. {
  221605. const unsigned long* const types = (const unsigned long*) data;
  221606. for (unsigned int i = 0; i < count; ++i)
  221607. if (types[i] != None)
  221608. srcMimeTypeAtomList.add (types[i]);
  221609. }
  221610. XFree (data);
  221611. }
  221612. }
  221613. if (srcMimeTypeAtomList.size() == 0)
  221614. {
  221615. for (int i = 2; i < 5; ++i)
  221616. if (clientMsg->data.l[i] != None)
  221617. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221618. if (srcMimeTypeAtomList.size() == 0)
  221619. {
  221620. dragAndDropSourceWindow = 0;
  221621. return;
  221622. }
  221623. }
  221624. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221625. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221626. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221627. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221628. handleDragAndDropPosition (clientMsg);
  221629. }
  221630. void handleDragAndDropSelection (const XEvent* const evt)
  221631. {
  221632. dragAndDropFiles.clear();
  221633. if (evt->xselection.property != 0)
  221634. {
  221635. StringArray lines;
  221636. {
  221637. MemoryBlock dropData;
  221638. for (;;)
  221639. {
  221640. Atom actual;
  221641. uint8* data = 0;
  221642. unsigned long count = 0, remaining = 0;
  221643. int format = 0;
  221644. ScopedXLock xlock;
  221645. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221646. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221647. &format, &count, &remaining, &data) == Success)
  221648. {
  221649. dropData.append (data, count * format / 8);
  221650. XFree (data);
  221651. if (remaining == 0)
  221652. break;
  221653. }
  221654. else
  221655. {
  221656. XFree (data);
  221657. break;
  221658. }
  221659. }
  221660. lines.addLines (dropData.toString());
  221661. }
  221662. for (int i = 0; i < lines.size(); ++i)
  221663. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221664. dragAndDropFiles.trim();
  221665. dragAndDropFiles.removeEmptyStrings();
  221666. }
  221667. }
  221668. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221669. {
  221670. dragAndDropFiles.clear();
  221671. if (dragAndDropSourceWindow != None
  221672. && dragAndDropCurrentMimeType != 0)
  221673. {
  221674. dragAndDropTimestamp = clientMsg->data.l[2];
  221675. ScopedXLock xlock;
  221676. XConvertSelection (display,
  221677. Atoms::XdndSelection,
  221678. dragAndDropCurrentMimeType,
  221679. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221680. windowH,
  221681. dragAndDropTimestamp);
  221682. }
  221683. }
  221684. StringArray dragAndDropFiles;
  221685. int dragAndDropTimestamp;
  221686. Point<int> lastDropPos;
  221687. Atom dragAndDropCurrentMimeType;
  221688. Window dragAndDropSourceWindow;
  221689. Array <Atom> srcMimeTypeAtomList;
  221690. static int pointerMap[5];
  221691. static Point<int> lastMousePos;
  221692. static void clearLastMousePos() throw()
  221693. {
  221694. lastMousePos = Point<int> (0x100000, 0x100000);
  221695. }
  221696. };
  221697. ModifierKeys LinuxComponentPeer::currentModifiers;
  221698. bool LinuxComponentPeer::isActiveApplication = false;
  221699. int LinuxComponentPeer::pointerMap[5];
  221700. Point<int> LinuxComponentPeer::lastMousePos;
  221701. bool Process::isForegroundProcess()
  221702. {
  221703. return LinuxComponentPeer::isActiveApplication;
  221704. }
  221705. void ModifierKeys::updateCurrentModifiers() throw()
  221706. {
  221707. currentModifiers = LinuxComponentPeer::currentModifiers;
  221708. }
  221709. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221710. {
  221711. Window root, child;
  221712. int x, y, winx, winy;
  221713. unsigned int mask;
  221714. int mouseMods = 0;
  221715. ScopedXLock xlock;
  221716. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221717. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221718. {
  221719. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221720. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221721. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221722. }
  221723. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221724. return LinuxComponentPeer::currentModifiers;
  221725. }
  221726. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221727. {
  221728. if (enableOrDisable)
  221729. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221730. }
  221731. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221732. {
  221733. return new LinuxComponentPeer (this, styleFlags);
  221734. }
  221735. // (this callback is hooked up in the messaging code)
  221736. void juce_windowMessageReceive (XEvent* event)
  221737. {
  221738. if (event->xany.window != None)
  221739. {
  221740. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  221741. if (ComponentPeer::isValidPeer (peer))
  221742. peer->handleWindowMessage (event);
  221743. }
  221744. else
  221745. {
  221746. switch (event->xany.type)
  221747. {
  221748. case KeymapNotify:
  221749. {
  221750. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  221751. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  221752. break;
  221753. }
  221754. default:
  221755. break;
  221756. }
  221757. }
  221758. }
  221759. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221760. {
  221761. if (display == 0)
  221762. return;
  221763. #if JUCE_USE_XINERAMA
  221764. int major_opcode, first_event, first_error;
  221765. ScopedXLock xlock;
  221766. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221767. {
  221768. typedef Bool (*tXineramaIsActive) (Display*);
  221769. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221770. static tXineramaIsActive xXineramaIsActive = 0;
  221771. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221772. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221773. {
  221774. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221775. if (h == 0)
  221776. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221777. if (h != 0)
  221778. {
  221779. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  221780. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  221781. }
  221782. }
  221783. if (xXineramaIsActive != 0
  221784. && xXineramaQueryScreens != 0
  221785. && xXineramaIsActive (display))
  221786. {
  221787. int numMonitors = 0;
  221788. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  221789. if (screens != 0)
  221790. {
  221791. for (int i = numMonitors; --i >= 0;)
  221792. {
  221793. int index = screens[i].screen_number;
  221794. if (index >= 0)
  221795. {
  221796. while (monitorCoords.size() < index)
  221797. monitorCoords.add (Rectangle<int>());
  221798. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  221799. screens[i].y_org,
  221800. screens[i].width,
  221801. screens[i].height));
  221802. }
  221803. }
  221804. XFree (screens);
  221805. }
  221806. }
  221807. }
  221808. if (monitorCoords.size() == 0)
  221809. #endif
  221810. {
  221811. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221812. if (hints != None)
  221813. {
  221814. const int numMonitors = ScreenCount (display);
  221815. for (int i = 0; i < numMonitors; ++i)
  221816. {
  221817. Window root = RootWindow (display, i);
  221818. unsigned long nitems, bytesLeft;
  221819. Atom actualType;
  221820. int actualFormat;
  221821. unsigned char* data = 0;
  221822. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  221823. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221824. &data) == Success)
  221825. {
  221826. const long* const position = (const long*) data;
  221827. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  221828. monitorCoords.add (Rectangle<int> (position[0], position[1],
  221829. position[2], position[3]));
  221830. XFree (data);
  221831. }
  221832. }
  221833. }
  221834. if (monitorCoords.size() == 0)
  221835. {
  221836. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  221837. DisplayHeight (display, DefaultScreen (display))));
  221838. }
  221839. }
  221840. }
  221841. void Desktop::createMouseInputSources()
  221842. {
  221843. mouseSources.add (new MouseInputSource (0, true));
  221844. }
  221845. bool Desktop::canUseSemiTransparentWindows() throw()
  221846. {
  221847. int matchedDepth = 0;
  221848. const int desiredDepth = 32;
  221849. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  221850. && (matchedDepth == desiredDepth);
  221851. }
  221852. const Point<int> Desktop::getMousePosition()
  221853. {
  221854. Window root, child;
  221855. int x, y, winx, winy;
  221856. unsigned int mask;
  221857. ScopedXLock xlock;
  221858. if (XQueryPointer (display,
  221859. RootWindow (display, DefaultScreen (display)),
  221860. &root, &child,
  221861. &x, &y, &winx, &winy, &mask) == False)
  221862. {
  221863. // Pointer not on the default screen
  221864. x = y = -1;
  221865. }
  221866. return Point<int> (x, y);
  221867. }
  221868. void Desktop::setMousePosition (const Point<int>& newPosition)
  221869. {
  221870. ScopedXLock xlock;
  221871. Window root = RootWindow (display, DefaultScreen (display));
  221872. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  221873. }
  221874. static bool screenSaverAllowed = true;
  221875. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  221876. {
  221877. if (screenSaverAllowed != isEnabled)
  221878. {
  221879. screenSaverAllowed = isEnabled;
  221880. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  221881. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  221882. if (xScreenSaverSuspend == 0)
  221883. {
  221884. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  221885. if (h != 0)
  221886. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  221887. }
  221888. ScopedXLock xlock;
  221889. if (xScreenSaverSuspend != 0)
  221890. xScreenSaverSuspend (display, ! isEnabled);
  221891. }
  221892. }
  221893. bool Desktop::isScreenSaverEnabled()
  221894. {
  221895. return screenSaverAllowed;
  221896. }
  221897. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  221898. {
  221899. ScopedXLock xlock;
  221900. const unsigned int imageW = image.getWidth();
  221901. const unsigned int imageH = image.getHeight();
  221902. #if JUCE_USE_XCURSOR
  221903. {
  221904. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  221905. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  221906. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  221907. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  221908. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  221909. static tXcursorImageCreate xXcursorImageCreate = 0;
  221910. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  221911. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  221912. static bool hasBeenLoaded = false;
  221913. if (! hasBeenLoaded)
  221914. {
  221915. hasBeenLoaded = true;
  221916. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  221917. if (h != 0)
  221918. {
  221919. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  221920. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  221921. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  221922. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  221923. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  221924. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  221925. || ! xXcursorSupportsARGB (display))
  221926. xXcursorSupportsARGB = 0;
  221927. }
  221928. }
  221929. if (xXcursorSupportsARGB != 0)
  221930. {
  221931. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  221932. if (xcImage != 0)
  221933. {
  221934. xcImage->xhot = hotspotX;
  221935. xcImage->yhot = hotspotY;
  221936. XcursorPixel* dest = xcImage->pixels;
  221937. for (int y = 0; y < (int) imageH; ++y)
  221938. for (int x = 0; x < (int) imageW; ++x)
  221939. *dest++ = image.getPixelAt (x, y).getARGB();
  221940. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  221941. xXcursorImageDestroy (xcImage);
  221942. if (result != 0)
  221943. return result;
  221944. }
  221945. }
  221946. }
  221947. #endif
  221948. Window root = RootWindow (display, DefaultScreen (display));
  221949. unsigned int cursorW, cursorH;
  221950. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  221951. return 0;
  221952. Image im (Image::ARGB, cursorW, cursorH, true);
  221953. {
  221954. Graphics g (im);
  221955. if (imageW > cursorW || imageH > cursorH)
  221956. {
  221957. hotspotX = (hotspotX * cursorW) / imageW;
  221958. hotspotY = (hotspotY * cursorH) / imageH;
  221959. g.drawImageWithin (image, 0, 0, imageW, imageH,
  221960. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221961. false);
  221962. }
  221963. else
  221964. {
  221965. g.drawImageAt (image, 0, 0);
  221966. }
  221967. }
  221968. const int stride = (cursorW + 7) >> 3;
  221969. HeapBlock <char> maskPlane, sourcePlane;
  221970. maskPlane.calloc (stride * cursorH);
  221971. sourcePlane.calloc (stride * cursorH);
  221972. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  221973. for (int y = cursorH; --y >= 0;)
  221974. {
  221975. for (int x = cursorW; --x >= 0;)
  221976. {
  221977. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  221978. const int offset = y * stride + (x >> 3);
  221979. const Colour c (im.getPixelAt (x, y));
  221980. if (c.getAlpha() >= 128)
  221981. maskPlane[offset] |= mask;
  221982. if (c.getBrightness() >= 0.5f)
  221983. sourcePlane[offset] |= mask;
  221984. }
  221985. }
  221986. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221987. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221988. XColor white, black;
  221989. black.red = black.green = black.blue = 0;
  221990. white.red = white.green = white.blue = 0xffff;
  221991. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  221992. XFreePixmap (display, sourcePixmap);
  221993. XFreePixmap (display, maskPixmap);
  221994. return result;
  221995. }
  221996. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  221997. {
  221998. ScopedXLock xlock;
  221999. if (cursorHandle != 0)
  222000. XFreeCursor (display, (Cursor) cursorHandle);
  222001. }
  222002. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  222003. {
  222004. unsigned int shape;
  222005. switch (type)
  222006. {
  222007. case NormalCursor: return None; // Use parent cursor
  222008. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  222009. case WaitCursor: shape = XC_watch; break;
  222010. case IBeamCursor: shape = XC_xterm; break;
  222011. case PointingHandCursor: shape = XC_hand2; break;
  222012. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  222013. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  222014. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  222015. case TopEdgeResizeCursor: shape = XC_top_side; break;
  222016. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  222017. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  222018. case RightEdgeResizeCursor: shape = XC_right_side; break;
  222019. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  222020. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  222021. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  222022. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  222023. case CrosshairCursor: shape = XC_crosshair; break;
  222024. case DraggingHandCursor:
  222025. {
  222026. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  222027. 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,
  222028. 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 };
  222029. const int dragHandDataSize = 99;
  222030. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  222031. }
  222032. case CopyingCursor:
  222033. {
  222034. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  222035. 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,
  222036. 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,
  222037. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  222038. const int copyCursorSize = 119;
  222039. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  222040. }
  222041. default:
  222042. jassertfalse;
  222043. return None;
  222044. }
  222045. ScopedXLock xlock;
  222046. return (void*) XCreateFontCursor (display, shape);
  222047. }
  222048. void MouseCursor::showInWindow (ComponentPeer* peer) const
  222049. {
  222050. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  222051. if (lp != 0)
  222052. lp->showMouseCursor ((Cursor) getHandle());
  222053. }
  222054. void MouseCursor::showInAllWindows() const
  222055. {
  222056. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  222057. showInWindow (ComponentPeer::getPeer (i));
  222058. }
  222059. const Image juce_createIconForFile (const File& file)
  222060. {
  222061. return Image::null;
  222062. }
  222063. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  222064. {
  222065. return createSoftwareImage (format, width, height, clearImage);
  222066. }
  222067. #if JUCE_OPENGL
  222068. class WindowedGLContext : public OpenGLContext
  222069. {
  222070. public:
  222071. WindowedGLContext (Component* const component,
  222072. const OpenGLPixelFormat& pixelFormat_,
  222073. GLXContext sharedContext)
  222074. : renderContext (0),
  222075. embeddedWindow (0),
  222076. pixelFormat (pixelFormat_),
  222077. swapInterval (0)
  222078. {
  222079. jassert (component != 0);
  222080. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222081. if (peer == 0)
  222082. return;
  222083. ScopedXLock xlock;
  222084. XSync (display, False);
  222085. GLint attribs [64];
  222086. int n = 0;
  222087. attribs[n++] = GLX_RGBA;
  222088. attribs[n++] = GLX_DOUBLEBUFFER;
  222089. attribs[n++] = GLX_RED_SIZE;
  222090. attribs[n++] = pixelFormat.redBits;
  222091. attribs[n++] = GLX_GREEN_SIZE;
  222092. attribs[n++] = pixelFormat.greenBits;
  222093. attribs[n++] = GLX_BLUE_SIZE;
  222094. attribs[n++] = pixelFormat.blueBits;
  222095. attribs[n++] = GLX_ALPHA_SIZE;
  222096. attribs[n++] = pixelFormat.alphaBits;
  222097. attribs[n++] = GLX_DEPTH_SIZE;
  222098. attribs[n++] = pixelFormat.depthBufferBits;
  222099. attribs[n++] = GLX_STENCIL_SIZE;
  222100. attribs[n++] = pixelFormat.stencilBufferBits;
  222101. attribs[n++] = GLX_ACCUM_RED_SIZE;
  222102. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222103. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  222104. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222105. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  222106. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222107. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  222108. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222109. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  222110. attribs[n++] = None;
  222111. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  222112. if (bestVisual == 0)
  222113. return;
  222114. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  222115. Window windowH = (Window) peer->getNativeHandle();
  222116. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  222117. XSetWindowAttributes swa;
  222118. swa.colormap = colourMap;
  222119. swa.border_pixel = 0;
  222120. swa.event_mask = ExposureMask | StructureNotifyMask;
  222121. embeddedWindow = XCreateWindow (display, windowH,
  222122. 0, 0, 1, 1, 0,
  222123. bestVisual->depth,
  222124. InputOutput,
  222125. bestVisual->visual,
  222126. CWBorderPixel | CWColormap | CWEventMask,
  222127. &swa);
  222128. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  222129. XMapWindow (display, embeddedWindow);
  222130. XFreeColormap (display, colourMap);
  222131. XFree (bestVisual);
  222132. XSync (display, False);
  222133. }
  222134. ~WindowedGLContext()
  222135. {
  222136. ScopedXLock xlock;
  222137. deleteContext();
  222138. XUnmapWindow (display, embeddedWindow);
  222139. XDestroyWindow (display, embeddedWindow);
  222140. }
  222141. void deleteContext()
  222142. {
  222143. makeInactive();
  222144. if (renderContext != 0)
  222145. {
  222146. ScopedXLock xlock;
  222147. glXDestroyContext (display, renderContext);
  222148. renderContext = 0;
  222149. }
  222150. }
  222151. bool makeActive() const throw()
  222152. {
  222153. jassert (renderContext != 0);
  222154. ScopedXLock xlock;
  222155. return glXMakeCurrent (display, embeddedWindow, renderContext)
  222156. && XSync (display, False);
  222157. }
  222158. bool makeInactive() const throw()
  222159. {
  222160. ScopedXLock xlock;
  222161. return (! isActive()) || glXMakeCurrent (display, None, 0);
  222162. }
  222163. bool isActive() const throw()
  222164. {
  222165. ScopedXLock xlock;
  222166. return glXGetCurrentContext() == renderContext;
  222167. }
  222168. const OpenGLPixelFormat getPixelFormat() const
  222169. {
  222170. return pixelFormat;
  222171. }
  222172. void* getRawContext() const throw()
  222173. {
  222174. return renderContext;
  222175. }
  222176. void updateWindowPosition (int x, int y, int w, int h, int)
  222177. {
  222178. ScopedXLock xlock;
  222179. XMoveResizeWindow (display, embeddedWindow,
  222180. x, y, jmax (1, w), jmax (1, h));
  222181. }
  222182. void swapBuffers()
  222183. {
  222184. ScopedXLock xlock;
  222185. glXSwapBuffers (display, embeddedWindow);
  222186. }
  222187. bool setSwapInterval (const int numFramesPerSwap)
  222188. {
  222189. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  222190. if (GLXSwapIntervalSGI != 0)
  222191. {
  222192. swapInterval = numFramesPerSwap;
  222193. GLXSwapIntervalSGI (numFramesPerSwap);
  222194. return true;
  222195. }
  222196. return false;
  222197. }
  222198. int getSwapInterval() const
  222199. {
  222200. return swapInterval;
  222201. }
  222202. void repaint()
  222203. {
  222204. }
  222205. juce_UseDebuggingNewOperator
  222206. GLXContext renderContext;
  222207. private:
  222208. Window embeddedWindow;
  222209. OpenGLPixelFormat pixelFormat;
  222210. int swapInterval;
  222211. WindowedGLContext (const WindowedGLContext&);
  222212. WindowedGLContext& operator= (const WindowedGLContext&);
  222213. };
  222214. OpenGLContext* OpenGLComponent::createContext()
  222215. {
  222216. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  222217. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  222218. return (c->renderContext != 0) ? c.release() : 0;
  222219. }
  222220. void juce_glViewport (const int w, const int h)
  222221. {
  222222. glViewport (0, 0, w, h);
  222223. }
  222224. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  222225. OwnedArray <OpenGLPixelFormat>& results)
  222226. {
  222227. results.add (new OpenGLPixelFormat()); // xxx
  222228. }
  222229. #endif
  222230. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  222231. {
  222232. jassertfalse; // not implemented!
  222233. return false;
  222234. }
  222235. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  222236. {
  222237. jassertfalse; // not implemented!
  222238. return false;
  222239. }
  222240. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  222241. {
  222242. if (! isOnDesktop ())
  222243. addToDesktop (0);
  222244. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222245. if (wp != 0)
  222246. {
  222247. wp->setTaskBarIcon (newImage);
  222248. setVisible (true);
  222249. toFront (false);
  222250. repaint();
  222251. }
  222252. }
  222253. void SystemTrayIconComponent::paint (Graphics& g)
  222254. {
  222255. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222256. if (wp != 0)
  222257. {
  222258. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  222259. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222260. false);
  222261. }
  222262. }
  222263. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  222264. {
  222265. // xxx not yet implemented!
  222266. }
  222267. void PlatformUtilities::beep()
  222268. {
  222269. std::cout << "\a" << std::flush;
  222270. }
  222271. bool AlertWindow::showNativeDialogBox (const String& title,
  222272. const String& bodyText,
  222273. bool isOkCancel)
  222274. {
  222275. // use a non-native one for the time being..
  222276. if (isOkCancel)
  222277. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  222278. else
  222279. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  222280. return true;
  222281. }
  222282. const int KeyPress::spaceKey = XK_space & 0xff;
  222283. const int KeyPress::returnKey = XK_Return & 0xff;
  222284. const int KeyPress::escapeKey = XK_Escape & 0xff;
  222285. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  222286. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  222287. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  222288. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  222289. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  222290. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  222291. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  222292. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  222293. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  222294. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  222295. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  222296. const int KeyPress::tabKey = XK_Tab & 0xff;
  222297. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  222298. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  222299. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  222300. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  222301. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  222302. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  222303. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  222304. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  222305. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  222306. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  222307. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  222308. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  222309. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  222310. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  222311. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  222312. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  222313. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  222314. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  222315. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  222316. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  222317. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  222318. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  222319. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  222320. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  222321. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  222322. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  222323. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  222324. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  222325. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  222326. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  222327. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  222328. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  222329. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  222330. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  222331. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  222332. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  222333. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  222334. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  222335. #endif
  222336. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  222337. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  222338. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222339. // compiled on its own).
  222340. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  222341. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  222342. {
  222343. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  222344. snd_pcm_hw_params_t* hwParams;
  222345. snd_pcm_hw_params_alloca (&hwParams);
  222346. for (int i = 0; ratesToTry[i] != 0; ++i)
  222347. {
  222348. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  222349. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  222350. {
  222351. rates.addIfNotAlreadyThere (ratesToTry[i]);
  222352. }
  222353. }
  222354. }
  222355. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  222356. {
  222357. snd_pcm_hw_params_t *params;
  222358. snd_pcm_hw_params_alloca (&params);
  222359. if (snd_pcm_hw_params_any (handle, params) >= 0)
  222360. {
  222361. snd_pcm_hw_params_get_channels_min (params, minChans);
  222362. snd_pcm_hw_params_get_channels_max (params, maxChans);
  222363. }
  222364. }
  222365. static void getDeviceProperties (const String& deviceID,
  222366. unsigned int& minChansOut,
  222367. unsigned int& maxChansOut,
  222368. unsigned int& minChansIn,
  222369. unsigned int& maxChansIn,
  222370. Array <int>& rates)
  222371. {
  222372. if (deviceID.isEmpty())
  222373. return;
  222374. snd_ctl_t* handle;
  222375. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222376. {
  222377. snd_pcm_info_t* info;
  222378. snd_pcm_info_alloca (&info);
  222379. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  222380. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  222381. snd_pcm_info_set_subdevice (info, 0);
  222382. if (snd_ctl_pcm_info (handle, info) >= 0)
  222383. {
  222384. snd_pcm_t* pcmHandle;
  222385. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222386. {
  222387. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  222388. getDeviceSampleRates (pcmHandle, rates);
  222389. snd_pcm_close (pcmHandle);
  222390. }
  222391. }
  222392. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  222393. if (snd_ctl_pcm_info (handle, info) >= 0)
  222394. {
  222395. snd_pcm_t* pcmHandle;
  222396. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222397. {
  222398. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  222399. if (rates.size() == 0)
  222400. getDeviceSampleRates (pcmHandle, rates);
  222401. snd_pcm_close (pcmHandle);
  222402. }
  222403. }
  222404. snd_ctl_close (handle);
  222405. }
  222406. }
  222407. class ALSADevice
  222408. {
  222409. public:
  222410. ALSADevice (const String& deviceID, bool forInput)
  222411. : handle (0),
  222412. bitDepth (16),
  222413. numChannelsRunning (0),
  222414. latency (0),
  222415. isInput (forInput)
  222416. {
  222417. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  222418. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  222419. SND_PCM_ASYNC));
  222420. }
  222421. ~ALSADevice()
  222422. {
  222423. if (handle != 0)
  222424. snd_pcm_close (handle);
  222425. }
  222426. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  222427. {
  222428. if (handle == 0)
  222429. return false;
  222430. snd_pcm_hw_params_t* hwParams;
  222431. snd_pcm_hw_params_alloca (&hwParams);
  222432. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  222433. return false;
  222434. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  222435. isInterleaved = false;
  222436. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  222437. isInterleaved = true;
  222438. else
  222439. {
  222440. jassertfalse;
  222441. return false;
  222442. }
  222443. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  222444. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  222445. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  222446. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  222447. SND_PCM_FORMAT_S32_BE, 32,
  222448. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  222449. SND_PCM_FORMAT_S24_3BE, 24,
  222450. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  222451. SND_PCM_FORMAT_S16_BE, 16 };
  222452. bitDepth = 0;
  222453. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  222454. {
  222455. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  222456. {
  222457. bitDepth = formatsToTry [i + 1] & 255;
  222458. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  222459. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  222460. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  222461. break;
  222462. }
  222463. }
  222464. if (bitDepth == 0)
  222465. {
  222466. error = "device doesn't support a compatible PCM format";
  222467. DBG ("ALSA error: " + error + "\n");
  222468. return false;
  222469. }
  222470. int dir = 0;
  222471. unsigned int periods = 4;
  222472. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  222473. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  222474. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  222475. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  222476. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  222477. || failed (snd_pcm_hw_params (handle, hwParams)))
  222478. {
  222479. return false;
  222480. }
  222481. snd_pcm_uframes_t frames = 0;
  222482. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  222483. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  222484. latency = 0;
  222485. else
  222486. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  222487. snd_pcm_sw_params_t* swParams;
  222488. snd_pcm_sw_params_alloca (&swParams);
  222489. snd_pcm_uframes_t boundary;
  222490. if (failed (snd_pcm_sw_params_current (handle, swParams))
  222491. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  222492. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  222493. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  222494. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  222495. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  222496. || failed (snd_pcm_sw_params (handle, swParams)))
  222497. {
  222498. return false;
  222499. }
  222500. /*
  222501. #if JUCE_DEBUG
  222502. // enable this to dump the config of the devices that get opened
  222503. snd_output_t* out;
  222504. snd_output_stdio_attach (&out, stderr, 0);
  222505. snd_pcm_hw_params_dump (hwParams, out);
  222506. snd_pcm_sw_params_dump (swParams, out);
  222507. #endif
  222508. */
  222509. numChannelsRunning = numChannels;
  222510. return true;
  222511. }
  222512. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222513. {
  222514. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222515. float** const data = outputChannelBuffer.getArrayOfChannels();
  222516. snd_pcm_sframes_t numDone = 0;
  222517. if (isInterleaved)
  222518. {
  222519. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222520. for (int i = 0; i < numChannelsRunning; ++i)
  222521. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  222522. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  222523. }
  222524. else
  222525. {
  222526. for (int i = 0; i < numChannelsRunning; ++i)
  222527. converter->convertSamples (data[i], data[i], numSamples);
  222528. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  222529. }
  222530. if (failed (numDone))
  222531. {
  222532. if (numDone == -EPIPE)
  222533. {
  222534. if (failed (snd_pcm_prepare (handle)))
  222535. return false;
  222536. }
  222537. else if (numDone != -ESTRPIPE)
  222538. return false;
  222539. }
  222540. return true;
  222541. }
  222542. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222543. {
  222544. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222545. float** const data = inputChannelBuffer.getArrayOfChannels();
  222546. if (isInterleaved)
  222547. {
  222548. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222549. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  222550. if (failed (num))
  222551. {
  222552. if (num == -EPIPE)
  222553. {
  222554. if (failed (snd_pcm_prepare (handle)))
  222555. return false;
  222556. }
  222557. else if (num != -ESTRPIPE)
  222558. return false;
  222559. }
  222560. for (int i = 0; i < numChannelsRunning; ++i)
  222561. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  222562. }
  222563. else
  222564. {
  222565. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222566. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222567. return false;
  222568. for (int i = 0; i < numChannelsRunning; ++i)
  222569. converter->convertSamples (data[i], data[i], numSamples);
  222570. }
  222571. return true;
  222572. }
  222573. juce_UseDebuggingNewOperator
  222574. snd_pcm_t* handle;
  222575. String error;
  222576. int bitDepth, numChannelsRunning, latency;
  222577. private:
  222578. const bool isInput;
  222579. bool isInterleaved;
  222580. MemoryBlock scratch;
  222581. ScopedPointer<AudioData::Converter> converter;
  222582. template <class SampleType>
  222583. struct ConverterHelper
  222584. {
  222585. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  222586. {
  222587. if (forInput)
  222588. {
  222589. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  222590. if (isLittleEndian)
  222591. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222592. else
  222593. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222594. }
  222595. else
  222596. {
  222597. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  222598. if (isLittleEndian)
  222599. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222600. else
  222601. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222602. }
  222603. }
  222604. };
  222605. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  222606. {
  222607. switch (bitDepth)
  222608. {
  222609. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222610. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222611. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  222612. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222613. default: jassertfalse; break; // unsupported format!
  222614. }
  222615. return 0;
  222616. }
  222617. bool failed (const int errorNum)
  222618. {
  222619. if (errorNum >= 0)
  222620. return false;
  222621. error = snd_strerror (errorNum);
  222622. DBG ("ALSA error: " + error + "\n");
  222623. return true;
  222624. }
  222625. };
  222626. class ALSAThread : public Thread
  222627. {
  222628. public:
  222629. ALSAThread (const String& inputId_,
  222630. const String& outputId_)
  222631. : Thread ("Juce ALSA"),
  222632. sampleRate (0),
  222633. bufferSize (0),
  222634. outputLatency (0),
  222635. inputLatency (0),
  222636. callback (0),
  222637. inputId (inputId_),
  222638. outputId (outputId_),
  222639. numCallbacks (0),
  222640. inputChannelBuffer (1, 1),
  222641. outputChannelBuffer (1, 1)
  222642. {
  222643. initialiseRatesAndChannels();
  222644. }
  222645. ~ALSAThread()
  222646. {
  222647. close();
  222648. }
  222649. void open (BigInteger inputChannels,
  222650. BigInteger outputChannels,
  222651. const double sampleRate_,
  222652. const int bufferSize_)
  222653. {
  222654. close();
  222655. error = String::empty;
  222656. sampleRate = sampleRate_;
  222657. bufferSize = bufferSize_;
  222658. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222659. inputChannelBuffer.clear();
  222660. inputChannelDataForCallback.clear();
  222661. currentInputChans.clear();
  222662. if (inputChannels.getHighestBit() >= 0)
  222663. {
  222664. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222665. {
  222666. if (inputChannels[i])
  222667. {
  222668. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222669. currentInputChans.setBit (i);
  222670. }
  222671. }
  222672. }
  222673. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222674. outputChannelBuffer.clear();
  222675. outputChannelDataForCallback.clear();
  222676. currentOutputChans.clear();
  222677. if (outputChannels.getHighestBit() >= 0)
  222678. {
  222679. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222680. {
  222681. if (outputChannels[i])
  222682. {
  222683. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222684. currentOutputChans.setBit (i);
  222685. }
  222686. }
  222687. }
  222688. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222689. {
  222690. outputDevice = new ALSADevice (outputId, false);
  222691. if (outputDevice->error.isNotEmpty())
  222692. {
  222693. error = outputDevice->error;
  222694. outputDevice = 0;
  222695. return;
  222696. }
  222697. currentOutputChans.setRange (0, minChansOut, true);
  222698. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222699. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222700. bufferSize))
  222701. {
  222702. error = outputDevice->error;
  222703. outputDevice = 0;
  222704. return;
  222705. }
  222706. outputLatency = outputDevice->latency;
  222707. }
  222708. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222709. {
  222710. inputDevice = new ALSADevice (inputId, true);
  222711. if (inputDevice->error.isNotEmpty())
  222712. {
  222713. error = inputDevice->error;
  222714. inputDevice = 0;
  222715. return;
  222716. }
  222717. currentInputChans.setRange (0, minChansIn, true);
  222718. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222719. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222720. bufferSize))
  222721. {
  222722. error = inputDevice->error;
  222723. inputDevice = 0;
  222724. return;
  222725. }
  222726. inputLatency = inputDevice->latency;
  222727. }
  222728. if (outputDevice == 0 && inputDevice == 0)
  222729. {
  222730. error = "no channels";
  222731. return;
  222732. }
  222733. if (outputDevice != 0 && inputDevice != 0)
  222734. {
  222735. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222736. }
  222737. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222738. return;
  222739. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222740. return;
  222741. startThread (9);
  222742. int count = 1000;
  222743. while (numCallbacks == 0)
  222744. {
  222745. sleep (5);
  222746. if (--count < 0 || ! isThreadRunning())
  222747. {
  222748. error = "device didn't start";
  222749. break;
  222750. }
  222751. }
  222752. }
  222753. void close()
  222754. {
  222755. stopThread (6000);
  222756. inputDevice = 0;
  222757. outputDevice = 0;
  222758. inputChannelBuffer.setSize (1, 1);
  222759. outputChannelBuffer.setSize (1, 1);
  222760. numCallbacks = 0;
  222761. }
  222762. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222763. {
  222764. const ScopedLock sl (callbackLock);
  222765. callback = newCallback;
  222766. }
  222767. void run()
  222768. {
  222769. while (! threadShouldExit())
  222770. {
  222771. if (inputDevice != 0)
  222772. {
  222773. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  222774. {
  222775. DBG ("ALSA: read failure");
  222776. break;
  222777. }
  222778. }
  222779. if (threadShouldExit())
  222780. break;
  222781. {
  222782. const ScopedLock sl (callbackLock);
  222783. ++numCallbacks;
  222784. if (callback != 0)
  222785. {
  222786. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  222787. inputChannelDataForCallback.size(),
  222788. outputChannelDataForCallback.getRawDataPointer(),
  222789. outputChannelDataForCallback.size(),
  222790. bufferSize);
  222791. }
  222792. else
  222793. {
  222794. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  222795. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222796. }
  222797. }
  222798. if (outputDevice != 0)
  222799. {
  222800. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222801. if (threadShouldExit())
  222802. break;
  222803. failed (snd_pcm_avail_update (outputDevice->handle));
  222804. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  222805. {
  222806. DBG ("ALSA: write failure");
  222807. break;
  222808. }
  222809. }
  222810. }
  222811. }
  222812. int getBitDepth() const throw()
  222813. {
  222814. if (outputDevice != 0)
  222815. return outputDevice->bitDepth;
  222816. if (inputDevice != 0)
  222817. return inputDevice->bitDepth;
  222818. return 16;
  222819. }
  222820. juce_UseDebuggingNewOperator
  222821. String error;
  222822. double sampleRate;
  222823. int bufferSize, outputLatency, inputLatency;
  222824. BigInteger currentInputChans, currentOutputChans;
  222825. Array <int> sampleRates;
  222826. StringArray channelNamesOut, channelNamesIn;
  222827. AudioIODeviceCallback* callback;
  222828. private:
  222829. const String inputId, outputId;
  222830. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222831. int numCallbacks;
  222832. CriticalSection callbackLock;
  222833. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222834. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222835. unsigned int minChansOut, maxChansOut;
  222836. unsigned int minChansIn, maxChansIn;
  222837. bool failed (const int errorNum)
  222838. {
  222839. if (errorNum >= 0)
  222840. return false;
  222841. error = snd_strerror (errorNum);
  222842. DBG ("ALSA error: " + error + "\n");
  222843. return true;
  222844. }
  222845. void initialiseRatesAndChannels()
  222846. {
  222847. sampleRates.clear();
  222848. channelNamesOut.clear();
  222849. channelNamesIn.clear();
  222850. minChansOut = 0;
  222851. maxChansOut = 0;
  222852. minChansIn = 0;
  222853. maxChansIn = 0;
  222854. unsigned int dummy = 0;
  222855. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  222856. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  222857. unsigned int i;
  222858. for (i = 0; i < maxChansOut; ++i)
  222859. channelNamesOut.add ("channel " + String ((int) i + 1));
  222860. for (i = 0; i < maxChansIn; ++i)
  222861. channelNamesIn.add ("channel " + String ((int) i + 1));
  222862. }
  222863. };
  222864. class ALSAAudioIODevice : public AudioIODevice
  222865. {
  222866. public:
  222867. ALSAAudioIODevice (const String& deviceName,
  222868. const String& inputId_,
  222869. const String& outputId_)
  222870. : AudioIODevice (deviceName, "ALSA"),
  222871. inputId (inputId_),
  222872. outputId (outputId_),
  222873. isOpen_ (false),
  222874. isStarted (false),
  222875. internal (inputId_, outputId_)
  222876. {
  222877. }
  222878. ~ALSAAudioIODevice()
  222879. {
  222880. }
  222881. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  222882. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  222883. int getNumSampleRates() { return internal.sampleRates.size(); }
  222884. double getSampleRate (int index) { return internal.sampleRates [index]; }
  222885. int getDefaultBufferSize() { return 512; }
  222886. int getNumBufferSizesAvailable() { return 50; }
  222887. int getBufferSizeSamples (int index)
  222888. {
  222889. int n = 16;
  222890. for (int i = 0; i < index; ++i)
  222891. n += n < 64 ? 16
  222892. : (n < 512 ? 32
  222893. : (n < 1024 ? 64
  222894. : (n < 2048 ? 128 : 256)));
  222895. return n;
  222896. }
  222897. const String open (const BigInteger& inputChannels,
  222898. const BigInteger& outputChannels,
  222899. double sampleRate,
  222900. int bufferSizeSamples)
  222901. {
  222902. close();
  222903. if (bufferSizeSamples <= 0)
  222904. bufferSizeSamples = getDefaultBufferSize();
  222905. if (sampleRate <= 0)
  222906. {
  222907. for (int i = 0; i < getNumSampleRates(); ++i)
  222908. {
  222909. if (getSampleRate (i) >= 44100)
  222910. {
  222911. sampleRate = getSampleRate (i);
  222912. break;
  222913. }
  222914. }
  222915. }
  222916. internal.open (inputChannels, outputChannels,
  222917. sampleRate, bufferSizeSamples);
  222918. isOpen_ = internal.error.isEmpty();
  222919. return internal.error;
  222920. }
  222921. void close()
  222922. {
  222923. stop();
  222924. internal.close();
  222925. isOpen_ = false;
  222926. }
  222927. bool isOpen() { return isOpen_; }
  222928. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  222929. const String getLastError() { return internal.error; }
  222930. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  222931. double getCurrentSampleRate() { return internal.sampleRate; }
  222932. int getCurrentBitDepth() { return internal.getBitDepth(); }
  222933. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  222934. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  222935. int getOutputLatencyInSamples() { return internal.outputLatency; }
  222936. int getInputLatencyInSamples() { return internal.inputLatency; }
  222937. void start (AudioIODeviceCallback* callback)
  222938. {
  222939. if (! isOpen_)
  222940. callback = 0;
  222941. if (callback != 0)
  222942. callback->audioDeviceAboutToStart (this);
  222943. internal.setCallback (callback);
  222944. isStarted = (callback != 0);
  222945. }
  222946. void stop()
  222947. {
  222948. AudioIODeviceCallback* const oldCallback = internal.callback;
  222949. start (0);
  222950. if (oldCallback != 0)
  222951. oldCallback->audioDeviceStopped();
  222952. }
  222953. String inputId, outputId;
  222954. private:
  222955. bool isOpen_, isStarted;
  222956. ALSAThread internal;
  222957. };
  222958. class ALSAAudioIODeviceType : public AudioIODeviceType
  222959. {
  222960. public:
  222961. ALSAAudioIODeviceType()
  222962. : AudioIODeviceType ("ALSA"),
  222963. hasScanned (false)
  222964. {
  222965. }
  222966. ~ALSAAudioIODeviceType()
  222967. {
  222968. }
  222969. void scanForDevices()
  222970. {
  222971. if (hasScanned)
  222972. return;
  222973. hasScanned = true;
  222974. inputNames.clear();
  222975. inputIds.clear();
  222976. outputNames.clear();
  222977. outputIds.clear();
  222978. /* void** hints = 0;
  222979. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  222980. {
  222981. for (void** hint = hints; *hint != 0; ++hint)
  222982. {
  222983. const String name (getHint (*hint, "NAME"));
  222984. if (name.isNotEmpty())
  222985. {
  222986. const String ioid (getHint (*hint, "IOID"));
  222987. String desc (getHint (*hint, "DESC"));
  222988. if (desc.isEmpty())
  222989. desc = name;
  222990. desc = desc.replaceCharacters ("\n\r", " ");
  222991. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  222992. if (ioid.isEmpty() || ioid == "Input")
  222993. {
  222994. inputNames.add (desc);
  222995. inputIds.add (name);
  222996. }
  222997. if (ioid.isEmpty() || ioid == "Output")
  222998. {
  222999. outputNames.add (desc);
  223000. outputIds.add (name);
  223001. }
  223002. }
  223003. }
  223004. snd_device_name_free_hint (hints);
  223005. }
  223006. */
  223007. snd_ctl_t* handle = 0;
  223008. snd_ctl_card_info_t* info = 0;
  223009. snd_ctl_card_info_alloca (&info);
  223010. int cardNum = -1;
  223011. while (outputIds.size() + inputIds.size() <= 32)
  223012. {
  223013. snd_card_next (&cardNum);
  223014. if (cardNum < 0)
  223015. break;
  223016. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  223017. {
  223018. if (snd_ctl_card_info (handle, info) >= 0)
  223019. {
  223020. String cardId (snd_ctl_card_info_get_id (info));
  223021. if (cardId.removeCharacters ("0123456789").isEmpty())
  223022. cardId = String (cardNum);
  223023. int device = -1;
  223024. for (;;)
  223025. {
  223026. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  223027. break;
  223028. String id, name;
  223029. id << "hw:" << cardId << ',' << device;
  223030. bool isInput, isOutput;
  223031. if (testDevice (id, isInput, isOutput))
  223032. {
  223033. name << snd_ctl_card_info_get_name (info);
  223034. if (name.isEmpty())
  223035. name = id;
  223036. if (isInput)
  223037. {
  223038. inputNames.add (name);
  223039. inputIds.add (id);
  223040. }
  223041. if (isOutput)
  223042. {
  223043. outputNames.add (name);
  223044. outputIds.add (id);
  223045. }
  223046. }
  223047. }
  223048. }
  223049. snd_ctl_close (handle);
  223050. }
  223051. }
  223052. inputNames.appendNumbersToDuplicates (false, true);
  223053. outputNames.appendNumbersToDuplicates (false, true);
  223054. }
  223055. const StringArray getDeviceNames (bool wantInputNames) const
  223056. {
  223057. jassert (hasScanned); // need to call scanForDevices() before doing this
  223058. return wantInputNames ? inputNames : outputNames;
  223059. }
  223060. int getDefaultDeviceIndex (bool forInput) const
  223061. {
  223062. jassert (hasScanned); // need to call scanForDevices() before doing this
  223063. return 0;
  223064. }
  223065. bool hasSeparateInputsAndOutputs() const { return true; }
  223066. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223067. {
  223068. jassert (hasScanned); // need to call scanForDevices() before doing this
  223069. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  223070. if (d == 0)
  223071. return -1;
  223072. return asInput ? inputIds.indexOf (d->inputId)
  223073. : outputIds.indexOf (d->outputId);
  223074. }
  223075. AudioIODevice* createDevice (const String& outputDeviceName,
  223076. const String& inputDeviceName)
  223077. {
  223078. jassert (hasScanned); // need to call scanForDevices() before doing this
  223079. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223080. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223081. String deviceName (outputIndex >= 0 ? outputDeviceName
  223082. : inputDeviceName);
  223083. if (inputIndex >= 0 || outputIndex >= 0)
  223084. return new ALSAAudioIODevice (deviceName,
  223085. inputIds [inputIndex],
  223086. outputIds [outputIndex]);
  223087. return 0;
  223088. }
  223089. juce_UseDebuggingNewOperator
  223090. private:
  223091. StringArray inputNames, outputNames, inputIds, outputIds;
  223092. bool hasScanned;
  223093. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  223094. {
  223095. unsigned int minChansOut = 0, maxChansOut = 0;
  223096. unsigned int minChansIn = 0, maxChansIn = 0;
  223097. Array <int> rates;
  223098. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  223099. DBG ("ALSA device: " + id
  223100. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  223101. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  223102. + " rates=" + String (rates.size()));
  223103. isInput = maxChansIn > 0;
  223104. isOutput = maxChansOut > 0;
  223105. return (isInput || isOutput) && rates.size() > 0;
  223106. }
  223107. /*static const String getHint (void* hint, const char* type)
  223108. {
  223109. char* const n = snd_device_name_get_hint (hint, type);
  223110. const String s ((const char*) n);
  223111. free (n);
  223112. return s;
  223113. }*/
  223114. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  223115. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  223116. };
  223117. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  223118. {
  223119. return new ALSAAudioIODeviceType();
  223120. }
  223121. #endif
  223122. /*** End of inlined file: juce_linux_Audio.cpp ***/
  223123. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  223124. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223125. // compiled on its own).
  223126. #ifdef JUCE_INCLUDED_FILE
  223127. #if JUCE_JACK
  223128. static void* juce_libjack_handle = 0;
  223129. void* juce_load_jack_function (const char* const name)
  223130. {
  223131. if (juce_libjack_handle == 0)
  223132. return 0;
  223133. return dlsym (juce_libjack_handle, name);
  223134. }
  223135. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  223136. typedef return_type (*fn_name##_ptr_t)argument_types; \
  223137. return_type fn_name argument_types { \
  223138. static fn_name##_ptr_t fn = 0; \
  223139. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223140. if (fn) return (*fn)arguments; \
  223141. else return 0; \
  223142. }
  223143. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  223144. typedef void (*fn_name##_ptr_t)argument_types; \
  223145. void fn_name argument_types { \
  223146. static fn_name##_ptr_t fn = 0; \
  223147. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223148. if (fn) (*fn)arguments; \
  223149. }
  223150. 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));
  223151. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  223152. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  223153. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  223154. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  223155. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  223156. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  223157. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  223158. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  223159. 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));
  223160. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  223161. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  223162. 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));
  223163. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  223164. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  223165. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  223166. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  223167. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  223168. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  223169. #if JUCE_DEBUG
  223170. #define JACK_LOGGING_ENABLED 1
  223171. #endif
  223172. #if JACK_LOGGING_ENABLED
  223173. static void jack_Log (const String& s)
  223174. {
  223175. std::cerr << s << std::endl;
  223176. }
  223177. static void dumpJackErrorMessage (const jack_status_t status)
  223178. {
  223179. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  223180. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  223181. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  223182. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  223183. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  223184. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  223185. }
  223186. #else
  223187. #define dumpJackErrorMessage(a) {}
  223188. #define jack_Log(...) {}
  223189. #endif
  223190. #ifndef JUCE_JACK_CLIENT_NAME
  223191. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  223192. #endif
  223193. class JackAudioIODevice : public AudioIODevice
  223194. {
  223195. public:
  223196. JackAudioIODevice (const String& deviceName,
  223197. const String& inputId_,
  223198. const String& outputId_)
  223199. : AudioIODevice (deviceName, "JACK"),
  223200. inputId (inputId_),
  223201. outputId (outputId_),
  223202. isOpen_ (false),
  223203. callback (0),
  223204. totalNumberOfInputChannels (0),
  223205. totalNumberOfOutputChannels (0)
  223206. {
  223207. jassert (deviceName.isNotEmpty());
  223208. jack_status_t status;
  223209. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  223210. if (client == 0)
  223211. {
  223212. dumpJackErrorMessage (status);
  223213. }
  223214. else
  223215. {
  223216. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  223217. // open input ports
  223218. const StringArray inputChannels (getInputChannelNames());
  223219. for (int i = 0; i < inputChannels.size(); i++)
  223220. {
  223221. String inputName;
  223222. inputName << "in_" << ++totalNumberOfInputChannels;
  223223. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  223224. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  223225. }
  223226. // open output ports
  223227. const StringArray outputChannels (getOutputChannelNames());
  223228. for (int i = 0; i < outputChannels.size (); i++)
  223229. {
  223230. String outputName;
  223231. outputName << "out_" << ++totalNumberOfOutputChannels;
  223232. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  223233. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  223234. }
  223235. inChans.calloc (totalNumberOfInputChannels + 2);
  223236. outChans.calloc (totalNumberOfOutputChannels + 2);
  223237. }
  223238. }
  223239. ~JackAudioIODevice()
  223240. {
  223241. close();
  223242. if (client != 0)
  223243. {
  223244. JUCE_NAMESPACE::jack_client_close (client);
  223245. client = 0;
  223246. }
  223247. }
  223248. const StringArray getChannelNames (bool forInput) const
  223249. {
  223250. StringArray names;
  223251. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  223252. forInput ? JackPortIsInput : JackPortIsOutput);
  223253. if (ports != 0)
  223254. {
  223255. int j = 0;
  223256. while (ports[j] != 0)
  223257. {
  223258. const String portName (ports [j++]);
  223259. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223260. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  223261. }
  223262. free (ports);
  223263. }
  223264. return names;
  223265. }
  223266. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  223267. const StringArray getInputChannelNames() { return getChannelNames (true); }
  223268. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  223269. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  223270. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  223271. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  223272. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  223273. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  223274. double sampleRate, int bufferSizeSamples)
  223275. {
  223276. if (client == 0)
  223277. {
  223278. lastError = "No JACK client running";
  223279. return lastError;
  223280. }
  223281. lastError = String::empty;
  223282. close();
  223283. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  223284. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  223285. JUCE_NAMESPACE::jack_activate (client);
  223286. isOpen_ = true;
  223287. if (! inputChannels.isZero())
  223288. {
  223289. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223290. if (ports != 0)
  223291. {
  223292. const int numInputChannels = inputChannels.getHighestBit() + 1;
  223293. for (int i = 0; i < numInputChannels; ++i)
  223294. {
  223295. const String portName (ports[i]);
  223296. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223297. {
  223298. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  223299. if (error != 0)
  223300. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223301. }
  223302. }
  223303. free (ports);
  223304. }
  223305. }
  223306. if (! outputChannels.isZero())
  223307. {
  223308. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223309. if (ports != 0)
  223310. {
  223311. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  223312. for (int i = 0; i < numOutputChannels; ++i)
  223313. {
  223314. const String portName (ports[i]);
  223315. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223316. {
  223317. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  223318. if (error != 0)
  223319. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223320. }
  223321. }
  223322. free (ports);
  223323. }
  223324. }
  223325. return lastError;
  223326. }
  223327. void close()
  223328. {
  223329. stop();
  223330. if (client != 0)
  223331. {
  223332. JUCE_NAMESPACE::jack_deactivate (client);
  223333. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  223334. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  223335. }
  223336. isOpen_ = false;
  223337. }
  223338. void start (AudioIODeviceCallback* newCallback)
  223339. {
  223340. if (isOpen_ && newCallback != callback)
  223341. {
  223342. if (newCallback != 0)
  223343. newCallback->audioDeviceAboutToStart (this);
  223344. AudioIODeviceCallback* const oldCallback = callback;
  223345. {
  223346. const ScopedLock sl (callbackLock);
  223347. callback = newCallback;
  223348. }
  223349. if (oldCallback != 0)
  223350. oldCallback->audioDeviceStopped();
  223351. }
  223352. }
  223353. void stop()
  223354. {
  223355. start (0);
  223356. }
  223357. bool isOpen() { return isOpen_; }
  223358. bool isPlaying() { return callback != 0; }
  223359. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  223360. double getCurrentSampleRate() { return getSampleRate (0); }
  223361. int getCurrentBitDepth() { return 32; }
  223362. const String getLastError() { return lastError; }
  223363. const BigInteger getActiveOutputChannels() const
  223364. {
  223365. BigInteger outputBits;
  223366. for (int i = 0; i < outputPorts.size(); i++)
  223367. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  223368. outputBits.setBit (i);
  223369. return outputBits;
  223370. }
  223371. const BigInteger getActiveInputChannels() const
  223372. {
  223373. BigInteger inputBits;
  223374. for (int i = 0; i < inputPorts.size(); i++)
  223375. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  223376. inputBits.setBit (i);
  223377. return inputBits;
  223378. }
  223379. int getOutputLatencyInSamples()
  223380. {
  223381. int latency = 0;
  223382. for (int i = 0; i < outputPorts.size(); i++)
  223383. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  223384. return latency;
  223385. }
  223386. int getInputLatencyInSamples()
  223387. {
  223388. int latency = 0;
  223389. for (int i = 0; i < inputPorts.size(); i++)
  223390. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  223391. return latency;
  223392. }
  223393. String inputId, outputId;
  223394. private:
  223395. void process (const int numSamples)
  223396. {
  223397. int i, numActiveInChans = 0, numActiveOutChans = 0;
  223398. for (i = 0; i < totalNumberOfInputChannels; ++i)
  223399. {
  223400. jack_default_audio_sample_t* in
  223401. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  223402. if (in != 0)
  223403. inChans [numActiveInChans++] = (float*) in;
  223404. }
  223405. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  223406. {
  223407. jack_default_audio_sample_t* out
  223408. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  223409. if (out != 0)
  223410. outChans [numActiveOutChans++] = (float*) out;
  223411. }
  223412. const ScopedLock sl (callbackLock);
  223413. if (callback != 0)
  223414. {
  223415. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  223416. outChans, numActiveOutChans, numSamples);
  223417. }
  223418. else
  223419. {
  223420. for (i = 0; i < numActiveOutChans; ++i)
  223421. zeromem (outChans[i], sizeof (float) * numSamples);
  223422. }
  223423. }
  223424. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  223425. {
  223426. if (callbackArgument != 0)
  223427. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  223428. return 0;
  223429. }
  223430. static void threadInitCallback (void* callbackArgument)
  223431. {
  223432. jack_Log ("JackAudioIODevice::initialise");
  223433. }
  223434. static void shutdownCallback (void* callbackArgument)
  223435. {
  223436. jack_Log ("JackAudioIODevice::shutdown");
  223437. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  223438. if (device != 0)
  223439. {
  223440. device->client = 0;
  223441. device->close();
  223442. }
  223443. }
  223444. static void errorCallback (const char* msg)
  223445. {
  223446. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  223447. }
  223448. bool isOpen_;
  223449. jack_client_t* client;
  223450. String lastError;
  223451. AudioIODeviceCallback* callback;
  223452. CriticalSection callbackLock;
  223453. HeapBlock <float*> inChans, outChans;
  223454. int totalNumberOfInputChannels;
  223455. int totalNumberOfOutputChannels;
  223456. Array<void*> inputPorts, outputPorts;
  223457. };
  223458. class JackAudioIODeviceType : public AudioIODeviceType
  223459. {
  223460. public:
  223461. JackAudioIODeviceType()
  223462. : AudioIODeviceType ("JACK"),
  223463. hasScanned (false)
  223464. {
  223465. }
  223466. ~JackAudioIODeviceType()
  223467. {
  223468. }
  223469. void scanForDevices()
  223470. {
  223471. hasScanned = true;
  223472. inputNames.clear();
  223473. inputIds.clear();
  223474. outputNames.clear();
  223475. outputIds.clear();
  223476. if (juce_libjack_handle == 0)
  223477. {
  223478. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  223479. if (juce_libjack_handle == 0)
  223480. return;
  223481. }
  223482. // open a dummy client
  223483. jack_status_t status;
  223484. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  223485. if (client == 0)
  223486. {
  223487. dumpJackErrorMessage (status);
  223488. }
  223489. else
  223490. {
  223491. // scan for output devices
  223492. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223493. if (ports != 0)
  223494. {
  223495. int j = 0;
  223496. while (ports[j] != 0)
  223497. {
  223498. String clientName (ports[j]);
  223499. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223500. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223501. && ! inputNames.contains (clientName))
  223502. {
  223503. inputNames.add (clientName);
  223504. inputIds.add (ports [j]);
  223505. }
  223506. ++j;
  223507. }
  223508. free (ports);
  223509. }
  223510. // scan for input devices
  223511. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223512. if (ports != 0)
  223513. {
  223514. int j = 0;
  223515. while (ports[j] != 0)
  223516. {
  223517. String clientName (ports[j]);
  223518. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223519. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223520. && ! outputNames.contains (clientName))
  223521. {
  223522. outputNames.add (clientName);
  223523. outputIds.add (ports [j]);
  223524. }
  223525. ++j;
  223526. }
  223527. free (ports);
  223528. }
  223529. JUCE_NAMESPACE::jack_client_close (client);
  223530. }
  223531. }
  223532. const StringArray getDeviceNames (bool wantInputNames) const
  223533. {
  223534. jassert (hasScanned); // need to call scanForDevices() before doing this
  223535. return wantInputNames ? inputNames : outputNames;
  223536. }
  223537. int getDefaultDeviceIndex (bool forInput) const
  223538. {
  223539. jassert (hasScanned); // need to call scanForDevices() before doing this
  223540. return 0;
  223541. }
  223542. bool hasSeparateInputsAndOutputs() const { return true; }
  223543. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223544. {
  223545. jassert (hasScanned); // need to call scanForDevices() before doing this
  223546. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223547. if (d == 0)
  223548. return -1;
  223549. return asInput ? inputIds.indexOf (d->inputId)
  223550. : outputIds.indexOf (d->outputId);
  223551. }
  223552. AudioIODevice* createDevice (const String& outputDeviceName,
  223553. const String& inputDeviceName)
  223554. {
  223555. jassert (hasScanned); // need to call scanForDevices() before doing this
  223556. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223557. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223558. if (inputIndex >= 0 || outputIndex >= 0)
  223559. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223560. : inputDeviceName,
  223561. inputIds [inputIndex],
  223562. outputIds [outputIndex]);
  223563. return 0;
  223564. }
  223565. juce_UseDebuggingNewOperator
  223566. private:
  223567. StringArray inputNames, outputNames, inputIds, outputIds;
  223568. bool hasScanned;
  223569. JackAudioIODeviceType (const JackAudioIODeviceType&);
  223570. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  223571. };
  223572. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  223573. {
  223574. return new JackAudioIODeviceType();
  223575. }
  223576. #else // if JACK is turned off..
  223577. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  223578. #endif
  223579. #endif
  223580. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223581. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223582. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223583. // compiled on its own).
  223584. #if JUCE_INCLUDED_FILE
  223585. #if JUCE_ALSA
  223586. static snd_seq_t* iterateMidiDevices (const bool forInput,
  223587. StringArray& deviceNamesFound,
  223588. const int deviceIndexToOpen)
  223589. {
  223590. snd_seq_t* returnedHandle = 0;
  223591. snd_seq_t* seqHandle;
  223592. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223593. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223594. {
  223595. snd_seq_system_info_t* systemInfo;
  223596. snd_seq_client_info_t* clientInfo;
  223597. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223598. {
  223599. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223600. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223601. {
  223602. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223603. while (--numClients >= 0 && returnedHandle == 0)
  223604. {
  223605. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223606. {
  223607. snd_seq_port_info_t* portInfo;
  223608. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223609. {
  223610. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223611. const int client = snd_seq_client_info_get_client (clientInfo);
  223612. snd_seq_port_info_set_client (portInfo, client);
  223613. snd_seq_port_info_set_port (portInfo, -1);
  223614. while (--numPorts >= 0)
  223615. {
  223616. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223617. && (snd_seq_port_info_get_capability (portInfo)
  223618. & (forInput ? SND_SEQ_PORT_CAP_READ
  223619. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223620. {
  223621. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223622. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223623. {
  223624. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223625. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223626. if (sourcePort != -1)
  223627. {
  223628. snd_seq_set_client_name (seqHandle,
  223629. forInput ? "Juce Midi Input"
  223630. : "Juce Midi Output");
  223631. const int portId
  223632. = snd_seq_create_simple_port (seqHandle,
  223633. forInput ? "Juce Midi In Port"
  223634. : "Juce Midi Out Port",
  223635. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223636. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223637. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223638. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223639. returnedHandle = seqHandle;
  223640. }
  223641. }
  223642. }
  223643. }
  223644. snd_seq_port_info_free (portInfo);
  223645. }
  223646. }
  223647. }
  223648. snd_seq_client_info_free (clientInfo);
  223649. }
  223650. snd_seq_system_info_free (systemInfo);
  223651. }
  223652. if (returnedHandle == 0)
  223653. snd_seq_close (seqHandle);
  223654. }
  223655. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223656. return returnedHandle;
  223657. }
  223658. static snd_seq_t* createMidiDevice (const bool forInput,
  223659. const String& deviceNameToOpen)
  223660. {
  223661. snd_seq_t* seqHandle = 0;
  223662. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223663. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223664. {
  223665. snd_seq_set_client_name (seqHandle,
  223666. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223667. const int portId
  223668. = snd_seq_create_simple_port (seqHandle,
  223669. forInput ? "in"
  223670. : "out",
  223671. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223672. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223673. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223674. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223675. if (portId < 0)
  223676. {
  223677. snd_seq_close (seqHandle);
  223678. seqHandle = 0;
  223679. }
  223680. }
  223681. return seqHandle;
  223682. }
  223683. class MidiOutputDevice
  223684. {
  223685. public:
  223686. MidiOutputDevice (MidiOutput* const midiOutput_,
  223687. snd_seq_t* const seqHandle_)
  223688. :
  223689. midiOutput (midiOutput_),
  223690. seqHandle (seqHandle_),
  223691. maxEventSize (16 * 1024)
  223692. {
  223693. jassert (seqHandle != 0 && midiOutput != 0);
  223694. snd_midi_event_new (maxEventSize, &midiParser);
  223695. }
  223696. ~MidiOutputDevice()
  223697. {
  223698. snd_midi_event_free (midiParser);
  223699. snd_seq_close (seqHandle);
  223700. }
  223701. void sendMessageNow (const MidiMessage& message)
  223702. {
  223703. if (message.getRawDataSize() > maxEventSize)
  223704. {
  223705. maxEventSize = message.getRawDataSize();
  223706. snd_midi_event_free (midiParser);
  223707. snd_midi_event_new (maxEventSize, &midiParser);
  223708. }
  223709. snd_seq_event_t event;
  223710. snd_seq_ev_clear (&event);
  223711. snd_midi_event_encode (midiParser,
  223712. message.getRawData(),
  223713. message.getRawDataSize(),
  223714. &event);
  223715. snd_midi_event_reset_encode (midiParser);
  223716. snd_seq_ev_set_source (&event, 0);
  223717. snd_seq_ev_set_subs (&event);
  223718. snd_seq_ev_set_direct (&event);
  223719. snd_seq_event_output (seqHandle, &event);
  223720. snd_seq_drain_output (seqHandle);
  223721. }
  223722. juce_UseDebuggingNewOperator
  223723. private:
  223724. MidiOutput* const midiOutput;
  223725. snd_seq_t* const seqHandle;
  223726. snd_midi_event_t* midiParser;
  223727. int maxEventSize;
  223728. };
  223729. const StringArray MidiOutput::getDevices()
  223730. {
  223731. StringArray devices;
  223732. iterateMidiDevices (false, devices, -1);
  223733. return devices;
  223734. }
  223735. int MidiOutput::getDefaultDeviceIndex()
  223736. {
  223737. return 0;
  223738. }
  223739. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223740. {
  223741. MidiOutput* newDevice = 0;
  223742. StringArray devices;
  223743. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  223744. if (handle != 0)
  223745. {
  223746. newDevice = new MidiOutput();
  223747. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223748. }
  223749. return newDevice;
  223750. }
  223751. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223752. {
  223753. MidiOutput* newDevice = 0;
  223754. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223755. if (handle != 0)
  223756. {
  223757. newDevice = new MidiOutput();
  223758. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223759. }
  223760. return newDevice;
  223761. }
  223762. MidiOutput::~MidiOutput()
  223763. {
  223764. delete static_cast <MidiOutputDevice*> (internal);
  223765. }
  223766. void MidiOutput::reset()
  223767. {
  223768. }
  223769. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223770. {
  223771. return false;
  223772. }
  223773. void MidiOutput::setVolume (float leftVol, float rightVol)
  223774. {
  223775. }
  223776. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223777. {
  223778. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  223779. }
  223780. class MidiInputThread : public Thread
  223781. {
  223782. public:
  223783. MidiInputThread (MidiInput* const midiInput_,
  223784. snd_seq_t* const seqHandle_,
  223785. MidiInputCallback* const callback_)
  223786. : Thread ("Juce MIDI Input"),
  223787. midiInput (midiInput_),
  223788. seqHandle (seqHandle_),
  223789. callback (callback_)
  223790. {
  223791. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  223792. }
  223793. ~MidiInputThread()
  223794. {
  223795. snd_seq_close (seqHandle);
  223796. }
  223797. void run()
  223798. {
  223799. const int maxEventSize = 16 * 1024;
  223800. snd_midi_event_t* midiParser;
  223801. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223802. {
  223803. HeapBlock <uint8> buffer (maxEventSize);
  223804. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223805. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223806. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223807. while (! threadShouldExit())
  223808. {
  223809. if (poll (pfd, numPfds, 500) > 0)
  223810. {
  223811. snd_seq_event_t* inputEvent = 0;
  223812. snd_seq_nonblock (seqHandle, 1);
  223813. do
  223814. {
  223815. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223816. {
  223817. // xxx what about SYSEXes that are too big for the buffer?
  223818. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223819. snd_midi_event_reset_decode (midiParser);
  223820. if (numBytes > 0)
  223821. {
  223822. const MidiMessage message ((const uint8*) buffer,
  223823. numBytes,
  223824. Time::getMillisecondCounter() * 0.001);
  223825. callback->handleIncomingMidiMessage (midiInput, message);
  223826. }
  223827. snd_seq_free_event (inputEvent);
  223828. }
  223829. }
  223830. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223831. snd_seq_free_event (inputEvent);
  223832. }
  223833. }
  223834. snd_midi_event_free (midiParser);
  223835. }
  223836. };
  223837. juce_UseDebuggingNewOperator
  223838. private:
  223839. MidiInput* const midiInput;
  223840. snd_seq_t* const seqHandle;
  223841. MidiInputCallback* const callback;
  223842. };
  223843. MidiInput::MidiInput (const String& name_)
  223844. : name (name_),
  223845. internal (0)
  223846. {
  223847. }
  223848. MidiInput::~MidiInput()
  223849. {
  223850. stop();
  223851. delete static_cast <MidiInputThread*> (internal);
  223852. }
  223853. void MidiInput::start()
  223854. {
  223855. static_cast <MidiInputThread*> (internal)->startThread();
  223856. }
  223857. void MidiInput::stop()
  223858. {
  223859. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  223860. }
  223861. int MidiInput::getDefaultDeviceIndex()
  223862. {
  223863. return 0;
  223864. }
  223865. const StringArray MidiInput::getDevices()
  223866. {
  223867. StringArray devices;
  223868. iterateMidiDevices (true, devices, -1);
  223869. return devices;
  223870. }
  223871. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  223872. {
  223873. MidiInput* newDevice = 0;
  223874. StringArray devices;
  223875. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  223876. if (handle != 0)
  223877. {
  223878. newDevice = new MidiInput (devices [deviceIndex]);
  223879. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223880. }
  223881. return newDevice;
  223882. }
  223883. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  223884. {
  223885. MidiInput* newDevice = 0;
  223886. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  223887. if (handle != 0)
  223888. {
  223889. newDevice = new MidiInput (deviceName);
  223890. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223891. }
  223892. return newDevice;
  223893. }
  223894. #else
  223895. // (These are just stub functions if ALSA is unavailable...)
  223896. const StringArray MidiOutput::getDevices() { return StringArray(); }
  223897. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  223898. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  223899. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  223900. MidiOutput::~MidiOutput() {}
  223901. void MidiOutput::reset() {}
  223902. bool MidiOutput::getVolume (float&, float&) { return false; }
  223903. void MidiOutput::setVolume (float, float) {}
  223904. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  223905. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  223906. MidiInput::~MidiInput() {}
  223907. void MidiInput::start() {}
  223908. void MidiInput::stop() {}
  223909. int MidiInput::getDefaultDeviceIndex() { return 0; }
  223910. const StringArray MidiInput::getDevices() { return StringArray(); }
  223911. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  223912. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  223913. #endif
  223914. #endif
  223915. /*** End of inlined file: juce_linux_Midi.cpp ***/
  223916. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  223917. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223918. // compiled on its own).
  223919. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  223920. AudioCDReader::AudioCDReader()
  223921. : AudioFormatReader (0, "CD Audio")
  223922. {
  223923. }
  223924. const StringArray AudioCDReader::getAvailableCDNames()
  223925. {
  223926. StringArray names;
  223927. return names;
  223928. }
  223929. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  223930. {
  223931. return 0;
  223932. }
  223933. AudioCDReader::~AudioCDReader()
  223934. {
  223935. }
  223936. void AudioCDReader::refreshTrackLengths()
  223937. {
  223938. }
  223939. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  223940. int64 startSampleInFile, int numSamples)
  223941. {
  223942. return false;
  223943. }
  223944. bool AudioCDReader::isCDStillPresent() const
  223945. {
  223946. return false;
  223947. }
  223948. bool AudioCDReader::isTrackAudio (int trackNum) const
  223949. {
  223950. return false;
  223951. }
  223952. void AudioCDReader::enableIndexScanning (bool b)
  223953. {
  223954. }
  223955. int AudioCDReader::getLastIndex() const
  223956. {
  223957. return 0;
  223958. }
  223959. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  223960. {
  223961. return Array<int>();
  223962. }
  223963. #endif
  223964. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  223965. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  223966. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223967. // compiled on its own).
  223968. #if JUCE_INCLUDED_FILE
  223969. void FileChooser::showPlatformDialog (Array<File>& results,
  223970. const String& title,
  223971. const File& file,
  223972. const String& filters,
  223973. bool isDirectory,
  223974. bool selectsFiles,
  223975. bool isSave,
  223976. bool warnAboutOverwritingExistingFiles,
  223977. bool selectMultipleFiles,
  223978. FilePreviewComponent* previewComponent)
  223979. {
  223980. const String separator (":");
  223981. String command ("zenity --file-selection");
  223982. if (title.isNotEmpty())
  223983. command << " --title=\"" << title << "\"";
  223984. if (file != File::nonexistent)
  223985. command << " --filename=\"" << file.getFullPathName () << "\"";
  223986. if (isDirectory)
  223987. command << " --directory";
  223988. if (isSave)
  223989. command << " --save";
  223990. if (selectMultipleFiles)
  223991. command << " --multiple --separator=\"" << separator << "\"";
  223992. command << " 2>&1";
  223993. MemoryOutputStream result;
  223994. int status = -1;
  223995. FILE* stream = popen (command.toUTF8(), "r");
  223996. if (stream != 0)
  223997. {
  223998. for (;;)
  223999. {
  224000. char buffer [1024];
  224001. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  224002. if (bytesRead <= 0)
  224003. break;
  224004. result.write (buffer, bytesRead);
  224005. }
  224006. status = pclose (stream);
  224007. }
  224008. if (status == 0)
  224009. {
  224010. StringArray tokens;
  224011. if (selectMultipleFiles)
  224012. tokens.addTokens (result.toUTF8(), separator, String::empty);
  224013. else
  224014. tokens.add (result.toUTF8());
  224015. for (int i = 0; i < tokens.size(); i++)
  224016. results.add (File (tokens[i]));
  224017. return;
  224018. }
  224019. //xxx ain't got one!
  224020. jassertfalse;
  224021. }
  224022. #endif
  224023. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  224024. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224025. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224026. // compiled on its own).
  224027. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  224028. /*
  224029. Sorry.. This class isn't implemented on Linux!
  224030. */
  224031. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  224032. : browser (0),
  224033. blankPageShown (false),
  224034. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  224035. {
  224036. setOpaque (true);
  224037. }
  224038. WebBrowserComponent::~WebBrowserComponent()
  224039. {
  224040. }
  224041. void WebBrowserComponent::goToURL (const String& url,
  224042. const StringArray* headers,
  224043. const MemoryBlock* postData)
  224044. {
  224045. lastURL = url;
  224046. lastHeaders.clear();
  224047. if (headers != 0)
  224048. lastHeaders = *headers;
  224049. lastPostData.setSize (0);
  224050. if (postData != 0)
  224051. lastPostData = *postData;
  224052. blankPageShown = false;
  224053. }
  224054. void WebBrowserComponent::stop()
  224055. {
  224056. }
  224057. void WebBrowserComponent::goBack()
  224058. {
  224059. lastURL = String::empty;
  224060. blankPageShown = false;
  224061. }
  224062. void WebBrowserComponent::goForward()
  224063. {
  224064. lastURL = String::empty;
  224065. }
  224066. void WebBrowserComponent::refresh()
  224067. {
  224068. }
  224069. void WebBrowserComponent::paint (Graphics& g)
  224070. {
  224071. g.fillAll (Colours::white);
  224072. }
  224073. void WebBrowserComponent::checkWindowAssociation()
  224074. {
  224075. }
  224076. void WebBrowserComponent::reloadLastURL()
  224077. {
  224078. if (lastURL.isNotEmpty())
  224079. {
  224080. goToURL (lastURL, &lastHeaders, &lastPostData);
  224081. lastURL = String::empty;
  224082. }
  224083. }
  224084. void WebBrowserComponent::parentHierarchyChanged()
  224085. {
  224086. checkWindowAssociation();
  224087. }
  224088. void WebBrowserComponent::resized()
  224089. {
  224090. }
  224091. void WebBrowserComponent::visibilityChanged()
  224092. {
  224093. checkWindowAssociation();
  224094. }
  224095. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  224096. {
  224097. return true;
  224098. }
  224099. #endif
  224100. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224101. #endif
  224102. END_JUCE_NAMESPACE
  224103. #endif
  224104. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  224105. #endif
  224106. #if JUCE_MAC || JUCE_IPHONE
  224107. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  224108. /*
  224109. This file wraps together all the mac-specific code, so that
  224110. we can include all the native headers just once, and compile all our
  224111. platform-specific stuff in one big lump, keeping it out of the way of
  224112. the rest of the codebase.
  224113. */
  224114. #if JUCE_MAC || JUCE_IOS
  224115. BEGIN_JUCE_NAMESPACE
  224116. #undef Point
  224117. #define JUCE_INCLUDED_FILE 1
  224118. // Now include the actual code files..
  224119. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  224120. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  224121. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  224122. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  224123. cross-linked so that when you make a call to a class that you thought was private, it ends up
  224124. actually calling into a similarly named class in the other module's address space.
  224125. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  224126. have unique names, and should avoid this problem.
  224127. If you're using the amalgamated version, you can just set this macro to something unique before
  224128. you include juce_amalgamated.cpp.
  224129. */
  224130. #ifndef JUCE_ObjCExtraSuffix
  224131. #define JUCE_ObjCExtraSuffix 3
  224132. #endif
  224133. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  224134. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  224135. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  224136. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  224137. /*** Start of inlined file: juce_mac_Strings.mm ***/
  224138. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224139. // compiled on its own).
  224140. #if JUCE_INCLUDED_FILE
  224141. static const String nsStringToJuce (NSString* s)
  224142. {
  224143. return String::fromUTF8 ([s UTF8String]);
  224144. }
  224145. static NSString* juceStringToNS (const String& s)
  224146. {
  224147. return [NSString stringWithUTF8String: s.toUTF8()];
  224148. }
  224149. static const String convertUTF16ToString (const UniChar* utf16)
  224150. {
  224151. String s;
  224152. while (*utf16 != 0)
  224153. s += (juce_wchar) *utf16++;
  224154. return s;
  224155. }
  224156. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  224157. {
  224158. String result;
  224159. if (cfString != 0)
  224160. {
  224161. CFRange range = { 0, CFStringGetLength (cfString) };
  224162. HeapBlock <UniChar> u (range.length + 1);
  224163. CFStringGetCharacters (cfString, range, u);
  224164. u[range.length] = 0;
  224165. result = convertUTF16ToString (u);
  224166. }
  224167. return result;
  224168. }
  224169. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  224170. {
  224171. const int len = s.length();
  224172. HeapBlock <UniChar> temp (len + 2);
  224173. for (int i = 0; i <= len; ++i)
  224174. temp[i] = s[i];
  224175. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  224176. }
  224177. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  224178. {
  224179. #if JUCE_IOS
  224180. const ScopedAutoReleasePool pool;
  224181. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  224182. #else
  224183. UnicodeMapping map;
  224184. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224185. kUnicodeNoSubset,
  224186. kTextEncodingDefaultFormat);
  224187. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224188. kUnicodeCanonicalCompVariant,
  224189. kTextEncodingDefaultFormat);
  224190. map.mappingVersion = kUnicodeUseLatestMapping;
  224191. UnicodeToTextInfo conversionInfo = 0;
  224192. String result;
  224193. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  224194. {
  224195. const int len = s.length();
  224196. HeapBlock <UniChar> tempIn, tempOut;
  224197. tempIn.calloc (len + 2);
  224198. tempOut.calloc (len + 2);
  224199. for (int i = 0; i <= len; ++i)
  224200. tempIn[i] = s[i];
  224201. ByteCount bytesRead = 0;
  224202. ByteCount outputBufferSize = 0;
  224203. if (ConvertFromUnicodeToText (conversionInfo,
  224204. len * sizeof (UniChar), tempIn,
  224205. kUnicodeDefaultDirectionMask,
  224206. 0, 0, 0, 0,
  224207. len * sizeof (UniChar), &bytesRead,
  224208. &outputBufferSize, tempOut) == noErr)
  224209. {
  224210. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  224211. juce_wchar* t = result;
  224212. unsigned int i;
  224213. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  224214. t[i] = (juce_wchar) tempOut[i];
  224215. t[i] = 0;
  224216. }
  224217. DisposeUnicodeToTextInfo (&conversionInfo);
  224218. }
  224219. return result;
  224220. #endif
  224221. }
  224222. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224223. void SystemClipboard::copyTextToClipboard (const String& text)
  224224. {
  224225. #if JUCE_IOS
  224226. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  224227. forPasteboardType: @"public.text"];
  224228. #else
  224229. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  224230. owner: nil];
  224231. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  224232. forType: NSStringPboardType];
  224233. #endif
  224234. }
  224235. const String SystemClipboard::getTextFromClipboard()
  224236. {
  224237. #if JUCE_IOS
  224238. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  224239. #else
  224240. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  224241. #endif
  224242. return text == 0 ? String::empty
  224243. : nsStringToJuce (text);
  224244. }
  224245. #endif
  224246. #endif
  224247. /*** End of inlined file: juce_mac_Strings.mm ***/
  224248. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  224249. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224250. // compiled on its own).
  224251. #if JUCE_INCLUDED_FILE
  224252. namespace SystemStatsHelpers
  224253. {
  224254. static int64 highResTimerFrequency = 0;
  224255. static double highResTimerToMillisecRatio = 0;
  224256. #if JUCE_INTEL
  224257. static void juce_getCpuVendor (char* const v) throw()
  224258. {
  224259. int vendor[4];
  224260. zerostruct (vendor);
  224261. int dummy = 0;
  224262. asm ("mov %%ebx, %%esi \n\t"
  224263. "cpuid \n\t"
  224264. "xchg %%esi, %%ebx"
  224265. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  224266. memcpy (v, vendor, 16);
  224267. }
  224268. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  224269. {
  224270. unsigned int cpu = 0;
  224271. unsigned int ext = 0;
  224272. unsigned int family = 0;
  224273. unsigned int dummy = 0;
  224274. asm ("mov %%ebx, %%esi \n\t"
  224275. "cpuid \n\t"
  224276. "xchg %%esi, %%ebx"
  224277. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  224278. familyModel = family;
  224279. extFeatures = ext;
  224280. return cpu;
  224281. }
  224282. #endif
  224283. }
  224284. void SystemStats::initialiseStats()
  224285. {
  224286. using namespace SystemStatsHelpers;
  224287. static bool initialised = false;
  224288. if (! initialised)
  224289. {
  224290. initialised = true;
  224291. #if JUCE_MAC
  224292. [NSApplication sharedApplication];
  224293. #endif
  224294. #if JUCE_INTEL
  224295. unsigned int familyModel, extFeatures;
  224296. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  224297. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  224298. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  224299. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  224300. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  224301. #else
  224302. cpuFlags.hasMMX = false;
  224303. cpuFlags.hasSSE = false;
  224304. cpuFlags.hasSSE2 = false;
  224305. cpuFlags.has3DNow = false;
  224306. #endif
  224307. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  224308. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  224309. #else
  224310. cpuFlags.numCpus = (int) MPProcessors();
  224311. #endif
  224312. mach_timebase_info_data_t timebase;
  224313. (void) mach_timebase_info (&timebase);
  224314. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  224315. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  224316. String s (SystemStats::getJUCEVersion());
  224317. rlimit lim;
  224318. getrlimit (RLIMIT_NOFILE, &lim);
  224319. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  224320. setrlimit (RLIMIT_NOFILE, &lim);
  224321. }
  224322. }
  224323. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  224324. {
  224325. return MacOSX;
  224326. }
  224327. const String SystemStats::getOperatingSystemName()
  224328. {
  224329. return "Mac OS X";
  224330. }
  224331. #if ! JUCE_IOS
  224332. int PlatformUtilities::getOSXMinorVersionNumber()
  224333. {
  224334. SInt32 versionMinor = 0;
  224335. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224336. (void) err;
  224337. jassert (err == noErr);
  224338. return (int) versionMinor;
  224339. }
  224340. #endif
  224341. bool SystemStats::isOperatingSystem64Bit()
  224342. {
  224343. #if JUCE_IOS
  224344. return false;
  224345. #elif JUCE_64BIT
  224346. return true;
  224347. #else
  224348. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  224349. #endif
  224350. }
  224351. int SystemStats::getMemorySizeInMegabytes()
  224352. {
  224353. uint64 mem = 0;
  224354. size_t memSize = sizeof (mem);
  224355. int mib[] = { CTL_HW, HW_MEMSIZE };
  224356. sysctl (mib, 2, &mem, &memSize, 0, 0);
  224357. return (int) (mem / (1024 * 1024));
  224358. }
  224359. const String SystemStats::getCpuVendor()
  224360. {
  224361. #if JUCE_INTEL
  224362. char v [16];
  224363. SystemStatsHelpers::juce_getCpuVendor (v);
  224364. return String (v, 16);
  224365. #else
  224366. return String::empty;
  224367. #endif
  224368. }
  224369. int SystemStats::getCpuSpeedInMegaherz()
  224370. {
  224371. uint64 speedHz = 0;
  224372. size_t speedSize = sizeof (speedHz);
  224373. int mib[] = { CTL_HW, HW_CPU_FREQ };
  224374. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  224375. #if JUCE_BIG_ENDIAN
  224376. if (speedSize == 4)
  224377. speedHz >>= 32;
  224378. #endif
  224379. return (int) (speedHz / 1000000);
  224380. }
  224381. const String SystemStats::getLogonName()
  224382. {
  224383. return nsStringToJuce (NSUserName());
  224384. }
  224385. const String SystemStats::getFullUserName()
  224386. {
  224387. return nsStringToJuce (NSFullUserName());
  224388. }
  224389. uint32 juce_millisecondsSinceStartup() throw()
  224390. {
  224391. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  224392. }
  224393. double Time::getMillisecondCounterHiRes() throw()
  224394. {
  224395. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  224396. }
  224397. int64 Time::getHighResolutionTicks() throw()
  224398. {
  224399. return (int64) mach_absolute_time();
  224400. }
  224401. int64 Time::getHighResolutionTicksPerSecond() throw()
  224402. {
  224403. return SystemStatsHelpers::highResTimerFrequency;
  224404. }
  224405. bool Time::setSystemTimeToThisTime() const
  224406. {
  224407. jassertfalse;
  224408. return false;
  224409. }
  224410. int SystemStats::getPageSize()
  224411. {
  224412. return (int) NSPageSize();
  224413. }
  224414. void PlatformUtilities::fpuReset()
  224415. {
  224416. }
  224417. #endif
  224418. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  224419. /*** Start of inlined file: juce_mac_Network.mm ***/
  224420. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224421. // compiled on its own).
  224422. #if JUCE_INCLUDED_FILE
  224423. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  224424. {
  224425. #ifndef IFT_ETHER
  224426. #define IFT_ETHER 6
  224427. #endif
  224428. ifaddrs* addrs = 0;
  224429. int numResults = 0;
  224430. if (getifaddrs (&addrs) == 0)
  224431. {
  224432. const ifaddrs* cursor = addrs;
  224433. while (cursor != 0 && numResults < maxNum)
  224434. {
  224435. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224436. if (sto->ss_family == AF_LINK)
  224437. {
  224438. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224439. if (sadd->sdl_type == IFT_ETHER)
  224440. {
  224441. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  224442. uint64 a = 0;
  224443. for (int i = 6; --i >= 0;)
  224444. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  224445. *addresses++ = (int64) a;
  224446. ++numResults;
  224447. }
  224448. }
  224449. cursor = cursor->ifa_next;
  224450. }
  224451. freeifaddrs (addrs);
  224452. }
  224453. return numResults;
  224454. }
  224455. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224456. const String& emailSubject,
  224457. const String& bodyText,
  224458. const StringArray& filesToAttach)
  224459. {
  224460. #if JUCE_IOS
  224461. //xxx probably need to use MFMailComposeViewController
  224462. jassertfalse;
  224463. return false;
  224464. #else
  224465. const ScopedAutoReleasePool pool;
  224466. String script;
  224467. script << "tell application \"Mail\"\r\n"
  224468. "set newMessage to make new outgoing message with properties {subject:\""
  224469. << emailSubject.replace ("\"", "\\\"")
  224470. << "\", content:\""
  224471. << bodyText.replace ("\"", "\\\"")
  224472. << "\" & return & return}\r\n"
  224473. "tell newMessage\r\n"
  224474. "set visible to true\r\n"
  224475. "set sender to \"sdfsdfsdfewf\"\r\n"
  224476. "make new to recipient at end of to recipients with properties {address:\""
  224477. << targetEmailAddress
  224478. << "\"}\r\n";
  224479. for (int i = 0; i < filesToAttach.size(); ++i)
  224480. {
  224481. script << "tell content\r\n"
  224482. "make new attachment with properties {file name:\""
  224483. << filesToAttach[i].replace ("\"", "\\\"")
  224484. << "\"} at after the last paragraph\r\n"
  224485. "end tell\r\n";
  224486. }
  224487. script << "end tell\r\n"
  224488. "end tell\r\n";
  224489. NSAppleScript* s = [[NSAppleScript alloc]
  224490. initWithSource: juceStringToNS (script)];
  224491. NSDictionary* error = 0;
  224492. const bool ok = [s executeAndReturnError: &error] != nil;
  224493. [s release];
  224494. return ok;
  224495. #endif
  224496. }
  224497. END_JUCE_NAMESPACE
  224498. using namespace JUCE_NAMESPACE;
  224499. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224500. @interface JuceURLConnection : NSObject
  224501. {
  224502. @public
  224503. NSURLRequest* request;
  224504. NSURLConnection* connection;
  224505. NSMutableData* data;
  224506. Thread* runLoopThread;
  224507. bool initialised, hasFailed, hasFinished;
  224508. int position;
  224509. int64 contentLength;
  224510. NSDictionary* headers;
  224511. NSLock* dataLock;
  224512. }
  224513. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224514. - (void) dealloc;
  224515. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224516. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224517. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224518. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224519. - (BOOL) isOpen;
  224520. - (int) read: (char*) dest numBytes: (int) num;
  224521. - (int) readPosition;
  224522. - (void) stop;
  224523. - (void) createConnection;
  224524. @end
  224525. class JuceURLConnectionMessageThread : public Thread
  224526. {
  224527. JuceURLConnection* owner;
  224528. public:
  224529. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224530. : Thread ("http connection"),
  224531. owner (owner_)
  224532. {
  224533. }
  224534. ~JuceURLConnectionMessageThread()
  224535. {
  224536. stopThread (10000);
  224537. }
  224538. void run()
  224539. {
  224540. [owner createConnection];
  224541. while (! threadShouldExit())
  224542. {
  224543. const ScopedAutoReleasePool pool;
  224544. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224545. }
  224546. }
  224547. };
  224548. @implementation JuceURLConnection
  224549. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224550. withCallback: (URL::OpenStreamProgressCallback*) callback
  224551. withContext: (void*) context;
  224552. {
  224553. [super init];
  224554. request = req;
  224555. [request retain];
  224556. data = [[NSMutableData data] retain];
  224557. dataLock = [[NSLock alloc] init];
  224558. connection = 0;
  224559. initialised = false;
  224560. hasFailed = false;
  224561. hasFinished = false;
  224562. contentLength = -1;
  224563. headers = 0;
  224564. runLoopThread = new JuceURLConnectionMessageThread (self);
  224565. runLoopThread->startThread();
  224566. while (runLoopThread->isThreadRunning() && ! initialised)
  224567. {
  224568. if (callback != 0)
  224569. callback (context, -1, (int) [[request HTTPBody] length]);
  224570. Thread::sleep (1);
  224571. }
  224572. return self;
  224573. }
  224574. - (void) dealloc
  224575. {
  224576. [self stop];
  224577. deleteAndZero (runLoopThread);
  224578. [connection release];
  224579. [data release];
  224580. [dataLock release];
  224581. [request release];
  224582. [headers release];
  224583. [super dealloc];
  224584. }
  224585. - (void) createConnection
  224586. {
  224587. NSUInteger oldRetainCount = [self retainCount];
  224588. connection = [[NSURLConnection alloc] initWithRequest: request
  224589. delegate: self];
  224590. if (oldRetainCount == [self retainCount])
  224591. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224592. if (connection == nil)
  224593. runLoopThread->signalThreadShouldExit();
  224594. }
  224595. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224596. {
  224597. (void) conn;
  224598. [dataLock lock];
  224599. [data setLength: 0];
  224600. [dataLock unlock];
  224601. initialised = true;
  224602. contentLength = [response expectedContentLength];
  224603. [headers release];
  224604. headers = 0;
  224605. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224606. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224607. }
  224608. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224609. {
  224610. (void) conn;
  224611. DBG (nsStringToJuce ([error description]));
  224612. hasFailed = true;
  224613. initialised = true;
  224614. if (runLoopThread != 0)
  224615. runLoopThread->signalThreadShouldExit();
  224616. }
  224617. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224618. {
  224619. (void) conn;
  224620. [dataLock lock];
  224621. [data appendData: newData];
  224622. [dataLock unlock];
  224623. initialised = true;
  224624. }
  224625. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224626. {
  224627. (void) conn;
  224628. hasFinished = true;
  224629. initialised = true;
  224630. if (runLoopThread != 0)
  224631. runLoopThread->signalThreadShouldExit();
  224632. }
  224633. - (BOOL) isOpen
  224634. {
  224635. return connection != 0 && ! hasFailed;
  224636. }
  224637. - (int) readPosition
  224638. {
  224639. return position;
  224640. }
  224641. - (int) read: (char*) dest numBytes: (int) numNeeded
  224642. {
  224643. int numDone = 0;
  224644. while (numNeeded > 0)
  224645. {
  224646. int available = jmin (numNeeded, (int) [data length]);
  224647. if (available > 0)
  224648. {
  224649. [dataLock lock];
  224650. [data getBytes: dest length: available];
  224651. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224652. [dataLock unlock];
  224653. numDone += available;
  224654. numNeeded -= available;
  224655. dest += available;
  224656. }
  224657. else
  224658. {
  224659. if (hasFailed || hasFinished)
  224660. break;
  224661. Thread::sleep (1);
  224662. }
  224663. }
  224664. position += numDone;
  224665. return numDone;
  224666. }
  224667. - (void) stop
  224668. {
  224669. [connection cancel];
  224670. if (runLoopThread != 0)
  224671. runLoopThread->stopThread (10000);
  224672. }
  224673. @end
  224674. BEGIN_JUCE_NAMESPACE
  224675. void* juce_openInternetFile (const String& url,
  224676. const String& headers,
  224677. const MemoryBlock& postData,
  224678. const bool isPost,
  224679. URL::OpenStreamProgressCallback* callback,
  224680. void* callbackContext,
  224681. int timeOutMs)
  224682. {
  224683. const ScopedAutoReleasePool pool;
  224684. NSMutableURLRequest* req = [NSMutableURLRequest
  224685. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224686. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224687. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224688. if (req == nil)
  224689. return 0;
  224690. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224691. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224692. StringArray headerLines;
  224693. headerLines.addLines (headers);
  224694. headerLines.removeEmptyStrings (true);
  224695. for (int i = 0; i < headerLines.size(); ++i)
  224696. {
  224697. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224698. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224699. if (key.isNotEmpty() && value.isNotEmpty())
  224700. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224701. }
  224702. if (isPost && postData.getSize() > 0)
  224703. {
  224704. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224705. length: postData.getSize()]];
  224706. }
  224707. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224708. withCallback: callback
  224709. withContext: callbackContext];
  224710. if ([s isOpen])
  224711. return s;
  224712. [s release];
  224713. return 0;
  224714. }
  224715. void juce_closeInternetFile (void* handle)
  224716. {
  224717. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224718. if (s != 0)
  224719. {
  224720. const ScopedAutoReleasePool pool;
  224721. [s stop];
  224722. [s release];
  224723. }
  224724. }
  224725. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  224726. {
  224727. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224728. if (s != 0)
  224729. {
  224730. const ScopedAutoReleasePool pool;
  224731. return [s read: (char*) buffer numBytes: bytesToRead];
  224732. }
  224733. return 0;
  224734. }
  224735. int64 juce_getInternetFileContentLength (void* handle)
  224736. {
  224737. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224738. if (s != 0)
  224739. return s->contentLength;
  224740. return -1;
  224741. }
  224742. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  224743. {
  224744. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224745. if (s != 0 && s->headers != 0)
  224746. {
  224747. NSEnumerator* enumerator = [s->headers keyEnumerator];
  224748. NSString* key;
  224749. while ((key = [enumerator nextObject]) != nil)
  224750. headers.set (nsStringToJuce (key),
  224751. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  224752. }
  224753. }
  224754. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  224755. {
  224756. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224757. if (s != 0)
  224758. return [s readPosition];
  224759. return 0;
  224760. }
  224761. #endif
  224762. /*** End of inlined file: juce_mac_Network.mm ***/
  224763. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224764. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224765. // compiled on its own).
  224766. #if JUCE_INCLUDED_FILE
  224767. struct NamedPipeInternal
  224768. {
  224769. String pipeInName, pipeOutName;
  224770. int pipeIn, pipeOut;
  224771. bool volatile createdPipe, blocked, stopReadOperation;
  224772. static void signalHandler (int) {}
  224773. };
  224774. void NamedPipe::cancelPendingReads()
  224775. {
  224776. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224777. {
  224778. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224779. intern->stopReadOperation = true;
  224780. char buffer [1] = { 0 };
  224781. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224782. (void) bytesWritten;
  224783. int timeout = 2000;
  224784. while (intern->blocked && --timeout >= 0)
  224785. Thread::sleep (2);
  224786. intern->stopReadOperation = false;
  224787. }
  224788. }
  224789. void NamedPipe::close()
  224790. {
  224791. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224792. if (intern != 0)
  224793. {
  224794. internal = 0;
  224795. if (intern->pipeIn != -1)
  224796. ::close (intern->pipeIn);
  224797. if (intern->pipeOut != -1)
  224798. ::close (intern->pipeOut);
  224799. if (intern->createdPipe)
  224800. {
  224801. unlink (intern->pipeInName.toUTF8());
  224802. unlink (intern->pipeOutName.toUTF8());
  224803. }
  224804. delete intern;
  224805. }
  224806. }
  224807. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224808. {
  224809. close();
  224810. NamedPipeInternal* const intern = new NamedPipeInternal();
  224811. internal = intern;
  224812. intern->createdPipe = createPipe;
  224813. intern->blocked = false;
  224814. intern->stopReadOperation = false;
  224815. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224816. siginterrupt (SIGPIPE, 1);
  224817. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224818. intern->pipeInName = pipePath + "_in";
  224819. intern->pipeOutName = pipePath + "_out";
  224820. intern->pipeIn = -1;
  224821. intern->pipeOut = -1;
  224822. if (createPipe)
  224823. {
  224824. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224825. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224826. {
  224827. delete intern;
  224828. internal = 0;
  224829. return false;
  224830. }
  224831. }
  224832. return true;
  224833. }
  224834. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224835. {
  224836. int bytesRead = -1;
  224837. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224838. if (intern != 0)
  224839. {
  224840. intern->blocked = true;
  224841. if (intern->pipeIn == -1)
  224842. {
  224843. if (intern->createdPipe)
  224844. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224845. else
  224846. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224847. if (intern->pipeIn == -1)
  224848. {
  224849. intern->blocked = false;
  224850. return -1;
  224851. }
  224852. }
  224853. bytesRead = 0;
  224854. char* p = static_cast<char*> (destBuffer);
  224855. while (bytesRead < maxBytesToRead)
  224856. {
  224857. const int bytesThisTime = maxBytesToRead - bytesRead;
  224858. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  224859. if (numRead <= 0 || intern->stopReadOperation)
  224860. {
  224861. bytesRead = -1;
  224862. break;
  224863. }
  224864. bytesRead += numRead;
  224865. p += bytesRead;
  224866. }
  224867. intern->blocked = false;
  224868. }
  224869. return bytesRead;
  224870. }
  224871. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  224872. {
  224873. int bytesWritten = -1;
  224874. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224875. if (intern != 0)
  224876. {
  224877. if (intern->pipeOut == -1)
  224878. {
  224879. if (intern->createdPipe)
  224880. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  224881. else
  224882. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  224883. if (intern->pipeOut == -1)
  224884. {
  224885. return -1;
  224886. }
  224887. }
  224888. const char* p = static_cast<const char*> (sourceBuffer);
  224889. bytesWritten = 0;
  224890. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  224891. while (bytesWritten < numBytesToWrite
  224892. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  224893. {
  224894. const int bytesThisTime = numBytesToWrite - bytesWritten;
  224895. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  224896. if (numWritten <= 0)
  224897. {
  224898. bytesWritten = -1;
  224899. break;
  224900. }
  224901. bytesWritten += numWritten;
  224902. p += bytesWritten;
  224903. }
  224904. }
  224905. return bytesWritten;
  224906. }
  224907. #endif
  224908. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224909. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224910. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224911. // compiled on its own).
  224912. #if JUCE_INCLUDED_FILE
  224913. /*
  224914. Note that a lot of methods that you'd expect to find in this file actually
  224915. live in juce_posix_SharedCode.h!
  224916. */
  224917. bool Process::isForegroundProcess()
  224918. {
  224919. #if JUCE_MAC
  224920. return [NSApp isActive];
  224921. #else
  224922. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224923. #endif
  224924. }
  224925. void Process::raisePrivilege()
  224926. {
  224927. jassertfalse;
  224928. }
  224929. void Process::lowerPrivilege()
  224930. {
  224931. jassertfalse;
  224932. }
  224933. void Process::terminate()
  224934. {
  224935. exit (0);
  224936. }
  224937. void Process::setPriority (ProcessPriority)
  224938. {
  224939. // xxx
  224940. }
  224941. #endif
  224942. /*** End of inlined file: juce_mac_Threads.mm ***/
  224943. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224944. /*
  224945. This file contains posix routines that are common to both the Linux and Mac builds.
  224946. It gets included directly in the cpp files for these platforms.
  224947. */
  224948. CriticalSection::CriticalSection() throw()
  224949. {
  224950. pthread_mutexattr_t atts;
  224951. pthread_mutexattr_init (&atts);
  224952. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224953. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224954. pthread_mutex_init (&internal, &atts);
  224955. }
  224956. CriticalSection::~CriticalSection() throw()
  224957. {
  224958. pthread_mutex_destroy (&internal);
  224959. }
  224960. void CriticalSection::enter() const throw()
  224961. {
  224962. pthread_mutex_lock (&internal);
  224963. }
  224964. bool CriticalSection::tryEnter() const throw()
  224965. {
  224966. return pthread_mutex_trylock (&internal) == 0;
  224967. }
  224968. void CriticalSection::exit() const throw()
  224969. {
  224970. pthread_mutex_unlock (&internal);
  224971. }
  224972. class WaitableEventImpl
  224973. {
  224974. public:
  224975. WaitableEventImpl (const bool manualReset_)
  224976. : triggered (false),
  224977. manualReset (manualReset_)
  224978. {
  224979. pthread_cond_init (&condition, 0);
  224980. pthread_mutexattr_t atts;
  224981. pthread_mutexattr_init (&atts);
  224982. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224983. pthread_mutex_init (&mutex, &atts);
  224984. }
  224985. ~WaitableEventImpl()
  224986. {
  224987. pthread_cond_destroy (&condition);
  224988. pthread_mutex_destroy (&mutex);
  224989. }
  224990. bool wait (const int timeOutMillisecs) throw()
  224991. {
  224992. pthread_mutex_lock (&mutex);
  224993. if (! triggered)
  224994. {
  224995. if (timeOutMillisecs < 0)
  224996. {
  224997. do
  224998. {
  224999. pthread_cond_wait (&condition, &mutex);
  225000. }
  225001. while (! triggered);
  225002. }
  225003. else
  225004. {
  225005. struct timeval now;
  225006. gettimeofday (&now, 0);
  225007. struct timespec time;
  225008. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  225009. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  225010. if (time.tv_nsec >= 1000000000)
  225011. {
  225012. time.tv_nsec -= 1000000000;
  225013. time.tv_sec++;
  225014. }
  225015. do
  225016. {
  225017. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  225018. {
  225019. pthread_mutex_unlock (&mutex);
  225020. return false;
  225021. }
  225022. }
  225023. while (! triggered);
  225024. }
  225025. }
  225026. if (! manualReset)
  225027. triggered = false;
  225028. pthread_mutex_unlock (&mutex);
  225029. return true;
  225030. }
  225031. void signal() throw()
  225032. {
  225033. pthread_mutex_lock (&mutex);
  225034. triggered = true;
  225035. pthread_cond_broadcast (&condition);
  225036. pthread_mutex_unlock (&mutex);
  225037. }
  225038. void reset() throw()
  225039. {
  225040. pthread_mutex_lock (&mutex);
  225041. triggered = false;
  225042. pthread_mutex_unlock (&mutex);
  225043. }
  225044. private:
  225045. pthread_cond_t condition;
  225046. pthread_mutex_t mutex;
  225047. bool triggered;
  225048. const bool manualReset;
  225049. WaitableEventImpl (const WaitableEventImpl&);
  225050. WaitableEventImpl& operator= (const WaitableEventImpl&);
  225051. };
  225052. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  225053. : internal (new WaitableEventImpl (manualReset))
  225054. {
  225055. }
  225056. WaitableEvent::~WaitableEvent() throw()
  225057. {
  225058. delete static_cast <WaitableEventImpl*> (internal);
  225059. }
  225060. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  225061. {
  225062. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  225063. }
  225064. void WaitableEvent::signal() const throw()
  225065. {
  225066. static_cast <WaitableEventImpl*> (internal)->signal();
  225067. }
  225068. void WaitableEvent::reset() const throw()
  225069. {
  225070. static_cast <WaitableEventImpl*> (internal)->reset();
  225071. }
  225072. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  225073. {
  225074. struct timespec time;
  225075. time.tv_sec = millisecs / 1000;
  225076. time.tv_nsec = (millisecs % 1000) * 1000000;
  225077. nanosleep (&time, 0);
  225078. }
  225079. const juce_wchar File::separator = '/';
  225080. const String File::separatorString ("/");
  225081. const File File::getCurrentWorkingDirectory()
  225082. {
  225083. HeapBlock<char> heapBuffer;
  225084. char localBuffer [1024];
  225085. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  225086. int bufferSize = 4096;
  225087. while (cwd == 0 && errno == ERANGE)
  225088. {
  225089. heapBuffer.malloc (bufferSize);
  225090. cwd = getcwd (heapBuffer, bufferSize - 1);
  225091. bufferSize += 1024;
  225092. }
  225093. return File (String::fromUTF8 (cwd));
  225094. }
  225095. bool File::setAsCurrentWorkingDirectory() const
  225096. {
  225097. return chdir (getFullPathName().toUTF8()) == 0;
  225098. }
  225099. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225100. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  225101. #else
  225102. typedef struct stat juce_statStruct;
  225103. #endif
  225104. static bool juce_stat (const String& fileName, juce_statStruct& info)
  225105. {
  225106. return fileName.isNotEmpty()
  225107. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225108. && (stat64 (fileName.toUTF8(), &info) == 0);
  225109. #else
  225110. && (stat (fileName.toUTF8(), &info) == 0);
  225111. #endif
  225112. }
  225113. bool File::isDirectory() const
  225114. {
  225115. juce_statStruct info;
  225116. return fullPath.isEmpty()
  225117. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  225118. }
  225119. bool File::exists() const
  225120. {
  225121. juce_statStruct info;
  225122. return fullPath.isNotEmpty()
  225123. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225124. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  225125. #else
  225126. && (lstat (fullPath.toUTF8(), &info) == 0);
  225127. #endif
  225128. }
  225129. bool File::existsAsFile() const
  225130. {
  225131. return exists() && ! isDirectory();
  225132. }
  225133. int64 File::getSize() const
  225134. {
  225135. juce_statStruct info;
  225136. return juce_stat (fullPath, info) ? info.st_size : 0;
  225137. }
  225138. bool File::hasWriteAccess() const
  225139. {
  225140. if (exists())
  225141. return access (fullPath.toUTF8(), W_OK) == 0;
  225142. if ((! isDirectory()) && fullPath.containsChar (separator))
  225143. return getParentDirectory().hasWriteAccess();
  225144. return false;
  225145. }
  225146. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  225147. {
  225148. juce_statStruct info;
  225149. if (! juce_stat (fullPath, info))
  225150. return false;
  225151. info.st_mode &= 0777; // Just permissions
  225152. if (shouldBeReadOnly)
  225153. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  225154. else
  225155. // Give everybody write permission?
  225156. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  225157. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  225158. }
  225159. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  225160. {
  225161. modificationTime = 0;
  225162. accessTime = 0;
  225163. creationTime = 0;
  225164. juce_statStruct info;
  225165. if (juce_stat (fullPath, info))
  225166. {
  225167. modificationTime = (int64) info.st_mtime * 1000;
  225168. accessTime = (int64) info.st_atime * 1000;
  225169. creationTime = (int64) info.st_ctime * 1000;
  225170. }
  225171. }
  225172. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  225173. {
  225174. struct utimbuf times;
  225175. times.actime = (time_t) (accessTime / 1000);
  225176. times.modtime = (time_t) (modificationTime / 1000);
  225177. return utime (fullPath.toUTF8(), &times) == 0;
  225178. }
  225179. bool File::deleteFile() const
  225180. {
  225181. if (! exists())
  225182. return true;
  225183. else if (isDirectory())
  225184. return rmdir (fullPath.toUTF8()) == 0;
  225185. else
  225186. return remove (fullPath.toUTF8()) == 0;
  225187. }
  225188. bool File::moveInternal (const File& dest) const
  225189. {
  225190. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  225191. return true;
  225192. if (hasWriteAccess() && copyInternal (dest))
  225193. {
  225194. if (deleteFile())
  225195. return true;
  225196. dest.deleteFile();
  225197. }
  225198. return false;
  225199. }
  225200. void File::createDirectoryInternal (const String& fileName) const
  225201. {
  225202. mkdir (fileName.toUTF8(), 0777);
  225203. }
  225204. int64 juce_fileSetPosition (void* handle, int64 pos)
  225205. {
  225206. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  225207. return pos;
  225208. return -1;
  225209. }
  225210. void FileInputStream::openHandle()
  225211. {
  225212. totalSize = file.getSize();
  225213. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  225214. if (f != -1)
  225215. fileHandle = (void*) f;
  225216. }
  225217. void FileInputStream::closeHandle()
  225218. {
  225219. if (fileHandle != 0)
  225220. {
  225221. close ((int) (pointer_sized_int) fileHandle);
  225222. fileHandle = 0;
  225223. }
  225224. }
  225225. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  225226. {
  225227. if (fileHandle != 0)
  225228. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  225229. return 0;
  225230. }
  225231. void FileOutputStream::openHandle()
  225232. {
  225233. if (file.exists())
  225234. {
  225235. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  225236. if (f != -1)
  225237. {
  225238. currentPosition = lseek (f, 0, SEEK_END);
  225239. if (currentPosition >= 0)
  225240. fileHandle = (void*) f;
  225241. else
  225242. close (f);
  225243. }
  225244. }
  225245. else
  225246. {
  225247. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  225248. if (f != -1)
  225249. fileHandle = (void*) f;
  225250. }
  225251. }
  225252. void FileOutputStream::closeHandle()
  225253. {
  225254. if (fileHandle != 0)
  225255. {
  225256. close ((int) (pointer_sized_int) fileHandle);
  225257. fileHandle = 0;
  225258. }
  225259. }
  225260. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  225261. {
  225262. if (fileHandle != 0)
  225263. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  225264. return 0;
  225265. }
  225266. void FileOutputStream::flushInternal()
  225267. {
  225268. if (fileHandle != 0)
  225269. fsync ((int) (pointer_sized_int) fileHandle);
  225270. }
  225271. const File juce_getExecutableFile()
  225272. {
  225273. Dl_info exeInfo;
  225274. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  225275. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  225276. }
  225277. // if this file doesn't exist, find a parent of it that does..
  225278. static bool juce_doStatFS (File f, struct statfs& result)
  225279. {
  225280. for (int i = 5; --i >= 0;)
  225281. {
  225282. if (f.exists())
  225283. break;
  225284. f = f.getParentDirectory();
  225285. }
  225286. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  225287. }
  225288. int64 File::getBytesFreeOnVolume() const
  225289. {
  225290. struct statfs buf;
  225291. if (juce_doStatFS (*this, buf))
  225292. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  225293. return 0;
  225294. }
  225295. int64 File::getVolumeTotalSize() const
  225296. {
  225297. struct statfs buf;
  225298. if (juce_doStatFS (*this, buf))
  225299. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  225300. return 0;
  225301. }
  225302. const String File::getVolumeLabel() const
  225303. {
  225304. #if JUCE_MAC
  225305. struct VolAttrBuf
  225306. {
  225307. u_int32_t length;
  225308. attrreference_t mountPointRef;
  225309. char mountPointSpace [MAXPATHLEN];
  225310. } attrBuf;
  225311. struct attrlist attrList;
  225312. zerostruct (attrList);
  225313. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  225314. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  225315. File f (*this);
  225316. for (;;)
  225317. {
  225318. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  225319. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  225320. (int) attrBuf.mountPointRef.attr_length);
  225321. const File parent (f.getParentDirectory());
  225322. if (f == parent)
  225323. break;
  225324. f = parent;
  225325. }
  225326. #endif
  225327. return String::empty;
  225328. }
  225329. int File::getVolumeSerialNumber() const
  225330. {
  225331. return 0; // xxx
  225332. }
  225333. void juce_runSystemCommand (const String& command)
  225334. {
  225335. int result = system (command.toUTF8());
  225336. (void) result;
  225337. }
  225338. const String juce_getOutputFromCommand (const String& command)
  225339. {
  225340. // slight bodge here, as we just pipe the output into a temp file and read it...
  225341. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  225342. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  225343. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  225344. String result (tempFile.loadFileAsString());
  225345. tempFile.deleteFile();
  225346. return result;
  225347. }
  225348. class InterProcessLock::Pimpl
  225349. {
  225350. public:
  225351. Pimpl (const String& name, const int timeOutMillisecs)
  225352. : handle (0), refCount (1)
  225353. {
  225354. #if JUCE_MAC
  225355. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  225356. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  225357. #else
  225358. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  225359. #endif
  225360. temp.create();
  225361. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  225362. if (handle != 0)
  225363. {
  225364. struct flock fl;
  225365. zerostruct (fl);
  225366. fl.l_whence = SEEK_SET;
  225367. fl.l_type = F_WRLCK;
  225368. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  225369. for (;;)
  225370. {
  225371. const int result = fcntl (handle, F_SETLK, &fl);
  225372. if (result >= 0)
  225373. return;
  225374. if (errno != EINTR)
  225375. {
  225376. if (timeOutMillisecs == 0
  225377. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  225378. break;
  225379. Thread::sleep (10);
  225380. }
  225381. }
  225382. }
  225383. closeFile();
  225384. }
  225385. ~Pimpl()
  225386. {
  225387. closeFile();
  225388. }
  225389. void closeFile()
  225390. {
  225391. if (handle != 0)
  225392. {
  225393. struct flock fl;
  225394. zerostruct (fl);
  225395. fl.l_whence = SEEK_SET;
  225396. fl.l_type = F_UNLCK;
  225397. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225398. {}
  225399. close (handle);
  225400. handle = 0;
  225401. }
  225402. }
  225403. int handle, refCount;
  225404. };
  225405. InterProcessLock::InterProcessLock (const String& name_)
  225406. : name (name_)
  225407. {
  225408. }
  225409. InterProcessLock::~InterProcessLock()
  225410. {
  225411. }
  225412. bool InterProcessLock::enter (const int timeOutMillisecs)
  225413. {
  225414. const ScopedLock sl (lock);
  225415. if (pimpl == 0)
  225416. {
  225417. pimpl = new Pimpl (name, timeOutMillisecs);
  225418. if (pimpl->handle == 0)
  225419. pimpl = 0;
  225420. }
  225421. else
  225422. {
  225423. pimpl->refCount++;
  225424. }
  225425. return pimpl != 0;
  225426. }
  225427. void InterProcessLock::exit()
  225428. {
  225429. const ScopedLock sl (lock);
  225430. // Trying to release the lock too many times!
  225431. jassert (pimpl != 0);
  225432. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225433. pimpl = 0;
  225434. }
  225435. void JUCE_API juce_threadEntryPoint (void*);
  225436. void* threadEntryProc (void* userData)
  225437. {
  225438. JUCE_AUTORELEASEPOOL
  225439. juce_threadEntryPoint (userData);
  225440. return 0;
  225441. }
  225442. void* juce_createThread (void* userData)
  225443. {
  225444. pthread_t handle = 0;
  225445. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  225446. {
  225447. pthread_detach (handle);
  225448. return (void*) handle;
  225449. }
  225450. return 0;
  225451. }
  225452. void juce_killThread (void* handle)
  225453. {
  225454. if (handle != 0)
  225455. pthread_cancel ((pthread_t) handle);
  225456. }
  225457. void juce_setCurrentThreadName (const String& /*name*/)
  225458. {
  225459. }
  225460. bool juce_setThreadPriority (void* handle, int priority)
  225461. {
  225462. struct sched_param param;
  225463. int policy;
  225464. priority = jlimit (0, 10, priority);
  225465. if (handle == 0)
  225466. handle = (void*) pthread_self();
  225467. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225468. return false;
  225469. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225470. const int minPriority = sched_get_priority_min (policy);
  225471. const int maxPriority = sched_get_priority_max (policy);
  225472. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225473. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225474. }
  225475. Thread::ThreadID Thread::getCurrentThreadId()
  225476. {
  225477. return (ThreadID) pthread_self();
  225478. }
  225479. void Thread::yield()
  225480. {
  225481. sched_yield();
  225482. }
  225483. /* Remove this macro if you're having problems compiling the cpu affinity
  225484. calls (the API for these has changed about quite a bit in various Linux
  225485. versions, and a lot of distros seem to ship with obsolete versions)
  225486. */
  225487. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225488. #define SUPPORT_AFFINITIES 1
  225489. #endif
  225490. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225491. {
  225492. #if SUPPORT_AFFINITIES
  225493. cpu_set_t affinity;
  225494. CPU_ZERO (&affinity);
  225495. for (int i = 0; i < 32; ++i)
  225496. if ((affinityMask & (1 << i)) != 0)
  225497. CPU_SET (i, &affinity);
  225498. /*
  225499. N.B. If this line causes a compile error, then you've probably not got the latest
  225500. version of glibc installed.
  225501. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225502. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225503. */
  225504. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225505. sched_yield();
  225506. #else
  225507. /* affinities aren't supported because either the appropriate header files weren't found,
  225508. or the SUPPORT_AFFINITIES macro was turned off
  225509. */
  225510. jassertfalse;
  225511. #endif
  225512. }
  225513. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225514. /*** Start of inlined file: juce_mac_Files.mm ***/
  225515. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225516. // compiled on its own).
  225517. #if JUCE_INCLUDED_FILE
  225518. /*
  225519. Note that a lot of methods that you'd expect to find in this file actually
  225520. live in juce_posix_SharedCode.h!
  225521. */
  225522. bool File::copyInternal (const File& dest) const
  225523. {
  225524. const ScopedAutoReleasePool pool;
  225525. NSFileManager* fm = [NSFileManager defaultManager];
  225526. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225527. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225528. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225529. toPath: juceStringToNS (dest.getFullPathName())
  225530. error: nil];
  225531. #else
  225532. && [fm copyPath: juceStringToNS (fullPath)
  225533. toPath: juceStringToNS (dest.getFullPathName())
  225534. handler: nil];
  225535. #endif
  225536. }
  225537. void File::findFileSystemRoots (Array<File>& destArray)
  225538. {
  225539. destArray.add (File ("/"));
  225540. }
  225541. static bool isFileOnDriveType (const File& f, const char* const* types)
  225542. {
  225543. struct statfs buf;
  225544. if (juce_doStatFS (f, buf))
  225545. {
  225546. const String type (buf.f_fstypename);
  225547. while (*types != 0)
  225548. if (type.equalsIgnoreCase (*types++))
  225549. return true;
  225550. }
  225551. return false;
  225552. }
  225553. bool File::isOnCDRomDrive() const
  225554. {
  225555. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225556. return isFileOnDriveType (*this, cdTypes);
  225557. }
  225558. bool File::isOnHardDisk() const
  225559. {
  225560. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225561. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  225562. }
  225563. bool File::isOnRemovableDrive() const
  225564. {
  225565. #if JUCE_IOS
  225566. return false; // xxx is this possible?
  225567. #else
  225568. const ScopedAutoReleasePool pool;
  225569. BOOL removable = false;
  225570. [[NSWorkspace sharedWorkspace]
  225571. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225572. isRemovable: &removable
  225573. isWritable: nil
  225574. isUnmountable: nil
  225575. description: nil
  225576. type: nil];
  225577. return removable;
  225578. #endif
  225579. }
  225580. static bool juce_isHiddenFile (const String& path)
  225581. {
  225582. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225583. const ScopedAutoReleasePool pool;
  225584. NSNumber* hidden = nil;
  225585. NSError* err = nil;
  225586. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225587. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225588. && [hidden boolValue];
  225589. #else
  225590. #if JUCE_IOS
  225591. return File (path).getFileName().startsWithChar ('.');
  225592. #else
  225593. FSRef ref;
  225594. LSItemInfoRecord info;
  225595. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225596. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225597. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225598. #endif
  225599. #endif
  225600. }
  225601. bool File::isHidden() const
  225602. {
  225603. return juce_isHiddenFile (getFullPathName());
  225604. }
  225605. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225606. const File File::getSpecialLocation (const SpecialLocationType type)
  225607. {
  225608. const ScopedAutoReleasePool pool;
  225609. String resultPath;
  225610. switch (type)
  225611. {
  225612. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  225613. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  225614. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  225615. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  225616. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  225617. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  225618. case userMusicDirectory: resultPath = "~/Music"; break;
  225619. case userMoviesDirectory: resultPath = "~/Movies"; break;
  225620. case tempDirectory:
  225621. {
  225622. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225623. tmp.createDirectory();
  225624. return tmp.getFullPathName();
  225625. }
  225626. case invokedExecutableFile:
  225627. if (juce_Argv0 != 0)
  225628. return File (String::fromUTF8 (juce_Argv0));
  225629. // deliberate fall-through...
  225630. case currentExecutableFile:
  225631. return juce_getExecutableFile();
  225632. case currentApplicationFile:
  225633. {
  225634. const File exe (juce_getExecutableFile());
  225635. const File parent (exe.getParentDirectory());
  225636. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225637. ? parent.getParentDirectory().getParentDirectory()
  225638. : exe;
  225639. }
  225640. case hostApplicationPath:
  225641. {
  225642. unsigned int size = 8192;
  225643. HeapBlock<char> buffer;
  225644. buffer.calloc (size + 8);
  225645. _NSGetExecutablePath (buffer.getData(), &size);
  225646. return String::fromUTF8 (buffer, size);
  225647. }
  225648. default:
  225649. jassertfalse; // unknown type?
  225650. break;
  225651. }
  225652. if (resultPath.isNotEmpty())
  225653. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225654. return File::nonexistent;
  225655. }
  225656. const String File::getVersion() const
  225657. {
  225658. const ScopedAutoReleasePool pool;
  225659. String result;
  225660. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225661. if (bundle != 0)
  225662. {
  225663. NSDictionary* info = [bundle infoDictionary];
  225664. if (info != 0)
  225665. {
  225666. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225667. if (name != nil)
  225668. result = nsStringToJuce (name);
  225669. }
  225670. }
  225671. return result;
  225672. }
  225673. const File File::getLinkedTarget() const
  225674. {
  225675. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225676. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225677. #else
  225678. // (the cast here avoids a deprecation warning)
  225679. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225680. #endif
  225681. if (dest != nil)
  225682. return File (nsStringToJuce (dest));
  225683. return *this;
  225684. }
  225685. bool File::moveToTrash() const
  225686. {
  225687. if (! exists())
  225688. return true;
  225689. #if JUCE_IOS
  225690. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225691. #else
  225692. const ScopedAutoReleasePool pool;
  225693. NSString* p = juceStringToNS (getFullPathName());
  225694. return [[NSWorkspace sharedWorkspace]
  225695. performFileOperation: NSWorkspaceRecycleOperation
  225696. source: [p stringByDeletingLastPathComponent]
  225697. destination: @""
  225698. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225699. tag: nil ];
  225700. #endif
  225701. }
  225702. class DirectoryIterator::NativeIterator::Pimpl
  225703. {
  225704. public:
  225705. Pimpl (const File& directory, const String& wildCard_)
  225706. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225707. wildCard (wildCard_),
  225708. enumerator (0)
  225709. {
  225710. const ScopedAutoReleasePool pool;
  225711. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225712. wildcardUTF8 = wildCard.toUTF8();
  225713. }
  225714. ~Pimpl()
  225715. {
  225716. [enumerator release];
  225717. }
  225718. bool next (String& filenameFound,
  225719. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225720. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225721. {
  225722. const ScopedAutoReleasePool pool;
  225723. for (;;)
  225724. {
  225725. NSString* file;
  225726. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225727. return false;
  225728. [enumerator skipDescendents];
  225729. filenameFound = nsStringToJuce (file);
  225730. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225731. continue;
  225732. const String path (parentDir + filenameFound);
  225733. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  225734. {
  225735. juce_statStruct info;
  225736. const bool statOk = juce_stat (path, info);
  225737. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  225738. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  225739. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  225740. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  225741. }
  225742. if (isHidden != 0)
  225743. *isHidden = juce_isHiddenFile (path);
  225744. if (isReadOnly != 0)
  225745. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  225746. return true;
  225747. }
  225748. }
  225749. private:
  225750. String parentDir, wildCard;
  225751. const char* wildcardUTF8;
  225752. NSDirectoryEnumerator* enumerator;
  225753. Pimpl (const Pimpl&);
  225754. Pimpl& operator= (const Pimpl&);
  225755. };
  225756. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225757. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225758. {
  225759. }
  225760. DirectoryIterator::NativeIterator::~NativeIterator()
  225761. {
  225762. }
  225763. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225764. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225765. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225766. {
  225767. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225768. }
  225769. bool juce_launchExecutable (const String& pathAndArguments)
  225770. {
  225771. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  225772. const int cpid = fork();
  225773. if (cpid == 0)
  225774. {
  225775. // Child process
  225776. if (execve (argv[0], (char**) argv, 0) < 0)
  225777. exit (0);
  225778. }
  225779. else
  225780. {
  225781. if (cpid < 0)
  225782. return false;
  225783. }
  225784. return true;
  225785. }
  225786. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225787. {
  225788. #if JUCE_IOS
  225789. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225790. #else
  225791. const ScopedAutoReleasePool pool;
  225792. if (parameters.isEmpty())
  225793. {
  225794. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225795. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225796. }
  225797. bool ok = false;
  225798. if (PlatformUtilities::isBundle (fileName))
  225799. {
  225800. NSMutableArray* urls = [NSMutableArray array];
  225801. StringArray docs;
  225802. docs.addTokens (parameters, true);
  225803. for (int i = 0; i < docs.size(); ++i)
  225804. [urls addObject: juceStringToNS (docs[i])];
  225805. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225806. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225807. options: 0
  225808. additionalEventParamDescriptor: nil
  225809. launchIdentifiers: nil];
  225810. }
  225811. else if (File (fileName).exists())
  225812. {
  225813. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  225814. }
  225815. return ok;
  225816. #endif
  225817. }
  225818. void File::revealToUser() const
  225819. {
  225820. #if ! JUCE_IOS
  225821. if (exists())
  225822. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225823. else if (getParentDirectory().exists())
  225824. getParentDirectory().revealToUser();
  225825. #endif
  225826. }
  225827. #if ! JUCE_IOS
  225828. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225829. {
  225830. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  225831. }
  225832. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225833. {
  225834. char path [2048];
  225835. zerostruct (path);
  225836. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225837. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225838. return String::empty;
  225839. }
  225840. #endif
  225841. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225842. {
  225843. const ScopedAutoReleasePool pool;
  225844. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225845. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225846. #else
  225847. // (the cast here avoids a deprecation warning)
  225848. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225849. #endif
  225850. return [fileDict fileHFSTypeCode];
  225851. }
  225852. bool PlatformUtilities::isBundle (const String& filename)
  225853. {
  225854. #if JUCE_IOS
  225855. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225856. #else
  225857. const ScopedAutoReleasePool pool;
  225858. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225859. #endif
  225860. }
  225861. #endif
  225862. /*** End of inlined file: juce_mac_Files.mm ***/
  225863. #if JUCE_IOS
  225864. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  225865. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225866. // compiled on its own).
  225867. #if JUCE_INCLUDED_FILE
  225868. END_JUCE_NAMESPACE
  225869. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225870. {
  225871. }
  225872. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225873. - (void) applicationWillTerminate: (UIApplication*) application;
  225874. @end
  225875. @implementation JuceAppStartupDelegate
  225876. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225877. {
  225878. initialiseJuce_GUI();
  225879. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225880. exit (0);
  225881. }
  225882. - (void) applicationWillTerminate: (UIApplication*) application
  225883. {
  225884. JUCEApplication::appWillTerminateByForce();
  225885. }
  225886. @end
  225887. BEGIN_JUCE_NAMESPACE
  225888. int juce_iOSMain (int argc, const char* argv[])
  225889. {
  225890. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225891. }
  225892. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225893. {
  225894. pool = [[NSAutoreleasePool alloc] init];
  225895. }
  225896. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225897. {
  225898. [((NSAutoreleasePool*) pool) release];
  225899. }
  225900. void PlatformUtilities::beep()
  225901. {
  225902. //xxx
  225903. //AudioServicesPlaySystemSound ();
  225904. }
  225905. void PlatformUtilities::addItemToDock (const File& file)
  225906. {
  225907. }
  225908. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225909. END_JUCE_NAMESPACE
  225910. @interface JuceAlertBoxDelegate : NSObject
  225911. {
  225912. @public
  225913. bool clickedOk;
  225914. }
  225915. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225916. @end
  225917. @implementation JuceAlertBoxDelegate
  225918. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225919. {
  225920. clickedOk = (buttonIndex == 0);
  225921. alertView.hidden = true;
  225922. }
  225923. @end
  225924. BEGIN_JUCE_NAMESPACE
  225925. // (This function is used directly by other bits of code)
  225926. bool juce_iPhoneShowModalAlert (const String& title,
  225927. const String& bodyText,
  225928. NSString* okButtonText,
  225929. NSString* cancelButtonText)
  225930. {
  225931. const ScopedAutoReleasePool pool;
  225932. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225933. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225934. message: juceStringToNS (bodyText)
  225935. delegate: callback
  225936. cancelButtonTitle: okButtonText
  225937. otherButtonTitles: cancelButtonText, nil];
  225938. [alert retain];
  225939. [alert show];
  225940. while (! alert.hidden && alert.superview != nil)
  225941. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225942. const bool result = callback->clickedOk;
  225943. [alert release];
  225944. [callback release];
  225945. return result;
  225946. }
  225947. bool AlertWindow::showNativeDialogBox (const String& title,
  225948. const String& bodyText,
  225949. bool isOkCancel)
  225950. {
  225951. return juce_iPhoneShowModalAlert (title, bodyText,
  225952. @"OK",
  225953. isOkCancel ? @"Cancel" : nil);
  225954. }
  225955. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225956. {
  225957. jassertfalse; // no such thing on the iphone!
  225958. return false;
  225959. }
  225960. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225961. {
  225962. jassertfalse; // no such thing on the iphone!
  225963. return false;
  225964. }
  225965. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225966. {
  225967. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225968. }
  225969. bool Desktop::isScreenSaverEnabled()
  225970. {
  225971. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225972. }
  225973. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  225974. {
  225975. const ScopedAutoReleasePool pool;
  225976. monitorCoords.clear();
  225977. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  225978. : [[UIScreen mainScreen] bounds];
  225979. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  225980. (int) r.origin.y,
  225981. (int) r.size.width,
  225982. (int) r.size.height));
  225983. }
  225984. #endif
  225985. #endif
  225986. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  225987. #else
  225988. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225989. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225990. // compiled on its own).
  225991. #if JUCE_INCLUDED_FILE
  225992. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225993. {
  225994. pool = [[NSAutoreleasePool alloc] init];
  225995. }
  225996. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225997. {
  225998. [((NSAutoreleasePool*) pool) release];
  225999. }
  226000. void PlatformUtilities::beep()
  226001. {
  226002. NSBeep();
  226003. }
  226004. void PlatformUtilities::addItemToDock (const File& file)
  226005. {
  226006. // check that it's not already there...
  226007. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  226008. .containsIgnoreCase (file.getFullPathName()))
  226009. {
  226010. 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>"
  226011. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  226012. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  226013. }
  226014. }
  226015. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226016. bool AlertWindow::showNativeDialogBox (const String& title,
  226017. const String& bodyText,
  226018. bool isOkCancel)
  226019. {
  226020. const ScopedAutoReleasePool pool;
  226021. return NSRunAlertPanel (juceStringToNS (title),
  226022. juceStringToNS (bodyText),
  226023. @"Ok",
  226024. isOkCancel ? @"Cancel" : nil,
  226025. nil) == NSAlertDefaultReturn;
  226026. }
  226027. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  226028. {
  226029. if (files.size() == 0)
  226030. return false;
  226031. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  226032. if (draggingSource == 0)
  226033. {
  226034. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226035. return false;
  226036. }
  226037. Component* sourceComp = draggingSource->getComponentUnderMouse();
  226038. if (sourceComp == 0)
  226039. {
  226040. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226041. return false;
  226042. }
  226043. const ScopedAutoReleasePool pool;
  226044. NSView* view = (NSView*) sourceComp->getWindowHandle();
  226045. if (view == 0)
  226046. return false;
  226047. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  226048. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  226049. owner: nil];
  226050. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  226051. for (int i = 0; i < files.size(); ++i)
  226052. [filesArray addObject: juceStringToNS (files[i])];
  226053. [pboard setPropertyList: filesArray
  226054. forType: NSFilenamesPboardType];
  226055. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  226056. fromView: nil];
  226057. dragPosition.x -= 16;
  226058. dragPosition.y -= 16;
  226059. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  226060. at: dragPosition
  226061. offset: NSMakeSize (0, 0)
  226062. event: [[view window] currentEvent]
  226063. pasteboard: pboard
  226064. source: view
  226065. slideBack: YES];
  226066. return true;
  226067. }
  226068. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  226069. {
  226070. jassertfalse; // not implemented!
  226071. return false;
  226072. }
  226073. bool Desktop::canUseSemiTransparentWindows() throw()
  226074. {
  226075. return true;
  226076. }
  226077. const Point<int> Desktop::getMousePosition()
  226078. {
  226079. const ScopedAutoReleasePool pool;
  226080. const NSPoint p ([NSEvent mouseLocation]);
  226081. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  226082. }
  226083. void Desktop::setMousePosition (const Point<int>& newPosition)
  226084. {
  226085. // this rubbish needs to be done around the warp call, to avoid causing a
  226086. // bizarre glitch..
  226087. CGAssociateMouseAndMouseCursorPosition (false);
  226088. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  226089. CGAssociateMouseAndMouseCursorPosition (true);
  226090. }
  226091. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226092. class ScreenSaverDefeater : public Timer,
  226093. public DeletedAtShutdown
  226094. {
  226095. public:
  226096. ScreenSaverDefeater()
  226097. {
  226098. startTimer (10000);
  226099. timerCallback();
  226100. }
  226101. ~ScreenSaverDefeater() {}
  226102. void timerCallback()
  226103. {
  226104. if (Process::isForegroundProcess())
  226105. UpdateSystemActivity (UsrActivity);
  226106. }
  226107. };
  226108. static ScreenSaverDefeater* screenSaverDefeater = 0;
  226109. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226110. {
  226111. if (isEnabled)
  226112. deleteAndZero (screenSaverDefeater);
  226113. else if (screenSaverDefeater == 0)
  226114. screenSaverDefeater = new ScreenSaverDefeater();
  226115. }
  226116. bool Desktop::isScreenSaverEnabled()
  226117. {
  226118. return screenSaverDefeater == 0;
  226119. }
  226120. #else
  226121. static IOPMAssertionID screenSaverDisablerID = 0;
  226122. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226123. {
  226124. if (isEnabled)
  226125. {
  226126. if (screenSaverDisablerID != 0)
  226127. {
  226128. IOPMAssertionRelease (screenSaverDisablerID);
  226129. screenSaverDisablerID = 0;
  226130. }
  226131. }
  226132. else
  226133. {
  226134. if (screenSaverDisablerID == 0)
  226135. {
  226136. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226137. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226138. CFSTR ("Juce"), &screenSaverDisablerID);
  226139. #else
  226140. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226141. &screenSaverDisablerID);
  226142. #endif
  226143. }
  226144. }
  226145. }
  226146. bool Desktop::isScreenSaverEnabled()
  226147. {
  226148. return screenSaverDisablerID == 0;
  226149. }
  226150. #endif
  226151. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  226152. {
  226153. const ScopedAutoReleasePool pool;
  226154. monitorCoords.clear();
  226155. NSArray* screens = [NSScreen screens];
  226156. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  226157. for (unsigned int i = 0; i < [screens count]; ++i)
  226158. {
  226159. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  226160. NSRect r = clipToWorkArea ? [s visibleFrame]
  226161. : [s frame];
  226162. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  226163. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  226164. (int) r.size.width,
  226165. (int) r.size.height));
  226166. }
  226167. jassert (monitorCoords.size() > 0);
  226168. }
  226169. #endif
  226170. #endif
  226171. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  226172. #endif
  226173. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  226174. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226175. // compiled on its own).
  226176. #if JUCE_INCLUDED_FILE
  226177. void Logger::outputDebugString (const String& text)
  226178. {
  226179. std::cerr << text << std::endl;
  226180. }
  226181. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  226182. {
  226183. static char testResult = 0;
  226184. if (testResult == 0)
  226185. {
  226186. struct kinfo_proc info;
  226187. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  226188. size_t sz = sizeof (info);
  226189. sysctl (m, 4, &info, &sz, 0, 0);
  226190. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  226191. }
  226192. return testResult > 0;
  226193. }
  226194. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  226195. {
  226196. return juce_isRunningUnderDebugger();
  226197. }
  226198. #endif
  226199. /*** End of inlined file: juce_mac_Debugging.mm ***/
  226200. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226201. #if JUCE_IOS
  226202. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  226203. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226204. // compiled on its own).
  226205. #if JUCE_INCLUDED_FILE
  226206. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226207. #define SUPPORT_10_4_FONTS 1
  226208. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  226209. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226210. #define SUPPORT_ONLY_10_4_FONTS 1
  226211. #endif
  226212. END_JUCE_NAMESPACE
  226213. @interface NSFont (PrivateHack)
  226214. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  226215. @end
  226216. BEGIN_JUCE_NAMESPACE
  226217. #endif
  226218. class MacTypeface : public Typeface
  226219. {
  226220. public:
  226221. MacTypeface (const Font& font)
  226222. : Typeface (font.getTypefaceName())
  226223. {
  226224. const ScopedAutoReleasePool pool;
  226225. renderingTransform = CGAffineTransformIdentity;
  226226. bool needsItalicTransform = false;
  226227. #if JUCE_IOS
  226228. NSString* fontName = juceStringToNS (font.getTypefaceName());
  226229. if (font.isItalic() || font.isBold())
  226230. {
  226231. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  226232. for (NSString* i in familyFonts)
  226233. {
  226234. const String fn (nsStringToJuce (i));
  226235. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  226236. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  226237. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  226238. || afterDash.containsIgnoreCase ("italic")
  226239. || fn.endsWithIgnoreCase ("oblique")
  226240. || fn.endsWithIgnoreCase ("italic");
  226241. if (probablyBold == font.isBold()
  226242. && probablyItalic == font.isItalic())
  226243. {
  226244. fontName = i;
  226245. needsItalicTransform = false;
  226246. break;
  226247. }
  226248. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  226249. {
  226250. fontName = i;
  226251. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  226252. }
  226253. }
  226254. if (needsItalicTransform)
  226255. renderingTransform.c = 0.15f;
  226256. }
  226257. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  226258. const int ascender = abs (CGFontGetAscent (fontRef));
  226259. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  226260. ascent = ascender / totalHeight;
  226261. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226262. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  226263. #else
  226264. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  226265. if (font.isItalic())
  226266. {
  226267. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  226268. toHaveTrait: NSItalicFontMask];
  226269. if (newFont == nsFont)
  226270. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226271. nsFont = newFont;
  226272. }
  226273. if (font.isBold())
  226274. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  226275. [nsFont retain];
  226276. ascent = std::abs ((float) [nsFont ascender]);
  226277. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  226278. ascent /= totalSize;
  226279. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  226280. if (needsItalicTransform)
  226281. {
  226282. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  226283. renderingTransform.c = 0.15f;
  226284. }
  226285. #if SUPPORT_ONLY_10_4_FONTS
  226286. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226287. if (atsFont == 0)
  226288. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226289. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226290. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226291. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226292. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226293. #else
  226294. #if SUPPORT_10_4_FONTS
  226295. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226296. {
  226297. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226298. if (atsFont == 0)
  226299. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226300. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226301. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226302. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226303. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226304. }
  226305. else
  226306. #endif
  226307. {
  226308. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226309. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226310. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226311. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226312. }
  226313. #endif
  226314. #endif
  226315. }
  226316. ~MacTypeface()
  226317. {
  226318. #if ! JUCE_IOS
  226319. [nsFont release];
  226320. #endif
  226321. if (fontRef != 0)
  226322. CGFontRelease (fontRef);
  226323. }
  226324. float getAscent() const
  226325. {
  226326. return ascent;
  226327. }
  226328. float getDescent() const
  226329. {
  226330. return 1.0f - ascent;
  226331. }
  226332. float getStringWidth (const String& text)
  226333. {
  226334. if (fontRef == 0 || text.isEmpty())
  226335. return 0;
  226336. const int length = text.length();
  226337. HeapBlock <CGGlyph> glyphs;
  226338. createGlyphsForString (text, length, glyphs);
  226339. float x = 0;
  226340. #if SUPPORT_ONLY_10_4_FONTS
  226341. HeapBlock <NSSize> advances (length);
  226342. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226343. for (int i = 0; i < length; ++i)
  226344. x += advances[i].width;
  226345. #else
  226346. #if SUPPORT_10_4_FONTS
  226347. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226348. {
  226349. HeapBlock <NSSize> advances (length);
  226350. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226351. for (int i = 0; i < length; ++i)
  226352. x += advances[i].width;
  226353. }
  226354. else
  226355. #endif
  226356. {
  226357. HeapBlock <int> advances (length);
  226358. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226359. for (int i = 0; i < length; ++i)
  226360. x += advances[i];
  226361. }
  226362. #endif
  226363. return x * unitsToHeightScaleFactor;
  226364. }
  226365. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226366. {
  226367. xOffsets.add (0);
  226368. if (fontRef == 0 || text.isEmpty())
  226369. return;
  226370. const int length = text.length();
  226371. HeapBlock <CGGlyph> glyphs;
  226372. createGlyphsForString (text, length, glyphs);
  226373. #if SUPPORT_ONLY_10_4_FONTS
  226374. HeapBlock <NSSize> advances (length);
  226375. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226376. int x = 0;
  226377. for (int i = 0; i < length; ++i)
  226378. {
  226379. x += advances[i].width;
  226380. xOffsets.add (x * unitsToHeightScaleFactor);
  226381. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226382. }
  226383. #else
  226384. #if SUPPORT_10_4_FONTS
  226385. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226386. {
  226387. HeapBlock <NSSize> advances (length);
  226388. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226389. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226390. float x = 0;
  226391. for (int i = 0; i < length; ++i)
  226392. {
  226393. x += advances[i].width;
  226394. xOffsets.add (x * unitsToHeightScaleFactor);
  226395. resultGlyphs.add (nsGlyphs[i]);
  226396. }
  226397. }
  226398. else
  226399. #endif
  226400. {
  226401. HeapBlock <int> advances (length);
  226402. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226403. {
  226404. int x = 0;
  226405. for (int i = 0; i < length; ++i)
  226406. {
  226407. x += advances [i];
  226408. xOffsets.add (x * unitsToHeightScaleFactor);
  226409. resultGlyphs.add (glyphs[i]);
  226410. }
  226411. }
  226412. }
  226413. #endif
  226414. }
  226415. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226416. {
  226417. #if JUCE_IOS
  226418. return false;
  226419. #else
  226420. if (nsFont == 0)
  226421. return false;
  226422. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226423. jassert (path.isEmpty());
  226424. const ScopedAutoReleasePool pool;
  226425. NSBezierPath* bez = [NSBezierPath bezierPath];
  226426. [bez moveToPoint: NSMakePoint (0, 0)];
  226427. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226428. inFont: nsFont];
  226429. for (int i = 0; i < [bez elementCount]; ++i)
  226430. {
  226431. NSPoint p[3];
  226432. switch ([bez elementAtIndex: i associatedPoints: p])
  226433. {
  226434. case NSMoveToBezierPathElement:
  226435. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226436. break;
  226437. case NSLineToBezierPathElement:
  226438. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226439. break;
  226440. case NSCurveToBezierPathElement:
  226441. 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);
  226442. break;
  226443. case NSClosePathBezierPathElement:
  226444. path.closeSubPath();
  226445. break;
  226446. default:
  226447. jassertfalse;
  226448. break;
  226449. }
  226450. }
  226451. path.applyTransform (pathTransform);
  226452. return true;
  226453. #endif
  226454. }
  226455. juce_UseDebuggingNewOperator
  226456. CGFontRef fontRef;
  226457. float fontHeightToCGSizeFactor;
  226458. CGAffineTransform renderingTransform;
  226459. private:
  226460. float ascent, unitsToHeightScaleFactor;
  226461. #if JUCE_IOS
  226462. #else
  226463. NSFont* nsFont;
  226464. AffineTransform pathTransform;
  226465. #endif
  226466. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226467. {
  226468. #if SUPPORT_10_4_FONTS
  226469. #if ! SUPPORT_ONLY_10_4_FONTS
  226470. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226471. #endif
  226472. {
  226473. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226474. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226475. for (int i = 0; i < length; ++i)
  226476. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226477. return;
  226478. }
  226479. #endif
  226480. #if ! SUPPORT_ONLY_10_4_FONTS
  226481. if (charToGlyphMapper == 0)
  226482. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226483. glyphs.malloc (length);
  226484. for (int i = 0; i < length; ++i)
  226485. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226486. #endif
  226487. }
  226488. #if ! SUPPORT_ONLY_10_4_FONTS
  226489. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226490. class CharToGlyphMapper
  226491. {
  226492. public:
  226493. CharToGlyphMapper (CGFontRef fontRef)
  226494. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226495. idRangeOffset (0), glyphIndexes (0)
  226496. {
  226497. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226498. if (cmapTable != 0)
  226499. {
  226500. const int numSubtables = getValue16 (cmapTable, 2);
  226501. for (int i = 0; i < numSubtables; ++i)
  226502. {
  226503. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226504. {
  226505. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226506. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226507. {
  226508. const int length = getValue16 (cmapTable, offset + 2);
  226509. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226510. segCount = segCountX2 / 2;
  226511. const int endCodeOffset = offset + 14;
  226512. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226513. const int idDeltaOffset = startCodeOffset + segCountX2;
  226514. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226515. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226516. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226517. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226518. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226519. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226520. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226521. }
  226522. break;
  226523. }
  226524. }
  226525. CFRelease (cmapTable);
  226526. }
  226527. }
  226528. ~CharToGlyphMapper()
  226529. {
  226530. if (endCode != 0)
  226531. {
  226532. CFRelease (endCode);
  226533. CFRelease (startCode);
  226534. CFRelease (idDelta);
  226535. CFRelease (idRangeOffset);
  226536. CFRelease (glyphIndexes);
  226537. }
  226538. }
  226539. int getGlyphForCharacter (const juce_wchar c) const
  226540. {
  226541. for (int i = 0; i < segCount; ++i)
  226542. {
  226543. if (getValue16 (endCode, i * 2) >= c)
  226544. {
  226545. const int start = getValue16 (startCode, i * 2);
  226546. if (start > c)
  226547. break;
  226548. const int delta = getValue16 (idDelta, i * 2);
  226549. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226550. if (rangeOffset == 0)
  226551. return delta + c;
  226552. else
  226553. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226554. }
  226555. }
  226556. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226557. return jmax (-1, (int) c - 29);
  226558. }
  226559. private:
  226560. int segCount;
  226561. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226562. static uint16 getValue16 (CFDataRef data, const int index)
  226563. {
  226564. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226565. }
  226566. static uint32 getValue32 (CFDataRef data, const int index)
  226567. {
  226568. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226569. }
  226570. };
  226571. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226572. #endif
  226573. MacTypeface (const MacTypeface&);
  226574. MacTypeface& operator= (const MacTypeface&);
  226575. };
  226576. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226577. {
  226578. return new MacTypeface (font);
  226579. }
  226580. const StringArray Font::findAllTypefaceNames()
  226581. {
  226582. StringArray names;
  226583. const ScopedAutoReleasePool pool;
  226584. #if JUCE_IOS
  226585. NSArray* fonts = [UIFont familyNames];
  226586. #else
  226587. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226588. #endif
  226589. for (unsigned int i = 0; i < [fonts count]; ++i)
  226590. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226591. names.sort (true);
  226592. return names;
  226593. }
  226594. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  226595. {
  226596. #if JUCE_IOS
  226597. defaultSans = "Helvetica";
  226598. defaultSerif = "Times New Roman";
  226599. defaultFixed = "Courier New";
  226600. #else
  226601. defaultSans = "Lucida Grande";
  226602. defaultSerif = "Times New Roman";
  226603. defaultFixed = "Monaco";
  226604. #endif
  226605. }
  226606. #endif
  226607. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226608. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226609. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226610. // compiled on its own).
  226611. #if JUCE_INCLUDED_FILE
  226612. class CoreGraphicsImage : public Image::SharedImage
  226613. {
  226614. public:
  226615. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226616. : Image::SharedImage (format_, width_, height_)
  226617. {
  226618. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226619. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226620. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  226621. imageData = imageDataAllocated;
  226622. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226623. : CGColorSpaceCreateDeviceRGB();
  226624. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226625. colourSpace, getCGImageFlags (format_));
  226626. CGColorSpaceRelease (colourSpace);
  226627. }
  226628. ~CoreGraphicsImage()
  226629. {
  226630. CGContextRelease (context);
  226631. }
  226632. Image::ImageType getType() const { return Image::NativeImage; }
  226633. LowLevelGraphicsContext* createLowLevelContext();
  226634. SharedImage* clone()
  226635. {
  226636. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226637. memcpy (im->imageData, imageData, lineStride * height);
  226638. return im;
  226639. }
  226640. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226641. {
  226642. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226643. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226644. {
  226645. return CGBitmapContextCreateImage (nativeImage->context);
  226646. }
  226647. else
  226648. {
  226649. const Image::BitmapData srcData (juceImage, false);
  226650. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226651. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226652. 8, srcData.pixelStride * 8, srcData.lineStride,
  226653. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226654. 0, true, kCGRenderingIntentDefault);
  226655. CGDataProviderRelease (provider);
  226656. return imageRef;
  226657. }
  226658. }
  226659. #if JUCE_MAC
  226660. static NSImage* createNSImage (const Image& image)
  226661. {
  226662. const ScopedAutoReleasePool pool;
  226663. NSImage* im = [[NSImage alloc] init];
  226664. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226665. [im lockFocus];
  226666. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226667. CGImageRef imageRef = createImage (image, false, colourSpace);
  226668. CGColorSpaceRelease (colourSpace);
  226669. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226670. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226671. CGImageRelease (imageRef);
  226672. [im unlockFocus];
  226673. return im;
  226674. }
  226675. #endif
  226676. CGContextRef context;
  226677. HeapBlock<uint8> imageDataAllocated;
  226678. private:
  226679. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226680. {
  226681. #if JUCE_BIG_ENDIAN
  226682. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226683. #else
  226684. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226685. #endif
  226686. }
  226687. };
  226688. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226689. {
  226690. #if USE_COREGRAPHICS_RENDERING
  226691. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226692. #else
  226693. return createSoftwareImage (format, width, height, clearImage);
  226694. #endif
  226695. }
  226696. class CoreGraphicsContext : public LowLevelGraphicsContext
  226697. {
  226698. public:
  226699. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226700. : context (context_),
  226701. flipHeight (flipHeight_),
  226702. state (new SavedState()),
  226703. numGradientLookupEntries (0),
  226704. lastClipRectIsValid (false)
  226705. {
  226706. CGContextRetain (context);
  226707. CGContextSaveGState(context);
  226708. CGContextSetShouldSmoothFonts (context, true);
  226709. CGContextSetShouldAntialias (context, true);
  226710. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226711. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226712. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226713. gradientCallbacks.version = 0;
  226714. gradientCallbacks.evaluate = gradientCallback;
  226715. gradientCallbacks.releaseInfo = 0;
  226716. setFont (Font());
  226717. }
  226718. ~CoreGraphicsContext()
  226719. {
  226720. CGContextRestoreGState (context);
  226721. CGContextRelease (context);
  226722. CGColorSpaceRelease (rgbColourSpace);
  226723. CGColorSpaceRelease (greyColourSpace);
  226724. }
  226725. bool isVectorDevice() const { return false; }
  226726. void setOrigin (int x, int y)
  226727. {
  226728. CGContextTranslateCTM (context, x, -y);
  226729. if (lastClipRectIsValid)
  226730. lastClipRect.translate (-x, -y);
  226731. }
  226732. bool clipToRectangle (const Rectangle<int>& r)
  226733. {
  226734. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226735. if (lastClipRectIsValid)
  226736. {
  226737. // This is actually incorrect, because the actual clip region may be complex, and
  226738. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226739. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226740. // when calculating the resultant clip bounds, and makes the same mistake!
  226741. lastClipRect = lastClipRect.getIntersection (r);
  226742. return ! lastClipRect.isEmpty();
  226743. }
  226744. return ! isClipEmpty();
  226745. }
  226746. bool clipToRectangleList (const RectangleList& clipRegion)
  226747. {
  226748. if (clipRegion.isEmpty())
  226749. {
  226750. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226751. lastClipRectIsValid = true;
  226752. lastClipRect = Rectangle<int>();
  226753. return false;
  226754. }
  226755. else
  226756. {
  226757. const int numRects = clipRegion.getNumRectangles();
  226758. HeapBlock <CGRect> rects (numRects);
  226759. for (int i = 0; i < numRects; ++i)
  226760. {
  226761. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226762. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226763. }
  226764. CGContextClipToRects (context, rects, numRects);
  226765. lastClipRectIsValid = false;
  226766. return ! isClipEmpty();
  226767. }
  226768. }
  226769. void excludeClipRectangle (const Rectangle<int>& r)
  226770. {
  226771. RectangleList remaining (getClipBounds());
  226772. remaining.subtract (r);
  226773. clipToRectangleList (remaining);
  226774. lastClipRectIsValid = false;
  226775. }
  226776. void clipToPath (const Path& path, const AffineTransform& transform)
  226777. {
  226778. createPath (path, transform);
  226779. CGContextClip (context);
  226780. lastClipRectIsValid = false;
  226781. }
  226782. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226783. {
  226784. if (! transform.isSingularity())
  226785. {
  226786. Image singleChannelImage (sourceImage);
  226787. if (sourceImage.getFormat() != Image::SingleChannel)
  226788. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226789. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  226790. flip();
  226791. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226792. applyTransform (t);
  226793. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226794. CGContextClipToMask (context, r, image);
  226795. applyTransform (t.inverted());
  226796. flip();
  226797. CGImageRelease (image);
  226798. lastClipRectIsValid = false;
  226799. }
  226800. }
  226801. bool clipRegionIntersects (const Rectangle<int>& r)
  226802. {
  226803. return getClipBounds().intersects (r);
  226804. }
  226805. const Rectangle<int> getClipBounds() const
  226806. {
  226807. if (! lastClipRectIsValid)
  226808. {
  226809. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226810. lastClipRectIsValid = true;
  226811. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226812. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226813. roundToInt (bounds.size.width),
  226814. roundToInt (bounds.size.height));
  226815. }
  226816. return lastClipRect;
  226817. }
  226818. bool isClipEmpty() const
  226819. {
  226820. return getClipBounds().isEmpty();
  226821. }
  226822. void saveState()
  226823. {
  226824. CGContextSaveGState (context);
  226825. stateStack.add (new SavedState (*state));
  226826. }
  226827. void restoreState()
  226828. {
  226829. CGContextRestoreGState (context);
  226830. SavedState* const top = stateStack.getLast();
  226831. if (top != 0)
  226832. {
  226833. state = top;
  226834. stateStack.removeLast (1, false);
  226835. lastClipRectIsValid = false;
  226836. }
  226837. else
  226838. {
  226839. jassertfalse; // trying to pop with an empty stack!
  226840. }
  226841. }
  226842. void setFill (const FillType& fillType)
  226843. {
  226844. state->fillType = fillType;
  226845. if (fillType.isColour())
  226846. {
  226847. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226848. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226849. CGContextSetAlpha (context, 1.0f);
  226850. }
  226851. }
  226852. void setOpacity (float newOpacity)
  226853. {
  226854. state->fillType.setOpacity (newOpacity);
  226855. setFill (state->fillType);
  226856. }
  226857. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226858. {
  226859. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226860. ? kCGInterpolationLow
  226861. : kCGInterpolationHigh);
  226862. }
  226863. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226864. {
  226865. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226866. }
  226867. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226868. {
  226869. if (replaceExistingContents)
  226870. {
  226871. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226872. CGContextClearRect (context, cgRect);
  226873. #else
  226874. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226875. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226876. CGContextClearRect (context, cgRect);
  226877. else
  226878. #endif
  226879. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226880. #endif
  226881. fillCGRect (cgRect, false);
  226882. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226883. }
  226884. else
  226885. {
  226886. if (state->fillType.isColour())
  226887. {
  226888. CGContextFillRect (context, cgRect);
  226889. }
  226890. else if (state->fillType.isGradient())
  226891. {
  226892. CGContextSaveGState (context);
  226893. CGContextClipToRect (context, cgRect);
  226894. drawGradient();
  226895. CGContextRestoreGState (context);
  226896. }
  226897. else
  226898. {
  226899. CGContextSaveGState (context);
  226900. CGContextClipToRect (context, cgRect);
  226901. drawImage (state->fillType.image, state->fillType.transform, true);
  226902. CGContextRestoreGState (context);
  226903. }
  226904. }
  226905. }
  226906. void fillPath (const Path& path, const AffineTransform& transform)
  226907. {
  226908. CGContextSaveGState (context);
  226909. if (state->fillType.isColour())
  226910. {
  226911. flip();
  226912. applyTransform (transform);
  226913. createPath (path);
  226914. if (path.isUsingNonZeroWinding())
  226915. CGContextFillPath (context);
  226916. else
  226917. CGContextEOFillPath (context);
  226918. }
  226919. else
  226920. {
  226921. createPath (path, transform);
  226922. if (path.isUsingNonZeroWinding())
  226923. CGContextClip (context);
  226924. else
  226925. CGContextEOClip (context);
  226926. if (state->fillType.isGradient())
  226927. drawGradient();
  226928. else
  226929. drawImage (state->fillType.image, state->fillType.transform, true);
  226930. }
  226931. CGContextRestoreGState (context);
  226932. }
  226933. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226934. {
  226935. const int iw = sourceImage.getWidth();
  226936. const int ih = sourceImage.getHeight();
  226937. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  226938. CGContextSaveGState (context);
  226939. CGContextSetAlpha (context, state->fillType.getOpacity());
  226940. flip();
  226941. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226942. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226943. if (fillEntireClipAsTiles)
  226944. {
  226945. #if JUCE_IOS
  226946. CGContextDrawTiledImage (context, imageRect, image);
  226947. #else
  226948. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226949. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226950. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226951. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226952. CGContextDrawTiledImage (context, imageRect, image);
  226953. else
  226954. #endif
  226955. {
  226956. // Fallback to manually doing a tiled fill on 10.4
  226957. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226958. int x = 0, y = 0;
  226959. while (x > clip.origin.x) x -= iw;
  226960. while (y > clip.origin.y) y -= ih;
  226961. const int right = (int) (clip.origin.x + clip.size.width);
  226962. const int bottom = (int) (clip.origin.y + clip.size.height);
  226963. while (y < bottom)
  226964. {
  226965. for (int x2 = x; x2 < right; x2 += iw)
  226966. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226967. y += ih;
  226968. }
  226969. }
  226970. #endif
  226971. }
  226972. else
  226973. {
  226974. CGContextDrawImage (context, imageRect, image);
  226975. }
  226976. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226977. CGContextRestoreGState (context);
  226978. }
  226979. void drawLine (const Line<float>& line)
  226980. {
  226981. if (state->fillType.isColour())
  226982. {
  226983. CGContextSetLineCap (context, kCGLineCapSquare);
  226984. CGContextSetLineWidth (context, 1.0f);
  226985. CGContextSetRGBStrokeColor (context,
  226986. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226987. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226988. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226989. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226990. CGContextStrokeLineSegments (context, cgLine, 1);
  226991. }
  226992. else
  226993. {
  226994. Path p;
  226995. p.addLineSegment (line, 1.0f);
  226996. fillPath (p, AffineTransform::identity);
  226997. }
  226998. }
  226999. void drawVerticalLine (const int x, float top, float bottom)
  227000. {
  227001. if (state->fillType.isColour())
  227002. {
  227003. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227004. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  227005. #else
  227006. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227007. // the x co-ord slightly to trick it..
  227008. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  227009. #endif
  227010. }
  227011. else
  227012. {
  227013. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  227014. }
  227015. }
  227016. void drawHorizontalLine (const int y, float left, float right)
  227017. {
  227018. if (state->fillType.isColour())
  227019. {
  227020. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227021. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  227022. #else
  227023. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227024. // the x co-ord slightly to trick it..
  227025. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  227026. #endif
  227027. }
  227028. else
  227029. {
  227030. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  227031. }
  227032. }
  227033. void setFont (const Font& newFont)
  227034. {
  227035. if (state->font != newFont)
  227036. {
  227037. state->fontRef = 0;
  227038. state->font = newFont;
  227039. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  227040. if (mf != 0)
  227041. {
  227042. state->fontRef = mf->fontRef;
  227043. CGContextSetFont (context, state->fontRef);
  227044. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  227045. state->fontTransform = mf->renderingTransform;
  227046. state->fontTransform.a *= state->font.getHorizontalScale();
  227047. CGContextSetTextMatrix (context, state->fontTransform);
  227048. }
  227049. }
  227050. }
  227051. const Font getFont()
  227052. {
  227053. return state->font;
  227054. }
  227055. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  227056. {
  227057. if (state->fontRef != 0 && state->fillType.isColour())
  227058. {
  227059. if (transform.isOnlyTranslation())
  227060. {
  227061. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  227062. CGGlyph g = glyphNumber;
  227063. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  227064. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  227065. }
  227066. else
  227067. {
  227068. CGContextSaveGState (context);
  227069. flip();
  227070. applyTransform (transform);
  227071. CGAffineTransform t = state->fontTransform;
  227072. t.d = -t.d;
  227073. CGContextSetTextMatrix (context, t);
  227074. CGGlyph g = glyphNumber;
  227075. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  227076. CGContextRestoreGState (context);
  227077. }
  227078. }
  227079. else
  227080. {
  227081. Path p;
  227082. Font& f = state->font;
  227083. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  227084. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  227085. .followedBy (transform));
  227086. }
  227087. }
  227088. private:
  227089. CGContextRef context;
  227090. const CGFloat flipHeight;
  227091. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  227092. CGFunctionCallbacks gradientCallbacks;
  227093. mutable Rectangle<int> lastClipRect;
  227094. mutable bool lastClipRectIsValid;
  227095. struct SavedState
  227096. {
  227097. SavedState()
  227098. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  227099. {
  227100. }
  227101. SavedState (const SavedState& other)
  227102. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  227103. fontTransform (other.fontTransform)
  227104. {
  227105. }
  227106. ~SavedState()
  227107. {
  227108. }
  227109. FillType fillType;
  227110. Font font;
  227111. CGFontRef fontRef;
  227112. CGAffineTransform fontTransform;
  227113. };
  227114. ScopedPointer <SavedState> state;
  227115. OwnedArray <SavedState> stateStack;
  227116. HeapBlock <PixelARGB> gradientLookupTable;
  227117. int numGradientLookupEntries;
  227118. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  227119. {
  227120. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  227121. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  227122. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  227123. colour.unpremultiply();
  227124. outData[0] = colour.getRed() / 255.0f;
  227125. outData[1] = colour.getGreen() / 255.0f;
  227126. outData[2] = colour.getBlue() / 255.0f;
  227127. outData[3] = colour.getAlpha() / 255.0f;
  227128. }
  227129. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  227130. {
  227131. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  227132. --numGradientLookupEntries;
  227133. CGShadingRef result = 0;
  227134. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  227135. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  227136. if (gradient.isRadial)
  227137. {
  227138. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  227139. p1, gradient.point1.getDistanceFrom (gradient.point2),
  227140. function, true, true);
  227141. }
  227142. else
  227143. {
  227144. result = CGShadingCreateAxial (rgbColourSpace, p1,
  227145. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  227146. function, true, true);
  227147. }
  227148. CGFunctionRelease (function);
  227149. return result;
  227150. }
  227151. void drawGradient()
  227152. {
  227153. flip();
  227154. applyTransform (state->fillType.transform);
  227155. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  227156. // you draw a gradient with high quality interp enabled).
  227157. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  227158. CGContextSetAlpha (context, state->fillType.getOpacity());
  227159. CGContextDrawShading (context, shading);
  227160. CGShadingRelease (shading);
  227161. }
  227162. void createPath (const Path& path) const
  227163. {
  227164. CGContextBeginPath (context);
  227165. Path::Iterator i (path);
  227166. while (i.next())
  227167. {
  227168. switch (i.elementType)
  227169. {
  227170. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  227171. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  227172. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  227173. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  227174. case Path::Iterator::closePath: CGContextClosePath (context); break;
  227175. default: jassertfalse; break;
  227176. }
  227177. }
  227178. }
  227179. void createPath (const Path& path, const AffineTransform& transform) const
  227180. {
  227181. CGContextBeginPath (context);
  227182. Path::Iterator i (path);
  227183. while (i.next())
  227184. {
  227185. switch (i.elementType)
  227186. {
  227187. case Path::Iterator::startNewSubPath:
  227188. transform.transformPoint (i.x1, i.y1);
  227189. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  227190. break;
  227191. case Path::Iterator::lineTo:
  227192. transform.transformPoint (i.x1, i.y1);
  227193. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  227194. break;
  227195. case Path::Iterator::quadraticTo:
  227196. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  227197. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  227198. break;
  227199. case Path::Iterator::cubicTo:
  227200. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  227201. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  227202. break;
  227203. case Path::Iterator::closePath:
  227204. CGContextClosePath (context); break;
  227205. default:
  227206. jassertfalse;
  227207. break;
  227208. }
  227209. }
  227210. }
  227211. void flip() const
  227212. {
  227213. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  227214. }
  227215. void applyTransform (const AffineTransform& transform) const
  227216. {
  227217. CGAffineTransform t;
  227218. t.a = transform.mat00;
  227219. t.b = transform.mat10;
  227220. t.c = transform.mat01;
  227221. t.d = transform.mat11;
  227222. t.tx = transform.mat02;
  227223. t.ty = transform.mat12;
  227224. CGContextConcatCTM (context, t);
  227225. }
  227226. CoreGraphicsContext (const CoreGraphicsContext&);
  227227. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  227228. };
  227229. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  227230. {
  227231. return new CoreGraphicsContext (context, height);
  227232. }
  227233. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  227234. const Image juce_loadWithCoreImage (InputStream& input)
  227235. {
  227236. MemoryBlock data;
  227237. input.readIntoMemoryBlock (data, -1);
  227238. #if JUCE_IOS
  227239. JUCE_AUTORELEASEPOOL
  227240. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  227241. length: data.getSize()
  227242. freeWhenDone: NO]];
  227243. if (image != nil)
  227244. {
  227245. CGImageRef loadedImage = image.CGImage;
  227246. #else
  227247. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  227248. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  227249. CGDataProviderRelease (provider);
  227250. if (imageSource != 0)
  227251. {
  227252. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  227253. CFRelease (imageSource);
  227254. #endif
  227255. if (loadedImage != 0)
  227256. {
  227257. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  227258. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  227259. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  227260. hasAlphaChan, Image::NativeImage);
  227261. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  227262. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  227263. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  227264. CGContextFlush (cgImage->context);
  227265. #if ! JUCE_IOS
  227266. CFRelease (loadedImage);
  227267. #endif
  227268. return image;
  227269. }
  227270. }
  227271. return Image::null;
  227272. }
  227273. #endif
  227274. #endif
  227275. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227276. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227277. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227278. // compiled on its own).
  227279. #if JUCE_INCLUDED_FILE
  227280. class UIViewComponentPeer;
  227281. END_JUCE_NAMESPACE
  227282. #define JuceUIView MakeObjCClassName(JuceUIView)
  227283. @interface JuceUIView : UIView <UITextViewDelegate>
  227284. {
  227285. @public
  227286. UIViewComponentPeer* owner;
  227287. UITextView* hiddenTextView;
  227288. }
  227289. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  227290. - (void) dealloc;
  227291. - (void) drawRect: (CGRect) r;
  227292. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  227293. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  227294. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  227295. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  227296. - (BOOL) becomeFirstResponder;
  227297. - (BOOL) resignFirstResponder;
  227298. - (BOOL) canBecomeFirstResponder;
  227299. - (void) asyncRepaint: (id) rect;
  227300. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  227301. @end
  227302. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  227303. @interface JuceUIWindow : UIWindow
  227304. {
  227305. @private
  227306. UIViewComponentPeer* owner;
  227307. bool isZooming;
  227308. }
  227309. - (void) setOwner: (UIViewComponentPeer*) owner;
  227310. - (void) becomeKeyWindow;
  227311. @end
  227312. BEGIN_JUCE_NAMESPACE
  227313. class UIViewComponentPeer : public ComponentPeer,
  227314. public FocusChangeListener
  227315. {
  227316. public:
  227317. UIViewComponentPeer (Component* const component,
  227318. const int windowStyleFlags,
  227319. UIView* viewToAttachTo);
  227320. ~UIViewComponentPeer();
  227321. void* getNativeHandle() const;
  227322. void setVisible (bool shouldBeVisible);
  227323. void setTitle (const String& title);
  227324. void setPosition (int x, int y);
  227325. void setSize (int w, int h);
  227326. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  227327. const Rectangle<int> getBounds() const;
  227328. const Rectangle<int> getBounds (const bool global) const;
  227329. const Point<int> getScreenPosition() const;
  227330. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  227331. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  227332. void setMinimised (bool shouldBeMinimised);
  227333. bool isMinimised() const;
  227334. void setFullScreen (bool shouldBeFullScreen);
  227335. bool isFullScreen() const;
  227336. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227337. const BorderSize getFrameSize() const;
  227338. bool setAlwaysOnTop (bool alwaysOnTop);
  227339. void toFront (bool makeActiveWindow);
  227340. void toBehind (ComponentPeer* other);
  227341. void setIcon (const Image& newIcon);
  227342. virtual void drawRect (CGRect r);
  227343. virtual bool canBecomeKeyWindow();
  227344. virtual bool windowShouldClose();
  227345. virtual void redirectMovedOrResized();
  227346. virtual CGRect constrainRect (CGRect r);
  227347. virtual void viewFocusGain();
  227348. virtual void viewFocusLoss();
  227349. bool isFocused() const;
  227350. void grabFocus();
  227351. void textInputRequired (const Point<int>& position);
  227352. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227353. void updateHiddenTextContent (TextInputTarget* target);
  227354. void globalFocusChanged (Component*);
  227355. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227356. void repaint (const Rectangle<int>& area);
  227357. void performAnyPendingRepaintsNow();
  227358. juce_UseDebuggingNewOperator
  227359. UIWindow* window;
  227360. JuceUIView* view;
  227361. bool isSharedWindow, fullScreen, insideDrawRect;
  227362. static ModifierKeys currentModifiers;
  227363. static int64 getMouseTime (UIEvent* e)
  227364. {
  227365. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227366. + (int64) ([e timestamp] * 1000.0);
  227367. }
  227368. Array <UITouch*> currentTouches;
  227369. };
  227370. END_JUCE_NAMESPACE
  227371. @implementation JuceUIView
  227372. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227373. withFrame: (CGRect) frame
  227374. {
  227375. [super initWithFrame: frame];
  227376. owner = owner_;
  227377. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227378. [self addSubview: hiddenTextView];
  227379. hiddenTextView.delegate = self;
  227380. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227381. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227382. return self;
  227383. }
  227384. - (void) dealloc
  227385. {
  227386. [hiddenTextView removeFromSuperview];
  227387. [hiddenTextView release];
  227388. [super dealloc];
  227389. }
  227390. - (void) drawRect: (CGRect) r
  227391. {
  227392. if (owner != 0)
  227393. owner->drawRect (r);
  227394. }
  227395. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227396. {
  227397. return false;
  227398. }
  227399. ModifierKeys UIViewComponentPeer::currentModifiers;
  227400. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227401. {
  227402. return UIViewComponentPeer::currentModifiers;
  227403. }
  227404. void ModifierKeys::updateCurrentModifiers() throw()
  227405. {
  227406. currentModifiers = UIViewComponentPeer::currentModifiers;
  227407. }
  227408. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227409. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227410. {
  227411. if (owner != 0)
  227412. owner->handleTouches (event, true, false, false);
  227413. }
  227414. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227415. {
  227416. if (owner != 0)
  227417. owner->handleTouches (event, false, false, false);
  227418. }
  227419. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227420. {
  227421. if (owner != 0)
  227422. owner->handleTouches (event, false, true, false);
  227423. }
  227424. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227425. {
  227426. if (owner != 0)
  227427. owner->handleTouches (event, false, true, true);
  227428. [self touchesEnded: touches withEvent: event];
  227429. }
  227430. - (BOOL) becomeFirstResponder
  227431. {
  227432. if (owner != 0)
  227433. owner->viewFocusGain();
  227434. return true;
  227435. }
  227436. - (BOOL) resignFirstResponder
  227437. {
  227438. if (owner != 0)
  227439. owner->viewFocusLoss();
  227440. return true;
  227441. }
  227442. - (BOOL) canBecomeFirstResponder
  227443. {
  227444. return owner != 0 && owner->canBecomeKeyWindow();
  227445. }
  227446. - (void) asyncRepaint: (id) rect
  227447. {
  227448. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227449. [self setNeedsDisplayInRect: *r];
  227450. }
  227451. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227452. {
  227453. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227454. nsStringToJuce (text));
  227455. }
  227456. @end
  227457. @implementation JuceUIWindow
  227458. - (void) setOwner: (UIViewComponentPeer*) owner_
  227459. {
  227460. owner = owner_;
  227461. isZooming = false;
  227462. }
  227463. - (void) becomeKeyWindow
  227464. {
  227465. [super becomeKeyWindow];
  227466. if (owner != 0)
  227467. owner->grabFocus();
  227468. }
  227469. @end
  227470. BEGIN_JUCE_NAMESPACE
  227471. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227472. const int windowStyleFlags,
  227473. UIView* viewToAttachTo)
  227474. : ComponentPeer (component, windowStyleFlags),
  227475. window (0),
  227476. view (0),
  227477. isSharedWindow (viewToAttachTo != 0),
  227478. fullScreen (false),
  227479. insideDrawRect (false)
  227480. {
  227481. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  227482. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227483. if (isSharedWindow)
  227484. {
  227485. window = [viewToAttachTo window];
  227486. [viewToAttachTo addSubview: view];
  227487. setVisible (component->isVisible());
  227488. }
  227489. else
  227490. {
  227491. r.origin.x = (float) component->getX();
  227492. r.origin.y = (float) component->getY();
  227493. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227494. window = [[JuceUIWindow alloc] init];
  227495. window.frame = r;
  227496. window.opaque = component->isOpaque();
  227497. view.opaque = component->isOpaque();
  227498. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227499. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227500. [((JuceUIWindow*) window) setOwner: this];
  227501. if (component->isAlwaysOnTop())
  227502. window.windowLevel = UIWindowLevelAlert;
  227503. [window addSubview: view];
  227504. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227505. view.hidden = ! component->isVisible();
  227506. window.hidden = ! component->isVisible();
  227507. view.multipleTouchEnabled = YES;
  227508. }
  227509. setTitle (component->getName());
  227510. Desktop::getInstance().addFocusChangeListener (this);
  227511. }
  227512. UIViewComponentPeer::~UIViewComponentPeer()
  227513. {
  227514. Desktop::getInstance().removeFocusChangeListener (this);
  227515. view->owner = 0;
  227516. [view removeFromSuperview];
  227517. [view release];
  227518. if (! isSharedWindow)
  227519. {
  227520. [((JuceUIWindow*) window) setOwner: 0];
  227521. [window release];
  227522. }
  227523. }
  227524. void* UIViewComponentPeer::getNativeHandle() const
  227525. {
  227526. return view;
  227527. }
  227528. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227529. {
  227530. view.hidden = ! shouldBeVisible;
  227531. if (! isSharedWindow)
  227532. window.hidden = ! shouldBeVisible;
  227533. }
  227534. void UIViewComponentPeer::setTitle (const String& title)
  227535. {
  227536. // xxx is this possible?
  227537. }
  227538. void UIViewComponentPeer::setPosition (int x, int y)
  227539. {
  227540. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227541. }
  227542. void UIViewComponentPeer::setSize (int w, int h)
  227543. {
  227544. setBounds (component->getX(), component->getY(), w, h, false);
  227545. }
  227546. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227547. {
  227548. fullScreen = isNowFullScreen;
  227549. w = jmax (0, w);
  227550. h = jmax (0, h);
  227551. CGRect r;
  227552. r.origin.x = (float) x;
  227553. r.origin.y = (float) y;
  227554. r.size.width = (float) w;
  227555. r.size.height = (float) h;
  227556. if (isSharedWindow)
  227557. {
  227558. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  227559. if ([view frame].size.width != r.size.width
  227560. || [view frame].size.height != r.size.height)
  227561. [view setNeedsDisplay];
  227562. view.frame = r;
  227563. }
  227564. else
  227565. {
  227566. window.frame = r;
  227567. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227568. }
  227569. }
  227570. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227571. {
  227572. CGRect r = [view frame];
  227573. if (global && [view window] != 0)
  227574. {
  227575. r = [view convertRect: r toView: nil];
  227576. CGRect wr = [[view window] frame];
  227577. r.origin.x += wr.origin.x;
  227578. r.origin.y += wr.origin.y;
  227579. }
  227580. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  227581. (int) r.size.width, (int) r.size.height);
  227582. }
  227583. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227584. {
  227585. return getBounds (! isSharedWindow);
  227586. }
  227587. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227588. {
  227589. return getBounds (true).getPosition();
  227590. }
  227591. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  227592. {
  227593. return relativePosition + getScreenPosition();
  227594. }
  227595. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  227596. {
  227597. return screenPosition - getScreenPosition();
  227598. }
  227599. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227600. {
  227601. if (constrainer != 0)
  227602. {
  227603. CGRect current = [window frame];
  227604. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227605. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227606. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  227607. (int) r.size.width, (int) r.size.height);
  227608. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  227609. (int) current.size.width, (int) current.size.height);
  227610. constrainer->checkBounds (pos, original,
  227611. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227612. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227613. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227614. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227615. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227616. r.origin.x = pos.getX();
  227617. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227618. r.size.width = pos.getWidth();
  227619. r.size.height = pos.getHeight();
  227620. }
  227621. return r;
  227622. }
  227623. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227624. {
  227625. // xxx
  227626. }
  227627. bool UIViewComponentPeer::isMinimised() const
  227628. {
  227629. return false;
  227630. }
  227631. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227632. {
  227633. if (! isSharedWindow)
  227634. {
  227635. Rectangle<int> r (lastNonFullscreenBounds);
  227636. setMinimised (false);
  227637. if (fullScreen != shouldBeFullScreen)
  227638. {
  227639. if (shouldBeFullScreen)
  227640. r = Desktop::getInstance().getMainMonitorArea();
  227641. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227642. if (r != getComponent()->getBounds() && ! r.isEmpty())
  227643. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227644. }
  227645. }
  227646. }
  227647. bool UIViewComponentPeer::isFullScreen() const
  227648. {
  227649. return fullScreen;
  227650. }
  227651. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227652. {
  227653. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  227654. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  227655. return false;
  227656. CGPoint p;
  227657. p.x = (float) position.getX();
  227658. p.y = (float) position.getY();
  227659. UIView* v = [view hitTest: p withEvent: nil];
  227660. if (trueIfInAChildWindow)
  227661. return v != nil;
  227662. return v == view;
  227663. }
  227664. const BorderSize UIViewComponentPeer::getFrameSize() const
  227665. {
  227666. BorderSize b;
  227667. if (! isSharedWindow)
  227668. {
  227669. CGRect v = [view convertRect: [view frame] toView: nil];
  227670. CGRect w = [window frame];
  227671. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  227672. b.setBottom ((int) v.origin.y);
  227673. b.setLeft ((int) v.origin.x);
  227674. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  227675. }
  227676. return b;
  227677. }
  227678. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227679. {
  227680. if (! isSharedWindow)
  227681. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227682. return true;
  227683. }
  227684. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227685. {
  227686. if (isSharedWindow)
  227687. [[view superview] bringSubviewToFront: view];
  227688. if (window != 0 && component->isVisible())
  227689. [window makeKeyAndVisible];
  227690. }
  227691. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227692. {
  227693. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227694. jassert (otherPeer != 0); // wrong type of window?
  227695. if (otherPeer != 0)
  227696. {
  227697. if (isSharedWindow)
  227698. {
  227699. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227700. }
  227701. else
  227702. {
  227703. jassertfalse; // don't know how to do this
  227704. }
  227705. }
  227706. }
  227707. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227708. {
  227709. // to do..
  227710. }
  227711. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227712. {
  227713. NSArray* touches = [[event touchesForView: view] allObjects];
  227714. for (unsigned int i = 0; i < [touches count]; ++i)
  227715. {
  227716. UITouch* touch = [touches objectAtIndex: i];
  227717. CGPoint p = [touch locationInView: view];
  227718. const Point<int> pos ((int) p.x, (int) p.y);
  227719. juce_lastMousePos = pos + getScreenPosition();
  227720. const int64 time = getMouseTime (event);
  227721. int touchIndex = currentTouches.indexOf (touch);
  227722. if (touchIndex < 0)
  227723. {
  227724. touchIndex = currentTouches.size();
  227725. currentTouches.add (touch);
  227726. }
  227727. if (isDown)
  227728. {
  227729. currentModifiers = currentModifiers.withoutMouseButtons();
  227730. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227731. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227732. }
  227733. else if (isUp)
  227734. {
  227735. currentModifiers = currentModifiers.withoutMouseButtons();
  227736. currentTouches.remove (touchIndex);
  227737. }
  227738. if (isCancel)
  227739. currentTouches.clear();
  227740. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227741. }
  227742. }
  227743. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227744. void UIViewComponentPeer::viewFocusGain()
  227745. {
  227746. if (currentlyFocusedPeer != this)
  227747. {
  227748. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227749. currentlyFocusedPeer->handleFocusLoss();
  227750. currentlyFocusedPeer = this;
  227751. handleFocusGain();
  227752. }
  227753. }
  227754. void UIViewComponentPeer::viewFocusLoss()
  227755. {
  227756. if (currentlyFocusedPeer == this)
  227757. {
  227758. currentlyFocusedPeer = 0;
  227759. handleFocusLoss();
  227760. }
  227761. }
  227762. void juce_HandleProcessFocusChange()
  227763. {
  227764. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227765. {
  227766. if (Process::isForegroundProcess())
  227767. {
  227768. currentlyFocusedPeer->handleFocusGain();
  227769. ComponentPeer::bringModalComponentToFront();
  227770. }
  227771. else
  227772. {
  227773. currentlyFocusedPeer->handleFocusLoss();
  227774. // turn kiosk mode off if we lose focus..
  227775. Desktop::getInstance().setKioskModeComponent (0);
  227776. }
  227777. }
  227778. }
  227779. bool UIViewComponentPeer::isFocused() const
  227780. {
  227781. return isSharedWindow ? this == currentlyFocusedPeer
  227782. : (window != 0 && [window isKeyWindow]);
  227783. }
  227784. void UIViewComponentPeer::grabFocus()
  227785. {
  227786. if (window != 0)
  227787. {
  227788. [window makeKeyWindow];
  227789. viewFocusGain();
  227790. }
  227791. }
  227792. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227793. {
  227794. }
  227795. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227796. {
  227797. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227798. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227799. }
  227800. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227801. {
  227802. TextInputTarget* const target = findCurrentTextInputTarget();
  227803. if (target != 0)
  227804. {
  227805. const Range<int> currentSelection (target->getHighlightedRegion());
  227806. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227807. if (currentSelection.isEmpty())
  227808. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227809. target->insertTextAtCaret (text);
  227810. updateHiddenTextContent (target);
  227811. }
  227812. return NO;
  227813. }
  227814. void UIViewComponentPeer::globalFocusChanged (Component*)
  227815. {
  227816. TextInputTarget* const target = findCurrentTextInputTarget();
  227817. if (target != 0)
  227818. {
  227819. Component* comp = dynamic_cast<Component*> (target);
  227820. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  227821. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227822. updateHiddenTextContent (target);
  227823. [view->hiddenTextView becomeFirstResponder];
  227824. }
  227825. else
  227826. {
  227827. [view->hiddenTextView resignFirstResponder];
  227828. }
  227829. }
  227830. void UIViewComponentPeer::drawRect (CGRect r)
  227831. {
  227832. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227833. return;
  227834. CGContextRef cg = UIGraphicsGetCurrentContext();
  227835. if (! component->isOpaque())
  227836. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227837. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227838. CoreGraphicsContext g (cg, view.bounds.size.height);
  227839. insideDrawRect = true;
  227840. handlePaint (g);
  227841. insideDrawRect = false;
  227842. }
  227843. bool UIViewComponentPeer::canBecomeKeyWindow()
  227844. {
  227845. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227846. }
  227847. bool UIViewComponentPeer::windowShouldClose()
  227848. {
  227849. if (! isValidPeer (this))
  227850. return YES;
  227851. handleUserClosingWindow();
  227852. return NO;
  227853. }
  227854. void UIViewComponentPeer::redirectMovedOrResized()
  227855. {
  227856. handleMovedOrResized();
  227857. }
  227858. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227859. {
  227860. }
  227861. class AsyncRepaintMessage : public CallbackMessage
  227862. {
  227863. public:
  227864. UIViewComponentPeer* const peer;
  227865. const Rectangle<int> rect;
  227866. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227867. : peer (peer_), rect (rect_)
  227868. {
  227869. }
  227870. void messageCallback()
  227871. {
  227872. if (ComponentPeer::isValidPeer (peer))
  227873. peer->repaint (rect);
  227874. }
  227875. };
  227876. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227877. {
  227878. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227879. {
  227880. (new AsyncRepaintMessage (this, area))->post();
  227881. }
  227882. else
  227883. {
  227884. [view setNeedsDisplayInRect: CGRectMake ((float) area.getX(), (float) area.getY(),
  227885. (float) area.getWidth(), (float) area.getHeight())];
  227886. }
  227887. }
  227888. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227889. {
  227890. }
  227891. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227892. {
  227893. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227894. }
  227895. const Image juce_createIconForFile (const File& file)
  227896. {
  227897. return Image::null;
  227898. }
  227899. void Desktop::createMouseInputSources()
  227900. {
  227901. for (int i = 0; i < 10; ++i)
  227902. mouseSources.add (new MouseInputSource (i, false));
  227903. }
  227904. bool Desktop::canUseSemiTransparentWindows() throw()
  227905. {
  227906. return true;
  227907. }
  227908. const Point<int> Desktop::getMousePosition()
  227909. {
  227910. return juce_lastMousePos;
  227911. }
  227912. void Desktop::setMousePosition (const Point<int>&)
  227913. {
  227914. }
  227915. const int KeyPress::spaceKey = ' ';
  227916. const int KeyPress::returnKey = 0x0d;
  227917. const int KeyPress::escapeKey = 0x1b;
  227918. const int KeyPress::backspaceKey = 0x7f;
  227919. const int KeyPress::leftKey = 0x1000;
  227920. const int KeyPress::rightKey = 0x1001;
  227921. const int KeyPress::upKey = 0x1002;
  227922. const int KeyPress::downKey = 0x1003;
  227923. const int KeyPress::pageUpKey = 0x1004;
  227924. const int KeyPress::pageDownKey = 0x1005;
  227925. const int KeyPress::endKey = 0x1006;
  227926. const int KeyPress::homeKey = 0x1007;
  227927. const int KeyPress::deleteKey = 0x1008;
  227928. const int KeyPress::insertKey = -1;
  227929. const int KeyPress::tabKey = 9;
  227930. const int KeyPress::F1Key = 0x2001;
  227931. const int KeyPress::F2Key = 0x2002;
  227932. const int KeyPress::F3Key = 0x2003;
  227933. const int KeyPress::F4Key = 0x2004;
  227934. const int KeyPress::F5Key = 0x2005;
  227935. const int KeyPress::F6Key = 0x2006;
  227936. const int KeyPress::F7Key = 0x2007;
  227937. const int KeyPress::F8Key = 0x2008;
  227938. const int KeyPress::F9Key = 0x2009;
  227939. const int KeyPress::F10Key = 0x200a;
  227940. const int KeyPress::F11Key = 0x200b;
  227941. const int KeyPress::F12Key = 0x200c;
  227942. const int KeyPress::F13Key = 0x200d;
  227943. const int KeyPress::F14Key = 0x200e;
  227944. const int KeyPress::F15Key = 0x200f;
  227945. const int KeyPress::F16Key = 0x2010;
  227946. const int KeyPress::numberPad0 = 0x30020;
  227947. const int KeyPress::numberPad1 = 0x30021;
  227948. const int KeyPress::numberPad2 = 0x30022;
  227949. const int KeyPress::numberPad3 = 0x30023;
  227950. const int KeyPress::numberPad4 = 0x30024;
  227951. const int KeyPress::numberPad5 = 0x30025;
  227952. const int KeyPress::numberPad6 = 0x30026;
  227953. const int KeyPress::numberPad7 = 0x30027;
  227954. const int KeyPress::numberPad8 = 0x30028;
  227955. const int KeyPress::numberPad9 = 0x30029;
  227956. const int KeyPress::numberPadAdd = 0x3002a;
  227957. const int KeyPress::numberPadSubtract = 0x3002b;
  227958. const int KeyPress::numberPadMultiply = 0x3002c;
  227959. const int KeyPress::numberPadDivide = 0x3002d;
  227960. const int KeyPress::numberPadSeparator = 0x3002e;
  227961. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227962. const int KeyPress::numberPadEquals = 0x30030;
  227963. const int KeyPress::numberPadDelete = 0x30031;
  227964. const int KeyPress::playKey = 0x30000;
  227965. const int KeyPress::stopKey = 0x30001;
  227966. const int KeyPress::fastForwardKey = 0x30002;
  227967. const int KeyPress::rewindKey = 0x30003;
  227968. #endif
  227969. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227970. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  227971. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227972. // compiled on its own).
  227973. #if JUCE_INCLUDED_FILE
  227974. struct CallbackMessagePayload
  227975. {
  227976. MessageCallbackFunction* function;
  227977. void* parameter;
  227978. void* volatile result;
  227979. bool volatile hasBeenExecuted;
  227980. };
  227981. END_JUCE_NAMESPACE
  227982. @interface JuceCustomMessageHandler : NSObject
  227983. {
  227984. }
  227985. - (void) performCallback: (id) info;
  227986. @end
  227987. @implementation JuceCustomMessageHandler
  227988. - (void) performCallback: (id) info
  227989. {
  227990. if ([info isKindOfClass: [NSData class]])
  227991. {
  227992. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227993. if (pl != 0)
  227994. {
  227995. pl->result = (*pl->function) (pl->parameter);
  227996. pl->hasBeenExecuted = true;
  227997. }
  227998. }
  227999. else
  228000. {
  228001. jassertfalse; // should never get here!
  228002. }
  228003. }
  228004. @end
  228005. BEGIN_JUCE_NAMESPACE
  228006. void MessageManager::runDispatchLoop()
  228007. {
  228008. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228009. runDispatchLoopUntil (-1);
  228010. }
  228011. void MessageManager::stopDispatchLoop()
  228012. {
  228013. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  228014. exit (0); // iPhone apps get no mercy..
  228015. }
  228016. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  228017. {
  228018. const ScopedAutoReleasePool pool;
  228019. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228020. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  228021. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  228022. while (! quitMessagePosted)
  228023. {
  228024. const ScopedAutoReleasePool pool;
  228025. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  228026. beforeDate: endDate];
  228027. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  228028. break;
  228029. }
  228030. return ! quitMessagePosted;
  228031. }
  228032. static CFRunLoopRef runLoop = 0;
  228033. static CFRunLoopSourceRef runLoopSource = 0;
  228034. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  228035. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  228036. static void runLoopSourceCallback (void*)
  228037. {
  228038. if (pendingMessages != 0)
  228039. {
  228040. int numDispatched = 0;
  228041. do
  228042. {
  228043. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  228044. if (nextMessage == 0)
  228045. return;
  228046. const ScopedAutoReleasePool pool;
  228047. MessageManager::getInstance()->deliverMessage (nextMessage);
  228048. } while (++numDispatched <= 4);
  228049. CFRunLoopSourceSignal (runLoopSource);
  228050. CFRunLoopWakeUp (runLoop);
  228051. }
  228052. }
  228053. void MessageManager::doPlatformSpecificInitialisation()
  228054. {
  228055. pendingMessages = new OwnedArray <Message, CriticalSection>();
  228056. runLoop = CFRunLoopGetCurrent();
  228057. CFRunLoopSourceContext sourceContext;
  228058. zerostruct (sourceContext);
  228059. sourceContext.perform = runLoopSourceCallback;
  228060. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  228061. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  228062. if (juceCustomMessageHandler == 0)
  228063. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  228064. }
  228065. void MessageManager::doPlatformSpecificShutdown()
  228066. {
  228067. CFRunLoopSourceInvalidate (runLoopSource);
  228068. CFRelease (runLoopSource);
  228069. runLoopSource = 0;
  228070. deleteAndZero (pendingMessages);
  228071. if (juceCustomMessageHandler != 0)
  228072. {
  228073. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  228074. [juceCustomMessageHandler release];
  228075. juceCustomMessageHandler = 0;
  228076. }
  228077. }
  228078. bool juce_postMessageToSystemQueue (Message* message)
  228079. {
  228080. if (pendingMessages != 0)
  228081. {
  228082. pendingMessages->add (message);
  228083. CFRunLoopSourceSignal (runLoopSource);
  228084. CFRunLoopWakeUp (runLoop);
  228085. }
  228086. return true;
  228087. }
  228088. void MessageManager::broadcastMessage (const String& value)
  228089. {
  228090. }
  228091. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  228092. {
  228093. if (isThisTheMessageThread())
  228094. {
  228095. return (*callback) (data);
  228096. }
  228097. else
  228098. {
  228099. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  228100. // deadlock because the message manager is blocked from running, so can never
  228101. // call your function..
  228102. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  228103. const ScopedAutoReleasePool pool;
  228104. CallbackMessagePayload cmp;
  228105. cmp.function = callback;
  228106. cmp.parameter = data;
  228107. cmp.result = 0;
  228108. cmp.hasBeenExecuted = false;
  228109. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  228110. withObject: [NSData dataWithBytesNoCopy: &cmp
  228111. length: sizeof (cmp)
  228112. freeWhenDone: NO]
  228113. waitUntilDone: YES];
  228114. return cmp.result;
  228115. }
  228116. }
  228117. #endif
  228118. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  228119. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  228120. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228121. // compiled on its own).
  228122. #if JUCE_INCLUDED_FILE
  228123. #if JUCE_MAC
  228124. END_JUCE_NAMESPACE
  228125. using namespace JUCE_NAMESPACE;
  228126. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  228127. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  228128. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  228129. #else
  228130. @interface JuceFileChooserDelegate : NSObject
  228131. #endif
  228132. {
  228133. StringArray* filters;
  228134. }
  228135. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  228136. - (void) dealloc;
  228137. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  228138. @end
  228139. @implementation JuceFileChooserDelegate
  228140. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  228141. {
  228142. [super init];
  228143. filters = filters_;
  228144. return self;
  228145. }
  228146. - (void) dealloc
  228147. {
  228148. delete filters;
  228149. [super dealloc];
  228150. }
  228151. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  228152. {
  228153. (void) sender;
  228154. const File f (nsStringToJuce (filename));
  228155. for (int i = filters->size(); --i >= 0;)
  228156. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  228157. return true;
  228158. return f.isDirectory();
  228159. }
  228160. @end
  228161. BEGIN_JUCE_NAMESPACE
  228162. void FileChooser::showPlatformDialog (Array<File>& results,
  228163. const String& title,
  228164. const File& currentFileOrDirectory,
  228165. const String& filter,
  228166. bool selectsDirectory,
  228167. bool selectsFiles,
  228168. bool isSaveDialogue,
  228169. bool warnAboutOverwritingExistingFiles,
  228170. bool selectMultipleFiles,
  228171. FilePreviewComponent* extraInfoComponent)
  228172. {
  228173. const ScopedAutoReleasePool pool;
  228174. StringArray* filters = new StringArray();
  228175. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  228176. filters->trim();
  228177. filters->removeEmptyStrings();
  228178. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  228179. [delegate autorelease];
  228180. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  228181. : [NSOpenPanel openPanel];
  228182. [panel setTitle: juceStringToNS (title)];
  228183. if (! isSaveDialogue)
  228184. {
  228185. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228186. [openPanel setCanChooseDirectories: selectsDirectory];
  228187. [openPanel setCanChooseFiles: selectsFiles];
  228188. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  228189. }
  228190. [panel setDelegate: delegate];
  228191. if (isSaveDialogue || selectsDirectory)
  228192. [panel setCanCreateDirectories: YES];
  228193. String directory, filename;
  228194. if (currentFileOrDirectory.isDirectory())
  228195. {
  228196. directory = currentFileOrDirectory.getFullPathName();
  228197. }
  228198. else
  228199. {
  228200. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  228201. filename = currentFileOrDirectory.getFileName();
  228202. }
  228203. if ([panel runModalForDirectory: juceStringToNS (directory)
  228204. file: juceStringToNS (filename)]
  228205. == NSOKButton)
  228206. {
  228207. if (isSaveDialogue)
  228208. {
  228209. results.add (File (nsStringToJuce ([panel filename])));
  228210. }
  228211. else
  228212. {
  228213. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228214. NSArray* urls = [openPanel filenames];
  228215. for (unsigned int i = 0; i < [urls count]; ++i)
  228216. {
  228217. NSString* f = [urls objectAtIndex: i];
  228218. results.add (File (nsStringToJuce (f)));
  228219. }
  228220. }
  228221. }
  228222. [panel setDelegate: nil];
  228223. }
  228224. #else
  228225. void FileChooser::showPlatformDialog (Array<File>& results,
  228226. const String& title,
  228227. const File& currentFileOrDirectory,
  228228. const String& filter,
  228229. bool selectsDirectory,
  228230. bool selectsFiles,
  228231. bool isSaveDialogue,
  228232. bool warnAboutOverwritingExistingFiles,
  228233. bool selectMultipleFiles,
  228234. FilePreviewComponent* extraInfoComponent)
  228235. {
  228236. const ScopedAutoReleasePool pool;
  228237. jassertfalse; //xxx to do
  228238. }
  228239. #endif
  228240. #endif
  228241. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  228242. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228243. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228244. // compiled on its own).
  228245. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228246. #if JUCE_MAC
  228247. END_JUCE_NAMESPACE
  228248. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228249. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228250. {
  228251. CriticalSection* contextLock;
  228252. bool needsUpdate;
  228253. }
  228254. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228255. - (bool) makeActive;
  228256. - (void) makeInactive;
  228257. - (void) reshape;
  228258. @end
  228259. @implementation ThreadSafeNSOpenGLView
  228260. - (id) initWithFrame: (NSRect) frameRect
  228261. pixelFormat: (NSOpenGLPixelFormat*) format
  228262. {
  228263. contextLock = new CriticalSection();
  228264. self = [super initWithFrame: frameRect pixelFormat: format];
  228265. if (self != nil)
  228266. [[NSNotificationCenter defaultCenter] addObserver: self
  228267. selector: @selector (_surfaceNeedsUpdate:)
  228268. name: NSViewGlobalFrameDidChangeNotification
  228269. object: self];
  228270. return self;
  228271. }
  228272. - (void) dealloc
  228273. {
  228274. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228275. delete contextLock;
  228276. [super dealloc];
  228277. }
  228278. - (bool) makeActive
  228279. {
  228280. const ScopedLock sl (*contextLock);
  228281. if ([self openGLContext] == 0)
  228282. return false;
  228283. [[self openGLContext] makeCurrentContext];
  228284. if (needsUpdate)
  228285. {
  228286. [super update];
  228287. needsUpdate = false;
  228288. }
  228289. return true;
  228290. }
  228291. - (void) makeInactive
  228292. {
  228293. const ScopedLock sl (*contextLock);
  228294. [NSOpenGLContext clearCurrentContext];
  228295. }
  228296. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228297. {
  228298. const ScopedLock sl (*contextLock);
  228299. needsUpdate = true;
  228300. }
  228301. - (void) update
  228302. {
  228303. const ScopedLock sl (*contextLock);
  228304. needsUpdate = true;
  228305. }
  228306. - (void) reshape
  228307. {
  228308. const ScopedLock sl (*contextLock);
  228309. needsUpdate = true;
  228310. }
  228311. @end
  228312. BEGIN_JUCE_NAMESPACE
  228313. class WindowedGLContext : public OpenGLContext
  228314. {
  228315. public:
  228316. WindowedGLContext (Component* const component,
  228317. const OpenGLPixelFormat& pixelFormat_,
  228318. NSOpenGLContext* sharedContext)
  228319. : renderContext (0),
  228320. pixelFormat (pixelFormat_)
  228321. {
  228322. jassert (component != 0);
  228323. NSOpenGLPixelFormatAttribute attribs [64];
  228324. int n = 0;
  228325. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228326. attribs[n++] = NSOpenGLPFAAccelerated;
  228327. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228328. attribs[n++] = NSOpenGLPFAColorSize;
  228329. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228330. pixelFormat.greenBits,
  228331. pixelFormat.blueBits);
  228332. attribs[n++] = NSOpenGLPFAAlphaSize;
  228333. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228334. attribs[n++] = NSOpenGLPFADepthSize;
  228335. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228336. attribs[n++] = NSOpenGLPFAStencilSize;
  228337. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228338. attribs[n++] = NSOpenGLPFAAccumSize;
  228339. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228340. pixelFormat.accumulationBufferGreenBits,
  228341. pixelFormat.accumulationBufferBlueBits,
  228342. pixelFormat.accumulationBufferAlphaBits);
  228343. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228344. attribs[n++] = NSOpenGLPFASampleBuffers;
  228345. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228346. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228347. attribs[n++] = NSOpenGLPFANoRecovery;
  228348. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228349. NSOpenGLPixelFormat* format
  228350. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228351. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228352. pixelFormat: format];
  228353. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228354. shareContext: sharedContext] autorelease];
  228355. const GLint swapInterval = 1;
  228356. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228357. [view setOpenGLContext: renderContext];
  228358. [format release];
  228359. viewHolder = new NSViewComponentInternal (view, component);
  228360. }
  228361. ~WindowedGLContext()
  228362. {
  228363. deleteContext();
  228364. viewHolder = 0;
  228365. }
  228366. void deleteContext()
  228367. {
  228368. makeInactive();
  228369. [renderContext clearDrawable];
  228370. [renderContext setView: nil];
  228371. [view setOpenGLContext: nil];
  228372. renderContext = nil;
  228373. }
  228374. bool makeActive() const throw()
  228375. {
  228376. jassert (renderContext != 0);
  228377. if ([renderContext view] != view)
  228378. [renderContext setView: view];
  228379. [view makeActive];
  228380. return isActive();
  228381. }
  228382. bool makeInactive() const throw()
  228383. {
  228384. [view makeInactive];
  228385. return true;
  228386. }
  228387. bool isActive() const throw()
  228388. {
  228389. return [NSOpenGLContext currentContext] == renderContext;
  228390. }
  228391. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228392. void* getRawContext() const throw() { return renderContext; }
  228393. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228394. {
  228395. }
  228396. void swapBuffers()
  228397. {
  228398. [renderContext flushBuffer];
  228399. }
  228400. bool setSwapInterval (const int numFramesPerSwap)
  228401. {
  228402. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228403. forParameter: NSOpenGLCPSwapInterval];
  228404. return true;
  228405. }
  228406. int getSwapInterval() const
  228407. {
  228408. GLint numFrames = 0;
  228409. [renderContext getValues: &numFrames
  228410. forParameter: NSOpenGLCPSwapInterval];
  228411. return numFrames;
  228412. }
  228413. void repaint()
  228414. {
  228415. // we need to invalidate the juce view that holds this gl view, to make it
  228416. // cause a repaint callback
  228417. NSView* v = (NSView*) viewHolder->view;
  228418. NSRect r = [v frame];
  228419. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228420. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228421. // repaint message, thus never causing our paint() callback, and never repainting
  228422. // the comp. So invalidating just a little bit around the edge helps..
  228423. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228424. }
  228425. void* getNativeWindowHandle() const { return viewHolder->view; }
  228426. juce_UseDebuggingNewOperator
  228427. NSOpenGLContext* renderContext;
  228428. ThreadSafeNSOpenGLView* view;
  228429. private:
  228430. OpenGLPixelFormat pixelFormat;
  228431. ScopedPointer <NSViewComponentInternal> viewHolder;
  228432. WindowedGLContext (const WindowedGLContext&);
  228433. WindowedGLContext& operator= (const WindowedGLContext&);
  228434. };
  228435. OpenGLContext* OpenGLComponent::createContext()
  228436. {
  228437. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228438. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228439. return (c->renderContext != 0) ? c.release() : 0;
  228440. }
  228441. void* OpenGLComponent::getNativeWindowHandle() const
  228442. {
  228443. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228444. : 0;
  228445. }
  228446. void juce_glViewport (const int w, const int h)
  228447. {
  228448. glViewport (0, 0, w, h);
  228449. }
  228450. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228451. OwnedArray <OpenGLPixelFormat>& results)
  228452. {
  228453. /* GLint attribs [64];
  228454. int n = 0;
  228455. attribs[n++] = AGL_RGBA;
  228456. attribs[n++] = AGL_DOUBLEBUFFER;
  228457. attribs[n++] = AGL_ACCELERATED;
  228458. attribs[n++] = AGL_NO_RECOVERY;
  228459. attribs[n++] = AGL_NONE;
  228460. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228461. while (p != 0)
  228462. {
  228463. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228464. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228465. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228466. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228467. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228468. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228469. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228470. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228471. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228472. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228473. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228474. results.add (pf);
  228475. p = aglNextPixelFormat (p);
  228476. }*/
  228477. //jassertfalse // can't see how you do this in cocoa!
  228478. }
  228479. #else
  228480. END_JUCE_NAMESPACE
  228481. @interface JuceGLView : UIView
  228482. {
  228483. }
  228484. + (Class) layerClass;
  228485. @end
  228486. @implementation JuceGLView
  228487. + (Class) layerClass
  228488. {
  228489. return [CAEAGLLayer class];
  228490. }
  228491. @end
  228492. BEGIN_JUCE_NAMESPACE
  228493. class GLESContext : public OpenGLContext
  228494. {
  228495. public:
  228496. GLESContext (UIViewComponentPeer* peer,
  228497. Component* const component_,
  228498. const OpenGLPixelFormat& pixelFormat_,
  228499. const GLESContext* const sharedContext,
  228500. NSUInteger apiType)
  228501. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228502. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228503. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228504. {
  228505. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228506. view.opaque = YES;
  228507. view.hidden = NO;
  228508. view.backgroundColor = [UIColor blackColor];
  228509. view.userInteractionEnabled = NO;
  228510. glLayer = (CAEAGLLayer*) [view layer];
  228511. [peer->view addSubview: view];
  228512. if (sharedContext != 0)
  228513. context = [[EAGLContext alloc] initWithAPI: apiType
  228514. sharegroup: [sharedContext->context sharegroup]];
  228515. else
  228516. context = [[EAGLContext alloc] initWithAPI: apiType];
  228517. createGLBuffers();
  228518. }
  228519. ~GLESContext()
  228520. {
  228521. deleteContext();
  228522. [view removeFromSuperview];
  228523. [view release];
  228524. freeGLBuffers();
  228525. }
  228526. void deleteContext()
  228527. {
  228528. makeInactive();
  228529. [context release];
  228530. context = nil;
  228531. }
  228532. bool makeActive() const throw()
  228533. {
  228534. jassert (context != 0);
  228535. [EAGLContext setCurrentContext: context];
  228536. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228537. return true;
  228538. }
  228539. void swapBuffers()
  228540. {
  228541. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228542. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228543. }
  228544. bool makeInactive() const throw()
  228545. {
  228546. return [EAGLContext setCurrentContext: nil];
  228547. }
  228548. bool isActive() const throw()
  228549. {
  228550. return [EAGLContext currentContext] == context;
  228551. }
  228552. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228553. void* getRawContext() const throw() { return glLayer; }
  228554. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228555. {
  228556. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228557. if (lastWidth != w || lastHeight != h)
  228558. {
  228559. lastWidth = w;
  228560. lastHeight = h;
  228561. freeGLBuffers();
  228562. createGLBuffers();
  228563. }
  228564. }
  228565. bool setSwapInterval (const int numFramesPerSwap)
  228566. {
  228567. numFrames = numFramesPerSwap;
  228568. return true;
  228569. }
  228570. int getSwapInterval() const
  228571. {
  228572. return numFrames;
  228573. }
  228574. void repaint()
  228575. {
  228576. }
  228577. void createGLBuffers()
  228578. {
  228579. makeActive();
  228580. glGenFramebuffersOES (1, &frameBufferHandle);
  228581. glGenRenderbuffersOES (1, &colorBufferHandle);
  228582. glGenRenderbuffersOES (1, &depthBufferHandle);
  228583. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228584. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228585. GLint width, height;
  228586. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228587. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228588. if (useDepthBuffer)
  228589. {
  228590. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228591. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228592. }
  228593. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228594. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228595. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228596. if (useDepthBuffer)
  228597. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228598. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228599. }
  228600. void freeGLBuffers()
  228601. {
  228602. if (frameBufferHandle != 0)
  228603. {
  228604. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228605. frameBufferHandle = 0;
  228606. }
  228607. if (colorBufferHandle != 0)
  228608. {
  228609. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228610. colorBufferHandle = 0;
  228611. }
  228612. if (depthBufferHandle != 0)
  228613. {
  228614. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228615. depthBufferHandle = 0;
  228616. }
  228617. }
  228618. juce_UseDebuggingNewOperator
  228619. private:
  228620. Component::SafePointer<Component> component;
  228621. OpenGLPixelFormat pixelFormat;
  228622. JuceGLView* view;
  228623. CAEAGLLayer* glLayer;
  228624. EAGLContext* context;
  228625. bool useDepthBuffer;
  228626. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228627. int numFrames;
  228628. int lastWidth, lastHeight;
  228629. GLESContext (const GLESContext&);
  228630. GLESContext& operator= (const GLESContext&);
  228631. };
  228632. OpenGLContext* OpenGLComponent::createContext()
  228633. {
  228634. ScopedAutoReleasePool pool;
  228635. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228636. if (peer != 0)
  228637. return new GLESContext (peer, this, preferredPixelFormat,
  228638. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228639. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228640. return 0;
  228641. }
  228642. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228643. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228644. {
  228645. }
  228646. void juce_glViewport (const int w, const int h)
  228647. {
  228648. glViewport (0, 0, w, h);
  228649. }
  228650. #endif
  228651. #endif
  228652. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228653. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228654. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228655. // compiled on its own).
  228656. #if JUCE_INCLUDED_FILE
  228657. #if JUCE_MAC
  228658. namespace MouseCursorHelpers
  228659. {
  228660. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228661. {
  228662. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228663. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228664. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228665. [im release];
  228666. return c;
  228667. }
  228668. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228669. {
  228670. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228671. BufferedInputStream buf (&fileStream, 4096, false);
  228672. PNGImageFormat pngFormat;
  228673. Image im (pngFormat.decodeImage (buf));
  228674. if (im.isValid())
  228675. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228676. jassertfalse;
  228677. return 0;
  228678. }
  228679. }
  228680. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228681. {
  228682. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228683. }
  228684. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228685. {
  228686. const ScopedAutoReleasePool pool;
  228687. NSCursor* c = 0;
  228688. switch (type)
  228689. {
  228690. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228691. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228692. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228693. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228694. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228695. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228696. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228697. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228698. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228699. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228700. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228701. case UpDownResizeCursor:
  228702. case TopEdgeResizeCursor:
  228703. case BottomEdgeResizeCursor:
  228704. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228705. case TopLeftCornerResizeCursor:
  228706. case BottomRightCornerResizeCursor:
  228707. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228708. case TopRightCornerResizeCursor:
  228709. case BottomLeftCornerResizeCursor:
  228710. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228711. case UpDownLeftRightResizeCursor:
  228712. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228713. default:
  228714. jassertfalse;
  228715. break;
  228716. }
  228717. [c retain];
  228718. return c;
  228719. }
  228720. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228721. {
  228722. [((NSCursor*) cursorHandle) release];
  228723. }
  228724. void MouseCursor::showInAllWindows() const
  228725. {
  228726. showInWindow (0);
  228727. }
  228728. void MouseCursor::showInWindow (ComponentPeer*) const
  228729. {
  228730. [((NSCursor*) getHandle()) set];
  228731. }
  228732. #else
  228733. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228734. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228735. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228736. void MouseCursor::showInAllWindows() const {}
  228737. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228738. #endif
  228739. #endif
  228740. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228741. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228742. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228743. // compiled on its own).
  228744. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228745. #if JUCE_MAC
  228746. END_JUCE_NAMESPACE
  228747. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228748. @interface DownloadClickDetector : NSObject
  228749. {
  228750. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228751. }
  228752. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228753. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228754. request: (NSURLRequest*) request
  228755. frame: (WebFrame*) frame
  228756. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228757. @end
  228758. @implementation DownloadClickDetector
  228759. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228760. {
  228761. [super init];
  228762. ownerComponent = ownerComponent_;
  228763. return self;
  228764. }
  228765. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228766. request: (NSURLRequest*) request
  228767. frame: (WebFrame*) frame
  228768. decisionListener: (id <WebPolicyDecisionListener>) listener
  228769. {
  228770. (void) sender;
  228771. (void) request;
  228772. (void) frame;
  228773. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228774. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228775. [listener use];
  228776. else
  228777. [listener ignore];
  228778. }
  228779. @end
  228780. BEGIN_JUCE_NAMESPACE
  228781. class WebBrowserComponentInternal : public NSViewComponent
  228782. {
  228783. public:
  228784. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228785. {
  228786. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228787. frameName: @""
  228788. groupName: @""];
  228789. setView (webView);
  228790. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228791. [webView setPolicyDelegate: clickListener];
  228792. }
  228793. ~WebBrowserComponentInternal()
  228794. {
  228795. [webView setPolicyDelegate: nil];
  228796. [clickListener release];
  228797. setView (0);
  228798. }
  228799. void goToURL (const String& url,
  228800. const StringArray* headers,
  228801. const MemoryBlock* postData)
  228802. {
  228803. NSMutableURLRequest* r
  228804. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228805. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228806. timeoutInterval: 30.0];
  228807. if (postData != 0 && postData->getSize() > 0)
  228808. {
  228809. [r setHTTPMethod: @"POST"];
  228810. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228811. length: postData->getSize()]];
  228812. }
  228813. if (headers != 0)
  228814. {
  228815. for (int i = 0; i < headers->size(); ++i)
  228816. {
  228817. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228818. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228819. [r setValue: juceStringToNS (headerValue)
  228820. forHTTPHeaderField: juceStringToNS (headerName)];
  228821. }
  228822. }
  228823. stop();
  228824. [[webView mainFrame] loadRequest: r];
  228825. }
  228826. void goBack()
  228827. {
  228828. [webView goBack];
  228829. }
  228830. void goForward()
  228831. {
  228832. [webView goForward];
  228833. }
  228834. void stop()
  228835. {
  228836. [webView stopLoading: nil];
  228837. }
  228838. void refresh()
  228839. {
  228840. [webView reload: nil];
  228841. }
  228842. private:
  228843. WebView* webView;
  228844. DownloadClickDetector* clickListener;
  228845. };
  228846. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228847. : browser (0),
  228848. blankPageShown (false),
  228849. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228850. {
  228851. setOpaque (true);
  228852. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228853. }
  228854. WebBrowserComponent::~WebBrowserComponent()
  228855. {
  228856. deleteAndZero (browser);
  228857. }
  228858. void WebBrowserComponent::goToURL (const String& url,
  228859. const StringArray* headers,
  228860. const MemoryBlock* postData)
  228861. {
  228862. lastURL = url;
  228863. lastHeaders.clear();
  228864. if (headers != 0)
  228865. lastHeaders = *headers;
  228866. lastPostData.setSize (0);
  228867. if (postData != 0)
  228868. lastPostData = *postData;
  228869. blankPageShown = false;
  228870. browser->goToURL (url, headers, postData);
  228871. }
  228872. void WebBrowserComponent::stop()
  228873. {
  228874. browser->stop();
  228875. }
  228876. void WebBrowserComponent::goBack()
  228877. {
  228878. lastURL = String::empty;
  228879. blankPageShown = false;
  228880. browser->goBack();
  228881. }
  228882. void WebBrowserComponent::goForward()
  228883. {
  228884. lastURL = String::empty;
  228885. browser->goForward();
  228886. }
  228887. void WebBrowserComponent::refresh()
  228888. {
  228889. browser->refresh();
  228890. }
  228891. void WebBrowserComponent::paint (Graphics&)
  228892. {
  228893. }
  228894. void WebBrowserComponent::checkWindowAssociation()
  228895. {
  228896. if (isShowing())
  228897. {
  228898. if (blankPageShown)
  228899. goBack();
  228900. }
  228901. else
  228902. {
  228903. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228904. {
  228905. // when the component becomes invisible, some stuff like flash
  228906. // carries on playing audio, so we need to force it onto a blank
  228907. // page to avoid this, (and send it back when it's made visible again).
  228908. blankPageShown = true;
  228909. browser->goToURL ("about:blank", 0, 0);
  228910. }
  228911. }
  228912. }
  228913. void WebBrowserComponent::reloadLastURL()
  228914. {
  228915. if (lastURL.isNotEmpty())
  228916. {
  228917. goToURL (lastURL, &lastHeaders, &lastPostData);
  228918. lastURL = String::empty;
  228919. }
  228920. }
  228921. void WebBrowserComponent::parentHierarchyChanged()
  228922. {
  228923. checkWindowAssociation();
  228924. }
  228925. void WebBrowserComponent::resized()
  228926. {
  228927. browser->setSize (getWidth(), getHeight());
  228928. }
  228929. void WebBrowserComponent::visibilityChanged()
  228930. {
  228931. checkWindowAssociation();
  228932. }
  228933. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228934. {
  228935. return true;
  228936. }
  228937. #else
  228938. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228939. {
  228940. }
  228941. WebBrowserComponent::~WebBrowserComponent()
  228942. {
  228943. }
  228944. void WebBrowserComponent::goToURL (const String& url,
  228945. const StringArray* headers,
  228946. const MemoryBlock* postData)
  228947. {
  228948. }
  228949. void WebBrowserComponent::stop()
  228950. {
  228951. }
  228952. void WebBrowserComponent::goBack()
  228953. {
  228954. }
  228955. void WebBrowserComponent::goForward()
  228956. {
  228957. }
  228958. void WebBrowserComponent::refresh()
  228959. {
  228960. }
  228961. void WebBrowserComponent::paint (Graphics& g)
  228962. {
  228963. }
  228964. void WebBrowserComponent::checkWindowAssociation()
  228965. {
  228966. }
  228967. void WebBrowserComponent::reloadLastURL()
  228968. {
  228969. }
  228970. void WebBrowserComponent::parentHierarchyChanged()
  228971. {
  228972. }
  228973. void WebBrowserComponent::resized()
  228974. {
  228975. }
  228976. void WebBrowserComponent::visibilityChanged()
  228977. {
  228978. }
  228979. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228980. {
  228981. return true;
  228982. }
  228983. #endif
  228984. #endif
  228985. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228986. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  228987. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228988. // compiled on its own).
  228989. #if JUCE_INCLUDED_FILE
  228990. class IPhoneAudioIODevice : public AudioIODevice
  228991. {
  228992. public:
  228993. IPhoneAudioIODevice (const String& deviceName)
  228994. : AudioIODevice (deviceName, "Audio"),
  228995. audioUnit (0),
  228996. isRunning (false),
  228997. callback (0),
  228998. actualBufferSize (0),
  228999. floatData (1, 2)
  229000. {
  229001. numInputChannels = 2;
  229002. numOutputChannels = 2;
  229003. preferredBufferSize = 0;
  229004. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  229005. updateDeviceInfo();
  229006. }
  229007. ~IPhoneAudioIODevice()
  229008. {
  229009. close();
  229010. }
  229011. const StringArray getOutputChannelNames()
  229012. {
  229013. StringArray s;
  229014. s.add ("Left");
  229015. s.add ("Right");
  229016. return s;
  229017. }
  229018. const StringArray getInputChannelNames()
  229019. {
  229020. StringArray s;
  229021. if (audioInputIsAvailable)
  229022. {
  229023. s.add ("Left");
  229024. s.add ("Right");
  229025. }
  229026. return s;
  229027. }
  229028. int getNumSampleRates()
  229029. {
  229030. return 1;
  229031. }
  229032. double getSampleRate (int index)
  229033. {
  229034. return sampleRate;
  229035. }
  229036. int getNumBufferSizesAvailable()
  229037. {
  229038. return 1;
  229039. }
  229040. int getBufferSizeSamples (int index)
  229041. {
  229042. return getDefaultBufferSize();
  229043. }
  229044. int getDefaultBufferSize()
  229045. {
  229046. return 1024;
  229047. }
  229048. const String open (const BigInteger& inputChannels,
  229049. const BigInteger& outputChannels,
  229050. double sampleRate,
  229051. int bufferSize)
  229052. {
  229053. close();
  229054. lastError = String::empty;
  229055. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  229056. // xxx set up channel mapping
  229057. activeOutputChans = outputChannels;
  229058. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  229059. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  229060. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  229061. activeInputChans = inputChannels;
  229062. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  229063. numInputChannels = activeInputChans.countNumberOfSetBits();
  229064. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  229065. AudioSessionSetActive (true);
  229066. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  229067. : kAudioSessionCategory_MediaPlayback;
  229068. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  229069. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  229070. fixAudioRouteIfSetToReceiver();
  229071. updateDeviceInfo();
  229072. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229073. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  229074. actualBufferSize = preferredBufferSize;
  229075. prepareFloatBuffers();
  229076. isRunning = true;
  229077. propertyChanged (0, 0, 0); // creates and starts the AU
  229078. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  229079. return lastError;
  229080. }
  229081. void close()
  229082. {
  229083. if (isRunning)
  229084. {
  229085. isRunning = false;
  229086. AudioSessionSetActive (false);
  229087. if (audioUnit != 0)
  229088. {
  229089. AudioComponentInstanceDispose (audioUnit);
  229090. audioUnit = 0;
  229091. }
  229092. }
  229093. }
  229094. bool isOpen()
  229095. {
  229096. return isRunning;
  229097. }
  229098. int getCurrentBufferSizeSamples()
  229099. {
  229100. return actualBufferSize;
  229101. }
  229102. double getCurrentSampleRate()
  229103. {
  229104. return sampleRate;
  229105. }
  229106. int getCurrentBitDepth()
  229107. {
  229108. return 16;
  229109. }
  229110. const BigInteger getActiveOutputChannels() const
  229111. {
  229112. return activeOutputChans;
  229113. }
  229114. const BigInteger getActiveInputChannels() const
  229115. {
  229116. return activeInputChans;
  229117. }
  229118. int getOutputLatencyInSamples()
  229119. {
  229120. return 0; //xxx
  229121. }
  229122. int getInputLatencyInSamples()
  229123. {
  229124. return 0; //xxx
  229125. }
  229126. void start (AudioIODeviceCallback* callback_)
  229127. {
  229128. if (isRunning && callback != callback_)
  229129. {
  229130. if (callback_ != 0)
  229131. callback_->audioDeviceAboutToStart (this);
  229132. const ScopedLock sl (callbackLock);
  229133. callback = callback_;
  229134. }
  229135. }
  229136. void stop()
  229137. {
  229138. if (isRunning)
  229139. {
  229140. AudioIODeviceCallback* lastCallback;
  229141. {
  229142. const ScopedLock sl (callbackLock);
  229143. lastCallback = callback;
  229144. callback = 0;
  229145. }
  229146. if (lastCallback != 0)
  229147. lastCallback->audioDeviceStopped();
  229148. }
  229149. }
  229150. bool isPlaying()
  229151. {
  229152. return isRunning && callback != 0;
  229153. }
  229154. const String getLastError()
  229155. {
  229156. return lastError;
  229157. }
  229158. private:
  229159. CriticalSection callbackLock;
  229160. Float64 sampleRate;
  229161. int numInputChannels, numOutputChannels;
  229162. int preferredBufferSize;
  229163. int actualBufferSize;
  229164. bool isRunning;
  229165. String lastError;
  229166. AudioStreamBasicDescription format;
  229167. AudioUnit audioUnit;
  229168. UInt32 audioInputIsAvailable;
  229169. AudioIODeviceCallback* callback;
  229170. BigInteger activeOutputChans, activeInputChans;
  229171. AudioSampleBuffer floatData;
  229172. float* inputChannels[3];
  229173. float* outputChannels[3];
  229174. bool monoInputChannelNumber, monoOutputChannelNumber;
  229175. void prepareFloatBuffers()
  229176. {
  229177. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  229178. zerostruct (inputChannels);
  229179. zerostruct (outputChannels);
  229180. for (int i = 0; i < numInputChannels; ++i)
  229181. inputChannels[i] = floatData.getSampleData (i);
  229182. for (int i = 0; i < numOutputChannels; ++i)
  229183. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  229184. }
  229185. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229186. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229187. {
  229188. OSStatus err = noErr;
  229189. if (audioInputIsAvailable)
  229190. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  229191. const ScopedLock sl (callbackLock);
  229192. if (callback != 0)
  229193. {
  229194. if (audioInputIsAvailable && numInputChannels > 0)
  229195. {
  229196. short* shortData = (short*) ioData->mBuffers[0].mData;
  229197. if (numInputChannels >= 2)
  229198. {
  229199. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229200. {
  229201. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229202. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  229203. }
  229204. }
  229205. else
  229206. {
  229207. if (monoInputChannelNumber > 0)
  229208. ++shortData;
  229209. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229210. {
  229211. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229212. ++shortData;
  229213. }
  229214. }
  229215. }
  229216. else
  229217. {
  229218. for (int i = numInputChannels; --i >= 0;)
  229219. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  229220. }
  229221. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  229222. outputChannels, numOutputChannels,
  229223. (int) inNumberFrames);
  229224. short* shortData = (short*) ioData->mBuffers[0].mData;
  229225. int n = 0;
  229226. if (numOutputChannels >= 2)
  229227. {
  229228. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229229. {
  229230. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  229231. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  229232. }
  229233. }
  229234. else if (numOutputChannels == 1)
  229235. {
  229236. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229237. {
  229238. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  229239. shortData [n++] = s;
  229240. shortData [n++] = s;
  229241. }
  229242. }
  229243. else
  229244. {
  229245. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229246. }
  229247. }
  229248. else
  229249. {
  229250. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229251. }
  229252. return err;
  229253. }
  229254. void updateDeviceInfo()
  229255. {
  229256. UInt32 size = sizeof (sampleRate);
  229257. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  229258. size = sizeof (audioInputIsAvailable);
  229259. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  229260. }
  229261. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229262. {
  229263. if (! isRunning)
  229264. return;
  229265. if (inPropertyValue != 0)
  229266. {
  229267. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  229268. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  229269. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229270. SInt32 routeChangeReason;
  229271. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229272. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229273. fixAudioRouteIfSetToReceiver();
  229274. }
  229275. updateDeviceInfo();
  229276. createAudioUnit();
  229277. AudioSessionSetActive (true);
  229278. if (audioUnit != 0)
  229279. {
  229280. UInt32 formatSize = sizeof (format);
  229281. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229282. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229283. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229284. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229285. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229286. AudioOutputUnitStart (audioUnit);
  229287. }
  229288. }
  229289. void interruptionListener (UInt32 inInterruption)
  229290. {
  229291. /*if (inInterruption == kAudioSessionBeginInterruption)
  229292. {
  229293. isRunning = false;
  229294. AudioOutputUnitStop (audioUnit);
  229295. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229296. "This could have been interrupted by another application or by unplugging a headset",
  229297. @"Resume",
  229298. @"Cancel"))
  229299. {
  229300. isRunning = true;
  229301. propertyChanged (0, 0, 0);
  229302. }
  229303. }*/
  229304. if (inInterruption == kAudioSessionEndInterruption)
  229305. {
  229306. isRunning = true;
  229307. AudioSessionSetActive (true);
  229308. AudioOutputUnitStart (audioUnit);
  229309. }
  229310. }
  229311. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229312. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229313. {
  229314. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229315. }
  229316. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229317. {
  229318. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229319. }
  229320. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229321. {
  229322. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229323. }
  229324. void resetFormat (const int numChannels)
  229325. {
  229326. memset (&format, 0, sizeof (format));
  229327. format.mFormatID = kAudioFormatLinearPCM;
  229328. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229329. format.mBitsPerChannel = 8 * sizeof (short);
  229330. format.mChannelsPerFrame = 2;
  229331. format.mFramesPerPacket = 1;
  229332. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229333. }
  229334. bool createAudioUnit()
  229335. {
  229336. if (audioUnit != 0)
  229337. {
  229338. AudioComponentInstanceDispose (audioUnit);
  229339. audioUnit = 0;
  229340. }
  229341. resetFormat (2);
  229342. AudioComponentDescription desc;
  229343. desc.componentType = kAudioUnitType_Output;
  229344. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229345. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229346. desc.componentFlags = 0;
  229347. desc.componentFlagsMask = 0;
  229348. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229349. AudioComponentInstanceNew (comp, &audioUnit);
  229350. if (audioUnit == 0)
  229351. return false;
  229352. const UInt32 one = 1;
  229353. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229354. AudioChannelLayout layout;
  229355. layout.mChannelBitmap = 0;
  229356. layout.mNumberChannelDescriptions = 0;
  229357. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229358. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229359. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229360. AURenderCallbackStruct inputProc;
  229361. inputProc.inputProc = processStatic;
  229362. inputProc.inputProcRefCon = this;
  229363. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229364. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229365. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229366. AudioUnitInitialize (audioUnit);
  229367. return true;
  229368. }
  229369. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229370. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229371. static void fixAudioRouteIfSetToReceiver()
  229372. {
  229373. CFStringRef audioRoute = 0;
  229374. UInt32 propertySize = sizeof (audioRoute);
  229375. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229376. {
  229377. NSString* route = (NSString*) audioRoute;
  229378. //DBG ("audio route: " + nsStringToJuce (route));
  229379. if ([route hasPrefix: @"Receiver"])
  229380. {
  229381. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229382. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229383. }
  229384. CFRelease (audioRoute);
  229385. }
  229386. }
  229387. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  229388. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  229389. };
  229390. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229391. {
  229392. public:
  229393. IPhoneAudioIODeviceType()
  229394. : AudioIODeviceType ("iPhone Audio")
  229395. {
  229396. }
  229397. ~IPhoneAudioIODeviceType()
  229398. {
  229399. }
  229400. void scanForDevices()
  229401. {
  229402. }
  229403. const StringArray getDeviceNames (bool wantInputNames) const
  229404. {
  229405. StringArray s;
  229406. s.add ("iPhone Audio");
  229407. return s;
  229408. }
  229409. int getDefaultDeviceIndex (bool forInput) const
  229410. {
  229411. return 0;
  229412. }
  229413. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229414. {
  229415. return device != 0 ? 0 : -1;
  229416. }
  229417. bool hasSeparateInputsAndOutputs() const { return false; }
  229418. AudioIODevice* createDevice (const String& outputDeviceName,
  229419. const String& inputDeviceName)
  229420. {
  229421. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229422. {
  229423. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229424. : inputDeviceName);
  229425. }
  229426. return 0;
  229427. }
  229428. juce_UseDebuggingNewOperator
  229429. private:
  229430. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  229431. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  229432. };
  229433. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  229434. {
  229435. return new IPhoneAudioIODeviceType();
  229436. }
  229437. #endif
  229438. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  229439. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229440. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229441. // compiled on its own).
  229442. #if JUCE_INCLUDED_FILE
  229443. #if JUCE_MAC
  229444. namespace CoreMidiHelpers
  229445. {
  229446. static bool logError (const OSStatus err, const int lineNum)
  229447. {
  229448. if (err == noErr)
  229449. return true;
  229450. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229451. jassertfalse;
  229452. return false;
  229453. }
  229454. #undef CHECK_ERROR
  229455. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  229456. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229457. {
  229458. String result;
  229459. CFStringRef str = 0;
  229460. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229461. if (str != 0)
  229462. {
  229463. result = PlatformUtilities::cfStringToJuceString (str);
  229464. CFRelease (str);
  229465. str = 0;
  229466. }
  229467. MIDIEntityRef entity = 0;
  229468. MIDIEndpointGetEntity (endpoint, &entity);
  229469. if (entity == 0)
  229470. return result; // probably virtual
  229471. if (result.isEmpty())
  229472. {
  229473. // endpoint name has zero length - try the entity
  229474. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229475. if (str != 0)
  229476. {
  229477. result += PlatformUtilities::cfStringToJuceString (str);
  229478. CFRelease (str);
  229479. str = 0;
  229480. }
  229481. }
  229482. // now consider the device's name
  229483. MIDIDeviceRef device = 0;
  229484. MIDIEntityGetDevice (entity, &device);
  229485. if (device == 0)
  229486. return result;
  229487. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229488. if (str != 0)
  229489. {
  229490. const String s (PlatformUtilities::cfStringToJuceString (str));
  229491. CFRelease (str);
  229492. // if an external device has only one entity, throw away
  229493. // the endpoint name and just use the device name
  229494. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229495. {
  229496. result = s;
  229497. }
  229498. else if (! result.startsWithIgnoreCase (s))
  229499. {
  229500. // prepend the device name to the entity name
  229501. result = (s + " " + result).trimEnd();
  229502. }
  229503. }
  229504. return result;
  229505. }
  229506. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229507. {
  229508. String result;
  229509. // Does the endpoint have connections?
  229510. CFDataRef connections = 0;
  229511. int numConnections = 0;
  229512. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229513. if (connections != 0)
  229514. {
  229515. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229516. if (numConnections > 0)
  229517. {
  229518. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229519. for (int i = 0; i < numConnections; ++i, ++pid)
  229520. {
  229521. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229522. MIDIObjectRef connObject;
  229523. MIDIObjectType connObjectType;
  229524. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229525. if (err == noErr)
  229526. {
  229527. String s;
  229528. if (connObjectType == kMIDIObjectType_ExternalSource
  229529. || connObjectType == kMIDIObjectType_ExternalDestination)
  229530. {
  229531. // Connected to an external device's endpoint (10.3 and later).
  229532. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229533. }
  229534. else
  229535. {
  229536. // Connected to an external device (10.2) (or something else, catch-all)
  229537. CFStringRef str = 0;
  229538. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229539. if (str != 0)
  229540. {
  229541. s = PlatformUtilities::cfStringToJuceString (str);
  229542. CFRelease (str);
  229543. }
  229544. }
  229545. if (s.isNotEmpty())
  229546. {
  229547. if (result.isNotEmpty())
  229548. result += ", ";
  229549. result += s;
  229550. }
  229551. }
  229552. }
  229553. }
  229554. CFRelease (connections);
  229555. }
  229556. if (result.isNotEmpty())
  229557. return result;
  229558. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229559. return getEndpointName (endpoint, false);
  229560. }
  229561. static MIDIClientRef getGlobalMidiClient()
  229562. {
  229563. static MIDIClientRef globalMidiClient = 0;
  229564. if (globalMidiClient == 0)
  229565. {
  229566. String name ("JUCE");
  229567. if (JUCEApplication::getInstance() != 0)
  229568. name = JUCEApplication::getInstance()->getApplicationName();
  229569. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229570. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229571. CFRelease (appName);
  229572. }
  229573. return globalMidiClient;
  229574. }
  229575. class MidiPortAndEndpoint
  229576. {
  229577. public:
  229578. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229579. : port (port_), endPoint (endPoint_)
  229580. {
  229581. }
  229582. ~MidiPortAndEndpoint()
  229583. {
  229584. if (port != 0)
  229585. MIDIPortDispose (port);
  229586. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229587. MIDIEndpointDispose (endPoint);
  229588. }
  229589. void send (const MIDIPacketList* const packets)
  229590. {
  229591. if (port != 0)
  229592. MIDISend (port, endPoint, packets);
  229593. else
  229594. MIDIReceived (endPoint, packets);
  229595. }
  229596. MIDIPortRef port;
  229597. MIDIEndpointRef endPoint;
  229598. };
  229599. class MidiPortAndCallback;
  229600. static CriticalSection callbackLock;
  229601. static Array<MidiPortAndCallback*> activeCallbacks;
  229602. class MidiPortAndCallback
  229603. {
  229604. public:
  229605. MidiPortAndCallback (MidiInputCallback& callback_)
  229606. : input (0), active (false), callback (callback_), concatenator (2048)
  229607. {
  229608. }
  229609. ~MidiPortAndCallback()
  229610. {
  229611. active = false;
  229612. {
  229613. const ScopedLock sl (callbackLock);
  229614. activeCallbacks.removeValue (this);
  229615. }
  229616. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  229617. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  229618. }
  229619. void handlePackets (const MIDIPacketList* const pktlist)
  229620. {
  229621. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  229622. const ScopedLock sl (callbackLock);
  229623. if (activeCallbacks.contains (this) && active)
  229624. {
  229625. const MIDIPacket* packet = &pktlist->packet[0];
  229626. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229627. {
  229628. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  229629. input, callback);
  229630. packet = MIDIPacketNext (packet);
  229631. }
  229632. }
  229633. }
  229634. MidiInput* input;
  229635. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  229636. volatile bool active;
  229637. private:
  229638. MidiInputCallback& callback;
  229639. MidiDataConcatenator concatenator;
  229640. };
  229641. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  229642. {
  229643. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  229644. }
  229645. }
  229646. const StringArray MidiOutput::getDevices()
  229647. {
  229648. StringArray s;
  229649. const ItemCount num = MIDIGetNumberOfDestinations();
  229650. for (ItemCount i = 0; i < num; ++i)
  229651. {
  229652. MIDIEndpointRef dest = MIDIGetDestination (i);
  229653. if (dest != 0)
  229654. {
  229655. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  229656. if (name.isEmpty())
  229657. name = "<error>";
  229658. s.add (name);
  229659. }
  229660. else
  229661. {
  229662. s.add ("<error>");
  229663. }
  229664. }
  229665. return s;
  229666. }
  229667. int MidiOutput::getDefaultDeviceIndex()
  229668. {
  229669. return 0;
  229670. }
  229671. MidiOutput* MidiOutput::openDevice (int index)
  229672. {
  229673. MidiOutput* mo = 0;
  229674. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  229675. {
  229676. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229677. CFStringRef pname;
  229678. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229679. {
  229680. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229681. MIDIPortRef port;
  229682. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  229683. {
  229684. mo = new MidiOutput();
  229685. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  229686. }
  229687. CFRelease (pname);
  229688. }
  229689. }
  229690. return mo;
  229691. }
  229692. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229693. {
  229694. MidiOutput* mo = 0;
  229695. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229696. MIDIEndpointRef endPoint;
  229697. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229698. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  229699. {
  229700. mo = new MidiOutput();
  229701. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  229702. }
  229703. CFRelease (name);
  229704. return mo;
  229705. }
  229706. MidiOutput::~MidiOutput()
  229707. {
  229708. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229709. }
  229710. void MidiOutput::reset()
  229711. {
  229712. }
  229713. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229714. {
  229715. return false;
  229716. }
  229717. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229718. {
  229719. }
  229720. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229721. {
  229722. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229723. if (message.isSysEx())
  229724. {
  229725. const int maxPacketSize = 256;
  229726. int pos = 0, bytesLeft = message.getRawDataSize();
  229727. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229728. HeapBlock <MIDIPacketList> packets;
  229729. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229730. packets->numPackets = numPackets;
  229731. MIDIPacket* p = packets->packet;
  229732. for (int i = 0; i < numPackets; ++i)
  229733. {
  229734. p->timeStamp = 0;
  229735. p->length = jmin (maxPacketSize, bytesLeft);
  229736. memcpy (p->data, message.getRawData() + pos, p->length);
  229737. pos += p->length;
  229738. bytesLeft -= p->length;
  229739. p = MIDIPacketNext (p);
  229740. }
  229741. mpe->send (packets);
  229742. }
  229743. else
  229744. {
  229745. MIDIPacketList packets;
  229746. packets.numPackets = 1;
  229747. packets.packet[0].timeStamp = 0;
  229748. packets.packet[0].length = message.getRawDataSize();
  229749. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229750. mpe->send (&packets);
  229751. }
  229752. }
  229753. const StringArray MidiInput::getDevices()
  229754. {
  229755. StringArray s;
  229756. const ItemCount num = MIDIGetNumberOfSources();
  229757. for (ItemCount i = 0; i < num; ++i)
  229758. {
  229759. MIDIEndpointRef source = MIDIGetSource (i);
  229760. if (source != 0)
  229761. {
  229762. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  229763. if (name.isEmpty())
  229764. name = "<error>";
  229765. s.add (name);
  229766. }
  229767. else
  229768. {
  229769. s.add ("<error>");
  229770. }
  229771. }
  229772. return s;
  229773. }
  229774. int MidiInput::getDefaultDeviceIndex()
  229775. {
  229776. return 0;
  229777. }
  229778. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229779. {
  229780. jassert (callback != 0);
  229781. using namespace CoreMidiHelpers;
  229782. MidiInput* newInput = 0;
  229783. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  229784. {
  229785. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229786. if (endPoint != 0)
  229787. {
  229788. CFStringRef name;
  229789. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  229790. {
  229791. MIDIClientRef client = getGlobalMidiClient();
  229792. if (client != 0)
  229793. {
  229794. MIDIPortRef port;
  229795. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229796. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229797. {
  229798. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229799. {
  229800. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229801. newInput = new MidiInput (getDevices() [index]);
  229802. mpc->input = newInput;
  229803. newInput->internal = mpc;
  229804. const ScopedLock sl (callbackLock);
  229805. activeCallbacks.add (mpc.release());
  229806. }
  229807. else
  229808. {
  229809. CHECK_ERROR (MIDIPortDispose (port));
  229810. }
  229811. }
  229812. }
  229813. }
  229814. CFRelease (name);
  229815. }
  229816. }
  229817. return newInput;
  229818. }
  229819. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229820. {
  229821. jassert (callback != 0);
  229822. using namespace CoreMidiHelpers;
  229823. MidiInput* mi = 0;
  229824. MIDIClientRef client = getGlobalMidiClient();
  229825. if (client != 0)
  229826. {
  229827. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229828. mpc->active = false;
  229829. MIDIEndpointRef endPoint;
  229830. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229831. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229832. {
  229833. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229834. mi = new MidiInput (deviceName);
  229835. mpc->input = mi;
  229836. mi->internal = mpc;
  229837. const ScopedLock sl (callbackLock);
  229838. activeCallbacks.add (mpc.release());
  229839. }
  229840. CFRelease (name);
  229841. }
  229842. return mi;
  229843. }
  229844. MidiInput::MidiInput (const String& name_)
  229845. : name (name_)
  229846. {
  229847. }
  229848. MidiInput::~MidiInput()
  229849. {
  229850. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  229851. }
  229852. void MidiInput::start()
  229853. {
  229854. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229855. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  229856. }
  229857. void MidiInput::stop()
  229858. {
  229859. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229860. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  229861. }
  229862. #undef CHECK_ERROR
  229863. #else // Stubs for iOS...
  229864. MidiOutput::~MidiOutput() {}
  229865. void MidiOutput::reset() {}
  229866. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  229867. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  229868. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  229869. const StringArray MidiOutput::getDevices() { return StringArray(); }
  229870. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  229871. const StringArray MidiInput::getDevices() { return StringArray(); }
  229872. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  229873. #endif
  229874. #endif
  229875. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229876. #else
  229877. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229878. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229879. // compiled on its own).
  229880. #if JUCE_INCLUDED_FILE
  229881. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229882. #define SUPPORT_10_4_FONTS 1
  229883. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229884. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229885. #define SUPPORT_ONLY_10_4_FONTS 1
  229886. #endif
  229887. END_JUCE_NAMESPACE
  229888. @interface NSFont (PrivateHack)
  229889. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229890. @end
  229891. BEGIN_JUCE_NAMESPACE
  229892. #endif
  229893. class MacTypeface : public Typeface
  229894. {
  229895. public:
  229896. MacTypeface (const Font& font)
  229897. : Typeface (font.getTypefaceName())
  229898. {
  229899. const ScopedAutoReleasePool pool;
  229900. renderingTransform = CGAffineTransformIdentity;
  229901. bool needsItalicTransform = false;
  229902. #if JUCE_IOS
  229903. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229904. if (font.isItalic() || font.isBold())
  229905. {
  229906. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229907. for (NSString* i in familyFonts)
  229908. {
  229909. const String fn (nsStringToJuce (i));
  229910. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229911. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229912. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229913. || afterDash.containsIgnoreCase ("italic")
  229914. || fn.endsWithIgnoreCase ("oblique")
  229915. || fn.endsWithIgnoreCase ("italic");
  229916. if (probablyBold == font.isBold()
  229917. && probablyItalic == font.isItalic())
  229918. {
  229919. fontName = i;
  229920. needsItalicTransform = false;
  229921. break;
  229922. }
  229923. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229924. {
  229925. fontName = i;
  229926. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229927. }
  229928. }
  229929. if (needsItalicTransform)
  229930. renderingTransform.c = 0.15f;
  229931. }
  229932. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229933. const int ascender = abs (CGFontGetAscent (fontRef));
  229934. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229935. ascent = ascender / totalHeight;
  229936. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229937. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229938. #else
  229939. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229940. if (font.isItalic())
  229941. {
  229942. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229943. toHaveTrait: NSItalicFontMask];
  229944. if (newFont == nsFont)
  229945. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229946. nsFont = newFont;
  229947. }
  229948. if (font.isBold())
  229949. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229950. [nsFont retain];
  229951. ascent = std::abs ((float) [nsFont ascender]);
  229952. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229953. ascent /= totalSize;
  229954. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229955. if (needsItalicTransform)
  229956. {
  229957. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229958. renderingTransform.c = 0.15f;
  229959. }
  229960. #if SUPPORT_ONLY_10_4_FONTS
  229961. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229962. if (atsFont == 0)
  229963. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229964. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229965. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229966. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229967. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229968. #else
  229969. #if SUPPORT_10_4_FONTS
  229970. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229971. {
  229972. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229973. if (atsFont == 0)
  229974. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229975. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229976. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229977. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229978. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229979. }
  229980. else
  229981. #endif
  229982. {
  229983. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229984. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229985. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229986. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229987. }
  229988. #endif
  229989. #endif
  229990. }
  229991. ~MacTypeface()
  229992. {
  229993. #if ! JUCE_IOS
  229994. [nsFont release];
  229995. #endif
  229996. if (fontRef != 0)
  229997. CGFontRelease (fontRef);
  229998. }
  229999. float getAscent() const
  230000. {
  230001. return ascent;
  230002. }
  230003. float getDescent() const
  230004. {
  230005. return 1.0f - ascent;
  230006. }
  230007. float getStringWidth (const String& text)
  230008. {
  230009. if (fontRef == 0 || text.isEmpty())
  230010. return 0;
  230011. const int length = text.length();
  230012. HeapBlock <CGGlyph> glyphs;
  230013. createGlyphsForString (text, length, glyphs);
  230014. float x = 0;
  230015. #if SUPPORT_ONLY_10_4_FONTS
  230016. HeapBlock <NSSize> advances (length);
  230017. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230018. for (int i = 0; i < length; ++i)
  230019. x += advances[i].width;
  230020. #else
  230021. #if SUPPORT_10_4_FONTS
  230022. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230023. {
  230024. HeapBlock <NSSize> advances (length);
  230025. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  230026. for (int i = 0; i < length; ++i)
  230027. x += advances[i].width;
  230028. }
  230029. else
  230030. #endif
  230031. {
  230032. HeapBlock <int> advances (length);
  230033. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230034. for (int i = 0; i < length; ++i)
  230035. x += advances[i];
  230036. }
  230037. #endif
  230038. return x * unitsToHeightScaleFactor;
  230039. }
  230040. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  230041. {
  230042. xOffsets.add (0);
  230043. if (fontRef == 0 || text.isEmpty())
  230044. return;
  230045. const int length = text.length();
  230046. HeapBlock <CGGlyph> glyphs;
  230047. createGlyphsForString (text, length, glyphs);
  230048. #if SUPPORT_ONLY_10_4_FONTS
  230049. HeapBlock <NSSize> advances (length);
  230050. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230051. int x = 0;
  230052. for (int i = 0; i < length; ++i)
  230053. {
  230054. x += advances[i].width;
  230055. xOffsets.add (x * unitsToHeightScaleFactor);
  230056. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  230057. }
  230058. #else
  230059. #if SUPPORT_10_4_FONTS
  230060. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230061. {
  230062. HeapBlock <NSSize> advances (length);
  230063. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230064. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  230065. float x = 0;
  230066. for (int i = 0; i < length; ++i)
  230067. {
  230068. x += advances[i].width;
  230069. xOffsets.add (x * unitsToHeightScaleFactor);
  230070. resultGlyphs.add (nsGlyphs[i]);
  230071. }
  230072. }
  230073. else
  230074. #endif
  230075. {
  230076. HeapBlock <int> advances (length);
  230077. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230078. {
  230079. int x = 0;
  230080. for (int i = 0; i < length; ++i)
  230081. {
  230082. x += advances [i];
  230083. xOffsets.add (x * unitsToHeightScaleFactor);
  230084. resultGlyphs.add (glyphs[i]);
  230085. }
  230086. }
  230087. }
  230088. #endif
  230089. }
  230090. bool getOutlineForGlyph (int glyphNumber, Path& path)
  230091. {
  230092. #if JUCE_IOS
  230093. return false;
  230094. #else
  230095. if (nsFont == 0)
  230096. return false;
  230097. // we might need to apply a transform to the path, so it mustn't have anything else in it
  230098. jassert (path.isEmpty());
  230099. const ScopedAutoReleasePool pool;
  230100. NSBezierPath* bez = [NSBezierPath bezierPath];
  230101. [bez moveToPoint: NSMakePoint (0, 0)];
  230102. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  230103. inFont: nsFont];
  230104. for (int i = 0; i < [bez elementCount]; ++i)
  230105. {
  230106. NSPoint p[3];
  230107. switch ([bez elementAtIndex: i associatedPoints: p])
  230108. {
  230109. case NSMoveToBezierPathElement:
  230110. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  230111. break;
  230112. case NSLineToBezierPathElement:
  230113. path.lineTo ((float) p[0].x, (float) -p[0].y);
  230114. break;
  230115. case NSCurveToBezierPathElement:
  230116. 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);
  230117. break;
  230118. case NSClosePathBezierPathElement:
  230119. path.closeSubPath();
  230120. break;
  230121. default:
  230122. jassertfalse;
  230123. break;
  230124. }
  230125. }
  230126. path.applyTransform (pathTransform);
  230127. return true;
  230128. #endif
  230129. }
  230130. juce_UseDebuggingNewOperator
  230131. CGFontRef fontRef;
  230132. float fontHeightToCGSizeFactor;
  230133. CGAffineTransform renderingTransform;
  230134. private:
  230135. float ascent, unitsToHeightScaleFactor;
  230136. #if JUCE_IOS
  230137. #else
  230138. NSFont* nsFont;
  230139. AffineTransform pathTransform;
  230140. #endif
  230141. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  230142. {
  230143. #if SUPPORT_10_4_FONTS
  230144. #if ! SUPPORT_ONLY_10_4_FONTS
  230145. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230146. #endif
  230147. {
  230148. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  230149. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230150. for (int i = 0; i < length; ++i)
  230151. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  230152. return;
  230153. }
  230154. #endif
  230155. #if ! SUPPORT_ONLY_10_4_FONTS
  230156. if (charToGlyphMapper == 0)
  230157. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  230158. glyphs.malloc (length);
  230159. for (int i = 0; i < length; ++i)
  230160. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  230161. #endif
  230162. }
  230163. #if ! SUPPORT_ONLY_10_4_FONTS
  230164. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  230165. class CharToGlyphMapper
  230166. {
  230167. public:
  230168. CharToGlyphMapper (CGFontRef fontRef)
  230169. : segCount (0), endCode (0), startCode (0), idDelta (0),
  230170. idRangeOffset (0), glyphIndexes (0)
  230171. {
  230172. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  230173. if (cmapTable != 0)
  230174. {
  230175. const int numSubtables = getValue16 (cmapTable, 2);
  230176. for (int i = 0; i < numSubtables; ++i)
  230177. {
  230178. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  230179. {
  230180. const int offset = getValue32 (cmapTable, i * 8 + 8);
  230181. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  230182. {
  230183. const int length = getValue16 (cmapTable, offset + 2);
  230184. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  230185. segCount = segCountX2 / 2;
  230186. const int endCodeOffset = offset + 14;
  230187. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  230188. const int idDeltaOffset = startCodeOffset + segCountX2;
  230189. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  230190. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  230191. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  230192. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  230193. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  230194. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  230195. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  230196. }
  230197. break;
  230198. }
  230199. }
  230200. CFRelease (cmapTable);
  230201. }
  230202. }
  230203. ~CharToGlyphMapper()
  230204. {
  230205. if (endCode != 0)
  230206. {
  230207. CFRelease (endCode);
  230208. CFRelease (startCode);
  230209. CFRelease (idDelta);
  230210. CFRelease (idRangeOffset);
  230211. CFRelease (glyphIndexes);
  230212. }
  230213. }
  230214. int getGlyphForCharacter (const juce_wchar c) const
  230215. {
  230216. for (int i = 0; i < segCount; ++i)
  230217. {
  230218. if (getValue16 (endCode, i * 2) >= c)
  230219. {
  230220. const int start = getValue16 (startCode, i * 2);
  230221. if (start > c)
  230222. break;
  230223. const int delta = getValue16 (idDelta, i * 2);
  230224. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  230225. if (rangeOffset == 0)
  230226. return delta + c;
  230227. else
  230228. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  230229. }
  230230. }
  230231. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  230232. return jmax (-1, (int) c - 29);
  230233. }
  230234. private:
  230235. int segCount;
  230236. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  230237. static uint16 getValue16 (CFDataRef data, const int index)
  230238. {
  230239. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  230240. }
  230241. static uint32 getValue32 (CFDataRef data, const int index)
  230242. {
  230243. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  230244. }
  230245. };
  230246. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  230247. #endif
  230248. MacTypeface (const MacTypeface&);
  230249. MacTypeface& operator= (const MacTypeface&);
  230250. };
  230251. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  230252. {
  230253. return new MacTypeface (font);
  230254. }
  230255. const StringArray Font::findAllTypefaceNames()
  230256. {
  230257. StringArray names;
  230258. const ScopedAutoReleasePool pool;
  230259. #if JUCE_IOS
  230260. NSArray* fonts = [UIFont familyNames];
  230261. #else
  230262. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  230263. #endif
  230264. for (unsigned int i = 0; i < [fonts count]; ++i)
  230265. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  230266. names.sort (true);
  230267. return names;
  230268. }
  230269. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  230270. {
  230271. #if JUCE_IOS
  230272. defaultSans = "Helvetica";
  230273. defaultSerif = "Times New Roman";
  230274. defaultFixed = "Courier New";
  230275. #else
  230276. defaultSans = "Lucida Grande";
  230277. defaultSerif = "Times New Roman";
  230278. defaultFixed = "Monaco";
  230279. #endif
  230280. }
  230281. #endif
  230282. /*** End of inlined file: juce_mac_Fonts.mm ***/
  230283. // (must go before juce_mac_CoreGraphicsContext.mm)
  230284. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230285. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230286. // compiled on its own).
  230287. #if JUCE_INCLUDED_FILE
  230288. class CoreGraphicsImage : public Image::SharedImage
  230289. {
  230290. public:
  230291. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230292. : Image::SharedImage (format_, width_, height_)
  230293. {
  230294. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230295. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230296. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  230297. imageData = imageDataAllocated;
  230298. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230299. : CGColorSpaceCreateDeviceRGB();
  230300. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230301. colourSpace, getCGImageFlags (format_));
  230302. CGColorSpaceRelease (colourSpace);
  230303. }
  230304. ~CoreGraphicsImage()
  230305. {
  230306. CGContextRelease (context);
  230307. }
  230308. Image::ImageType getType() const { return Image::NativeImage; }
  230309. LowLevelGraphicsContext* createLowLevelContext();
  230310. SharedImage* clone()
  230311. {
  230312. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230313. memcpy (im->imageData, imageData, lineStride * height);
  230314. return im;
  230315. }
  230316. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  230317. {
  230318. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230319. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230320. {
  230321. return CGBitmapContextCreateImage (nativeImage->context);
  230322. }
  230323. else
  230324. {
  230325. const Image::BitmapData srcData (juceImage, false);
  230326. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230327. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230328. 8, srcData.pixelStride * 8, srcData.lineStride,
  230329. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230330. 0, true, kCGRenderingIntentDefault);
  230331. CGDataProviderRelease (provider);
  230332. return imageRef;
  230333. }
  230334. }
  230335. #if JUCE_MAC
  230336. static NSImage* createNSImage (const Image& image)
  230337. {
  230338. const ScopedAutoReleasePool pool;
  230339. NSImage* im = [[NSImage alloc] init];
  230340. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230341. [im lockFocus];
  230342. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230343. CGImageRef imageRef = createImage (image, false, colourSpace);
  230344. CGColorSpaceRelease (colourSpace);
  230345. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230346. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230347. CGImageRelease (imageRef);
  230348. [im unlockFocus];
  230349. return im;
  230350. }
  230351. #endif
  230352. CGContextRef context;
  230353. HeapBlock<uint8> imageDataAllocated;
  230354. private:
  230355. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230356. {
  230357. #if JUCE_BIG_ENDIAN
  230358. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230359. #else
  230360. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230361. #endif
  230362. }
  230363. };
  230364. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230365. {
  230366. #if USE_COREGRAPHICS_RENDERING
  230367. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230368. #else
  230369. return createSoftwareImage (format, width, height, clearImage);
  230370. #endif
  230371. }
  230372. class CoreGraphicsContext : public LowLevelGraphicsContext
  230373. {
  230374. public:
  230375. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230376. : context (context_),
  230377. flipHeight (flipHeight_),
  230378. state (new SavedState()),
  230379. numGradientLookupEntries (0),
  230380. lastClipRectIsValid (false)
  230381. {
  230382. CGContextRetain (context);
  230383. CGContextSaveGState(context);
  230384. CGContextSetShouldSmoothFonts (context, true);
  230385. CGContextSetShouldAntialias (context, true);
  230386. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230387. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230388. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230389. gradientCallbacks.version = 0;
  230390. gradientCallbacks.evaluate = gradientCallback;
  230391. gradientCallbacks.releaseInfo = 0;
  230392. setFont (Font());
  230393. }
  230394. ~CoreGraphicsContext()
  230395. {
  230396. CGContextRestoreGState (context);
  230397. CGContextRelease (context);
  230398. CGColorSpaceRelease (rgbColourSpace);
  230399. CGColorSpaceRelease (greyColourSpace);
  230400. }
  230401. bool isVectorDevice() const { return false; }
  230402. void setOrigin (int x, int y)
  230403. {
  230404. CGContextTranslateCTM (context, x, -y);
  230405. if (lastClipRectIsValid)
  230406. lastClipRect.translate (-x, -y);
  230407. }
  230408. bool clipToRectangle (const Rectangle<int>& r)
  230409. {
  230410. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230411. if (lastClipRectIsValid)
  230412. {
  230413. // This is actually incorrect, because the actual clip region may be complex, and
  230414. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230415. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230416. // when calculating the resultant clip bounds, and makes the same mistake!
  230417. lastClipRect = lastClipRect.getIntersection (r);
  230418. return ! lastClipRect.isEmpty();
  230419. }
  230420. return ! isClipEmpty();
  230421. }
  230422. bool clipToRectangleList (const RectangleList& clipRegion)
  230423. {
  230424. if (clipRegion.isEmpty())
  230425. {
  230426. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230427. lastClipRectIsValid = true;
  230428. lastClipRect = Rectangle<int>();
  230429. return false;
  230430. }
  230431. else
  230432. {
  230433. const int numRects = clipRegion.getNumRectangles();
  230434. HeapBlock <CGRect> rects (numRects);
  230435. for (int i = 0; i < numRects; ++i)
  230436. {
  230437. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230438. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230439. }
  230440. CGContextClipToRects (context, rects, numRects);
  230441. lastClipRectIsValid = false;
  230442. return ! isClipEmpty();
  230443. }
  230444. }
  230445. void excludeClipRectangle (const Rectangle<int>& r)
  230446. {
  230447. RectangleList remaining (getClipBounds());
  230448. remaining.subtract (r);
  230449. clipToRectangleList (remaining);
  230450. lastClipRectIsValid = false;
  230451. }
  230452. void clipToPath (const Path& path, const AffineTransform& transform)
  230453. {
  230454. createPath (path, transform);
  230455. CGContextClip (context);
  230456. lastClipRectIsValid = false;
  230457. }
  230458. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230459. {
  230460. if (! transform.isSingularity())
  230461. {
  230462. Image singleChannelImage (sourceImage);
  230463. if (sourceImage.getFormat() != Image::SingleChannel)
  230464. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230465. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  230466. flip();
  230467. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230468. applyTransform (t);
  230469. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230470. CGContextClipToMask (context, r, image);
  230471. applyTransform (t.inverted());
  230472. flip();
  230473. CGImageRelease (image);
  230474. lastClipRectIsValid = false;
  230475. }
  230476. }
  230477. bool clipRegionIntersects (const Rectangle<int>& r)
  230478. {
  230479. return getClipBounds().intersects (r);
  230480. }
  230481. const Rectangle<int> getClipBounds() const
  230482. {
  230483. if (! lastClipRectIsValid)
  230484. {
  230485. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230486. lastClipRectIsValid = true;
  230487. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230488. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230489. roundToInt (bounds.size.width),
  230490. roundToInt (bounds.size.height));
  230491. }
  230492. return lastClipRect;
  230493. }
  230494. bool isClipEmpty() const
  230495. {
  230496. return getClipBounds().isEmpty();
  230497. }
  230498. void saveState()
  230499. {
  230500. CGContextSaveGState (context);
  230501. stateStack.add (new SavedState (*state));
  230502. }
  230503. void restoreState()
  230504. {
  230505. CGContextRestoreGState (context);
  230506. SavedState* const top = stateStack.getLast();
  230507. if (top != 0)
  230508. {
  230509. state = top;
  230510. stateStack.removeLast (1, false);
  230511. lastClipRectIsValid = false;
  230512. }
  230513. else
  230514. {
  230515. jassertfalse; // trying to pop with an empty stack!
  230516. }
  230517. }
  230518. void setFill (const FillType& fillType)
  230519. {
  230520. state->fillType = fillType;
  230521. if (fillType.isColour())
  230522. {
  230523. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230524. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230525. CGContextSetAlpha (context, 1.0f);
  230526. }
  230527. }
  230528. void setOpacity (float newOpacity)
  230529. {
  230530. state->fillType.setOpacity (newOpacity);
  230531. setFill (state->fillType);
  230532. }
  230533. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230534. {
  230535. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230536. ? kCGInterpolationLow
  230537. : kCGInterpolationHigh);
  230538. }
  230539. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230540. {
  230541. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230542. }
  230543. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230544. {
  230545. if (replaceExistingContents)
  230546. {
  230547. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230548. CGContextClearRect (context, cgRect);
  230549. #else
  230550. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230551. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230552. CGContextClearRect (context, cgRect);
  230553. else
  230554. #endif
  230555. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230556. #endif
  230557. fillCGRect (cgRect, false);
  230558. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230559. }
  230560. else
  230561. {
  230562. if (state->fillType.isColour())
  230563. {
  230564. CGContextFillRect (context, cgRect);
  230565. }
  230566. else if (state->fillType.isGradient())
  230567. {
  230568. CGContextSaveGState (context);
  230569. CGContextClipToRect (context, cgRect);
  230570. drawGradient();
  230571. CGContextRestoreGState (context);
  230572. }
  230573. else
  230574. {
  230575. CGContextSaveGState (context);
  230576. CGContextClipToRect (context, cgRect);
  230577. drawImage (state->fillType.image, state->fillType.transform, true);
  230578. CGContextRestoreGState (context);
  230579. }
  230580. }
  230581. }
  230582. void fillPath (const Path& path, const AffineTransform& transform)
  230583. {
  230584. CGContextSaveGState (context);
  230585. if (state->fillType.isColour())
  230586. {
  230587. flip();
  230588. applyTransform (transform);
  230589. createPath (path);
  230590. if (path.isUsingNonZeroWinding())
  230591. CGContextFillPath (context);
  230592. else
  230593. CGContextEOFillPath (context);
  230594. }
  230595. else
  230596. {
  230597. createPath (path, transform);
  230598. if (path.isUsingNonZeroWinding())
  230599. CGContextClip (context);
  230600. else
  230601. CGContextEOClip (context);
  230602. if (state->fillType.isGradient())
  230603. drawGradient();
  230604. else
  230605. drawImage (state->fillType.image, state->fillType.transform, true);
  230606. }
  230607. CGContextRestoreGState (context);
  230608. }
  230609. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230610. {
  230611. const int iw = sourceImage.getWidth();
  230612. const int ih = sourceImage.getHeight();
  230613. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230614. CGContextSaveGState (context);
  230615. CGContextSetAlpha (context, state->fillType.getOpacity());
  230616. flip();
  230617. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230618. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230619. if (fillEntireClipAsTiles)
  230620. {
  230621. #if JUCE_IOS
  230622. CGContextDrawTiledImage (context, imageRect, image);
  230623. #else
  230624. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230625. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230626. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230627. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230628. CGContextDrawTiledImage (context, imageRect, image);
  230629. else
  230630. #endif
  230631. {
  230632. // Fallback to manually doing a tiled fill on 10.4
  230633. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230634. int x = 0, y = 0;
  230635. while (x > clip.origin.x) x -= iw;
  230636. while (y > clip.origin.y) y -= ih;
  230637. const int right = (int) (clip.origin.x + clip.size.width);
  230638. const int bottom = (int) (clip.origin.y + clip.size.height);
  230639. while (y < bottom)
  230640. {
  230641. for (int x2 = x; x2 < right; x2 += iw)
  230642. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230643. y += ih;
  230644. }
  230645. }
  230646. #endif
  230647. }
  230648. else
  230649. {
  230650. CGContextDrawImage (context, imageRect, image);
  230651. }
  230652. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230653. CGContextRestoreGState (context);
  230654. }
  230655. void drawLine (const Line<float>& line)
  230656. {
  230657. if (state->fillType.isColour())
  230658. {
  230659. CGContextSetLineCap (context, kCGLineCapSquare);
  230660. CGContextSetLineWidth (context, 1.0f);
  230661. CGContextSetRGBStrokeColor (context,
  230662. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230663. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230664. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230665. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230666. CGContextStrokeLineSegments (context, cgLine, 1);
  230667. }
  230668. else
  230669. {
  230670. Path p;
  230671. p.addLineSegment (line, 1.0f);
  230672. fillPath (p, AffineTransform::identity);
  230673. }
  230674. }
  230675. void drawVerticalLine (const int x, float top, float bottom)
  230676. {
  230677. if (state->fillType.isColour())
  230678. {
  230679. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230680. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230681. #else
  230682. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230683. // the x co-ord slightly to trick it..
  230684. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230685. #endif
  230686. }
  230687. else
  230688. {
  230689. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230690. }
  230691. }
  230692. void drawHorizontalLine (const int y, float left, float right)
  230693. {
  230694. if (state->fillType.isColour())
  230695. {
  230696. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230697. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230698. #else
  230699. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230700. // the x co-ord slightly to trick it..
  230701. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230702. #endif
  230703. }
  230704. else
  230705. {
  230706. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230707. }
  230708. }
  230709. void setFont (const Font& newFont)
  230710. {
  230711. if (state->font != newFont)
  230712. {
  230713. state->fontRef = 0;
  230714. state->font = newFont;
  230715. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230716. if (mf != 0)
  230717. {
  230718. state->fontRef = mf->fontRef;
  230719. CGContextSetFont (context, state->fontRef);
  230720. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230721. state->fontTransform = mf->renderingTransform;
  230722. state->fontTransform.a *= state->font.getHorizontalScale();
  230723. CGContextSetTextMatrix (context, state->fontTransform);
  230724. }
  230725. }
  230726. }
  230727. const Font getFont()
  230728. {
  230729. return state->font;
  230730. }
  230731. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230732. {
  230733. if (state->fontRef != 0 && state->fillType.isColour())
  230734. {
  230735. if (transform.isOnlyTranslation())
  230736. {
  230737. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230738. CGGlyph g = glyphNumber;
  230739. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230740. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230741. }
  230742. else
  230743. {
  230744. CGContextSaveGState (context);
  230745. flip();
  230746. applyTransform (transform);
  230747. CGAffineTransform t = state->fontTransform;
  230748. t.d = -t.d;
  230749. CGContextSetTextMatrix (context, t);
  230750. CGGlyph g = glyphNumber;
  230751. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230752. CGContextRestoreGState (context);
  230753. }
  230754. }
  230755. else
  230756. {
  230757. Path p;
  230758. Font& f = state->font;
  230759. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230760. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230761. .followedBy (transform));
  230762. }
  230763. }
  230764. private:
  230765. CGContextRef context;
  230766. const CGFloat flipHeight;
  230767. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230768. CGFunctionCallbacks gradientCallbacks;
  230769. mutable Rectangle<int> lastClipRect;
  230770. mutable bool lastClipRectIsValid;
  230771. struct SavedState
  230772. {
  230773. SavedState()
  230774. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230775. {
  230776. }
  230777. SavedState (const SavedState& other)
  230778. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230779. fontTransform (other.fontTransform)
  230780. {
  230781. }
  230782. ~SavedState()
  230783. {
  230784. }
  230785. FillType fillType;
  230786. Font font;
  230787. CGFontRef fontRef;
  230788. CGAffineTransform fontTransform;
  230789. };
  230790. ScopedPointer <SavedState> state;
  230791. OwnedArray <SavedState> stateStack;
  230792. HeapBlock <PixelARGB> gradientLookupTable;
  230793. int numGradientLookupEntries;
  230794. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230795. {
  230796. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230797. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230798. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230799. colour.unpremultiply();
  230800. outData[0] = colour.getRed() / 255.0f;
  230801. outData[1] = colour.getGreen() / 255.0f;
  230802. outData[2] = colour.getBlue() / 255.0f;
  230803. outData[3] = colour.getAlpha() / 255.0f;
  230804. }
  230805. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230806. {
  230807. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  230808. --numGradientLookupEntries;
  230809. CGShadingRef result = 0;
  230810. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230811. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230812. if (gradient.isRadial)
  230813. {
  230814. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230815. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230816. function, true, true);
  230817. }
  230818. else
  230819. {
  230820. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230821. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230822. function, true, true);
  230823. }
  230824. CGFunctionRelease (function);
  230825. return result;
  230826. }
  230827. void drawGradient()
  230828. {
  230829. flip();
  230830. applyTransform (state->fillType.transform);
  230831. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230832. // you draw a gradient with high quality interp enabled).
  230833. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230834. CGContextSetAlpha (context, state->fillType.getOpacity());
  230835. CGContextDrawShading (context, shading);
  230836. CGShadingRelease (shading);
  230837. }
  230838. void createPath (const Path& path) const
  230839. {
  230840. CGContextBeginPath (context);
  230841. Path::Iterator i (path);
  230842. while (i.next())
  230843. {
  230844. switch (i.elementType)
  230845. {
  230846. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230847. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230848. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230849. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230850. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230851. default: jassertfalse; break;
  230852. }
  230853. }
  230854. }
  230855. void createPath (const Path& path, const AffineTransform& transform) const
  230856. {
  230857. CGContextBeginPath (context);
  230858. Path::Iterator i (path);
  230859. while (i.next())
  230860. {
  230861. switch (i.elementType)
  230862. {
  230863. case Path::Iterator::startNewSubPath:
  230864. transform.transformPoint (i.x1, i.y1);
  230865. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230866. break;
  230867. case Path::Iterator::lineTo:
  230868. transform.transformPoint (i.x1, i.y1);
  230869. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230870. break;
  230871. case Path::Iterator::quadraticTo:
  230872. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230873. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230874. break;
  230875. case Path::Iterator::cubicTo:
  230876. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230877. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230878. break;
  230879. case Path::Iterator::closePath:
  230880. CGContextClosePath (context); break;
  230881. default:
  230882. jassertfalse;
  230883. break;
  230884. }
  230885. }
  230886. }
  230887. void flip() const
  230888. {
  230889. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230890. }
  230891. void applyTransform (const AffineTransform& transform) const
  230892. {
  230893. CGAffineTransform t;
  230894. t.a = transform.mat00;
  230895. t.b = transform.mat10;
  230896. t.c = transform.mat01;
  230897. t.d = transform.mat11;
  230898. t.tx = transform.mat02;
  230899. t.ty = transform.mat12;
  230900. CGContextConcatCTM (context, t);
  230901. }
  230902. CoreGraphicsContext (const CoreGraphicsContext&);
  230903. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  230904. };
  230905. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230906. {
  230907. return new CoreGraphicsContext (context, height);
  230908. }
  230909. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230910. const Image juce_loadWithCoreImage (InputStream& input)
  230911. {
  230912. MemoryBlock data;
  230913. input.readIntoMemoryBlock (data, -1);
  230914. #if JUCE_IOS
  230915. JUCE_AUTORELEASEPOOL
  230916. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  230917. length: data.getSize()
  230918. freeWhenDone: NO]];
  230919. if (image != nil)
  230920. {
  230921. CGImageRef loadedImage = image.CGImage;
  230922. #else
  230923. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230924. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230925. CGDataProviderRelease (provider);
  230926. if (imageSource != 0)
  230927. {
  230928. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230929. CFRelease (imageSource);
  230930. #endif
  230931. if (loadedImage != 0)
  230932. {
  230933. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  230934. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  230935. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  230936. hasAlphaChan, Image::NativeImage);
  230937. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  230938. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  230939. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  230940. CGContextFlush (cgImage->context);
  230941. #if ! JUCE_IOS
  230942. CFRelease (loadedImage);
  230943. #endif
  230944. return image;
  230945. }
  230946. }
  230947. return Image::null;
  230948. }
  230949. #endif
  230950. #endif
  230951. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230952. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230953. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230954. // compiled on its own).
  230955. #if JUCE_INCLUDED_FILE
  230956. class NSViewComponentPeer;
  230957. END_JUCE_NAMESPACE
  230958. @interface NSEvent (JuceDeviceDelta)
  230959. - (float) deviceDeltaX;
  230960. - (float) deviceDeltaY;
  230961. @end
  230962. #define JuceNSView MakeObjCClassName(JuceNSView)
  230963. @interface JuceNSView : NSView<NSTextInput>
  230964. {
  230965. @public
  230966. NSViewComponentPeer* owner;
  230967. NSNotificationCenter* notificationCenter;
  230968. String* stringBeingComposed;
  230969. bool textWasInserted;
  230970. }
  230971. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230972. - (void) dealloc;
  230973. - (BOOL) isOpaque;
  230974. - (void) drawRect: (NSRect) r;
  230975. - (void) mouseDown: (NSEvent*) ev;
  230976. - (void) asyncMouseDown: (NSEvent*) ev;
  230977. - (void) mouseUp: (NSEvent*) ev;
  230978. - (void) asyncMouseUp: (NSEvent*) ev;
  230979. - (void) mouseDragged: (NSEvent*) ev;
  230980. - (void) mouseMoved: (NSEvent*) ev;
  230981. - (void) mouseEntered: (NSEvent*) ev;
  230982. - (void) mouseExited: (NSEvent*) ev;
  230983. - (void) rightMouseDown: (NSEvent*) ev;
  230984. - (void) rightMouseDragged: (NSEvent*) ev;
  230985. - (void) rightMouseUp: (NSEvent*) ev;
  230986. - (void) otherMouseDown: (NSEvent*) ev;
  230987. - (void) otherMouseDragged: (NSEvent*) ev;
  230988. - (void) otherMouseUp: (NSEvent*) ev;
  230989. - (void) scrollWheel: (NSEvent*) ev;
  230990. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230991. - (void) frameChanged: (NSNotification*) n;
  230992. - (void) viewDidMoveToWindow;
  230993. - (void) keyDown: (NSEvent*) ev;
  230994. - (void) keyUp: (NSEvent*) ev;
  230995. // NSTextInput Methods
  230996. - (void) insertText: (id) aString;
  230997. - (void) doCommandBySelector: (SEL) aSelector;
  230998. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  230999. - (void) unmarkText;
  231000. - (BOOL) hasMarkedText;
  231001. - (long) conversationIdentifier;
  231002. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  231003. - (NSRange) markedRange;
  231004. - (NSRange) selectedRange;
  231005. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  231006. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  231007. - (NSArray*) validAttributesForMarkedText;
  231008. - (void) flagsChanged: (NSEvent*) ev;
  231009. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231010. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  231011. #endif
  231012. - (BOOL) becomeFirstResponder;
  231013. - (BOOL) resignFirstResponder;
  231014. - (BOOL) acceptsFirstResponder;
  231015. - (void) asyncRepaint: (id) rect;
  231016. - (NSArray*) getSupportedDragTypes;
  231017. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  231018. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  231019. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  231020. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  231021. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  231022. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  231023. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  231024. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  231025. @end
  231026. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  231027. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231028. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  231029. #else
  231030. @interface JuceNSWindow : NSWindow
  231031. #endif
  231032. {
  231033. @private
  231034. NSViewComponentPeer* owner;
  231035. bool isZooming;
  231036. }
  231037. - (void) setOwner: (NSViewComponentPeer*) owner;
  231038. - (BOOL) canBecomeKeyWindow;
  231039. - (void) becomeKeyWindow;
  231040. - (BOOL) windowShouldClose: (id) window;
  231041. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  231042. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  231043. - (void) zoom: (id) sender;
  231044. @end
  231045. BEGIN_JUCE_NAMESPACE
  231046. class NSViewComponentPeer : public ComponentPeer
  231047. {
  231048. public:
  231049. NSViewComponentPeer (Component* const component,
  231050. const int windowStyleFlags,
  231051. NSView* viewToAttachTo);
  231052. ~NSViewComponentPeer();
  231053. void* getNativeHandle() const;
  231054. void setVisible (bool shouldBeVisible);
  231055. void setTitle (const String& title);
  231056. void setPosition (int x, int y);
  231057. void setSize (int w, int h);
  231058. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  231059. const Rectangle<int> getBounds (const bool global) const;
  231060. const Rectangle<int> getBounds() const;
  231061. const Point<int> getScreenPosition() const;
  231062. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  231063. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  231064. void setMinimised (bool shouldBeMinimised);
  231065. bool isMinimised() const;
  231066. void setFullScreen (bool shouldBeFullScreen);
  231067. bool isFullScreen() const;
  231068. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  231069. const BorderSize getFrameSize() const;
  231070. bool setAlwaysOnTop (bool alwaysOnTop);
  231071. void toFront (bool makeActiveWindow);
  231072. void toBehind (ComponentPeer* other);
  231073. void setIcon (const Image& newIcon);
  231074. const StringArray getAvailableRenderingEngines();
  231075. int getCurrentRenderingEngine() throw();
  231076. void setCurrentRenderingEngine (int index);
  231077. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  231078. for example having more than one juce plugin loaded into a host, then when a
  231079. method is called, the actual code that runs might actually be in a different module
  231080. than the one you expect... So any calls to library functions or statics that are
  231081. made inside obj-c methods will probably end up getting executed in a different DLL's
  231082. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  231083. To work around this insanity, I'm only allowing obj-c methods to make calls to
  231084. virtual methods of an object that's known to live inside the right module's space.
  231085. */
  231086. virtual void redirectMouseDown (NSEvent* ev);
  231087. virtual void redirectMouseUp (NSEvent* ev);
  231088. virtual void redirectMouseDrag (NSEvent* ev);
  231089. virtual void redirectMouseMove (NSEvent* ev);
  231090. virtual void redirectMouseEnter (NSEvent* ev);
  231091. virtual void redirectMouseExit (NSEvent* ev);
  231092. virtual void redirectMouseWheel (NSEvent* ev);
  231093. void sendMouseEvent (NSEvent* ev);
  231094. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  231095. virtual bool redirectKeyDown (NSEvent* ev);
  231096. virtual bool redirectKeyUp (NSEvent* ev);
  231097. virtual void redirectModKeyChange (NSEvent* ev);
  231098. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231099. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  231100. #endif
  231101. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  231102. virtual bool isOpaque();
  231103. virtual void drawRect (NSRect r);
  231104. virtual bool canBecomeKeyWindow();
  231105. virtual bool windowShouldClose();
  231106. virtual void redirectMovedOrResized();
  231107. virtual void viewMovedToWindow();
  231108. virtual NSRect constrainRect (NSRect r);
  231109. static void showArrowCursorIfNeeded();
  231110. static void updateModifiers (NSEvent* e);
  231111. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  231112. static int getKeyCodeFromEvent (NSEvent* ev)
  231113. {
  231114. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231115. int keyCode = unmodified[0];
  231116. if (keyCode == 0x19) // (backwards-tab)
  231117. keyCode = '\t';
  231118. else if (keyCode == 0x03) // (enter)
  231119. keyCode = '\r';
  231120. else
  231121. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  231122. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  231123. {
  231124. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  231125. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  231126. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  231127. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  231128. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  231129. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  231130. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  231131. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  231132. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  231133. if (keyCode == numPadConversions [i])
  231134. keyCode = numPadConversions [i + 1];
  231135. }
  231136. return keyCode;
  231137. }
  231138. static int64 getMouseTime (NSEvent* e)
  231139. {
  231140. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  231141. + (int64) ([e timestamp] * 1000.0);
  231142. }
  231143. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  231144. {
  231145. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  231146. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  231147. }
  231148. static int getModifierForButtonNumber (const NSInteger num)
  231149. {
  231150. return num == 0 ? ModifierKeys::leftButtonModifier
  231151. : (num == 1 ? ModifierKeys::rightButtonModifier
  231152. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  231153. }
  231154. virtual void viewFocusGain();
  231155. virtual void viewFocusLoss();
  231156. bool isFocused() const;
  231157. void grabFocus();
  231158. void textInputRequired (const Point<int>& position);
  231159. void repaint (const Rectangle<int>& area);
  231160. void performAnyPendingRepaintsNow();
  231161. juce_UseDebuggingNewOperator
  231162. NSWindow* window;
  231163. JuceNSView* view;
  231164. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  231165. static ModifierKeys currentModifiers;
  231166. static ComponentPeer* currentlyFocusedPeer;
  231167. static Array<int> keysCurrentlyDown;
  231168. };
  231169. END_JUCE_NAMESPACE
  231170. @implementation JuceNSView
  231171. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  231172. withFrame: (NSRect) frame
  231173. {
  231174. [super initWithFrame: frame];
  231175. owner = owner_;
  231176. stringBeingComposed = 0;
  231177. textWasInserted = false;
  231178. notificationCenter = [NSNotificationCenter defaultCenter];
  231179. [notificationCenter addObserver: self
  231180. selector: @selector (frameChanged:)
  231181. name: NSViewFrameDidChangeNotification
  231182. object: self];
  231183. if (! owner_->isSharedWindow)
  231184. {
  231185. [notificationCenter addObserver: self
  231186. selector: @selector (frameChanged:)
  231187. name: NSWindowDidMoveNotification
  231188. object: owner_->window];
  231189. }
  231190. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  231191. return self;
  231192. }
  231193. - (void) dealloc
  231194. {
  231195. [notificationCenter removeObserver: self];
  231196. delete stringBeingComposed;
  231197. [super dealloc];
  231198. }
  231199. - (void) drawRect: (NSRect) r
  231200. {
  231201. if (owner != 0)
  231202. owner->drawRect (r);
  231203. }
  231204. - (BOOL) isOpaque
  231205. {
  231206. return owner == 0 || owner->isOpaque();
  231207. }
  231208. - (void) mouseDown: (NSEvent*) ev
  231209. {
  231210. if (JUCEApplication::isStandaloneApp())
  231211. [self asyncMouseDown: ev];
  231212. else
  231213. // In some host situations, the host will stop modal loops from working
  231214. // correctly if they're called from a mouse event, so we'll trigger
  231215. // the event asynchronously..
  231216. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  231217. withObject: ev
  231218. waitUntilDone: NO];
  231219. }
  231220. - (void) asyncMouseDown: (NSEvent*) ev
  231221. {
  231222. if (owner != 0)
  231223. owner->redirectMouseDown (ev);
  231224. }
  231225. - (void) mouseUp: (NSEvent*) ev
  231226. {
  231227. if (! JUCEApplication::isStandaloneApp())
  231228. [self asyncMouseUp: ev];
  231229. else
  231230. // In some host situations, the host will stop modal loops from working
  231231. // correctly if they're called from a mouse event, so we'll trigger
  231232. // the event asynchronously..
  231233. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  231234. withObject: ev
  231235. waitUntilDone: NO];
  231236. }
  231237. - (void) asyncMouseUp: (NSEvent*) ev
  231238. {
  231239. if (owner != 0)
  231240. owner->redirectMouseUp (ev);
  231241. }
  231242. - (void) mouseDragged: (NSEvent*) ev
  231243. {
  231244. if (owner != 0)
  231245. owner->redirectMouseDrag (ev);
  231246. }
  231247. - (void) mouseMoved: (NSEvent*) ev
  231248. {
  231249. if (owner != 0)
  231250. owner->redirectMouseMove (ev);
  231251. }
  231252. - (void) mouseEntered: (NSEvent*) ev
  231253. {
  231254. if (owner != 0)
  231255. owner->redirectMouseEnter (ev);
  231256. }
  231257. - (void) mouseExited: (NSEvent*) ev
  231258. {
  231259. if (owner != 0)
  231260. owner->redirectMouseExit (ev);
  231261. }
  231262. - (void) rightMouseDown: (NSEvent*) ev
  231263. {
  231264. [self mouseDown: ev];
  231265. }
  231266. - (void) rightMouseDragged: (NSEvent*) ev
  231267. {
  231268. [self mouseDragged: ev];
  231269. }
  231270. - (void) rightMouseUp: (NSEvent*) ev
  231271. {
  231272. [self mouseUp: ev];
  231273. }
  231274. - (void) otherMouseDown: (NSEvent*) ev
  231275. {
  231276. [self mouseDown: ev];
  231277. }
  231278. - (void) otherMouseDragged: (NSEvent*) ev
  231279. {
  231280. [self mouseDragged: ev];
  231281. }
  231282. - (void) otherMouseUp: (NSEvent*) ev
  231283. {
  231284. [self mouseUp: ev];
  231285. }
  231286. - (void) scrollWheel: (NSEvent*) ev
  231287. {
  231288. if (owner != 0)
  231289. owner->redirectMouseWheel (ev);
  231290. }
  231291. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231292. {
  231293. (void) ev;
  231294. return YES;
  231295. }
  231296. - (void) frameChanged: (NSNotification*) n
  231297. {
  231298. (void) n;
  231299. if (owner != 0)
  231300. owner->redirectMovedOrResized();
  231301. }
  231302. - (void) viewDidMoveToWindow
  231303. {
  231304. if (owner != 0)
  231305. owner->viewMovedToWindow();
  231306. }
  231307. - (void) asyncRepaint: (id) rect
  231308. {
  231309. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231310. [self setNeedsDisplayInRect: *r];
  231311. }
  231312. - (void) keyDown: (NSEvent*) ev
  231313. {
  231314. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231315. textWasInserted = false;
  231316. if (target != 0)
  231317. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231318. else
  231319. deleteAndZero (stringBeingComposed);
  231320. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231321. [super keyDown: ev];
  231322. }
  231323. - (void) keyUp: (NSEvent*) ev
  231324. {
  231325. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231326. [super keyUp: ev];
  231327. }
  231328. - (void) insertText: (id) aString
  231329. {
  231330. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231331. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231332. if ([newText length] > 0)
  231333. {
  231334. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231335. if (target != 0)
  231336. {
  231337. target->insertTextAtCaret (nsStringToJuce (newText));
  231338. textWasInserted = true;
  231339. }
  231340. }
  231341. deleteAndZero (stringBeingComposed);
  231342. }
  231343. - (void) doCommandBySelector: (SEL) aSelector
  231344. {
  231345. (void) aSelector;
  231346. }
  231347. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231348. {
  231349. (void) selectionRange;
  231350. if (stringBeingComposed == 0)
  231351. stringBeingComposed = new String();
  231352. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231353. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231354. if (target != 0)
  231355. {
  231356. const Range<int> currentHighlight (target->getHighlightedRegion());
  231357. target->insertTextAtCaret (*stringBeingComposed);
  231358. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231359. textWasInserted = true;
  231360. }
  231361. }
  231362. - (void) unmarkText
  231363. {
  231364. if (stringBeingComposed != 0)
  231365. {
  231366. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231367. if (target != 0)
  231368. {
  231369. target->insertTextAtCaret (*stringBeingComposed);
  231370. textWasInserted = true;
  231371. }
  231372. }
  231373. deleteAndZero (stringBeingComposed);
  231374. }
  231375. - (BOOL) hasMarkedText
  231376. {
  231377. return stringBeingComposed != 0;
  231378. }
  231379. - (long) conversationIdentifier
  231380. {
  231381. return (long) (pointer_sized_int) self;
  231382. }
  231383. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231384. {
  231385. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231386. if (target != 0)
  231387. {
  231388. const Range<int> r ((int) theRange.location,
  231389. (int) (theRange.location + theRange.length));
  231390. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231391. }
  231392. return nil;
  231393. }
  231394. - (NSRange) markedRange
  231395. {
  231396. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231397. : NSMakeRange (NSNotFound, 0);
  231398. }
  231399. - (NSRange) selectedRange
  231400. {
  231401. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231402. if (target != 0)
  231403. {
  231404. const Range<int> highlight (target->getHighlightedRegion());
  231405. if (! highlight.isEmpty())
  231406. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231407. }
  231408. return NSMakeRange (NSNotFound, 0);
  231409. }
  231410. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231411. {
  231412. (void) theRange;
  231413. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231414. if (comp == 0)
  231415. return NSMakeRect (0, 0, 0, 0);
  231416. const Rectangle<int> bounds (comp->getScreenBounds());
  231417. return NSMakeRect (bounds.getX(),
  231418. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231419. bounds.getWidth(),
  231420. bounds.getHeight());
  231421. }
  231422. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231423. {
  231424. (void) thePoint;
  231425. return NSNotFound;
  231426. }
  231427. - (NSArray*) validAttributesForMarkedText
  231428. {
  231429. return [NSArray array];
  231430. }
  231431. - (void) flagsChanged: (NSEvent*) ev
  231432. {
  231433. if (owner != 0)
  231434. owner->redirectModKeyChange (ev);
  231435. }
  231436. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231437. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231438. {
  231439. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231440. return true;
  231441. return [super performKeyEquivalent: ev];
  231442. }
  231443. #endif
  231444. - (BOOL) becomeFirstResponder
  231445. {
  231446. if (owner != 0)
  231447. owner->viewFocusGain();
  231448. return true;
  231449. }
  231450. - (BOOL) resignFirstResponder
  231451. {
  231452. if (owner != 0)
  231453. owner->viewFocusLoss();
  231454. return true;
  231455. }
  231456. - (BOOL) acceptsFirstResponder
  231457. {
  231458. return owner != 0 && owner->canBecomeKeyWindow();
  231459. }
  231460. - (NSArray*) getSupportedDragTypes
  231461. {
  231462. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  231463. }
  231464. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231465. {
  231466. return owner != 0 && owner->sendDragCallback (type, sender);
  231467. }
  231468. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231469. {
  231470. if ([self sendDragCallback: 0 sender: sender])
  231471. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231472. else
  231473. return NSDragOperationNone;
  231474. }
  231475. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231476. {
  231477. if ([self sendDragCallback: 0 sender: sender])
  231478. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231479. else
  231480. return NSDragOperationNone;
  231481. }
  231482. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231483. {
  231484. [self sendDragCallback: 1 sender: sender];
  231485. }
  231486. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231487. {
  231488. [self sendDragCallback: 1 sender: sender];
  231489. }
  231490. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231491. {
  231492. (void) sender;
  231493. return YES;
  231494. }
  231495. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231496. {
  231497. return [self sendDragCallback: 2 sender: sender];
  231498. }
  231499. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231500. {
  231501. (void) sender;
  231502. }
  231503. @end
  231504. @implementation JuceNSWindow
  231505. - (void) setOwner: (NSViewComponentPeer*) owner_
  231506. {
  231507. owner = owner_;
  231508. isZooming = false;
  231509. }
  231510. - (BOOL) canBecomeKeyWindow
  231511. {
  231512. return owner != 0 && owner->canBecomeKeyWindow();
  231513. }
  231514. - (void) becomeKeyWindow
  231515. {
  231516. [super becomeKeyWindow];
  231517. if (owner != 0)
  231518. owner->grabFocus();
  231519. }
  231520. - (BOOL) windowShouldClose: (id) window
  231521. {
  231522. (void) window;
  231523. return owner == 0 || owner->windowShouldClose();
  231524. }
  231525. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231526. {
  231527. (void) screen;
  231528. if (owner != 0)
  231529. frameRect = owner->constrainRect (frameRect);
  231530. return frameRect;
  231531. }
  231532. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231533. {
  231534. (void) window;
  231535. if (isZooming)
  231536. return proposedFrameSize;
  231537. NSRect frameRect = [self frame];
  231538. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231539. frameRect.size = proposedFrameSize;
  231540. if (owner != 0)
  231541. frameRect = owner->constrainRect (frameRect);
  231542. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231543. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231544. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231545. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231546. return frameRect.size;
  231547. }
  231548. - (void) zoom: (id) sender
  231549. {
  231550. isZooming = true;
  231551. [super zoom: sender];
  231552. isZooming = false;
  231553. }
  231554. - (void) windowWillMove: (NSNotification*) notification
  231555. {
  231556. (void) notification;
  231557. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231558. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231559. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231560. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231561. }
  231562. @end
  231563. BEGIN_JUCE_NAMESPACE
  231564. ModifierKeys NSViewComponentPeer::currentModifiers;
  231565. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231566. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231567. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231568. {
  231569. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231570. return true;
  231571. if (keyCode >= 'A' && keyCode <= 'Z'
  231572. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231573. return true;
  231574. if (keyCode >= 'a' && keyCode <= 'z'
  231575. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231576. return true;
  231577. return false;
  231578. }
  231579. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231580. {
  231581. int m = 0;
  231582. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231583. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231584. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231585. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231586. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231587. }
  231588. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231589. {
  231590. updateModifiers (ev);
  231591. int keyCode = getKeyCodeFromEvent (ev);
  231592. if (keyCode != 0)
  231593. {
  231594. if (isKeyDown)
  231595. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231596. else
  231597. keysCurrentlyDown.removeValue (keyCode);
  231598. }
  231599. }
  231600. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231601. {
  231602. return NSViewComponentPeer::currentModifiers;
  231603. }
  231604. void ModifierKeys::updateCurrentModifiers() throw()
  231605. {
  231606. currentModifiers = NSViewComponentPeer::currentModifiers;
  231607. }
  231608. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231609. const int windowStyleFlags,
  231610. NSView* viewToAttachTo)
  231611. : ComponentPeer (component_, windowStyleFlags),
  231612. window (0),
  231613. view (0),
  231614. isSharedWindow (viewToAttachTo != 0),
  231615. fullScreen (false),
  231616. insideDrawRect (false),
  231617. #if USE_COREGRAPHICS_RENDERING
  231618. usingCoreGraphics (true),
  231619. #else
  231620. usingCoreGraphics (false),
  231621. #endif
  231622. recursiveToFrontCall (false)
  231623. {
  231624. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  231625. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231626. [view setPostsFrameChangedNotifications: YES];
  231627. if (isSharedWindow)
  231628. {
  231629. window = [viewToAttachTo window];
  231630. [viewToAttachTo addSubview: view];
  231631. setVisible (component->isVisible());
  231632. }
  231633. else
  231634. {
  231635. r.origin.x = (float) component->getX();
  231636. r.origin.y = (float) component->getY();
  231637. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231638. unsigned int style = 0;
  231639. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231640. style = NSBorderlessWindowMask;
  231641. else
  231642. style = NSTitledWindowMask;
  231643. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231644. style |= NSMiniaturizableWindowMask;
  231645. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231646. style |= NSClosableWindowMask;
  231647. if ((windowStyleFlags & windowIsResizable) != 0)
  231648. style |= NSResizableWindowMask;
  231649. window = [[JuceNSWindow alloc] initWithContentRect: r
  231650. styleMask: style
  231651. backing: NSBackingStoreBuffered
  231652. defer: YES];
  231653. [((JuceNSWindow*) window) setOwner: this];
  231654. [window orderOut: nil];
  231655. [window setDelegate: (JuceNSWindow*) window];
  231656. [window setOpaque: component->isOpaque()];
  231657. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231658. if (component->isAlwaysOnTop())
  231659. [window setLevel: NSFloatingWindowLevel];
  231660. [window setContentView: view];
  231661. [window setAutodisplay: YES];
  231662. [window setAcceptsMouseMovedEvents: YES];
  231663. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231664. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231665. [window setReleasedWhenClosed: YES];
  231666. [window retain];
  231667. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231668. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231669. }
  231670. setTitle (component->getName());
  231671. }
  231672. NSViewComponentPeer::~NSViewComponentPeer()
  231673. {
  231674. view->owner = 0;
  231675. [view removeFromSuperview];
  231676. [view release];
  231677. if (! isSharedWindow)
  231678. {
  231679. [((JuceNSWindow*) window) setOwner: 0];
  231680. [window close];
  231681. [window release];
  231682. }
  231683. }
  231684. void* NSViewComponentPeer::getNativeHandle() const
  231685. {
  231686. return view;
  231687. }
  231688. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231689. {
  231690. if (isSharedWindow)
  231691. {
  231692. [view setHidden: ! shouldBeVisible];
  231693. }
  231694. else
  231695. {
  231696. if (shouldBeVisible)
  231697. {
  231698. [window orderFront: nil];
  231699. handleBroughtToFront();
  231700. }
  231701. else
  231702. {
  231703. [window orderOut: nil];
  231704. }
  231705. }
  231706. }
  231707. void NSViewComponentPeer::setTitle (const String& title)
  231708. {
  231709. const ScopedAutoReleasePool pool;
  231710. if (! isSharedWindow)
  231711. [window setTitle: juceStringToNS (title)];
  231712. }
  231713. void NSViewComponentPeer::setPosition (int x, int y)
  231714. {
  231715. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231716. }
  231717. void NSViewComponentPeer::setSize (int w, int h)
  231718. {
  231719. setBounds (component->getX(), component->getY(), w, h, false);
  231720. }
  231721. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231722. {
  231723. fullScreen = isNowFullScreen;
  231724. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  231725. if (isSharedWindow)
  231726. {
  231727. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231728. if ([view frame].size.width != r.size.width
  231729. || [view frame].size.height != r.size.height)
  231730. [view setNeedsDisplay: true];
  231731. [view setFrame: r];
  231732. }
  231733. else
  231734. {
  231735. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231736. [window setFrame: [window frameRectForContentRect: r]
  231737. display: true];
  231738. }
  231739. }
  231740. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231741. {
  231742. NSRect r = [view frame];
  231743. if (global && [view window] != 0)
  231744. {
  231745. r = [view convertRect: r toView: nil];
  231746. NSRect wr = [[view window] frame];
  231747. r.origin.x += wr.origin.x;
  231748. r.origin.y += wr.origin.y;
  231749. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231750. }
  231751. else
  231752. {
  231753. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231754. }
  231755. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  231756. }
  231757. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231758. {
  231759. return getBounds (! isSharedWindow);
  231760. }
  231761. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231762. {
  231763. return getBounds (true).getPosition();
  231764. }
  231765. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  231766. {
  231767. return relativePosition + getScreenPosition();
  231768. }
  231769. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  231770. {
  231771. return screenPosition - getScreenPosition();
  231772. }
  231773. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231774. {
  231775. if (constrainer != 0)
  231776. {
  231777. NSRect current = [window frame];
  231778. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231779. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231780. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  231781. (int) r.size.width, (int) r.size.height);
  231782. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  231783. (int) current.size.width, (int) current.size.height);
  231784. constrainer->checkBounds (pos, original,
  231785. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231786. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231787. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231788. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231789. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231790. r.origin.x = pos.getX();
  231791. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231792. r.size.width = pos.getWidth();
  231793. r.size.height = pos.getHeight();
  231794. }
  231795. return r;
  231796. }
  231797. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231798. {
  231799. if (! isSharedWindow)
  231800. {
  231801. if (shouldBeMinimised)
  231802. [window miniaturize: nil];
  231803. else
  231804. [window deminiaturize: nil];
  231805. }
  231806. }
  231807. bool NSViewComponentPeer::isMinimised() const
  231808. {
  231809. return window != 0 && [window isMiniaturized];
  231810. }
  231811. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231812. {
  231813. if (! isSharedWindow)
  231814. {
  231815. Rectangle<int> r (lastNonFullscreenBounds);
  231816. setMinimised (false);
  231817. if (fullScreen != shouldBeFullScreen)
  231818. {
  231819. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231820. {
  231821. fullScreen = true;
  231822. [window performZoom: nil];
  231823. }
  231824. else
  231825. {
  231826. if (shouldBeFullScreen)
  231827. r = Desktop::getInstance().getMainMonitorArea();
  231828. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231829. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231830. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231831. }
  231832. }
  231833. }
  231834. }
  231835. bool NSViewComponentPeer::isFullScreen() const
  231836. {
  231837. return fullScreen;
  231838. }
  231839. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231840. {
  231841. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  231842. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  231843. return false;
  231844. NSPoint p;
  231845. p.x = (float) position.getX();
  231846. p.y = (float) position.getY();
  231847. NSView* v = [view hitTest: p];
  231848. if (trueIfInAChildWindow)
  231849. return v != nil;
  231850. return v == view;
  231851. }
  231852. const BorderSize NSViewComponentPeer::getFrameSize() const
  231853. {
  231854. BorderSize b;
  231855. if (! isSharedWindow)
  231856. {
  231857. NSRect v = [view convertRect: [view frame] toView: nil];
  231858. NSRect w = [window frame];
  231859. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231860. b.setBottom ((int) v.origin.y);
  231861. b.setLeft ((int) v.origin.x);
  231862. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231863. }
  231864. return b;
  231865. }
  231866. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231867. {
  231868. if (! isSharedWindow)
  231869. {
  231870. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231871. : NSNormalWindowLevel];
  231872. }
  231873. return true;
  231874. }
  231875. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231876. {
  231877. if (isSharedWindow)
  231878. {
  231879. [[view superview] addSubview: view
  231880. positioned: NSWindowAbove
  231881. relativeTo: nil];
  231882. }
  231883. if (window != 0 && component->isVisible())
  231884. {
  231885. if (makeActiveWindow)
  231886. [window makeKeyAndOrderFront: nil];
  231887. else
  231888. [window orderFront: nil];
  231889. if (! recursiveToFrontCall)
  231890. {
  231891. recursiveToFrontCall = true;
  231892. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231893. handleBroughtToFront();
  231894. recursiveToFrontCall = false;
  231895. }
  231896. }
  231897. }
  231898. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231899. {
  231900. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231901. jassert (otherPeer != 0); // wrong type of window?
  231902. if (otherPeer != 0)
  231903. {
  231904. if (isSharedWindow)
  231905. {
  231906. [[view superview] addSubview: view
  231907. positioned: NSWindowBelow
  231908. relativeTo: otherPeer->view];
  231909. }
  231910. else
  231911. {
  231912. [window orderWindow: NSWindowBelow
  231913. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231914. : nil ];
  231915. }
  231916. }
  231917. }
  231918. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231919. {
  231920. // to do..
  231921. }
  231922. void NSViewComponentPeer::viewFocusGain()
  231923. {
  231924. if (currentlyFocusedPeer != this)
  231925. {
  231926. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231927. currentlyFocusedPeer->handleFocusLoss();
  231928. currentlyFocusedPeer = this;
  231929. handleFocusGain();
  231930. }
  231931. }
  231932. void NSViewComponentPeer::viewFocusLoss()
  231933. {
  231934. if (currentlyFocusedPeer == this)
  231935. {
  231936. currentlyFocusedPeer = 0;
  231937. handleFocusLoss();
  231938. }
  231939. }
  231940. void juce_HandleProcessFocusChange()
  231941. {
  231942. NSViewComponentPeer::keysCurrentlyDown.clear();
  231943. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231944. {
  231945. if (Process::isForegroundProcess())
  231946. {
  231947. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231948. ComponentPeer::bringModalComponentToFront();
  231949. }
  231950. else
  231951. {
  231952. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231953. // turn kiosk mode off if we lose focus..
  231954. Desktop::getInstance().setKioskModeComponent (0);
  231955. }
  231956. }
  231957. }
  231958. bool NSViewComponentPeer::isFocused() const
  231959. {
  231960. return isSharedWindow ? this == currentlyFocusedPeer
  231961. : (window != 0 && [window isKeyWindow]);
  231962. }
  231963. void NSViewComponentPeer::grabFocus()
  231964. {
  231965. if (window != 0)
  231966. {
  231967. [window makeKeyWindow];
  231968. [window makeFirstResponder: view];
  231969. viewFocusGain();
  231970. }
  231971. }
  231972. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231973. {
  231974. }
  231975. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231976. {
  231977. String unicode (nsStringToJuce ([ev characters]));
  231978. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231979. int keyCode = getKeyCodeFromEvent (ev);
  231980. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231981. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231982. if (unicode.isNotEmpty() || keyCode != 0)
  231983. {
  231984. if (isKeyDown)
  231985. {
  231986. bool used = false;
  231987. while (unicode.length() > 0)
  231988. {
  231989. juce_wchar textCharacter = unicode[0];
  231990. unicode = unicode.substring (1);
  231991. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231992. textCharacter = 0;
  231993. used = handleKeyUpOrDown (true) || used;
  231994. used = handleKeyPress (keyCode, textCharacter) || used;
  231995. }
  231996. return used;
  231997. }
  231998. else
  231999. {
  232000. if (handleKeyUpOrDown (false))
  232001. return true;
  232002. }
  232003. }
  232004. return false;
  232005. }
  232006. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  232007. {
  232008. updateKeysDown (ev, true);
  232009. bool used = handleKeyEvent (ev, true);
  232010. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232011. {
  232012. // for command keys, the key-up event is thrown away, so simulate one..
  232013. updateKeysDown (ev, false);
  232014. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  232015. }
  232016. // (If we're running modally, don't allow unused keystrokes to be passed
  232017. // along to other blocked views..)
  232018. if (Component::getCurrentlyModalComponent() != 0)
  232019. used = true;
  232020. return used;
  232021. }
  232022. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  232023. {
  232024. updateKeysDown (ev, false);
  232025. return handleKeyEvent (ev, false)
  232026. || Component::getCurrentlyModalComponent() != 0;
  232027. }
  232028. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  232029. {
  232030. keysCurrentlyDown.clear();
  232031. handleKeyUpOrDown (true);
  232032. updateModifiers (ev);
  232033. handleModifierKeysChange();
  232034. }
  232035. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  232036. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  232037. {
  232038. if ([ev type] == NSKeyDown)
  232039. return redirectKeyDown (ev);
  232040. else if ([ev type] == NSKeyUp)
  232041. return redirectKeyUp (ev);
  232042. return false;
  232043. }
  232044. #endif
  232045. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  232046. {
  232047. updateModifiers (ev);
  232048. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  232049. }
  232050. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  232051. {
  232052. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232053. sendMouseEvent (ev);
  232054. }
  232055. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  232056. {
  232057. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232058. sendMouseEvent (ev);
  232059. showArrowCursorIfNeeded();
  232060. }
  232061. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  232062. {
  232063. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232064. sendMouseEvent (ev);
  232065. }
  232066. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  232067. {
  232068. currentModifiers = currentModifiers.withoutMouseButtons();
  232069. sendMouseEvent (ev);
  232070. showArrowCursorIfNeeded();
  232071. }
  232072. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  232073. {
  232074. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232075. currentModifiers = currentModifiers.withoutMouseButtons();
  232076. sendMouseEvent (ev);
  232077. }
  232078. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  232079. {
  232080. currentModifiers = currentModifiers.withoutMouseButtons();
  232081. sendMouseEvent (ev);
  232082. }
  232083. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  232084. {
  232085. updateModifiers (ev);
  232086. float x = 0, y = 0;
  232087. @try
  232088. {
  232089. x = [ev deviceDeltaX] * 0.5f;
  232090. y = [ev deviceDeltaY] * 0.5f;
  232091. }
  232092. @catch (...)
  232093. {}
  232094. if (x == 0 && y == 0)
  232095. {
  232096. x = [ev deltaX] * 10.0f;
  232097. y = [ev deltaY] * 10.0f;
  232098. }
  232099. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  232100. }
  232101. void NSViewComponentPeer::showArrowCursorIfNeeded()
  232102. {
  232103. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  232104. if (mouse.getComponentUnderMouse() == 0
  232105. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  232106. {
  232107. [[NSCursor arrowCursor] set];
  232108. }
  232109. }
  232110. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  232111. {
  232112. NSString* bestType
  232113. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  232114. if (bestType == nil)
  232115. return false;
  232116. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  232117. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  232118. StringArray files;
  232119. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  232120. if (list == nil)
  232121. return false;
  232122. if ([list isKindOfClass: [NSArray class]])
  232123. {
  232124. NSArray* items = (NSArray*) list;
  232125. for (unsigned int i = 0; i < [items count]; ++i)
  232126. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  232127. }
  232128. if (files.size() == 0)
  232129. return false;
  232130. if (type == 0)
  232131. handleFileDragMove (files, pos);
  232132. else if (type == 1)
  232133. handleFileDragExit (files);
  232134. else if (type == 2)
  232135. handleFileDragDrop (files, pos);
  232136. return true;
  232137. }
  232138. bool NSViewComponentPeer::isOpaque()
  232139. {
  232140. return component == 0 || component->isOpaque();
  232141. }
  232142. void NSViewComponentPeer::drawRect (NSRect r)
  232143. {
  232144. if (r.size.width < 1.0f || r.size.height < 1.0f)
  232145. return;
  232146. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  232147. if (! component->isOpaque())
  232148. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  232149. #if USE_COREGRAPHICS_RENDERING
  232150. if (usingCoreGraphics)
  232151. {
  232152. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  232153. insideDrawRect = true;
  232154. handlePaint (context);
  232155. insideDrawRect = false;
  232156. }
  232157. else
  232158. #endif
  232159. {
  232160. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  232161. (int) (r.size.width + 0.5f),
  232162. (int) (r.size.height + 0.5f),
  232163. ! getComponent()->isOpaque());
  232164. const int xOffset = -roundToInt (r.origin.x);
  232165. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  232166. const NSRect* rects = 0;
  232167. NSInteger numRects = 0;
  232168. [view getRectsBeingDrawn: &rects count: &numRects];
  232169. const Rectangle<int> clipBounds (temp.getBounds());
  232170. RectangleList clip;
  232171. for (int i = 0; i < numRects; ++i)
  232172. {
  232173. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  232174. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  232175. roundToInt (rects[i].size.width),
  232176. roundToInt (rects[i].size.height))));
  232177. }
  232178. if (! clip.isEmpty())
  232179. {
  232180. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  232181. insideDrawRect = true;
  232182. handlePaint (context);
  232183. insideDrawRect = false;
  232184. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  232185. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  232186. CGColorSpaceRelease (colourSpace);
  232187. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  232188. CGImageRelease (image);
  232189. }
  232190. }
  232191. }
  232192. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  232193. {
  232194. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  232195. #if USE_COREGRAPHICS_RENDERING
  232196. s.add ("CoreGraphics Renderer");
  232197. #endif
  232198. return s;
  232199. }
  232200. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  232201. {
  232202. return usingCoreGraphics ? 1 : 0;
  232203. }
  232204. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  232205. {
  232206. #if USE_COREGRAPHICS_RENDERING
  232207. if (usingCoreGraphics != (index > 0))
  232208. {
  232209. usingCoreGraphics = index > 0;
  232210. [view setNeedsDisplay: true];
  232211. }
  232212. #endif
  232213. }
  232214. bool NSViewComponentPeer::canBecomeKeyWindow()
  232215. {
  232216. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  232217. }
  232218. bool NSViewComponentPeer::windowShouldClose()
  232219. {
  232220. if (! isValidPeer (this))
  232221. return YES;
  232222. handleUserClosingWindow();
  232223. return NO;
  232224. }
  232225. void NSViewComponentPeer::redirectMovedOrResized()
  232226. {
  232227. handleMovedOrResized();
  232228. }
  232229. void NSViewComponentPeer::viewMovedToWindow()
  232230. {
  232231. if (isSharedWindow)
  232232. window = [view window];
  232233. }
  232234. void Desktop::createMouseInputSources()
  232235. {
  232236. mouseSources.add (new MouseInputSource (0, true));
  232237. }
  232238. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232239. {
  232240. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  232241. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  232242. // is apparently still available in 64-bit apps..
  232243. if (enableOrDisable)
  232244. {
  232245. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232246. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232247. }
  232248. else
  232249. {
  232250. SetSystemUIMode (kUIModeNormal, 0);
  232251. }
  232252. }
  232253. class AsyncRepaintMessage : public CallbackMessage
  232254. {
  232255. public:
  232256. NSViewComponentPeer* const peer;
  232257. const Rectangle<int> rect;
  232258. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232259. : peer (peer_), rect (rect_)
  232260. {
  232261. }
  232262. void messageCallback()
  232263. {
  232264. if (ComponentPeer::isValidPeer (peer))
  232265. peer->repaint (rect);
  232266. }
  232267. };
  232268. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232269. {
  232270. if (insideDrawRect)
  232271. {
  232272. (new AsyncRepaintMessage (this, area))->post();
  232273. }
  232274. else
  232275. {
  232276. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232277. (float) area.getWidth(), (float) area.getHeight())];
  232278. }
  232279. }
  232280. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232281. {
  232282. [view displayIfNeeded];
  232283. }
  232284. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232285. {
  232286. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232287. }
  232288. const Image juce_createIconForFile (const File& file)
  232289. {
  232290. const ScopedAutoReleasePool pool;
  232291. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232292. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232293. [NSGraphicsContext saveGraphicsState];
  232294. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232295. [image drawAtPoint: NSMakePoint (0, 0)
  232296. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232297. operation: NSCompositeSourceOver fraction: 1.0f];
  232298. [[NSGraphicsContext currentContext] flushGraphics];
  232299. [NSGraphicsContext restoreGraphicsState];
  232300. return Image (result);
  232301. }
  232302. const int KeyPress::spaceKey = ' ';
  232303. const int KeyPress::returnKey = 0x0d;
  232304. const int KeyPress::escapeKey = 0x1b;
  232305. const int KeyPress::backspaceKey = 0x7f;
  232306. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232307. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232308. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232309. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232310. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232311. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232312. const int KeyPress::endKey = NSEndFunctionKey;
  232313. const int KeyPress::homeKey = NSHomeFunctionKey;
  232314. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232315. const int KeyPress::insertKey = -1;
  232316. const int KeyPress::tabKey = 9;
  232317. const int KeyPress::F1Key = NSF1FunctionKey;
  232318. const int KeyPress::F2Key = NSF2FunctionKey;
  232319. const int KeyPress::F3Key = NSF3FunctionKey;
  232320. const int KeyPress::F4Key = NSF4FunctionKey;
  232321. const int KeyPress::F5Key = NSF5FunctionKey;
  232322. const int KeyPress::F6Key = NSF6FunctionKey;
  232323. const int KeyPress::F7Key = NSF7FunctionKey;
  232324. const int KeyPress::F8Key = NSF8FunctionKey;
  232325. const int KeyPress::F9Key = NSF9FunctionKey;
  232326. const int KeyPress::F10Key = NSF10FunctionKey;
  232327. const int KeyPress::F11Key = NSF1FunctionKey;
  232328. const int KeyPress::F12Key = NSF12FunctionKey;
  232329. const int KeyPress::F13Key = NSF13FunctionKey;
  232330. const int KeyPress::F14Key = NSF14FunctionKey;
  232331. const int KeyPress::F15Key = NSF15FunctionKey;
  232332. const int KeyPress::F16Key = NSF16FunctionKey;
  232333. const int KeyPress::numberPad0 = 0x30020;
  232334. const int KeyPress::numberPad1 = 0x30021;
  232335. const int KeyPress::numberPad2 = 0x30022;
  232336. const int KeyPress::numberPad3 = 0x30023;
  232337. const int KeyPress::numberPad4 = 0x30024;
  232338. const int KeyPress::numberPad5 = 0x30025;
  232339. const int KeyPress::numberPad6 = 0x30026;
  232340. const int KeyPress::numberPad7 = 0x30027;
  232341. const int KeyPress::numberPad8 = 0x30028;
  232342. const int KeyPress::numberPad9 = 0x30029;
  232343. const int KeyPress::numberPadAdd = 0x3002a;
  232344. const int KeyPress::numberPadSubtract = 0x3002b;
  232345. const int KeyPress::numberPadMultiply = 0x3002c;
  232346. const int KeyPress::numberPadDivide = 0x3002d;
  232347. const int KeyPress::numberPadSeparator = 0x3002e;
  232348. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232349. const int KeyPress::numberPadEquals = 0x30030;
  232350. const int KeyPress::numberPadDelete = 0x30031;
  232351. const int KeyPress::playKey = 0x30000;
  232352. const int KeyPress::stopKey = 0x30001;
  232353. const int KeyPress::fastForwardKey = 0x30002;
  232354. const int KeyPress::rewindKey = 0x30003;
  232355. #endif
  232356. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232357. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232358. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232359. // compiled on its own).
  232360. #if JUCE_INCLUDED_FILE
  232361. #if JUCE_MAC
  232362. namespace MouseCursorHelpers
  232363. {
  232364. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232365. {
  232366. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232367. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232368. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232369. [im release];
  232370. return c;
  232371. }
  232372. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232373. {
  232374. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232375. BufferedInputStream buf (&fileStream, 4096, false);
  232376. PNGImageFormat pngFormat;
  232377. Image im (pngFormat.decodeImage (buf));
  232378. if (im.isValid())
  232379. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232380. jassertfalse;
  232381. return 0;
  232382. }
  232383. }
  232384. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232385. {
  232386. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232387. }
  232388. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232389. {
  232390. const ScopedAutoReleasePool pool;
  232391. NSCursor* c = 0;
  232392. switch (type)
  232393. {
  232394. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232395. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232396. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232397. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232398. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232399. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232400. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232401. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232402. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232403. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232404. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232405. case UpDownResizeCursor:
  232406. case TopEdgeResizeCursor:
  232407. case BottomEdgeResizeCursor:
  232408. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232409. case TopLeftCornerResizeCursor:
  232410. case BottomRightCornerResizeCursor:
  232411. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232412. case TopRightCornerResizeCursor:
  232413. case BottomLeftCornerResizeCursor:
  232414. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232415. case UpDownLeftRightResizeCursor:
  232416. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232417. default:
  232418. jassertfalse;
  232419. break;
  232420. }
  232421. [c retain];
  232422. return c;
  232423. }
  232424. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232425. {
  232426. [((NSCursor*) cursorHandle) release];
  232427. }
  232428. void MouseCursor::showInAllWindows() const
  232429. {
  232430. showInWindow (0);
  232431. }
  232432. void MouseCursor::showInWindow (ComponentPeer*) const
  232433. {
  232434. [((NSCursor*) getHandle()) set];
  232435. }
  232436. #else
  232437. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232438. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232439. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232440. void MouseCursor::showInAllWindows() const {}
  232441. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232442. #endif
  232443. #endif
  232444. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232445. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232446. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232447. // compiled on its own).
  232448. #if JUCE_INCLUDED_FILE
  232449. class NSViewComponentInternal : public ComponentMovementWatcher
  232450. {
  232451. Component* const owner;
  232452. NSViewComponentPeer* currentPeer;
  232453. bool wasShowing;
  232454. public:
  232455. NSView* const view;
  232456. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  232457. : ComponentMovementWatcher (owner_),
  232458. owner (owner_),
  232459. currentPeer (0),
  232460. wasShowing (false),
  232461. view (view_)
  232462. {
  232463. [view_ retain];
  232464. if (owner_->isShowing())
  232465. componentPeerChanged();
  232466. }
  232467. ~NSViewComponentInternal()
  232468. {
  232469. [view removeFromSuperview];
  232470. [view release];
  232471. }
  232472. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232473. {
  232474. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232475. // The ComponentMovementWatcher version of this method avoids calling
  232476. // us when the top-level comp is resized, but for an NSView we need to know this
  232477. // because with inverted co-ords, we need to update the position even if the
  232478. // top-left pos hasn't changed
  232479. if (comp.isOnDesktop() && wasResized)
  232480. componentMovedOrResized (wasMoved, wasResized);
  232481. }
  232482. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232483. {
  232484. Component* const topComp = owner->getTopLevelComponent();
  232485. if (topComp->getPeer() != 0)
  232486. {
  232487. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  232488. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner->getWidth(), (float) owner->getHeight());
  232489. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232490. [view setFrame: r];
  232491. }
  232492. }
  232493. void componentPeerChanged()
  232494. {
  232495. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  232496. if (currentPeer != peer)
  232497. {
  232498. [view removeFromSuperview];
  232499. currentPeer = peer;
  232500. if (peer != 0)
  232501. {
  232502. [peer->view addSubview: view];
  232503. componentMovedOrResized (false, false);
  232504. }
  232505. }
  232506. [view setHidden: ! owner->isShowing()];
  232507. }
  232508. void componentVisibilityChanged (Component&)
  232509. {
  232510. componentPeerChanged();
  232511. }
  232512. juce_UseDebuggingNewOperator
  232513. private:
  232514. NSViewComponentInternal (const NSViewComponentInternal&);
  232515. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  232516. };
  232517. NSViewComponent::NSViewComponent()
  232518. {
  232519. }
  232520. NSViewComponent::~NSViewComponent()
  232521. {
  232522. }
  232523. void NSViewComponent::setView (void* view)
  232524. {
  232525. if (view != getView())
  232526. {
  232527. if (view != 0)
  232528. info = new NSViewComponentInternal ((NSView*) view, this);
  232529. else
  232530. info = 0;
  232531. }
  232532. }
  232533. void* NSViewComponent::getView() const
  232534. {
  232535. return info == 0 ? 0 : info->view;
  232536. }
  232537. void NSViewComponent::paint (Graphics&)
  232538. {
  232539. }
  232540. #endif
  232541. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232542. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232543. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232544. // compiled on its own).
  232545. #if JUCE_INCLUDED_FILE
  232546. AppleRemoteDevice::AppleRemoteDevice()
  232547. : device (0),
  232548. queue (0),
  232549. remoteId (0)
  232550. {
  232551. }
  232552. AppleRemoteDevice::~AppleRemoteDevice()
  232553. {
  232554. stop();
  232555. }
  232556. static io_object_t getAppleRemoteDevice()
  232557. {
  232558. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232559. io_iterator_t iter = 0;
  232560. io_object_t iod = 0;
  232561. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232562. && iter != 0)
  232563. {
  232564. iod = IOIteratorNext (iter);
  232565. }
  232566. IOObjectRelease (iter);
  232567. return iod;
  232568. }
  232569. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  232570. {
  232571. jassert (*device == 0);
  232572. io_name_t classname;
  232573. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232574. {
  232575. IOCFPlugInInterface** cfPlugInInterface = 0;
  232576. SInt32 score = 0;
  232577. if (IOCreatePlugInInterfaceForService (iod,
  232578. kIOHIDDeviceUserClientTypeID,
  232579. kIOCFPlugInInterfaceID,
  232580. &cfPlugInInterface,
  232581. &score) == kIOReturnSuccess)
  232582. {
  232583. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232584. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232585. device);
  232586. (void) hr;
  232587. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232588. }
  232589. }
  232590. return *device != 0;
  232591. }
  232592. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232593. {
  232594. if (queue != 0)
  232595. return true;
  232596. stop();
  232597. bool result = false;
  232598. io_object_t iod = getAppleRemoteDevice();
  232599. if (iod != 0)
  232600. {
  232601. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232602. result = true;
  232603. else
  232604. stop();
  232605. IOObjectRelease (iod);
  232606. }
  232607. return result;
  232608. }
  232609. void AppleRemoteDevice::stop()
  232610. {
  232611. if (queue != 0)
  232612. {
  232613. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232614. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232615. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232616. queue = 0;
  232617. }
  232618. if (device != 0)
  232619. {
  232620. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232621. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232622. device = 0;
  232623. }
  232624. }
  232625. bool AppleRemoteDevice::isActive() const
  232626. {
  232627. return queue != 0;
  232628. }
  232629. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232630. {
  232631. if (result == kIOReturnSuccess)
  232632. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232633. }
  232634. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232635. {
  232636. Array <int> cookies;
  232637. CFArrayRef elements;
  232638. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232639. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232640. return false;
  232641. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232642. {
  232643. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232644. // get the cookie
  232645. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232646. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232647. continue;
  232648. long number;
  232649. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232650. continue;
  232651. cookies.add ((int) number);
  232652. }
  232653. CFRelease (elements);
  232654. if ((*(IOHIDDeviceInterface**) device)
  232655. ->open ((IOHIDDeviceInterface**) device,
  232656. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232657. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232658. {
  232659. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232660. if (queue != 0)
  232661. {
  232662. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232663. for (int i = 0; i < cookies.size(); ++i)
  232664. {
  232665. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232666. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232667. }
  232668. CFRunLoopSourceRef eventSource;
  232669. if ((*(IOHIDQueueInterface**) queue)
  232670. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232671. {
  232672. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232673. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232674. {
  232675. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232676. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232677. return true;
  232678. }
  232679. }
  232680. }
  232681. }
  232682. return false;
  232683. }
  232684. void AppleRemoteDevice::handleCallbackInternal()
  232685. {
  232686. int totalValues = 0;
  232687. AbsoluteTime nullTime = { 0, 0 };
  232688. char cookies [12];
  232689. int numCookies = 0;
  232690. while (numCookies < numElementsInArray (cookies))
  232691. {
  232692. IOHIDEventStruct e;
  232693. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232694. break;
  232695. if ((int) e.elementCookie == 19)
  232696. {
  232697. remoteId = e.value;
  232698. buttonPressed (switched, false);
  232699. }
  232700. else
  232701. {
  232702. totalValues += e.value;
  232703. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232704. }
  232705. }
  232706. cookies [numCookies++] = 0;
  232707. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232708. static const char buttonPatterns[] =
  232709. {
  232710. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232711. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232712. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232713. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232714. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232715. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232716. 0x1f, 0x12, 0x04, 0x02, 0,
  232717. 0x1f, 0x12, 0x03, 0x02, 0,
  232718. 0x1f, 0x12, 0x1f, 0x12, 0,
  232719. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232720. 19, 0
  232721. };
  232722. int buttonNum = (int) menuButton;
  232723. int i = 0;
  232724. while (i < numElementsInArray (buttonPatterns))
  232725. {
  232726. if (strcmp (cookies, buttonPatterns + i) == 0)
  232727. {
  232728. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232729. break;
  232730. }
  232731. i += (int) strlen (buttonPatterns + i) + 1;
  232732. ++buttonNum;
  232733. }
  232734. }
  232735. #endif
  232736. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232737. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232738. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232739. // compiled on its own).
  232740. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232741. #if JUCE_MAC
  232742. END_JUCE_NAMESPACE
  232743. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232744. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232745. {
  232746. CriticalSection* contextLock;
  232747. bool needsUpdate;
  232748. }
  232749. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232750. - (bool) makeActive;
  232751. - (void) makeInactive;
  232752. - (void) reshape;
  232753. @end
  232754. @implementation ThreadSafeNSOpenGLView
  232755. - (id) initWithFrame: (NSRect) frameRect
  232756. pixelFormat: (NSOpenGLPixelFormat*) format
  232757. {
  232758. contextLock = new CriticalSection();
  232759. self = [super initWithFrame: frameRect pixelFormat: format];
  232760. if (self != nil)
  232761. [[NSNotificationCenter defaultCenter] addObserver: self
  232762. selector: @selector (_surfaceNeedsUpdate:)
  232763. name: NSViewGlobalFrameDidChangeNotification
  232764. object: self];
  232765. return self;
  232766. }
  232767. - (void) dealloc
  232768. {
  232769. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232770. delete contextLock;
  232771. [super dealloc];
  232772. }
  232773. - (bool) makeActive
  232774. {
  232775. const ScopedLock sl (*contextLock);
  232776. if ([self openGLContext] == 0)
  232777. return false;
  232778. [[self openGLContext] makeCurrentContext];
  232779. if (needsUpdate)
  232780. {
  232781. [super update];
  232782. needsUpdate = false;
  232783. }
  232784. return true;
  232785. }
  232786. - (void) makeInactive
  232787. {
  232788. const ScopedLock sl (*contextLock);
  232789. [NSOpenGLContext clearCurrentContext];
  232790. }
  232791. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232792. {
  232793. const ScopedLock sl (*contextLock);
  232794. needsUpdate = true;
  232795. }
  232796. - (void) update
  232797. {
  232798. const ScopedLock sl (*contextLock);
  232799. needsUpdate = true;
  232800. }
  232801. - (void) reshape
  232802. {
  232803. const ScopedLock sl (*contextLock);
  232804. needsUpdate = true;
  232805. }
  232806. @end
  232807. BEGIN_JUCE_NAMESPACE
  232808. class WindowedGLContext : public OpenGLContext
  232809. {
  232810. public:
  232811. WindowedGLContext (Component* const component,
  232812. const OpenGLPixelFormat& pixelFormat_,
  232813. NSOpenGLContext* sharedContext)
  232814. : renderContext (0),
  232815. pixelFormat (pixelFormat_)
  232816. {
  232817. jassert (component != 0);
  232818. NSOpenGLPixelFormatAttribute attribs [64];
  232819. int n = 0;
  232820. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232821. attribs[n++] = NSOpenGLPFAAccelerated;
  232822. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232823. attribs[n++] = NSOpenGLPFAColorSize;
  232824. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232825. pixelFormat.greenBits,
  232826. pixelFormat.blueBits);
  232827. attribs[n++] = NSOpenGLPFAAlphaSize;
  232828. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232829. attribs[n++] = NSOpenGLPFADepthSize;
  232830. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232831. attribs[n++] = NSOpenGLPFAStencilSize;
  232832. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232833. attribs[n++] = NSOpenGLPFAAccumSize;
  232834. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232835. pixelFormat.accumulationBufferGreenBits,
  232836. pixelFormat.accumulationBufferBlueBits,
  232837. pixelFormat.accumulationBufferAlphaBits);
  232838. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232839. attribs[n++] = NSOpenGLPFASampleBuffers;
  232840. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232841. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232842. attribs[n++] = NSOpenGLPFANoRecovery;
  232843. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232844. NSOpenGLPixelFormat* format
  232845. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232846. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232847. pixelFormat: format];
  232848. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232849. shareContext: sharedContext] autorelease];
  232850. const GLint swapInterval = 1;
  232851. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232852. [view setOpenGLContext: renderContext];
  232853. [format release];
  232854. viewHolder = new NSViewComponentInternal (view, component);
  232855. }
  232856. ~WindowedGLContext()
  232857. {
  232858. deleteContext();
  232859. viewHolder = 0;
  232860. }
  232861. void deleteContext()
  232862. {
  232863. makeInactive();
  232864. [renderContext clearDrawable];
  232865. [renderContext setView: nil];
  232866. [view setOpenGLContext: nil];
  232867. renderContext = nil;
  232868. }
  232869. bool makeActive() const throw()
  232870. {
  232871. jassert (renderContext != 0);
  232872. if ([renderContext view] != view)
  232873. [renderContext setView: view];
  232874. [view makeActive];
  232875. return isActive();
  232876. }
  232877. bool makeInactive() const throw()
  232878. {
  232879. [view makeInactive];
  232880. return true;
  232881. }
  232882. bool isActive() const throw()
  232883. {
  232884. return [NSOpenGLContext currentContext] == renderContext;
  232885. }
  232886. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232887. void* getRawContext() const throw() { return renderContext; }
  232888. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232889. {
  232890. }
  232891. void swapBuffers()
  232892. {
  232893. [renderContext flushBuffer];
  232894. }
  232895. bool setSwapInterval (const int numFramesPerSwap)
  232896. {
  232897. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232898. forParameter: NSOpenGLCPSwapInterval];
  232899. return true;
  232900. }
  232901. int getSwapInterval() const
  232902. {
  232903. GLint numFrames = 0;
  232904. [renderContext getValues: &numFrames
  232905. forParameter: NSOpenGLCPSwapInterval];
  232906. return numFrames;
  232907. }
  232908. void repaint()
  232909. {
  232910. // we need to invalidate the juce view that holds this gl view, to make it
  232911. // cause a repaint callback
  232912. NSView* v = (NSView*) viewHolder->view;
  232913. NSRect r = [v frame];
  232914. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232915. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232916. // repaint message, thus never causing our paint() callback, and never repainting
  232917. // the comp. So invalidating just a little bit around the edge helps..
  232918. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232919. }
  232920. void* getNativeWindowHandle() const { return viewHolder->view; }
  232921. juce_UseDebuggingNewOperator
  232922. NSOpenGLContext* renderContext;
  232923. ThreadSafeNSOpenGLView* view;
  232924. private:
  232925. OpenGLPixelFormat pixelFormat;
  232926. ScopedPointer <NSViewComponentInternal> viewHolder;
  232927. WindowedGLContext (const WindowedGLContext&);
  232928. WindowedGLContext& operator= (const WindowedGLContext&);
  232929. };
  232930. OpenGLContext* OpenGLComponent::createContext()
  232931. {
  232932. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  232933. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232934. return (c->renderContext != 0) ? c.release() : 0;
  232935. }
  232936. void* OpenGLComponent::getNativeWindowHandle() const
  232937. {
  232938. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232939. : 0;
  232940. }
  232941. void juce_glViewport (const int w, const int h)
  232942. {
  232943. glViewport (0, 0, w, h);
  232944. }
  232945. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232946. OwnedArray <OpenGLPixelFormat>& results)
  232947. {
  232948. /* GLint attribs [64];
  232949. int n = 0;
  232950. attribs[n++] = AGL_RGBA;
  232951. attribs[n++] = AGL_DOUBLEBUFFER;
  232952. attribs[n++] = AGL_ACCELERATED;
  232953. attribs[n++] = AGL_NO_RECOVERY;
  232954. attribs[n++] = AGL_NONE;
  232955. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  232956. while (p != 0)
  232957. {
  232958. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232959. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  232960. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  232961. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  232962. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  232963. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  232964. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  232965. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  232966. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  232967. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  232968. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  232969. results.add (pf);
  232970. p = aglNextPixelFormat (p);
  232971. }*/
  232972. //jassertfalse // can't see how you do this in cocoa!
  232973. }
  232974. #else
  232975. END_JUCE_NAMESPACE
  232976. @interface JuceGLView : UIView
  232977. {
  232978. }
  232979. + (Class) layerClass;
  232980. @end
  232981. @implementation JuceGLView
  232982. + (Class) layerClass
  232983. {
  232984. return [CAEAGLLayer class];
  232985. }
  232986. @end
  232987. BEGIN_JUCE_NAMESPACE
  232988. class GLESContext : public OpenGLContext
  232989. {
  232990. public:
  232991. GLESContext (UIViewComponentPeer* peer,
  232992. Component* const component_,
  232993. const OpenGLPixelFormat& pixelFormat_,
  232994. const GLESContext* const sharedContext,
  232995. NSUInteger apiType)
  232996. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  232997. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  232998. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  232999. {
  233000. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  233001. view.opaque = YES;
  233002. view.hidden = NO;
  233003. view.backgroundColor = [UIColor blackColor];
  233004. view.userInteractionEnabled = NO;
  233005. glLayer = (CAEAGLLayer*) [view layer];
  233006. [peer->view addSubview: view];
  233007. if (sharedContext != 0)
  233008. context = [[EAGLContext alloc] initWithAPI: apiType
  233009. sharegroup: [sharedContext->context sharegroup]];
  233010. else
  233011. context = [[EAGLContext alloc] initWithAPI: apiType];
  233012. createGLBuffers();
  233013. }
  233014. ~GLESContext()
  233015. {
  233016. deleteContext();
  233017. [view removeFromSuperview];
  233018. [view release];
  233019. freeGLBuffers();
  233020. }
  233021. void deleteContext()
  233022. {
  233023. makeInactive();
  233024. [context release];
  233025. context = nil;
  233026. }
  233027. bool makeActive() const throw()
  233028. {
  233029. jassert (context != 0);
  233030. [EAGLContext setCurrentContext: context];
  233031. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233032. return true;
  233033. }
  233034. void swapBuffers()
  233035. {
  233036. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233037. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  233038. }
  233039. bool makeInactive() const throw()
  233040. {
  233041. return [EAGLContext setCurrentContext: nil];
  233042. }
  233043. bool isActive() const throw()
  233044. {
  233045. return [EAGLContext currentContext] == context;
  233046. }
  233047. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233048. void* getRawContext() const throw() { return glLayer; }
  233049. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233050. {
  233051. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  233052. if (lastWidth != w || lastHeight != h)
  233053. {
  233054. lastWidth = w;
  233055. lastHeight = h;
  233056. freeGLBuffers();
  233057. createGLBuffers();
  233058. }
  233059. }
  233060. bool setSwapInterval (const int numFramesPerSwap)
  233061. {
  233062. numFrames = numFramesPerSwap;
  233063. return true;
  233064. }
  233065. int getSwapInterval() const
  233066. {
  233067. return numFrames;
  233068. }
  233069. void repaint()
  233070. {
  233071. }
  233072. void createGLBuffers()
  233073. {
  233074. makeActive();
  233075. glGenFramebuffersOES (1, &frameBufferHandle);
  233076. glGenRenderbuffersOES (1, &colorBufferHandle);
  233077. glGenRenderbuffersOES (1, &depthBufferHandle);
  233078. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233079. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  233080. GLint width, height;
  233081. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  233082. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  233083. if (useDepthBuffer)
  233084. {
  233085. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  233086. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  233087. }
  233088. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233089. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233090. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  233091. if (useDepthBuffer)
  233092. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  233093. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  233094. }
  233095. void freeGLBuffers()
  233096. {
  233097. if (frameBufferHandle != 0)
  233098. {
  233099. glDeleteFramebuffersOES (1, &frameBufferHandle);
  233100. frameBufferHandle = 0;
  233101. }
  233102. if (colorBufferHandle != 0)
  233103. {
  233104. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  233105. colorBufferHandle = 0;
  233106. }
  233107. if (depthBufferHandle != 0)
  233108. {
  233109. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  233110. depthBufferHandle = 0;
  233111. }
  233112. }
  233113. juce_UseDebuggingNewOperator
  233114. private:
  233115. Component::SafePointer<Component> component;
  233116. OpenGLPixelFormat pixelFormat;
  233117. JuceGLView* view;
  233118. CAEAGLLayer* glLayer;
  233119. EAGLContext* context;
  233120. bool useDepthBuffer;
  233121. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  233122. int numFrames;
  233123. int lastWidth, lastHeight;
  233124. GLESContext (const GLESContext&);
  233125. GLESContext& operator= (const GLESContext&);
  233126. };
  233127. OpenGLContext* OpenGLComponent::createContext()
  233128. {
  233129. ScopedAutoReleasePool pool;
  233130. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  233131. if (peer != 0)
  233132. return new GLESContext (peer, this, preferredPixelFormat,
  233133. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  233134. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  233135. return 0;
  233136. }
  233137. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233138. OwnedArray <OpenGLPixelFormat>& /*results*/)
  233139. {
  233140. }
  233141. void juce_glViewport (const int w, const int h)
  233142. {
  233143. glViewport (0, 0, w, h);
  233144. }
  233145. #endif
  233146. #endif
  233147. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  233148. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  233149. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233150. // compiled on its own).
  233151. #if JUCE_INCLUDED_FILE
  233152. class JuceMainMenuHandler;
  233153. END_JUCE_NAMESPACE
  233154. using namespace JUCE_NAMESPACE;
  233155. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  233156. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233157. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  233158. #else
  233159. @interface JuceMenuCallback : NSObject
  233160. #endif
  233161. {
  233162. JuceMainMenuHandler* owner;
  233163. }
  233164. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  233165. - (void) dealloc;
  233166. - (void) menuItemInvoked: (id) menu;
  233167. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233168. @end
  233169. BEGIN_JUCE_NAMESPACE
  233170. class JuceMainMenuHandler : private MenuBarModel::Listener,
  233171. private DeletedAtShutdown
  233172. {
  233173. public:
  233174. static JuceMainMenuHandler* instance;
  233175. JuceMainMenuHandler()
  233176. : currentModel (0),
  233177. lastUpdateTime (0)
  233178. {
  233179. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  233180. }
  233181. ~JuceMainMenuHandler()
  233182. {
  233183. setMenu (0);
  233184. jassert (instance == this);
  233185. instance = 0;
  233186. [callback release];
  233187. }
  233188. void setMenu (MenuBarModel* const newMenuBarModel)
  233189. {
  233190. if (currentModel != newMenuBarModel)
  233191. {
  233192. if (currentModel != 0)
  233193. currentModel->removeListener (this);
  233194. currentModel = newMenuBarModel;
  233195. if (currentModel != 0)
  233196. currentModel->addListener (this);
  233197. menuBarItemsChanged (0);
  233198. }
  233199. }
  233200. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  233201. const String& name, const int menuId, const int tag)
  233202. {
  233203. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  233204. action: nil
  233205. keyEquivalent: @""];
  233206. [item setTag: tag];
  233207. NSMenu* sub = createMenu (child, name, menuId, tag);
  233208. [parent setSubmenu: sub forItem: item];
  233209. [sub setAutoenablesItems: false];
  233210. [sub release];
  233211. }
  233212. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233213. const String& name, const int menuId, const int tag)
  233214. {
  233215. [parentItem setTag: tag];
  233216. NSMenu* menu = [parentItem submenu];
  233217. [menu setTitle: juceStringToNS (name)];
  233218. while ([menu numberOfItems] > 0)
  233219. [menu removeItemAtIndex: 0];
  233220. PopupMenu::MenuItemIterator iter (menuToCopy);
  233221. while (iter.next())
  233222. addMenuItem (iter, menu, menuId, tag);
  233223. [menu setAutoenablesItems: false];
  233224. [menu update];
  233225. }
  233226. void menuBarItemsChanged (MenuBarModel*)
  233227. {
  233228. lastUpdateTime = Time::getMillisecondCounter();
  233229. StringArray menuNames;
  233230. if (currentModel != 0)
  233231. menuNames = currentModel->getMenuBarNames();
  233232. NSMenu* menuBar = [NSApp mainMenu];
  233233. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233234. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233235. int menuId = 1;
  233236. for (int i = 0; i < menuNames.size(); ++i)
  233237. {
  233238. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233239. if (i >= [menuBar numberOfItems] - 1)
  233240. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233241. else
  233242. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233243. }
  233244. }
  233245. static void flashMenuBar (NSMenu* menu)
  233246. {
  233247. if ([[menu title] isEqualToString: @"Apple"])
  233248. return;
  233249. [menu retain];
  233250. const unichar f35Key = NSF35FunctionKey;
  233251. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233252. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233253. action: nil
  233254. keyEquivalent: f35String];
  233255. [item setTarget: nil];
  233256. [menu insertItem: item atIndex: [menu numberOfItems]];
  233257. [item release];
  233258. if ([menu indexOfItem: item] >= 0)
  233259. {
  233260. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233261. location: NSZeroPoint
  233262. modifierFlags: NSCommandKeyMask
  233263. timestamp: 0
  233264. windowNumber: 0
  233265. context: [NSGraphicsContext currentContext]
  233266. characters: f35String
  233267. charactersIgnoringModifiers: f35String
  233268. isARepeat: NO
  233269. keyCode: 0];
  233270. [menu performKeyEquivalent: f35Event];
  233271. if ([menu indexOfItem: item] >= 0)
  233272. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233273. }
  233274. [menu release];
  233275. }
  233276. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233277. {
  233278. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233279. {
  233280. NSMenuItem* m = [menu itemAtIndex: i];
  233281. if ([m tag] == info.commandID)
  233282. return m;
  233283. if ([m submenu] != 0)
  233284. {
  233285. NSMenuItem* found = findMenuItem ([m submenu], info);
  233286. if (found != 0)
  233287. return found;
  233288. }
  233289. }
  233290. return 0;
  233291. }
  233292. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233293. {
  233294. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233295. if (item != 0)
  233296. flashMenuBar ([item menu]);
  233297. }
  233298. void updateMenus()
  233299. {
  233300. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233301. menuBarItemsChanged (0);
  233302. }
  233303. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233304. {
  233305. if (currentModel != 0)
  233306. {
  233307. if (commandManager != 0)
  233308. {
  233309. ApplicationCommandTarget::InvocationInfo info (commandId);
  233310. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233311. commandManager->invoke (info, true);
  233312. }
  233313. currentModel->menuItemSelected (commandId, topLevelIndex);
  233314. }
  233315. }
  233316. MenuBarModel* currentModel;
  233317. uint32 lastUpdateTime;
  233318. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233319. const int topLevelMenuId, const int topLevelIndex)
  233320. {
  233321. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233322. if (text == 0)
  233323. text = @"";
  233324. if (iter.isSeparator)
  233325. {
  233326. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233327. }
  233328. else if (iter.isSectionHeader)
  233329. {
  233330. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233331. action: nil
  233332. keyEquivalent: @""];
  233333. [item setEnabled: false];
  233334. }
  233335. else if (iter.subMenu != 0)
  233336. {
  233337. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233338. action: nil
  233339. keyEquivalent: @""];
  233340. [item setTag: iter.itemId];
  233341. [item setEnabled: iter.isEnabled];
  233342. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233343. [sub setDelegate: nil];
  233344. [menuToAddTo setSubmenu: sub forItem: item];
  233345. [sub release];
  233346. }
  233347. else
  233348. {
  233349. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233350. action: @selector (menuItemInvoked:)
  233351. keyEquivalent: @""];
  233352. [item setTag: iter.itemId];
  233353. [item setEnabled: iter.isEnabled];
  233354. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233355. [item setTarget: (id) callback];
  233356. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233357. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233358. [item setRepresentedObject: info];
  233359. if (iter.commandManager != 0)
  233360. {
  233361. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233362. ->getKeyPressesAssignedToCommand (iter.itemId));
  233363. if (keyPresses.size() > 0)
  233364. {
  233365. const KeyPress& kp = keyPresses.getReference(0);
  233366. if (kp.getKeyCode() != KeyPress::backspaceKey
  233367. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233368. // every time you press the key while editing text)
  233369. {
  233370. juce_wchar key = kp.getTextCharacter();
  233371. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233372. key = NSBackspaceCharacter;
  233373. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233374. key = NSDeleteCharacter;
  233375. else if (key == 0)
  233376. key = (juce_wchar) kp.getKeyCode();
  233377. unsigned int mods = 0;
  233378. if (kp.getModifiers().isShiftDown())
  233379. mods |= NSShiftKeyMask;
  233380. if (kp.getModifiers().isCtrlDown())
  233381. mods |= NSControlKeyMask;
  233382. if (kp.getModifiers().isAltDown())
  233383. mods |= NSAlternateKeyMask;
  233384. if (kp.getModifiers().isCommandDown())
  233385. mods |= NSCommandKeyMask;
  233386. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233387. [item setKeyEquivalentModifierMask: mods];
  233388. }
  233389. }
  233390. }
  233391. }
  233392. }
  233393. JuceMenuCallback* callback;
  233394. private:
  233395. NSMenu* createMenu (const PopupMenu menu,
  233396. const String& menuName,
  233397. const int topLevelMenuId,
  233398. const int topLevelIndex)
  233399. {
  233400. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233401. [m setAutoenablesItems: false];
  233402. [m setDelegate: callback];
  233403. PopupMenu::MenuItemIterator iter (menu);
  233404. while (iter.next())
  233405. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233406. [m update];
  233407. return m;
  233408. }
  233409. };
  233410. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233411. END_JUCE_NAMESPACE
  233412. @implementation JuceMenuCallback
  233413. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233414. {
  233415. [super init];
  233416. owner = owner_;
  233417. return self;
  233418. }
  233419. - (void) dealloc
  233420. {
  233421. [super dealloc];
  233422. }
  233423. - (void) menuItemInvoked: (id) menu
  233424. {
  233425. NSMenuItem* item = (NSMenuItem*) menu;
  233426. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233427. {
  233428. // 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
  233429. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233430. // into the focused component and let it trigger the menu item indirectly.
  233431. NSEvent* e = [NSApp currentEvent];
  233432. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233433. {
  233434. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233435. {
  233436. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233437. if (peer != 0)
  233438. {
  233439. if ([e type] == NSKeyDown)
  233440. peer->redirectKeyDown (e);
  233441. else
  233442. peer->redirectKeyUp (e);
  233443. return;
  233444. }
  233445. }
  233446. }
  233447. NSArray* info = (NSArray*) [item representedObject];
  233448. owner->invoke ((int) [item tag],
  233449. (ApplicationCommandManager*) (pointer_sized_int)
  233450. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233451. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233452. }
  233453. }
  233454. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233455. {
  233456. (void) menu;
  233457. if (JuceMainMenuHandler::instance != 0)
  233458. JuceMainMenuHandler::instance->updateMenus();
  233459. }
  233460. @end
  233461. BEGIN_JUCE_NAMESPACE
  233462. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  233463. const PopupMenu* extraItems)
  233464. {
  233465. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233466. {
  233467. PopupMenu::MenuItemIterator iter (*extraItems);
  233468. while (iter.next())
  233469. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233470. [menu addItem: [NSMenuItem separatorItem]];
  233471. }
  233472. NSMenuItem* item;
  233473. // Services...
  233474. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233475. action: nil keyEquivalent: @""];
  233476. [menu addItem: item];
  233477. [item release];
  233478. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233479. [menu setSubmenu: servicesMenu forItem: item];
  233480. [NSApp setServicesMenu: servicesMenu];
  233481. [servicesMenu release];
  233482. [menu addItem: [NSMenuItem separatorItem]];
  233483. // Hide + Show stuff...
  233484. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233485. action: @selector (hide:) keyEquivalent: @"h"];
  233486. [item setTarget: NSApp];
  233487. [menu addItem: item];
  233488. [item release];
  233489. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233490. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233491. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233492. [item setTarget: NSApp];
  233493. [menu addItem: item];
  233494. [item release];
  233495. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233496. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233497. [item setTarget: NSApp];
  233498. [menu addItem: item];
  233499. [item release];
  233500. [menu addItem: [NSMenuItem separatorItem]];
  233501. // Quit item....
  233502. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233503. action: @selector (terminate:) keyEquivalent: @"q"];
  233504. [item setTarget: NSApp];
  233505. [menu addItem: item];
  233506. [item release];
  233507. return menu;
  233508. }
  233509. // Since our app has no NIB, this initialises a standard app menu...
  233510. static void rebuildMainMenu (const PopupMenu* extraItems)
  233511. {
  233512. // this can't be used in a plugin!
  233513. jassert (JUCEApplication::isStandaloneApp());
  233514. if (JUCEApplication::getInstance() != 0)
  233515. {
  233516. const ScopedAutoReleasePool pool;
  233517. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233518. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233519. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233520. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233521. [mainMenu setSubmenu: appMenu forItem: item];
  233522. [NSApp setMainMenu: mainMenu];
  233523. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233524. [appMenu release];
  233525. [mainMenu release];
  233526. }
  233527. }
  233528. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233529. const PopupMenu* extraAppleMenuItems)
  233530. {
  233531. if (getMacMainMenu() != newMenuBarModel)
  233532. {
  233533. const ScopedAutoReleasePool pool;
  233534. if (newMenuBarModel == 0)
  233535. {
  233536. delete JuceMainMenuHandler::instance;
  233537. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233538. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233539. extraAppleMenuItems = 0;
  233540. }
  233541. else
  233542. {
  233543. if (JuceMainMenuHandler::instance == 0)
  233544. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233545. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233546. }
  233547. }
  233548. rebuildMainMenu (extraAppleMenuItems);
  233549. if (newMenuBarModel != 0)
  233550. newMenuBarModel->menuItemsChanged();
  233551. }
  233552. MenuBarModel* MenuBarModel::getMacMainMenu()
  233553. {
  233554. return JuceMainMenuHandler::instance != 0
  233555. ? JuceMainMenuHandler::instance->currentModel : 0;
  233556. }
  233557. void juce_initialiseMacMainMenu()
  233558. {
  233559. if (JuceMainMenuHandler::instance == 0)
  233560. rebuildMainMenu (0);
  233561. }
  233562. #endif
  233563. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233564. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233565. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233566. // compiled on its own).
  233567. #if JUCE_INCLUDED_FILE
  233568. #if JUCE_MAC
  233569. END_JUCE_NAMESPACE
  233570. using namespace JUCE_NAMESPACE;
  233571. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233572. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233573. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233574. #else
  233575. @interface JuceFileChooserDelegate : NSObject
  233576. #endif
  233577. {
  233578. StringArray* filters;
  233579. }
  233580. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233581. - (void) dealloc;
  233582. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233583. @end
  233584. @implementation JuceFileChooserDelegate
  233585. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233586. {
  233587. [super init];
  233588. filters = filters_;
  233589. return self;
  233590. }
  233591. - (void) dealloc
  233592. {
  233593. delete filters;
  233594. [super dealloc];
  233595. }
  233596. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233597. {
  233598. (void) sender;
  233599. const File f (nsStringToJuce (filename));
  233600. for (int i = filters->size(); --i >= 0;)
  233601. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233602. return true;
  233603. return f.isDirectory();
  233604. }
  233605. @end
  233606. BEGIN_JUCE_NAMESPACE
  233607. void FileChooser::showPlatformDialog (Array<File>& results,
  233608. const String& title,
  233609. const File& currentFileOrDirectory,
  233610. const String& filter,
  233611. bool selectsDirectory,
  233612. bool selectsFiles,
  233613. bool isSaveDialogue,
  233614. bool warnAboutOverwritingExistingFiles,
  233615. bool selectMultipleFiles,
  233616. FilePreviewComponent* extraInfoComponent)
  233617. {
  233618. const ScopedAutoReleasePool pool;
  233619. StringArray* filters = new StringArray();
  233620. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233621. filters->trim();
  233622. filters->removeEmptyStrings();
  233623. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233624. [delegate autorelease];
  233625. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233626. : [NSOpenPanel openPanel];
  233627. [panel setTitle: juceStringToNS (title)];
  233628. if (! isSaveDialogue)
  233629. {
  233630. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233631. [openPanel setCanChooseDirectories: selectsDirectory];
  233632. [openPanel setCanChooseFiles: selectsFiles];
  233633. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233634. }
  233635. [panel setDelegate: delegate];
  233636. if (isSaveDialogue || selectsDirectory)
  233637. [panel setCanCreateDirectories: YES];
  233638. String directory, filename;
  233639. if (currentFileOrDirectory.isDirectory())
  233640. {
  233641. directory = currentFileOrDirectory.getFullPathName();
  233642. }
  233643. else
  233644. {
  233645. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233646. filename = currentFileOrDirectory.getFileName();
  233647. }
  233648. if ([panel runModalForDirectory: juceStringToNS (directory)
  233649. file: juceStringToNS (filename)]
  233650. == NSOKButton)
  233651. {
  233652. if (isSaveDialogue)
  233653. {
  233654. results.add (File (nsStringToJuce ([panel filename])));
  233655. }
  233656. else
  233657. {
  233658. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233659. NSArray* urls = [openPanel filenames];
  233660. for (unsigned int i = 0; i < [urls count]; ++i)
  233661. {
  233662. NSString* f = [urls objectAtIndex: i];
  233663. results.add (File (nsStringToJuce (f)));
  233664. }
  233665. }
  233666. }
  233667. [panel setDelegate: nil];
  233668. }
  233669. #else
  233670. void FileChooser::showPlatformDialog (Array<File>& results,
  233671. const String& title,
  233672. const File& currentFileOrDirectory,
  233673. const String& filter,
  233674. bool selectsDirectory,
  233675. bool selectsFiles,
  233676. bool isSaveDialogue,
  233677. bool warnAboutOverwritingExistingFiles,
  233678. bool selectMultipleFiles,
  233679. FilePreviewComponent* extraInfoComponent)
  233680. {
  233681. const ScopedAutoReleasePool pool;
  233682. jassertfalse; //xxx to do
  233683. }
  233684. #endif
  233685. #endif
  233686. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233687. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233688. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233689. // compiled on its own).
  233690. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233691. END_JUCE_NAMESPACE
  233692. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233693. @interface NonInterceptingQTMovieView : QTMovieView
  233694. {
  233695. }
  233696. - (id) initWithFrame: (NSRect) frame;
  233697. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233698. - (NSView*) hitTest: (NSPoint) p;
  233699. @end
  233700. @implementation NonInterceptingQTMovieView
  233701. - (id) initWithFrame: (NSRect) frame
  233702. {
  233703. self = [super initWithFrame: frame];
  233704. [self setNextResponder: [self superview]];
  233705. return self;
  233706. }
  233707. - (void) dealloc
  233708. {
  233709. [super dealloc];
  233710. }
  233711. - (NSView*) hitTest: (NSPoint) point
  233712. {
  233713. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233714. }
  233715. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233716. {
  233717. return YES;
  233718. }
  233719. @end
  233720. BEGIN_JUCE_NAMESPACE
  233721. #define theMovie (static_cast <QTMovie*> (movie))
  233722. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233723. : movie (0)
  233724. {
  233725. setOpaque (true);
  233726. setVisible (true);
  233727. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233728. setView (view);
  233729. [view release];
  233730. }
  233731. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233732. {
  233733. closeMovie();
  233734. setView (0);
  233735. }
  233736. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233737. {
  233738. return true;
  233739. }
  233740. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233741. {
  233742. // unfortunately, QTMovie objects can only be created on the main thread..
  233743. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233744. QTMovie* movie = 0;
  233745. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233746. if (fin != 0)
  233747. {
  233748. movieFile = fin->getFile();
  233749. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233750. error: nil];
  233751. }
  233752. else
  233753. {
  233754. MemoryBlock temp;
  233755. movieStream->readIntoMemoryBlock (temp);
  233756. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233757. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233758. {
  233759. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233760. length: temp.getSize()]
  233761. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233762. MIMEType: @""]
  233763. error: nil];
  233764. if (movie != 0)
  233765. break;
  233766. }
  233767. }
  233768. return movie;
  233769. }
  233770. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233771. const bool isControllerVisible_)
  233772. {
  233773. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233774. }
  233775. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233776. const bool controllerVisible_)
  233777. {
  233778. closeMovie();
  233779. if (getPeer() == 0)
  233780. {
  233781. // To open a movie, this component must be visible inside a functioning window, so that
  233782. // the QT control can be assigned to the window.
  233783. jassertfalse;
  233784. return false;
  233785. }
  233786. movie = openMovieFromStream (movieStream, movieFile);
  233787. [theMovie retain];
  233788. QTMovieView* view = (QTMovieView*) getView();
  233789. [view setMovie: theMovie];
  233790. [view setControllerVisible: controllerVisible_];
  233791. setLooping (looping);
  233792. return movie != nil;
  233793. }
  233794. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233795. const bool isControllerVisible_)
  233796. {
  233797. // unfortunately, QTMovie objects can only be created on the main thread..
  233798. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233799. closeMovie();
  233800. if (getPeer() == 0)
  233801. {
  233802. // To open a movie, this component must be visible inside a functioning window, so that
  233803. // the QT control can be assigned to the window.
  233804. jassertfalse;
  233805. return false;
  233806. }
  233807. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233808. NSError* err;
  233809. if ([QTMovie canInitWithURL: url])
  233810. movie = [QTMovie movieWithURL: url error: &err];
  233811. [theMovie retain];
  233812. QTMovieView* view = (QTMovieView*) getView();
  233813. [view setMovie: theMovie];
  233814. [view setControllerVisible: controllerVisible];
  233815. setLooping (looping);
  233816. return movie != nil;
  233817. }
  233818. void QuickTimeMovieComponent::closeMovie()
  233819. {
  233820. stop();
  233821. QTMovieView* view = (QTMovieView*) getView();
  233822. [view setMovie: nil];
  233823. [theMovie release];
  233824. movie = 0;
  233825. movieFile = File::nonexistent;
  233826. }
  233827. bool QuickTimeMovieComponent::isMovieOpen() const
  233828. {
  233829. return movie != nil;
  233830. }
  233831. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233832. {
  233833. return movieFile;
  233834. }
  233835. void QuickTimeMovieComponent::play()
  233836. {
  233837. [theMovie play];
  233838. }
  233839. void QuickTimeMovieComponent::stop()
  233840. {
  233841. [theMovie stop];
  233842. }
  233843. bool QuickTimeMovieComponent::isPlaying() const
  233844. {
  233845. return movie != 0 && [theMovie rate] != 0;
  233846. }
  233847. void QuickTimeMovieComponent::setPosition (const double seconds)
  233848. {
  233849. if (movie != 0)
  233850. {
  233851. QTTime t;
  233852. t.timeValue = (uint64) (100000.0 * seconds);
  233853. t.timeScale = 100000;
  233854. t.flags = 0;
  233855. [theMovie setCurrentTime: t];
  233856. }
  233857. }
  233858. double QuickTimeMovieComponent::getPosition() const
  233859. {
  233860. if (movie == 0)
  233861. return 0.0;
  233862. QTTime t = [theMovie currentTime];
  233863. return t.timeValue / (double) t.timeScale;
  233864. }
  233865. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233866. {
  233867. [theMovie setRate: newSpeed];
  233868. }
  233869. double QuickTimeMovieComponent::getMovieDuration() const
  233870. {
  233871. if (movie == 0)
  233872. return 0.0;
  233873. QTTime t = [theMovie duration];
  233874. return t.timeValue / (double) t.timeScale;
  233875. }
  233876. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233877. {
  233878. looping = shouldLoop;
  233879. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233880. forKey: QTMovieLoopsAttribute];
  233881. }
  233882. bool QuickTimeMovieComponent::isLooping() const
  233883. {
  233884. return looping;
  233885. }
  233886. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233887. {
  233888. [theMovie setVolume: newVolume];
  233889. }
  233890. float QuickTimeMovieComponent::getMovieVolume() const
  233891. {
  233892. return movie != 0 ? [theMovie volume] : 0.0f;
  233893. }
  233894. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233895. {
  233896. width = 0;
  233897. height = 0;
  233898. if (movie != 0)
  233899. {
  233900. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233901. width = (int) s.width;
  233902. height = (int) s.height;
  233903. }
  233904. }
  233905. void QuickTimeMovieComponent::paint (Graphics& g)
  233906. {
  233907. if (movie == 0)
  233908. g.fillAll (Colours::black);
  233909. }
  233910. bool QuickTimeMovieComponent::isControllerVisible() const
  233911. {
  233912. return controllerVisible;
  233913. }
  233914. void QuickTimeMovieComponent::goToStart()
  233915. {
  233916. setPosition (0.0);
  233917. }
  233918. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233919. const RectanglePlacement& placement)
  233920. {
  233921. int normalWidth, normalHeight;
  233922. getMovieNormalSize (normalWidth, normalHeight);
  233923. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  233924. {
  233925. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  233926. placement.applyTo (x, y, w, h,
  233927. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  233928. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  233929. if (w > 0 && h > 0)
  233930. {
  233931. setBounds (roundToInt (x), roundToInt (y),
  233932. roundToInt (w), roundToInt (h));
  233933. }
  233934. }
  233935. else
  233936. {
  233937. setBounds (spaceToFitWithin);
  233938. }
  233939. }
  233940. #if ! (JUCE_MAC && JUCE_64BIT)
  233941. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233942. {
  233943. if (movieStream == 0)
  233944. return false;
  233945. File file;
  233946. QTMovie* movie = openMovieFromStream (movieStream, file);
  233947. if (movie != nil)
  233948. result = [movie quickTimeMovie];
  233949. return movie != nil;
  233950. }
  233951. #endif
  233952. #endif
  233953. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233954. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233955. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233956. // compiled on its own).
  233957. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233958. const int kilobytesPerSecond1x = 176;
  233959. END_JUCE_NAMESPACE
  233960. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233961. @interface OpenDiskDevice : NSObject
  233962. {
  233963. @public
  233964. DRDevice* device;
  233965. NSMutableArray* tracks;
  233966. bool underrunProtection;
  233967. }
  233968. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233969. - (void) dealloc;
  233970. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233971. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233972. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233973. @end
  233974. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233975. @interface AudioTrackProducer : NSObject
  233976. {
  233977. JUCE_NAMESPACE::AudioSource* source;
  233978. int readPosition, lengthInFrames;
  233979. }
  233980. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233981. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233982. - (void) dealloc;
  233983. - (void) setupTrackProperties: (DRTrack*) track;
  233984. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233985. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233986. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233987. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233988. toMedia:(NSDictionary*)mediaInfo;
  233989. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233990. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233991. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233992. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233993. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233994. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233995. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233996. ioFlags:(uint32_t*)flags;
  233997. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  233998. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233999. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234000. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234001. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234002. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234003. ioFlags:(uint32_t*)flags;
  234004. @end
  234005. @implementation OpenDiskDevice
  234006. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  234007. {
  234008. [super init];
  234009. device = device_;
  234010. tracks = [[NSMutableArray alloc] init];
  234011. underrunProtection = true;
  234012. return self;
  234013. }
  234014. - (void) dealloc
  234015. {
  234016. [tracks release];
  234017. [super dealloc];
  234018. }
  234019. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  234020. {
  234021. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  234022. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  234023. [p setupTrackProperties: t];
  234024. [tracks addObject: t];
  234025. [t release];
  234026. [p release];
  234027. }
  234028. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234029. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  234030. {
  234031. DRBurn* burn = [DRBurn burnForDevice: device];
  234032. if (! [device acquireExclusiveAccess])
  234033. {
  234034. *error = "Couldn't open or write to the CD device";
  234035. return;
  234036. }
  234037. [device acquireMediaReservation];
  234038. NSMutableDictionary* d = [[burn properties] mutableCopy];
  234039. [d autorelease];
  234040. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  234041. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  234042. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  234043. if (burnSpeed > 0)
  234044. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  234045. if (! underrunProtection)
  234046. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  234047. [burn setProperties: d];
  234048. [burn writeLayout: tracks];
  234049. for (;;)
  234050. {
  234051. JUCE_NAMESPACE::Thread::sleep (300);
  234052. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  234053. if (listener != 0 && listener->audioCDBurnProgress (progress))
  234054. {
  234055. [burn abort];
  234056. *error = "User cancelled the write operation";
  234057. break;
  234058. }
  234059. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  234060. {
  234061. *error = "Write operation failed";
  234062. break;
  234063. }
  234064. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  234065. {
  234066. break;
  234067. }
  234068. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  234069. objectForKey: DRErrorStatusErrorStringKey];
  234070. if ([err length] > 0)
  234071. {
  234072. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  234073. break;
  234074. }
  234075. }
  234076. [device releaseMediaReservation];
  234077. [device releaseExclusiveAccess];
  234078. }
  234079. @end
  234080. @implementation AudioTrackProducer
  234081. - (AudioTrackProducer*) init: (int) lengthInFrames_
  234082. {
  234083. lengthInFrames = lengthInFrames_;
  234084. readPosition = 0;
  234085. return self;
  234086. }
  234087. - (void) setupTrackProperties: (DRTrack*) track
  234088. {
  234089. NSMutableDictionary* p = [[track properties] mutableCopy];
  234090. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  234091. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  234092. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  234093. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  234094. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  234095. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  234096. [track setProperties: p];
  234097. [p release];
  234098. }
  234099. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  234100. {
  234101. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  234102. if (s != nil)
  234103. s->source = source_;
  234104. return s;
  234105. }
  234106. - (void) dealloc
  234107. {
  234108. if (source != 0)
  234109. {
  234110. source->releaseResources();
  234111. delete source;
  234112. }
  234113. [super dealloc];
  234114. }
  234115. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  234116. {
  234117. }
  234118. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  234119. {
  234120. return true;
  234121. }
  234122. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  234123. {
  234124. return lengthInFrames;
  234125. }
  234126. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  234127. toMedia: (NSDictionary*) mediaInfo
  234128. {
  234129. if (source != 0)
  234130. source->prepareToPlay (44100 / 75, 44100);
  234131. readPosition = 0;
  234132. return true;
  234133. }
  234134. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  234135. {
  234136. if (source != 0)
  234137. source->prepareToPlay (44100 / 75, 44100);
  234138. return true;
  234139. }
  234140. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  234141. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234142. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234143. {
  234144. if (source != 0)
  234145. {
  234146. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  234147. if (numSamples > 0)
  234148. {
  234149. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  234150. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  234151. info.buffer = &tempBuffer;
  234152. info.startSample = 0;
  234153. info.numSamples = numSamples;
  234154. source->getNextAudioBlock (info);
  234155. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  234156. JUCE_NAMESPACE::AudioData::LittleEndian,
  234157. JUCE_NAMESPACE::AudioData::Interleaved,
  234158. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  234159. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  234160. JUCE_NAMESPACE::AudioData::NativeEndian,
  234161. JUCE_NAMESPACE::AudioData::NonInterleaved,
  234162. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  234163. CDSampleFormat left (buffer, 2);
  234164. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  234165. CDSampleFormat right (buffer + 2, 2);
  234166. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  234167. readPosition += numSamples;
  234168. }
  234169. return numSamples * 4;
  234170. }
  234171. return 0;
  234172. }
  234173. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  234174. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  234175. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  234176. ioFlags: (uint32_t*) flags
  234177. {
  234178. zeromem (buffer, bufferLength);
  234179. return bufferLength;
  234180. }
  234181. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  234182. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234183. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234184. {
  234185. return true;
  234186. }
  234187. @end
  234188. BEGIN_JUCE_NAMESPACE
  234189. class AudioCDBurner::Pimpl : public Timer
  234190. {
  234191. public:
  234192. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  234193. : device (0), owner (owner_)
  234194. {
  234195. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  234196. if (dev != 0)
  234197. {
  234198. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  234199. lastState = getDiskState();
  234200. startTimer (1000);
  234201. }
  234202. }
  234203. ~Pimpl()
  234204. {
  234205. stopTimer();
  234206. [device release];
  234207. }
  234208. void timerCallback()
  234209. {
  234210. const DiskState state = getDiskState();
  234211. if (state != lastState)
  234212. {
  234213. lastState = state;
  234214. owner.sendChangeMessage (&owner);
  234215. }
  234216. }
  234217. DiskState getDiskState() const
  234218. {
  234219. if ([device->device isValid])
  234220. {
  234221. NSDictionary* status = [device->device status];
  234222. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234223. if ([state isEqualTo: DRDeviceMediaStateNone])
  234224. {
  234225. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234226. return trayOpen;
  234227. return noDisc;
  234228. }
  234229. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234230. {
  234231. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234232. return writableDiskPresent;
  234233. else
  234234. return readOnlyDiskPresent;
  234235. }
  234236. }
  234237. return unknown;
  234238. }
  234239. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234240. const Array<int> getAvailableWriteSpeeds() const
  234241. {
  234242. Array<int> results;
  234243. if ([device->device isValid])
  234244. {
  234245. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234246. for (unsigned int i = 0; i < [speeds count]; ++i)
  234247. {
  234248. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234249. results.add (kbPerSec / kilobytesPerSecond1x);
  234250. }
  234251. }
  234252. return results;
  234253. }
  234254. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234255. {
  234256. if ([device->device isValid])
  234257. {
  234258. device->underrunProtection = shouldBeEnabled;
  234259. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234260. }
  234261. return false;
  234262. }
  234263. int getNumAvailableAudioBlocks() const
  234264. {
  234265. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234266. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234267. }
  234268. OpenDiskDevice* device;
  234269. private:
  234270. DiskState lastState;
  234271. AudioCDBurner& owner;
  234272. };
  234273. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234274. {
  234275. pimpl = new Pimpl (*this, deviceIndex);
  234276. }
  234277. AudioCDBurner::~AudioCDBurner()
  234278. {
  234279. }
  234280. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234281. {
  234282. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234283. if (b->pimpl->device == 0)
  234284. b = 0;
  234285. return b.release();
  234286. }
  234287. static NSArray* findDiskBurnerDevices()
  234288. {
  234289. NSMutableArray* results = [NSMutableArray array];
  234290. NSArray* devs = [DRDevice devices];
  234291. if (devs != 0)
  234292. {
  234293. int num = [devs count];
  234294. int i;
  234295. for (i = 0; i < num; ++i)
  234296. {
  234297. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234298. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234299. if (name != nil)
  234300. [results addObject: name];
  234301. }
  234302. }
  234303. return results;
  234304. }
  234305. const StringArray AudioCDBurner::findAvailableDevices()
  234306. {
  234307. NSArray* names = findDiskBurnerDevices();
  234308. StringArray s;
  234309. for (unsigned int i = 0; i < [names count]; ++i)
  234310. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234311. return s;
  234312. }
  234313. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234314. {
  234315. return pimpl->getDiskState();
  234316. }
  234317. bool AudioCDBurner::isDiskPresent() const
  234318. {
  234319. return getDiskState() == writableDiskPresent;
  234320. }
  234321. bool AudioCDBurner::openTray()
  234322. {
  234323. return pimpl->openTray();
  234324. }
  234325. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234326. {
  234327. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234328. DiskState oldState = getDiskState();
  234329. DiskState newState = oldState;
  234330. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234331. {
  234332. newState = getDiskState();
  234333. Thread::sleep (100);
  234334. }
  234335. return newState;
  234336. }
  234337. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234338. {
  234339. return pimpl->getAvailableWriteSpeeds();
  234340. }
  234341. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234342. {
  234343. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234344. }
  234345. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234346. {
  234347. return pimpl->getNumAvailableAudioBlocks();
  234348. }
  234349. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234350. {
  234351. if ([pimpl->device->device isValid])
  234352. {
  234353. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234354. return true;
  234355. }
  234356. return false;
  234357. }
  234358. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234359. bool ejectDiscAfterwards,
  234360. bool performFakeBurnForTesting,
  234361. int writeSpeed)
  234362. {
  234363. String error ("Couldn't open or write to the CD device");
  234364. if ([pimpl->device->device isValid])
  234365. {
  234366. error = String::empty;
  234367. [pimpl->device burn: listener
  234368. errorString: &error
  234369. ejectAfterwards: ejectDiscAfterwards
  234370. isFake: performFakeBurnForTesting
  234371. speed: writeSpeed];
  234372. }
  234373. return error;
  234374. }
  234375. #endif
  234376. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234377. void AudioCDReader::ejectDisk()
  234378. {
  234379. const ScopedAutoReleasePool p;
  234380. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234381. }
  234382. #endif
  234383. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234384. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234385. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234386. // compiled on its own).
  234387. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234388. namespace CDReaderHelpers
  234389. {
  234390. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234391. {
  234392. forEachXmlChildElementWithTagName (xml, child, "key")
  234393. if (child->getAllSubText().trim() == key)
  234394. return child->getNextElement();
  234395. return 0;
  234396. }
  234397. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234398. {
  234399. const XmlElement* const block = getElementForKey (xml, key);
  234400. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  234401. }
  234402. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234403. // Returns NULL on success, otherwise a const char* representing an error.
  234404. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234405. {
  234406. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234407. if (xml == 0)
  234408. return "Couldn't parse XML in file";
  234409. const XmlElement* const dict = xml->getChildByName ("dict");
  234410. if (dict == 0)
  234411. return "Couldn't get top level dictionary";
  234412. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234413. if (sessions == 0)
  234414. return "Couldn't find sessions key";
  234415. const XmlElement* const session = sessions->getFirstChildElement();
  234416. if (session == 0)
  234417. return "Couldn't find first session";
  234418. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234419. if (leadOut < 0)
  234420. return "Couldn't find Leadout Block";
  234421. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234422. if (trackArray == 0)
  234423. return "Couldn't find Track Array";
  234424. forEachXmlChildElement (*trackArray, track)
  234425. {
  234426. const int trackValue = getIntValueForKey (*track, "Start Block");
  234427. if (trackValue < 0)
  234428. return "Couldn't find Start Block in the track";
  234429. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234430. }
  234431. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234432. return 0;
  234433. }
  234434. static void findDevices (Array<File>& cds)
  234435. {
  234436. File volumes ("/Volumes");
  234437. volumes.findChildFiles (cds, File::findDirectories, false);
  234438. for (int i = cds.size(); --i >= 0;)
  234439. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234440. cds.remove (i);
  234441. }
  234442. struct TrackSorter
  234443. {
  234444. static int getCDTrackNumber (const File& file)
  234445. {
  234446. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234447. }
  234448. static int compareElements (const File& first, const File& second)
  234449. {
  234450. const int firstTrack = getCDTrackNumber (first);
  234451. const int secondTrack = getCDTrackNumber (second);
  234452. jassert (firstTrack > 0 && secondTrack > 0);
  234453. return firstTrack - secondTrack;
  234454. }
  234455. };
  234456. }
  234457. const StringArray AudioCDReader::getAvailableCDNames()
  234458. {
  234459. Array<File> cds;
  234460. CDReaderHelpers::findDevices (cds);
  234461. StringArray names;
  234462. for (int i = 0; i < cds.size(); ++i)
  234463. names.add (cds.getReference(i).getFileName());
  234464. return names;
  234465. }
  234466. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234467. {
  234468. Array<File> cds;
  234469. CDReaderHelpers::findDevices (cds);
  234470. if (cds[index].exists())
  234471. return new AudioCDReader (cds[index]);
  234472. return 0;
  234473. }
  234474. AudioCDReader::AudioCDReader (const File& volume)
  234475. : AudioFormatReader (0, "CD Audio"),
  234476. volumeDir (volume),
  234477. currentReaderTrack (-1),
  234478. reader (0)
  234479. {
  234480. sampleRate = 44100.0;
  234481. bitsPerSample = 16;
  234482. numChannels = 2;
  234483. usesFloatingPointData = false;
  234484. refreshTrackLengths();
  234485. }
  234486. AudioCDReader::~AudioCDReader()
  234487. {
  234488. }
  234489. void AudioCDReader::refreshTrackLengths()
  234490. {
  234491. tracks.clear();
  234492. trackStartSamples.clear();
  234493. lengthInSamples = 0;
  234494. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234495. CDReaderHelpers::TrackSorter sorter;
  234496. tracks.sort (sorter);
  234497. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234498. if (toc.exists())
  234499. {
  234500. XmlDocument doc (toc);
  234501. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234502. (void) error; // could be logged..
  234503. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234504. }
  234505. }
  234506. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234507. int64 startSampleInFile, int numSamples)
  234508. {
  234509. while (numSamples > 0)
  234510. {
  234511. int track = -1;
  234512. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234513. {
  234514. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234515. {
  234516. track = i;
  234517. break;
  234518. }
  234519. }
  234520. if (track < 0)
  234521. return false;
  234522. if (track != currentReaderTrack)
  234523. {
  234524. reader = 0;
  234525. FileInputStream* const in = tracks [track].createInputStream();
  234526. if (in != 0)
  234527. {
  234528. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234529. AiffAudioFormat format;
  234530. reader = format.createReaderFor (bin, true);
  234531. if (reader == 0)
  234532. currentReaderTrack = -1;
  234533. else
  234534. currentReaderTrack = track;
  234535. }
  234536. }
  234537. if (reader == 0)
  234538. return false;
  234539. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234540. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234541. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234542. numSamples -= numAvailable;
  234543. startSampleInFile += numAvailable;
  234544. }
  234545. return true;
  234546. }
  234547. bool AudioCDReader::isCDStillPresent() const
  234548. {
  234549. return volumeDir.exists();
  234550. }
  234551. bool AudioCDReader::isTrackAudio (int trackNum) const
  234552. {
  234553. return tracks [trackNum].hasFileExtension (".aiff");
  234554. }
  234555. void AudioCDReader::enableIndexScanning (bool b)
  234556. {
  234557. // any way to do this on a Mac??
  234558. }
  234559. int AudioCDReader::getLastIndex() const
  234560. {
  234561. return 0;
  234562. }
  234563. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  234564. {
  234565. return Array <int>();
  234566. }
  234567. #endif
  234568. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234569. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234570. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234571. // compiled on its own).
  234572. #if JUCE_INCLUDED_FILE
  234573. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234574. for example having more than one juce plugin loaded into a host, then when a
  234575. method is called, the actual code that runs might actually be in a different module
  234576. than the one you expect... So any calls to library functions or statics that are
  234577. made inside obj-c methods will probably end up getting executed in a different DLL's
  234578. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234579. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234580. virtual methods of an object that's known to live inside the right module's space.
  234581. */
  234582. class AppDelegateRedirector
  234583. {
  234584. public:
  234585. AppDelegateRedirector()
  234586. {
  234587. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  234588. runLoop = CFRunLoopGetMain();
  234589. #else
  234590. runLoop = CFRunLoopGetCurrent();
  234591. #endif
  234592. CFRunLoopSourceContext sourceContext;
  234593. zerostruct (sourceContext);
  234594. sourceContext.info = this;
  234595. sourceContext.perform = runLoopSourceCallback;
  234596. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  234597. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234598. }
  234599. virtual ~AppDelegateRedirector()
  234600. {
  234601. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234602. CFRunLoopSourceInvalidate (runLoopSource);
  234603. CFRelease (runLoopSource);
  234604. }
  234605. virtual NSApplicationTerminateReply shouldTerminate()
  234606. {
  234607. if (JUCEApplication::getInstance() != 0)
  234608. {
  234609. JUCEApplication::getInstance()->systemRequestedQuit();
  234610. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  234611. return NSTerminateCancel;
  234612. }
  234613. return NSTerminateNow;
  234614. }
  234615. virtual void willTerminate()
  234616. {
  234617. JUCEApplication::appWillTerminateByForce();
  234618. }
  234619. virtual BOOL openFile (NSString* filename)
  234620. {
  234621. if (JUCEApplication::getInstance() != 0)
  234622. {
  234623. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234624. return YES;
  234625. }
  234626. return NO;
  234627. }
  234628. virtual void openFiles (NSArray* filenames)
  234629. {
  234630. StringArray files;
  234631. for (unsigned int i = 0; i < [filenames count]; ++i)
  234632. {
  234633. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234634. if (filename.containsChar (' '))
  234635. filename = filename.quoted('"');
  234636. files.add (filename);
  234637. }
  234638. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234639. {
  234640. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234641. }
  234642. }
  234643. virtual void focusChanged()
  234644. {
  234645. juce_HandleProcessFocusChange();
  234646. }
  234647. struct CallbackMessagePayload
  234648. {
  234649. MessageCallbackFunction* function;
  234650. void* parameter;
  234651. void* volatile result;
  234652. bool volatile hasBeenExecuted;
  234653. };
  234654. virtual void performCallback (CallbackMessagePayload* pl)
  234655. {
  234656. pl->result = (*pl->function) (pl->parameter);
  234657. pl->hasBeenExecuted = true;
  234658. }
  234659. virtual void deleteSelf()
  234660. {
  234661. delete this;
  234662. }
  234663. void postMessage (Message* const m)
  234664. {
  234665. messages.add (m);
  234666. CFRunLoopSourceSignal (runLoopSource);
  234667. CFRunLoopWakeUp (runLoop);
  234668. }
  234669. private:
  234670. CFRunLoopRef runLoop;
  234671. CFRunLoopSourceRef runLoopSource;
  234672. OwnedArray <Message, CriticalSection> messages;
  234673. void runLoopCallback()
  234674. {
  234675. int numDispatched = 0;
  234676. do
  234677. {
  234678. Message* const nextMessage = messages.removeAndReturn (0);
  234679. if (nextMessage == 0)
  234680. return;
  234681. const ScopedAutoReleasePool pool;
  234682. MessageManager::getInstance()->deliverMessage (nextMessage);
  234683. } while (++numDispatched <= 4);
  234684. CFRunLoopSourceSignal (runLoopSource);
  234685. CFRunLoopWakeUp (runLoop);
  234686. }
  234687. static void runLoopSourceCallback (void* info)
  234688. {
  234689. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  234690. }
  234691. };
  234692. END_JUCE_NAMESPACE
  234693. using namespace JUCE_NAMESPACE;
  234694. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234695. @interface JuceAppDelegate : NSObject
  234696. {
  234697. @private
  234698. id oldDelegate;
  234699. @public
  234700. AppDelegateRedirector* redirector;
  234701. }
  234702. - (JuceAppDelegate*) init;
  234703. - (void) dealloc;
  234704. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234705. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234706. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234707. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  234708. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234709. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234710. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234711. - (void) performCallback: (id) info;
  234712. - (void) dummyMethod;
  234713. @end
  234714. @implementation JuceAppDelegate
  234715. - (JuceAppDelegate*) init
  234716. {
  234717. [super init];
  234718. redirector = new AppDelegateRedirector();
  234719. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234720. if (JUCEApplication::isStandaloneApp())
  234721. {
  234722. oldDelegate = [NSApp delegate];
  234723. [NSApp setDelegate: self];
  234724. }
  234725. else
  234726. {
  234727. oldDelegate = 0;
  234728. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234729. name: NSApplicationDidResignActiveNotification object: NSApp];
  234730. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234731. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234732. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234733. name: NSApplicationWillUnhideNotification object: NSApp];
  234734. }
  234735. return self;
  234736. }
  234737. - (void) dealloc
  234738. {
  234739. if (oldDelegate != 0)
  234740. [NSApp setDelegate: oldDelegate];
  234741. redirector->deleteSelf();
  234742. [super dealloc];
  234743. }
  234744. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234745. {
  234746. (void) app;
  234747. return redirector->shouldTerminate();
  234748. }
  234749. - (void) applicationWillTerminate: (NSNotification*) aNotification
  234750. {
  234751. (void) aNotification;
  234752. redirector->willTerminate();
  234753. }
  234754. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234755. {
  234756. (void) app;
  234757. return redirector->openFile (filename);
  234758. }
  234759. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234760. {
  234761. (void) sender;
  234762. return redirector->openFiles (filenames);
  234763. }
  234764. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234765. {
  234766. (void) notification;
  234767. redirector->focusChanged();
  234768. }
  234769. - (void) applicationDidResignActive: (NSNotification*) notification
  234770. {
  234771. (void) notification;
  234772. redirector->focusChanged();
  234773. }
  234774. - (void) applicationWillUnhide: (NSNotification*) notification
  234775. {
  234776. (void) notification;
  234777. redirector->focusChanged();
  234778. }
  234779. - (void) performCallback: (id) info
  234780. {
  234781. if ([info isKindOfClass: [NSData class]])
  234782. {
  234783. AppDelegateRedirector::CallbackMessagePayload* pl
  234784. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234785. if (pl != 0)
  234786. redirector->performCallback (pl);
  234787. }
  234788. else
  234789. {
  234790. jassertfalse; // should never get here!
  234791. }
  234792. }
  234793. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234794. @end
  234795. BEGIN_JUCE_NAMESPACE
  234796. static JuceAppDelegate* juceAppDelegate = 0;
  234797. void MessageManager::runDispatchLoop()
  234798. {
  234799. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234800. {
  234801. const ScopedAutoReleasePool pool;
  234802. // must only be called by the message thread!
  234803. jassert (isThisTheMessageThread());
  234804. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234805. @try
  234806. {
  234807. [NSApp run];
  234808. }
  234809. @catch (NSException* e)
  234810. {
  234811. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234812. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234813. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234814. }
  234815. @finally
  234816. {
  234817. }
  234818. #else
  234819. [NSApp run];
  234820. #endif
  234821. }
  234822. }
  234823. void MessageManager::stopDispatchLoop()
  234824. {
  234825. quitMessagePosted = true;
  234826. [NSApp stop: nil];
  234827. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234828. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234829. }
  234830. static bool isEventBlockedByModalComps (NSEvent* e)
  234831. {
  234832. if (Component::getNumCurrentlyModalComponents() == 0)
  234833. return false;
  234834. NSWindow* const w = [e window];
  234835. if (w == 0 || [w worksWhenModal])
  234836. return false;
  234837. bool isKey = false, isInputAttempt = false;
  234838. switch ([e type])
  234839. {
  234840. case NSKeyDown:
  234841. case NSKeyUp:
  234842. isKey = isInputAttempt = true;
  234843. break;
  234844. case NSLeftMouseDown:
  234845. case NSRightMouseDown:
  234846. case NSOtherMouseDown:
  234847. isInputAttempt = true;
  234848. break;
  234849. case NSLeftMouseDragged:
  234850. case NSRightMouseDragged:
  234851. case NSLeftMouseUp:
  234852. case NSRightMouseUp:
  234853. case NSOtherMouseUp:
  234854. case NSOtherMouseDragged:
  234855. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234856. return false;
  234857. break;
  234858. case NSMouseMoved:
  234859. case NSMouseEntered:
  234860. case NSMouseExited:
  234861. case NSCursorUpdate:
  234862. case NSScrollWheel:
  234863. case NSTabletPoint:
  234864. case NSTabletProximity:
  234865. break;
  234866. default:
  234867. return false;
  234868. }
  234869. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234870. {
  234871. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234872. NSView* const compView = (NSView*) peer->getNativeHandle();
  234873. if ([compView window] == w)
  234874. {
  234875. if (isKey)
  234876. {
  234877. if (compView == [w firstResponder])
  234878. return false;
  234879. }
  234880. else
  234881. {
  234882. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234883. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234884. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234885. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234886. return false;
  234887. }
  234888. }
  234889. }
  234890. if (isInputAttempt)
  234891. {
  234892. if (! [NSApp isActive])
  234893. [NSApp activateIgnoringOtherApps: YES];
  234894. Component* const modal = Component::getCurrentlyModalComponent (0);
  234895. if (modal != 0)
  234896. modal->inputAttemptWhenModal();
  234897. }
  234898. return true;
  234899. }
  234900. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234901. {
  234902. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234903. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234904. while (! quitMessagePosted)
  234905. {
  234906. const ScopedAutoReleasePool pool;
  234907. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234908. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234909. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234910. inMode: NSDefaultRunLoopMode
  234911. dequeue: YES];
  234912. if (e != 0 && ! isEventBlockedByModalComps (e))
  234913. [NSApp sendEvent: e];
  234914. if (Time::getMillisecondCounter() >= endTime)
  234915. break;
  234916. }
  234917. return ! quitMessagePosted;
  234918. }
  234919. void MessageManager::doPlatformSpecificInitialisation()
  234920. {
  234921. if (juceAppDelegate == 0)
  234922. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234923. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234924. // correctly (needed prior to 10.5)
  234925. if (! [NSThread isMultiThreaded])
  234926. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234927. toTarget: juceAppDelegate
  234928. withObject: nil];
  234929. }
  234930. void MessageManager::doPlatformSpecificShutdown()
  234931. {
  234932. if (juceAppDelegate != 0)
  234933. {
  234934. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234935. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234936. [juceAppDelegate release];
  234937. juceAppDelegate = 0;
  234938. }
  234939. }
  234940. bool juce_postMessageToSystemQueue (Message* message)
  234941. {
  234942. juceAppDelegate->redirector->postMessage (message);
  234943. return true;
  234944. }
  234945. void MessageManager::broadcastMessage (const String& value)
  234946. {
  234947. }
  234948. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234949. {
  234950. if (isThisTheMessageThread())
  234951. {
  234952. return (*callback) (data);
  234953. }
  234954. else
  234955. {
  234956. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234957. // deadlock because the message manager is blocked from running, so can never
  234958. // call your function..
  234959. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234960. const ScopedAutoReleasePool pool;
  234961. AppDelegateRedirector::CallbackMessagePayload cmp;
  234962. cmp.function = callback;
  234963. cmp.parameter = data;
  234964. cmp.result = 0;
  234965. cmp.hasBeenExecuted = false;
  234966. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234967. withObject: [NSData dataWithBytesNoCopy: &cmp
  234968. length: sizeof (cmp)
  234969. freeWhenDone: NO]
  234970. waitUntilDone: YES];
  234971. return cmp.result;
  234972. }
  234973. }
  234974. #endif
  234975. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234976. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234977. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234978. // compiled on its own).
  234979. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234980. #if JUCE_MAC
  234981. END_JUCE_NAMESPACE
  234982. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234983. @interface DownloadClickDetector : NSObject
  234984. {
  234985. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234986. }
  234987. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234988. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234989. request: (NSURLRequest*) request
  234990. frame: (WebFrame*) frame
  234991. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234992. @end
  234993. @implementation DownloadClickDetector
  234994. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  234995. {
  234996. [super init];
  234997. ownerComponent = ownerComponent_;
  234998. return self;
  234999. }
  235000. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235001. request: (NSURLRequest*) request
  235002. frame: (WebFrame*) frame
  235003. decisionListener: (id <WebPolicyDecisionListener>) listener
  235004. {
  235005. (void) sender;
  235006. (void) request;
  235007. (void) frame;
  235008. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  235009. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  235010. [listener use];
  235011. else
  235012. [listener ignore];
  235013. }
  235014. @end
  235015. BEGIN_JUCE_NAMESPACE
  235016. class WebBrowserComponentInternal : public NSViewComponent
  235017. {
  235018. public:
  235019. WebBrowserComponentInternal (WebBrowserComponent* owner)
  235020. {
  235021. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  235022. frameName: @""
  235023. groupName: @""];
  235024. setView (webView);
  235025. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  235026. [webView setPolicyDelegate: clickListener];
  235027. }
  235028. ~WebBrowserComponentInternal()
  235029. {
  235030. [webView setPolicyDelegate: nil];
  235031. [clickListener release];
  235032. setView (0);
  235033. }
  235034. void goToURL (const String& url,
  235035. const StringArray* headers,
  235036. const MemoryBlock* postData)
  235037. {
  235038. NSMutableURLRequest* r
  235039. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  235040. cachePolicy: NSURLRequestUseProtocolCachePolicy
  235041. timeoutInterval: 30.0];
  235042. if (postData != 0 && postData->getSize() > 0)
  235043. {
  235044. [r setHTTPMethod: @"POST"];
  235045. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  235046. length: postData->getSize()]];
  235047. }
  235048. if (headers != 0)
  235049. {
  235050. for (int i = 0; i < headers->size(); ++i)
  235051. {
  235052. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  235053. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  235054. [r setValue: juceStringToNS (headerValue)
  235055. forHTTPHeaderField: juceStringToNS (headerName)];
  235056. }
  235057. }
  235058. stop();
  235059. [[webView mainFrame] loadRequest: r];
  235060. }
  235061. void goBack()
  235062. {
  235063. [webView goBack];
  235064. }
  235065. void goForward()
  235066. {
  235067. [webView goForward];
  235068. }
  235069. void stop()
  235070. {
  235071. [webView stopLoading: nil];
  235072. }
  235073. void refresh()
  235074. {
  235075. [webView reload: nil];
  235076. }
  235077. private:
  235078. WebView* webView;
  235079. DownloadClickDetector* clickListener;
  235080. };
  235081. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235082. : browser (0),
  235083. blankPageShown (false),
  235084. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  235085. {
  235086. setOpaque (true);
  235087. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  235088. }
  235089. WebBrowserComponent::~WebBrowserComponent()
  235090. {
  235091. deleteAndZero (browser);
  235092. }
  235093. void WebBrowserComponent::goToURL (const String& url,
  235094. const StringArray* headers,
  235095. const MemoryBlock* postData)
  235096. {
  235097. lastURL = url;
  235098. lastHeaders.clear();
  235099. if (headers != 0)
  235100. lastHeaders = *headers;
  235101. lastPostData.setSize (0);
  235102. if (postData != 0)
  235103. lastPostData = *postData;
  235104. blankPageShown = false;
  235105. browser->goToURL (url, headers, postData);
  235106. }
  235107. void WebBrowserComponent::stop()
  235108. {
  235109. browser->stop();
  235110. }
  235111. void WebBrowserComponent::goBack()
  235112. {
  235113. lastURL = String::empty;
  235114. blankPageShown = false;
  235115. browser->goBack();
  235116. }
  235117. void WebBrowserComponent::goForward()
  235118. {
  235119. lastURL = String::empty;
  235120. browser->goForward();
  235121. }
  235122. void WebBrowserComponent::refresh()
  235123. {
  235124. browser->refresh();
  235125. }
  235126. void WebBrowserComponent::paint (Graphics&)
  235127. {
  235128. }
  235129. void WebBrowserComponent::checkWindowAssociation()
  235130. {
  235131. if (isShowing())
  235132. {
  235133. if (blankPageShown)
  235134. goBack();
  235135. }
  235136. else
  235137. {
  235138. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  235139. {
  235140. // when the component becomes invisible, some stuff like flash
  235141. // carries on playing audio, so we need to force it onto a blank
  235142. // page to avoid this, (and send it back when it's made visible again).
  235143. blankPageShown = true;
  235144. browser->goToURL ("about:blank", 0, 0);
  235145. }
  235146. }
  235147. }
  235148. void WebBrowserComponent::reloadLastURL()
  235149. {
  235150. if (lastURL.isNotEmpty())
  235151. {
  235152. goToURL (lastURL, &lastHeaders, &lastPostData);
  235153. lastURL = String::empty;
  235154. }
  235155. }
  235156. void WebBrowserComponent::parentHierarchyChanged()
  235157. {
  235158. checkWindowAssociation();
  235159. }
  235160. void WebBrowserComponent::resized()
  235161. {
  235162. browser->setSize (getWidth(), getHeight());
  235163. }
  235164. void WebBrowserComponent::visibilityChanged()
  235165. {
  235166. checkWindowAssociation();
  235167. }
  235168. bool WebBrowserComponent::pageAboutToLoad (const String&)
  235169. {
  235170. return true;
  235171. }
  235172. #else
  235173. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235174. {
  235175. }
  235176. WebBrowserComponent::~WebBrowserComponent()
  235177. {
  235178. }
  235179. void WebBrowserComponent::goToURL (const String& url,
  235180. const StringArray* headers,
  235181. const MemoryBlock* postData)
  235182. {
  235183. }
  235184. void WebBrowserComponent::stop()
  235185. {
  235186. }
  235187. void WebBrowserComponent::goBack()
  235188. {
  235189. }
  235190. void WebBrowserComponent::goForward()
  235191. {
  235192. }
  235193. void WebBrowserComponent::refresh()
  235194. {
  235195. }
  235196. void WebBrowserComponent::paint (Graphics& g)
  235197. {
  235198. }
  235199. void WebBrowserComponent::checkWindowAssociation()
  235200. {
  235201. }
  235202. void WebBrowserComponent::reloadLastURL()
  235203. {
  235204. }
  235205. void WebBrowserComponent::parentHierarchyChanged()
  235206. {
  235207. }
  235208. void WebBrowserComponent::resized()
  235209. {
  235210. }
  235211. void WebBrowserComponent::visibilityChanged()
  235212. {
  235213. }
  235214. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  235215. {
  235216. return true;
  235217. }
  235218. #endif
  235219. #endif
  235220. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235221. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  235222. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235223. // compiled on its own).
  235224. #if JUCE_INCLUDED_FILE
  235225. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235226. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  235227. #endif
  235228. #undef log
  235229. #if JUCE_COREAUDIO_LOGGING_ENABLED
  235230. #define log(a) Logger::writeToLog (a)
  235231. #else
  235232. #define log(a)
  235233. #endif
  235234. #undef OK
  235235. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235236. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235237. {
  235238. if (err == noErr)
  235239. return true;
  235240. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235241. jassertfalse;
  235242. return false;
  235243. }
  235244. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235245. #else
  235246. #define OK(a) (a == noErr)
  235247. #endif
  235248. class CoreAudioInternal : public Timer
  235249. {
  235250. public:
  235251. CoreAudioInternal (AudioDeviceID id)
  235252. : inputLatency (0),
  235253. outputLatency (0),
  235254. callback (0),
  235255. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235256. audioProcID (0),
  235257. #endif
  235258. isSlaveDevice (false),
  235259. deviceID (id),
  235260. started (false),
  235261. sampleRate (0),
  235262. bufferSize (512),
  235263. numInputChans (0),
  235264. numOutputChans (0),
  235265. callbacksAllowed (true),
  235266. numInputChannelInfos (0),
  235267. numOutputChannelInfos (0)
  235268. {
  235269. jassert (deviceID != 0);
  235270. updateDetailsFromDevice();
  235271. AudioObjectPropertyAddress pa;
  235272. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235273. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235274. pa.mElement = kAudioObjectPropertyElementWildcard;
  235275. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235276. }
  235277. ~CoreAudioInternal()
  235278. {
  235279. AudioObjectPropertyAddress pa;
  235280. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235281. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235282. pa.mElement = kAudioObjectPropertyElementWildcard;
  235283. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235284. stop (false);
  235285. }
  235286. void allocateTempBuffers()
  235287. {
  235288. const int tempBufSize = bufferSize + 4;
  235289. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235290. tempInputBuffers.calloc (numInputChans + 2);
  235291. tempOutputBuffers.calloc (numOutputChans + 2);
  235292. int i, count = 0;
  235293. for (i = 0; i < numInputChans; ++i)
  235294. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235295. for (i = 0; i < numOutputChans; ++i)
  235296. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235297. }
  235298. // returns the number of actual available channels
  235299. void fillInChannelInfo (const bool input)
  235300. {
  235301. int chanNum = 0;
  235302. UInt32 size;
  235303. AudioObjectPropertyAddress pa;
  235304. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235305. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235306. pa.mElement = kAudioObjectPropertyElementMaster;
  235307. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235308. {
  235309. HeapBlock <AudioBufferList> bufList;
  235310. bufList.calloc (size, 1);
  235311. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235312. {
  235313. const int numStreams = bufList->mNumberBuffers;
  235314. for (int i = 0; i < numStreams; ++i)
  235315. {
  235316. const AudioBuffer& b = bufList->mBuffers[i];
  235317. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235318. {
  235319. String name;
  235320. {
  235321. char channelName [256];
  235322. zerostruct (channelName);
  235323. UInt32 nameSize = sizeof (channelName);
  235324. UInt32 channelNum = chanNum + 1;
  235325. pa.mSelector = kAudioDevicePropertyChannelName;
  235326. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235327. name = String::fromUTF8 (channelName, nameSize);
  235328. }
  235329. if (input)
  235330. {
  235331. if (activeInputChans[chanNum])
  235332. {
  235333. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235334. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235335. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235336. ++numInputChannelInfos;
  235337. }
  235338. if (name.isEmpty())
  235339. name << "Input " << (chanNum + 1);
  235340. inChanNames.add (name);
  235341. }
  235342. else
  235343. {
  235344. if (activeOutputChans[chanNum])
  235345. {
  235346. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235347. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235348. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235349. ++numOutputChannelInfos;
  235350. }
  235351. if (name.isEmpty())
  235352. name << "Output " << (chanNum + 1);
  235353. outChanNames.add (name);
  235354. }
  235355. ++chanNum;
  235356. }
  235357. }
  235358. }
  235359. }
  235360. }
  235361. void updateDetailsFromDevice()
  235362. {
  235363. stopTimer();
  235364. if (deviceID == 0)
  235365. return;
  235366. const ScopedLock sl (callbackLock);
  235367. Float64 sr;
  235368. UInt32 size = sizeof (Float64);
  235369. AudioObjectPropertyAddress pa;
  235370. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235371. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235372. pa.mElement = kAudioObjectPropertyElementMaster;
  235373. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235374. sampleRate = sr;
  235375. UInt32 framesPerBuf;
  235376. size = sizeof (framesPerBuf);
  235377. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235378. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235379. {
  235380. bufferSize = framesPerBuf;
  235381. allocateTempBuffers();
  235382. }
  235383. bufferSizes.clear();
  235384. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235385. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235386. {
  235387. HeapBlock <AudioValueRange> ranges;
  235388. ranges.calloc (size, 1);
  235389. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235390. {
  235391. bufferSizes.add ((int) ranges[0].mMinimum);
  235392. for (int i = 32; i < 2048; i += 32)
  235393. {
  235394. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235395. {
  235396. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235397. {
  235398. bufferSizes.addIfNotAlreadyThere (i);
  235399. break;
  235400. }
  235401. }
  235402. }
  235403. if (bufferSize > 0)
  235404. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235405. }
  235406. }
  235407. if (bufferSizes.size() == 0 && bufferSize > 0)
  235408. bufferSizes.add (bufferSize);
  235409. sampleRates.clear();
  235410. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235411. String rates;
  235412. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235413. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235414. {
  235415. HeapBlock <AudioValueRange> ranges;
  235416. ranges.calloc (size, 1);
  235417. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235418. {
  235419. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235420. {
  235421. bool ok = false;
  235422. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235423. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235424. ok = true;
  235425. if (ok)
  235426. {
  235427. sampleRates.add (possibleRates[i]);
  235428. rates << possibleRates[i] << ' ';
  235429. }
  235430. }
  235431. }
  235432. }
  235433. if (sampleRates.size() == 0 && sampleRate > 0)
  235434. {
  235435. sampleRates.add (sampleRate);
  235436. rates << sampleRate;
  235437. }
  235438. log ("sr: " + rates);
  235439. inputLatency = 0;
  235440. outputLatency = 0;
  235441. UInt32 lat;
  235442. size = sizeof (lat);
  235443. pa.mSelector = kAudioDevicePropertyLatency;
  235444. pa.mScope = kAudioDevicePropertyScopeInput;
  235445. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235446. inputLatency = (int) lat;
  235447. pa.mScope = kAudioDevicePropertyScopeOutput;
  235448. size = sizeof (lat);
  235449. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235450. outputLatency = (int) lat;
  235451. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235452. inChanNames.clear();
  235453. outChanNames.clear();
  235454. inputChannelInfo.calloc (numInputChans + 2);
  235455. numInputChannelInfos = 0;
  235456. outputChannelInfo.calloc (numOutputChans + 2);
  235457. numOutputChannelInfos = 0;
  235458. fillInChannelInfo (true);
  235459. fillInChannelInfo (false);
  235460. }
  235461. const StringArray getSources (bool input)
  235462. {
  235463. StringArray s;
  235464. HeapBlock <OSType> types;
  235465. const int num = getAllDataSourcesForDevice (deviceID, types);
  235466. for (int i = 0; i < num; ++i)
  235467. {
  235468. AudioValueTranslation avt;
  235469. char buffer[256];
  235470. avt.mInputData = &(types[i]);
  235471. avt.mInputDataSize = sizeof (UInt32);
  235472. avt.mOutputData = buffer;
  235473. avt.mOutputDataSize = 256;
  235474. UInt32 transSize = sizeof (avt);
  235475. AudioObjectPropertyAddress pa;
  235476. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235477. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235478. pa.mElement = kAudioObjectPropertyElementMaster;
  235479. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235480. {
  235481. DBG (buffer);
  235482. s.add (buffer);
  235483. }
  235484. }
  235485. return s;
  235486. }
  235487. int getCurrentSourceIndex (bool input) const
  235488. {
  235489. OSType currentSourceID = 0;
  235490. UInt32 size = sizeof (currentSourceID);
  235491. int result = -1;
  235492. AudioObjectPropertyAddress pa;
  235493. pa.mSelector = kAudioDevicePropertyDataSource;
  235494. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235495. pa.mElement = kAudioObjectPropertyElementMaster;
  235496. if (deviceID != 0)
  235497. {
  235498. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235499. {
  235500. HeapBlock <OSType> types;
  235501. const int num = getAllDataSourcesForDevice (deviceID, types);
  235502. for (int i = 0; i < num; ++i)
  235503. {
  235504. if (types[num] == currentSourceID)
  235505. {
  235506. result = i;
  235507. break;
  235508. }
  235509. }
  235510. }
  235511. }
  235512. return result;
  235513. }
  235514. void setCurrentSourceIndex (int index, bool input)
  235515. {
  235516. if (deviceID != 0)
  235517. {
  235518. HeapBlock <OSType> types;
  235519. const int num = getAllDataSourcesForDevice (deviceID, types);
  235520. if (((unsigned int) index) < (unsigned int) num)
  235521. {
  235522. AudioObjectPropertyAddress pa;
  235523. pa.mSelector = kAudioDevicePropertyDataSource;
  235524. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235525. pa.mElement = kAudioObjectPropertyElementMaster;
  235526. OSType typeId = types[index];
  235527. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235528. }
  235529. }
  235530. }
  235531. const String reopen (const BigInteger& inputChannels,
  235532. const BigInteger& outputChannels,
  235533. double newSampleRate,
  235534. int bufferSizeSamples)
  235535. {
  235536. String error;
  235537. log ("CoreAudio reopen");
  235538. callbacksAllowed = false;
  235539. stopTimer();
  235540. stop (false);
  235541. activeInputChans = inputChannels;
  235542. activeInputChans.setRange (inChanNames.size(),
  235543. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235544. false);
  235545. activeOutputChans = outputChannels;
  235546. activeOutputChans.setRange (outChanNames.size(),
  235547. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235548. false);
  235549. numInputChans = activeInputChans.countNumberOfSetBits();
  235550. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235551. // set sample rate
  235552. AudioObjectPropertyAddress pa;
  235553. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235554. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235555. pa.mElement = kAudioObjectPropertyElementMaster;
  235556. Float64 sr = newSampleRate;
  235557. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235558. {
  235559. error = "Couldn't change sample rate";
  235560. }
  235561. else
  235562. {
  235563. // change buffer size
  235564. UInt32 framesPerBuf = bufferSizeSamples;
  235565. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235566. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235567. {
  235568. error = "Couldn't change buffer size";
  235569. }
  235570. else
  235571. {
  235572. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235573. // correctly report their new settings until some random time in the future, so
  235574. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235575. // to make sure we're using the correct numbers..
  235576. updateDetailsFromDevice();
  235577. sampleRate = newSampleRate;
  235578. bufferSize = bufferSizeSamples;
  235579. if (sampleRates.size() == 0)
  235580. error = "Device has no available sample-rates";
  235581. else if (bufferSizes.size() == 0)
  235582. error = "Device has no available buffer-sizes";
  235583. else if (inputDevice != 0)
  235584. error = inputDevice->reopen (inputChannels,
  235585. outputChannels,
  235586. newSampleRate,
  235587. bufferSizeSamples);
  235588. }
  235589. }
  235590. callbacksAllowed = true;
  235591. return error;
  235592. }
  235593. bool start (AudioIODeviceCallback* cb)
  235594. {
  235595. if (! started)
  235596. {
  235597. callback = 0;
  235598. if (deviceID != 0)
  235599. {
  235600. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235601. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235602. #else
  235603. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235604. #endif
  235605. {
  235606. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235607. {
  235608. started = true;
  235609. }
  235610. else
  235611. {
  235612. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235613. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235614. #else
  235615. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235616. audioProcID = 0;
  235617. #endif
  235618. }
  235619. }
  235620. }
  235621. }
  235622. if (started)
  235623. {
  235624. const ScopedLock sl (callbackLock);
  235625. callback = cb;
  235626. }
  235627. if (inputDevice != 0)
  235628. return started && inputDevice->start (cb);
  235629. else
  235630. return started;
  235631. }
  235632. void stop (bool leaveInterruptRunning)
  235633. {
  235634. {
  235635. const ScopedLock sl (callbackLock);
  235636. callback = 0;
  235637. }
  235638. if (started
  235639. && (deviceID != 0)
  235640. && ! leaveInterruptRunning)
  235641. {
  235642. OK (AudioDeviceStop (deviceID, audioIOProc));
  235643. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235644. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235645. #else
  235646. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235647. audioProcID = 0;
  235648. #endif
  235649. started = false;
  235650. { const ScopedLock sl (callbackLock); }
  235651. // wait until it's definately stopped calling back..
  235652. for (int i = 40; --i >= 0;)
  235653. {
  235654. Thread::sleep (50);
  235655. UInt32 running = 0;
  235656. UInt32 size = sizeof (running);
  235657. AudioObjectPropertyAddress pa;
  235658. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235659. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235660. pa.mElement = kAudioObjectPropertyElementMaster;
  235661. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235662. if (running == 0)
  235663. break;
  235664. }
  235665. const ScopedLock sl (callbackLock);
  235666. }
  235667. if (inputDevice != 0)
  235668. inputDevice->stop (leaveInterruptRunning);
  235669. }
  235670. double getSampleRate() const
  235671. {
  235672. return sampleRate;
  235673. }
  235674. int getBufferSize() const
  235675. {
  235676. return bufferSize;
  235677. }
  235678. void audioCallback (const AudioBufferList* inInputData,
  235679. AudioBufferList* outOutputData)
  235680. {
  235681. int i;
  235682. const ScopedLock sl (callbackLock);
  235683. if (callback != 0)
  235684. {
  235685. if (inputDevice == 0)
  235686. {
  235687. for (i = numInputChans; --i >= 0;)
  235688. {
  235689. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235690. float* dest = tempInputBuffers [i];
  235691. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235692. + info.dataOffsetSamples;
  235693. const int stride = info.dataStrideSamples;
  235694. if (stride != 0) // if this is zero, info is invalid
  235695. {
  235696. for (int j = bufferSize; --j >= 0;)
  235697. {
  235698. *dest++ = *src;
  235699. src += stride;
  235700. }
  235701. }
  235702. }
  235703. }
  235704. if (! isSlaveDevice)
  235705. {
  235706. if (inputDevice == 0)
  235707. {
  235708. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235709. numInputChans,
  235710. tempOutputBuffers,
  235711. numOutputChans,
  235712. bufferSize);
  235713. }
  235714. else
  235715. {
  235716. jassert (inputDevice->bufferSize == bufferSize);
  235717. // Sometimes the two linked devices seem to get their callbacks in
  235718. // parallel, so we need to lock both devices to stop the input data being
  235719. // changed while inside our callback..
  235720. const ScopedLock sl2 (inputDevice->callbackLock);
  235721. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235722. inputDevice->numInputChans,
  235723. tempOutputBuffers,
  235724. numOutputChans,
  235725. bufferSize);
  235726. }
  235727. for (i = numOutputChans; --i >= 0;)
  235728. {
  235729. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235730. const float* src = tempOutputBuffers [i];
  235731. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235732. + info.dataOffsetSamples;
  235733. const int stride = info.dataStrideSamples;
  235734. if (stride != 0) // if this is zero, info is invalid
  235735. {
  235736. for (int j = bufferSize; --j >= 0;)
  235737. {
  235738. *dest = *src++;
  235739. dest += stride;
  235740. }
  235741. }
  235742. }
  235743. }
  235744. }
  235745. else
  235746. {
  235747. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235748. {
  235749. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235750. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235751. + info.dataOffsetSamples;
  235752. const int stride = info.dataStrideSamples;
  235753. if (stride != 0) // if this is zero, info is invalid
  235754. {
  235755. for (int j = bufferSize; --j >= 0;)
  235756. {
  235757. *dest = 0.0f;
  235758. dest += stride;
  235759. }
  235760. }
  235761. }
  235762. }
  235763. }
  235764. // called by callbacks
  235765. void deviceDetailsChanged()
  235766. {
  235767. if (callbacksAllowed)
  235768. startTimer (100);
  235769. }
  235770. void timerCallback()
  235771. {
  235772. stopTimer();
  235773. log ("CoreAudio device changed callback");
  235774. const double oldSampleRate = sampleRate;
  235775. const int oldBufferSize = bufferSize;
  235776. updateDetailsFromDevice();
  235777. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235778. {
  235779. callbacksAllowed = false;
  235780. stop (false);
  235781. updateDetailsFromDevice();
  235782. callbacksAllowed = true;
  235783. }
  235784. }
  235785. CoreAudioInternal* getRelatedDevice() const
  235786. {
  235787. UInt32 size = 0;
  235788. ScopedPointer <CoreAudioInternal> result;
  235789. AudioObjectPropertyAddress pa;
  235790. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235791. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235792. pa.mElement = kAudioObjectPropertyElementMaster;
  235793. if (deviceID != 0
  235794. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235795. && size > 0)
  235796. {
  235797. HeapBlock <AudioDeviceID> devs;
  235798. devs.calloc (size, 1);
  235799. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235800. {
  235801. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235802. {
  235803. if (devs[i] != deviceID && devs[i] != 0)
  235804. {
  235805. result = new CoreAudioInternal (devs[i]);
  235806. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235807. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235808. if (thisIsInput != otherIsInput
  235809. || (inChanNames.size() + outChanNames.size() == 0)
  235810. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235811. break;
  235812. result = 0;
  235813. }
  235814. }
  235815. }
  235816. }
  235817. return result.release();
  235818. }
  235819. juce_UseDebuggingNewOperator
  235820. int inputLatency, outputLatency;
  235821. BigInteger activeInputChans, activeOutputChans;
  235822. StringArray inChanNames, outChanNames;
  235823. Array <double> sampleRates;
  235824. Array <int> bufferSizes;
  235825. AudioIODeviceCallback* callback;
  235826. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235827. AudioDeviceIOProcID audioProcID;
  235828. #endif
  235829. ScopedPointer<CoreAudioInternal> inputDevice;
  235830. bool isSlaveDevice;
  235831. private:
  235832. CriticalSection callbackLock;
  235833. AudioDeviceID deviceID;
  235834. bool started;
  235835. double sampleRate;
  235836. int bufferSize;
  235837. HeapBlock <float> audioBuffer;
  235838. int numInputChans, numOutputChans;
  235839. bool callbacksAllowed;
  235840. struct CallbackDetailsForChannel
  235841. {
  235842. int streamNum;
  235843. int dataOffsetSamples;
  235844. int dataStrideSamples;
  235845. };
  235846. int numInputChannelInfos, numOutputChannelInfos;
  235847. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235848. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235849. CoreAudioInternal (const CoreAudioInternal&);
  235850. CoreAudioInternal& operator= (const CoreAudioInternal&);
  235851. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235852. const AudioTimeStamp* /*inNow*/,
  235853. const AudioBufferList* inInputData,
  235854. const AudioTimeStamp* /*inInputTime*/,
  235855. AudioBufferList* outOutputData,
  235856. const AudioTimeStamp* /*inOutputTime*/,
  235857. void* device)
  235858. {
  235859. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235860. return noErr;
  235861. }
  235862. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235863. {
  235864. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235865. switch (pa->mSelector)
  235866. {
  235867. case kAudioDevicePropertyBufferSize:
  235868. case kAudioDevicePropertyBufferFrameSize:
  235869. case kAudioDevicePropertyNominalSampleRate:
  235870. case kAudioDevicePropertyStreamFormat:
  235871. case kAudioDevicePropertyDeviceIsAlive:
  235872. intern->deviceDetailsChanged();
  235873. break;
  235874. case kAudioDevicePropertyBufferSizeRange:
  235875. case kAudioDevicePropertyVolumeScalar:
  235876. case kAudioDevicePropertyMute:
  235877. case kAudioDevicePropertyPlayThru:
  235878. case kAudioDevicePropertyDataSource:
  235879. case kAudioDevicePropertyDeviceIsRunning:
  235880. break;
  235881. }
  235882. return noErr;
  235883. }
  235884. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235885. {
  235886. AudioObjectPropertyAddress pa;
  235887. pa.mSelector = kAudioDevicePropertyDataSources;
  235888. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235889. pa.mElement = kAudioObjectPropertyElementMaster;
  235890. UInt32 size = 0;
  235891. if (deviceID != 0
  235892. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235893. {
  235894. types.calloc (size, 1);
  235895. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235896. return size / (int) sizeof (OSType);
  235897. }
  235898. return 0;
  235899. }
  235900. };
  235901. class CoreAudioIODevice : public AudioIODevice
  235902. {
  235903. public:
  235904. CoreAudioIODevice (const String& deviceName,
  235905. AudioDeviceID inputDeviceId,
  235906. const int inputIndex_,
  235907. AudioDeviceID outputDeviceId,
  235908. const int outputIndex_)
  235909. : AudioIODevice (deviceName, "CoreAudio"),
  235910. inputIndex (inputIndex_),
  235911. outputIndex (outputIndex_),
  235912. isOpen_ (false),
  235913. isStarted (false)
  235914. {
  235915. CoreAudioInternal* device = 0;
  235916. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235917. {
  235918. jassert (inputDeviceId != 0);
  235919. device = new CoreAudioInternal (inputDeviceId);
  235920. }
  235921. else
  235922. {
  235923. device = new CoreAudioInternal (outputDeviceId);
  235924. if (inputDeviceId != 0)
  235925. {
  235926. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235927. device->inputDevice = secondDevice;
  235928. secondDevice->isSlaveDevice = true;
  235929. }
  235930. }
  235931. internal = device;
  235932. AudioObjectPropertyAddress pa;
  235933. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235934. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235935. pa.mElement = kAudioObjectPropertyElementWildcard;
  235936. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235937. }
  235938. ~CoreAudioIODevice()
  235939. {
  235940. AudioObjectPropertyAddress pa;
  235941. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235942. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235943. pa.mElement = kAudioObjectPropertyElementWildcard;
  235944. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235945. }
  235946. const StringArray getOutputChannelNames()
  235947. {
  235948. return internal->outChanNames;
  235949. }
  235950. const StringArray getInputChannelNames()
  235951. {
  235952. if (internal->inputDevice != 0)
  235953. return internal->inputDevice->inChanNames;
  235954. else
  235955. return internal->inChanNames;
  235956. }
  235957. int getNumSampleRates()
  235958. {
  235959. return internal->sampleRates.size();
  235960. }
  235961. double getSampleRate (int index)
  235962. {
  235963. return internal->sampleRates [index];
  235964. }
  235965. int getNumBufferSizesAvailable()
  235966. {
  235967. return internal->bufferSizes.size();
  235968. }
  235969. int getBufferSizeSamples (int index)
  235970. {
  235971. return internal->bufferSizes [index];
  235972. }
  235973. int getDefaultBufferSize()
  235974. {
  235975. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235976. if (getBufferSizeSamples(i) >= 512)
  235977. return getBufferSizeSamples(i);
  235978. return 512;
  235979. }
  235980. const String open (const BigInteger& inputChannels,
  235981. const BigInteger& outputChannels,
  235982. double sampleRate,
  235983. int bufferSizeSamples)
  235984. {
  235985. isOpen_ = true;
  235986. if (bufferSizeSamples <= 0)
  235987. bufferSizeSamples = getDefaultBufferSize();
  235988. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235989. isOpen_ = lastError.isEmpty();
  235990. return lastError;
  235991. }
  235992. void close()
  235993. {
  235994. isOpen_ = false;
  235995. internal->stop (false);
  235996. }
  235997. bool isOpen()
  235998. {
  235999. return isOpen_;
  236000. }
  236001. int getCurrentBufferSizeSamples()
  236002. {
  236003. return internal != 0 ? internal->getBufferSize() : 512;
  236004. }
  236005. double getCurrentSampleRate()
  236006. {
  236007. return internal != 0 ? internal->getSampleRate() : 0;
  236008. }
  236009. int getCurrentBitDepth()
  236010. {
  236011. return 32; // no way to find out, so just assume it's high..
  236012. }
  236013. const BigInteger getActiveOutputChannels() const
  236014. {
  236015. return internal != 0 ? internal->activeOutputChans : BigInteger();
  236016. }
  236017. const BigInteger getActiveInputChannels() const
  236018. {
  236019. BigInteger chans;
  236020. if (internal != 0)
  236021. {
  236022. chans = internal->activeInputChans;
  236023. if (internal->inputDevice != 0)
  236024. chans |= internal->inputDevice->activeInputChans;
  236025. }
  236026. return chans;
  236027. }
  236028. int getOutputLatencyInSamples()
  236029. {
  236030. if (internal == 0)
  236031. return 0;
  236032. // this seems like a good guess at getting the latency right - comparing
  236033. // this with a round-trip measurement, it gets it to within a few millisecs
  236034. // for the built-in mac soundcard
  236035. return internal->outputLatency + internal->getBufferSize() * 2;
  236036. }
  236037. int getInputLatencyInSamples()
  236038. {
  236039. if (internal == 0)
  236040. return 0;
  236041. return internal->inputLatency + internal->getBufferSize() * 2;
  236042. }
  236043. void start (AudioIODeviceCallback* callback)
  236044. {
  236045. if (internal != 0 && ! isStarted)
  236046. {
  236047. if (callback != 0)
  236048. callback->audioDeviceAboutToStart (this);
  236049. isStarted = true;
  236050. internal->start (callback);
  236051. }
  236052. }
  236053. void stop()
  236054. {
  236055. if (isStarted && internal != 0)
  236056. {
  236057. AudioIODeviceCallback* const lastCallback = internal->callback;
  236058. isStarted = false;
  236059. internal->stop (true);
  236060. if (lastCallback != 0)
  236061. lastCallback->audioDeviceStopped();
  236062. }
  236063. }
  236064. bool isPlaying()
  236065. {
  236066. if (internal->callback == 0)
  236067. isStarted = false;
  236068. return isStarted;
  236069. }
  236070. const String getLastError()
  236071. {
  236072. return lastError;
  236073. }
  236074. int inputIndex, outputIndex;
  236075. juce_UseDebuggingNewOperator
  236076. private:
  236077. ScopedPointer<CoreAudioInternal> internal;
  236078. bool isOpen_, isStarted;
  236079. String lastError;
  236080. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236081. {
  236082. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236083. switch (pa->mSelector)
  236084. {
  236085. case kAudioHardwarePropertyDevices:
  236086. intern->deviceDetailsChanged();
  236087. break;
  236088. case kAudioHardwarePropertyDefaultOutputDevice:
  236089. case kAudioHardwarePropertyDefaultInputDevice:
  236090. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  236091. break;
  236092. }
  236093. return noErr;
  236094. }
  236095. CoreAudioIODevice (const CoreAudioIODevice&);
  236096. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  236097. };
  236098. class CoreAudioIODeviceType : public AudioIODeviceType
  236099. {
  236100. public:
  236101. CoreAudioIODeviceType()
  236102. : AudioIODeviceType ("CoreAudio"),
  236103. hasScanned (false)
  236104. {
  236105. }
  236106. ~CoreAudioIODeviceType()
  236107. {
  236108. }
  236109. void scanForDevices()
  236110. {
  236111. hasScanned = true;
  236112. inputDeviceNames.clear();
  236113. outputDeviceNames.clear();
  236114. inputIds.clear();
  236115. outputIds.clear();
  236116. UInt32 size;
  236117. AudioObjectPropertyAddress pa;
  236118. pa.mSelector = kAudioHardwarePropertyDevices;
  236119. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236120. pa.mElement = kAudioObjectPropertyElementMaster;
  236121. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  236122. {
  236123. HeapBlock <AudioDeviceID> devs;
  236124. devs.calloc (size, 1);
  236125. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  236126. {
  236127. const int num = size / (int) sizeof (AudioDeviceID);
  236128. for (int i = 0; i < num; ++i)
  236129. {
  236130. char name [1024];
  236131. size = sizeof (name);
  236132. pa.mSelector = kAudioDevicePropertyDeviceName;
  236133. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  236134. {
  236135. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  236136. const int numIns = getNumChannels (devs[i], true);
  236137. const int numOuts = getNumChannels (devs[i], false);
  236138. if (numIns > 0)
  236139. {
  236140. inputDeviceNames.add (nameString);
  236141. inputIds.add (devs[i]);
  236142. }
  236143. if (numOuts > 0)
  236144. {
  236145. outputDeviceNames.add (nameString);
  236146. outputIds.add (devs[i]);
  236147. }
  236148. }
  236149. }
  236150. }
  236151. }
  236152. inputDeviceNames.appendNumbersToDuplicates (false, true);
  236153. outputDeviceNames.appendNumbersToDuplicates (false, true);
  236154. }
  236155. const StringArray getDeviceNames (bool wantInputNames) const
  236156. {
  236157. jassert (hasScanned); // need to call scanForDevices() before doing this
  236158. if (wantInputNames)
  236159. return inputDeviceNames;
  236160. else
  236161. return outputDeviceNames;
  236162. }
  236163. int getDefaultDeviceIndex (bool forInput) const
  236164. {
  236165. jassert (hasScanned); // need to call scanForDevices() before doing this
  236166. AudioDeviceID deviceID;
  236167. UInt32 size = sizeof (deviceID);
  236168. // if they're asking for any input channels at all, use the default input, so we
  236169. // get the built-in mic rather than the built-in output with no inputs..
  236170. AudioObjectPropertyAddress pa;
  236171. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  236172. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236173. pa.mElement = kAudioObjectPropertyElementMaster;
  236174. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  236175. {
  236176. if (forInput)
  236177. {
  236178. for (int i = inputIds.size(); --i >= 0;)
  236179. if (inputIds[i] == deviceID)
  236180. return i;
  236181. }
  236182. else
  236183. {
  236184. for (int i = outputIds.size(); --i >= 0;)
  236185. if (outputIds[i] == deviceID)
  236186. return i;
  236187. }
  236188. }
  236189. return 0;
  236190. }
  236191. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  236192. {
  236193. jassert (hasScanned); // need to call scanForDevices() before doing this
  236194. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  236195. if (d == 0)
  236196. return -1;
  236197. return asInput ? d->inputIndex
  236198. : d->outputIndex;
  236199. }
  236200. bool hasSeparateInputsAndOutputs() const { return true; }
  236201. AudioIODevice* createDevice (const String& outputDeviceName,
  236202. const String& inputDeviceName)
  236203. {
  236204. jassert (hasScanned); // need to call scanForDevices() before doing this
  236205. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  236206. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  236207. String deviceName (outputDeviceName);
  236208. if (deviceName.isEmpty())
  236209. deviceName = inputDeviceName;
  236210. if (index >= 0)
  236211. return new CoreAudioIODevice (deviceName,
  236212. inputIds [inputIndex],
  236213. inputIndex,
  236214. outputIds [outputIndex],
  236215. outputIndex);
  236216. return 0;
  236217. }
  236218. juce_UseDebuggingNewOperator
  236219. private:
  236220. StringArray inputDeviceNames, outputDeviceNames;
  236221. Array <AudioDeviceID> inputIds, outputIds;
  236222. bool hasScanned;
  236223. static int getNumChannels (AudioDeviceID deviceID, bool input)
  236224. {
  236225. int total = 0;
  236226. UInt32 size;
  236227. AudioObjectPropertyAddress pa;
  236228. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  236229. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236230. pa.mElement = kAudioObjectPropertyElementMaster;
  236231. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236232. {
  236233. HeapBlock <AudioBufferList> bufList;
  236234. bufList.calloc (size, 1);
  236235. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  236236. {
  236237. const int numStreams = bufList->mNumberBuffers;
  236238. for (int i = 0; i < numStreams; ++i)
  236239. {
  236240. const AudioBuffer& b = bufList->mBuffers[i];
  236241. total += b.mNumberChannels;
  236242. }
  236243. }
  236244. }
  236245. return total;
  236246. }
  236247. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  236248. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  236249. };
  236250. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  236251. {
  236252. return new CoreAudioIODeviceType();
  236253. }
  236254. #undef log
  236255. #endif
  236256. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236257. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236258. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236259. // compiled on its own).
  236260. #if JUCE_INCLUDED_FILE
  236261. #if JUCE_MAC
  236262. namespace CoreMidiHelpers
  236263. {
  236264. static bool logError (const OSStatus err, const int lineNum)
  236265. {
  236266. if (err == noErr)
  236267. return true;
  236268. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236269. jassertfalse;
  236270. return false;
  236271. }
  236272. #undef CHECK_ERROR
  236273. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  236274. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236275. {
  236276. String result;
  236277. CFStringRef str = 0;
  236278. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236279. if (str != 0)
  236280. {
  236281. result = PlatformUtilities::cfStringToJuceString (str);
  236282. CFRelease (str);
  236283. str = 0;
  236284. }
  236285. MIDIEntityRef entity = 0;
  236286. MIDIEndpointGetEntity (endpoint, &entity);
  236287. if (entity == 0)
  236288. return result; // probably virtual
  236289. if (result.isEmpty())
  236290. {
  236291. // endpoint name has zero length - try the entity
  236292. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236293. if (str != 0)
  236294. {
  236295. result += PlatformUtilities::cfStringToJuceString (str);
  236296. CFRelease (str);
  236297. str = 0;
  236298. }
  236299. }
  236300. // now consider the device's name
  236301. MIDIDeviceRef device = 0;
  236302. MIDIEntityGetDevice (entity, &device);
  236303. if (device == 0)
  236304. return result;
  236305. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236306. if (str != 0)
  236307. {
  236308. const String s (PlatformUtilities::cfStringToJuceString (str));
  236309. CFRelease (str);
  236310. // if an external device has only one entity, throw away
  236311. // the endpoint name and just use the device name
  236312. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236313. {
  236314. result = s;
  236315. }
  236316. else if (! result.startsWithIgnoreCase (s))
  236317. {
  236318. // prepend the device name to the entity name
  236319. result = (s + " " + result).trimEnd();
  236320. }
  236321. }
  236322. return result;
  236323. }
  236324. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236325. {
  236326. String result;
  236327. // Does the endpoint have connections?
  236328. CFDataRef connections = 0;
  236329. int numConnections = 0;
  236330. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236331. if (connections != 0)
  236332. {
  236333. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236334. if (numConnections > 0)
  236335. {
  236336. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236337. for (int i = 0; i < numConnections; ++i, ++pid)
  236338. {
  236339. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236340. MIDIObjectRef connObject;
  236341. MIDIObjectType connObjectType;
  236342. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236343. if (err == noErr)
  236344. {
  236345. String s;
  236346. if (connObjectType == kMIDIObjectType_ExternalSource
  236347. || connObjectType == kMIDIObjectType_ExternalDestination)
  236348. {
  236349. // Connected to an external device's endpoint (10.3 and later).
  236350. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236351. }
  236352. else
  236353. {
  236354. // Connected to an external device (10.2) (or something else, catch-all)
  236355. CFStringRef str = 0;
  236356. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236357. if (str != 0)
  236358. {
  236359. s = PlatformUtilities::cfStringToJuceString (str);
  236360. CFRelease (str);
  236361. }
  236362. }
  236363. if (s.isNotEmpty())
  236364. {
  236365. if (result.isNotEmpty())
  236366. result += ", ";
  236367. result += s;
  236368. }
  236369. }
  236370. }
  236371. }
  236372. CFRelease (connections);
  236373. }
  236374. if (result.isNotEmpty())
  236375. return result;
  236376. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236377. return getEndpointName (endpoint, false);
  236378. }
  236379. static MIDIClientRef getGlobalMidiClient()
  236380. {
  236381. static MIDIClientRef globalMidiClient = 0;
  236382. if (globalMidiClient == 0)
  236383. {
  236384. String name ("JUCE");
  236385. if (JUCEApplication::getInstance() != 0)
  236386. name = JUCEApplication::getInstance()->getApplicationName();
  236387. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236388. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236389. CFRelease (appName);
  236390. }
  236391. return globalMidiClient;
  236392. }
  236393. class MidiPortAndEndpoint
  236394. {
  236395. public:
  236396. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236397. : port (port_), endPoint (endPoint_)
  236398. {
  236399. }
  236400. ~MidiPortAndEndpoint()
  236401. {
  236402. if (port != 0)
  236403. MIDIPortDispose (port);
  236404. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236405. MIDIEndpointDispose (endPoint);
  236406. }
  236407. void send (const MIDIPacketList* const packets)
  236408. {
  236409. if (port != 0)
  236410. MIDISend (port, endPoint, packets);
  236411. else
  236412. MIDIReceived (endPoint, packets);
  236413. }
  236414. MIDIPortRef port;
  236415. MIDIEndpointRef endPoint;
  236416. };
  236417. class MidiPortAndCallback;
  236418. static CriticalSection callbackLock;
  236419. static Array<MidiPortAndCallback*> activeCallbacks;
  236420. class MidiPortAndCallback
  236421. {
  236422. public:
  236423. MidiPortAndCallback (MidiInputCallback& callback_)
  236424. : input (0), active (false), callback (callback_), concatenator (2048)
  236425. {
  236426. }
  236427. ~MidiPortAndCallback()
  236428. {
  236429. active = false;
  236430. {
  236431. const ScopedLock sl (callbackLock);
  236432. activeCallbacks.removeValue (this);
  236433. }
  236434. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  236435. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  236436. }
  236437. void handlePackets (const MIDIPacketList* const pktlist)
  236438. {
  236439. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  236440. const ScopedLock sl (callbackLock);
  236441. if (activeCallbacks.contains (this) && active)
  236442. {
  236443. const MIDIPacket* packet = &pktlist->packet[0];
  236444. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236445. {
  236446. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  236447. input, callback);
  236448. packet = MIDIPacketNext (packet);
  236449. }
  236450. }
  236451. }
  236452. MidiInput* input;
  236453. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  236454. volatile bool active;
  236455. private:
  236456. MidiInputCallback& callback;
  236457. MidiDataConcatenator concatenator;
  236458. };
  236459. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  236460. {
  236461. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  236462. }
  236463. }
  236464. const StringArray MidiOutput::getDevices()
  236465. {
  236466. StringArray s;
  236467. const ItemCount num = MIDIGetNumberOfDestinations();
  236468. for (ItemCount i = 0; i < num; ++i)
  236469. {
  236470. MIDIEndpointRef dest = MIDIGetDestination (i);
  236471. if (dest != 0)
  236472. {
  236473. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  236474. if (name.isEmpty())
  236475. name = "<error>";
  236476. s.add (name);
  236477. }
  236478. else
  236479. {
  236480. s.add ("<error>");
  236481. }
  236482. }
  236483. return s;
  236484. }
  236485. int MidiOutput::getDefaultDeviceIndex()
  236486. {
  236487. return 0;
  236488. }
  236489. MidiOutput* MidiOutput::openDevice (int index)
  236490. {
  236491. MidiOutput* mo = 0;
  236492. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  236493. {
  236494. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236495. CFStringRef pname;
  236496. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236497. {
  236498. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236499. MIDIPortRef port;
  236500. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  236501. {
  236502. mo = new MidiOutput();
  236503. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  236504. }
  236505. CFRelease (pname);
  236506. }
  236507. }
  236508. return mo;
  236509. }
  236510. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236511. {
  236512. MidiOutput* mo = 0;
  236513. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236514. MIDIEndpointRef endPoint;
  236515. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236516. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  236517. {
  236518. mo = new MidiOutput();
  236519. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  236520. }
  236521. CFRelease (name);
  236522. return mo;
  236523. }
  236524. MidiOutput::~MidiOutput()
  236525. {
  236526. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236527. }
  236528. void MidiOutput::reset()
  236529. {
  236530. }
  236531. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236532. {
  236533. return false;
  236534. }
  236535. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236536. {
  236537. }
  236538. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236539. {
  236540. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236541. if (message.isSysEx())
  236542. {
  236543. const int maxPacketSize = 256;
  236544. int pos = 0, bytesLeft = message.getRawDataSize();
  236545. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236546. HeapBlock <MIDIPacketList> packets;
  236547. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236548. packets->numPackets = numPackets;
  236549. MIDIPacket* p = packets->packet;
  236550. for (int i = 0; i < numPackets; ++i)
  236551. {
  236552. p->timeStamp = 0;
  236553. p->length = jmin (maxPacketSize, bytesLeft);
  236554. memcpy (p->data, message.getRawData() + pos, p->length);
  236555. pos += p->length;
  236556. bytesLeft -= p->length;
  236557. p = MIDIPacketNext (p);
  236558. }
  236559. mpe->send (packets);
  236560. }
  236561. else
  236562. {
  236563. MIDIPacketList packets;
  236564. packets.numPackets = 1;
  236565. packets.packet[0].timeStamp = 0;
  236566. packets.packet[0].length = message.getRawDataSize();
  236567. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236568. mpe->send (&packets);
  236569. }
  236570. }
  236571. const StringArray MidiInput::getDevices()
  236572. {
  236573. StringArray s;
  236574. const ItemCount num = MIDIGetNumberOfSources();
  236575. for (ItemCount i = 0; i < num; ++i)
  236576. {
  236577. MIDIEndpointRef source = MIDIGetSource (i);
  236578. if (source != 0)
  236579. {
  236580. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  236581. if (name.isEmpty())
  236582. name = "<error>";
  236583. s.add (name);
  236584. }
  236585. else
  236586. {
  236587. s.add ("<error>");
  236588. }
  236589. }
  236590. return s;
  236591. }
  236592. int MidiInput::getDefaultDeviceIndex()
  236593. {
  236594. return 0;
  236595. }
  236596. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236597. {
  236598. jassert (callback != 0);
  236599. using namespace CoreMidiHelpers;
  236600. MidiInput* newInput = 0;
  236601. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  236602. {
  236603. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236604. if (endPoint != 0)
  236605. {
  236606. CFStringRef name;
  236607. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  236608. {
  236609. MIDIClientRef client = getGlobalMidiClient();
  236610. if (client != 0)
  236611. {
  236612. MIDIPortRef port;
  236613. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236614. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  236615. {
  236616. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  236617. {
  236618. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236619. newInput = new MidiInput (getDevices() [index]);
  236620. mpc->input = newInput;
  236621. newInput->internal = mpc;
  236622. const ScopedLock sl (callbackLock);
  236623. activeCallbacks.add (mpc.release());
  236624. }
  236625. else
  236626. {
  236627. CHECK_ERROR (MIDIPortDispose (port));
  236628. }
  236629. }
  236630. }
  236631. }
  236632. CFRelease (name);
  236633. }
  236634. }
  236635. return newInput;
  236636. }
  236637. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236638. {
  236639. jassert (callback != 0);
  236640. using namespace CoreMidiHelpers;
  236641. MidiInput* mi = 0;
  236642. MIDIClientRef client = getGlobalMidiClient();
  236643. if (client != 0)
  236644. {
  236645. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236646. mpc->active = false;
  236647. MIDIEndpointRef endPoint;
  236648. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236649. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  236650. {
  236651. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236652. mi = new MidiInput (deviceName);
  236653. mpc->input = mi;
  236654. mi->internal = mpc;
  236655. const ScopedLock sl (callbackLock);
  236656. activeCallbacks.add (mpc.release());
  236657. }
  236658. CFRelease (name);
  236659. }
  236660. return mi;
  236661. }
  236662. MidiInput::MidiInput (const String& name_)
  236663. : name (name_)
  236664. {
  236665. }
  236666. MidiInput::~MidiInput()
  236667. {
  236668. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  236669. }
  236670. void MidiInput::start()
  236671. {
  236672. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236673. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  236674. }
  236675. void MidiInput::stop()
  236676. {
  236677. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236678. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  236679. }
  236680. #undef CHECK_ERROR
  236681. #else // Stubs for iOS...
  236682. MidiOutput::~MidiOutput() {}
  236683. void MidiOutput::reset() {}
  236684. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  236685. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  236686. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  236687. const StringArray MidiOutput::getDevices() { return StringArray(); }
  236688. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  236689. const StringArray MidiInput::getDevices() { return StringArray(); }
  236690. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  236691. #endif
  236692. #endif
  236693. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236694. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236695. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236696. // compiled on its own).
  236697. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236698. #if ! JUCE_QUICKTIME
  236699. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236700. #endif
  236701. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236702. class QTCameraDeviceInteral;
  236703. END_JUCE_NAMESPACE
  236704. @interface QTCaptureCallbackDelegate : NSObject
  236705. {
  236706. @public
  236707. CameraDevice* owner;
  236708. QTCameraDeviceInteral* internal;
  236709. int64 firstPresentationTime;
  236710. int64 averageTimeOffset;
  236711. }
  236712. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236713. - (void) dealloc;
  236714. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236715. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236716. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236717. fromConnection: (QTCaptureConnection*) connection;
  236718. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236719. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236720. fromConnection: (QTCaptureConnection*) connection;
  236721. @end
  236722. BEGIN_JUCE_NAMESPACE
  236723. class QTCameraDeviceInteral
  236724. {
  236725. public:
  236726. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236727. {
  236728. const ScopedAutoReleasePool pool;
  236729. session = [[QTCaptureSession alloc] init];
  236730. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236731. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236732. input = 0;
  236733. audioInput = 0;
  236734. audioDevice = 0;
  236735. fileOutput = 0;
  236736. imageOutput = 0;
  236737. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236738. internalDev: this];
  236739. NSError* err = 0;
  236740. [device retain];
  236741. [device open: &err];
  236742. if (err == 0)
  236743. {
  236744. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236745. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236746. [session addInput: input error: &err];
  236747. if (err == 0)
  236748. {
  236749. resetFile();
  236750. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236751. [imageOutput setDelegate: callbackDelegate];
  236752. if (err == 0)
  236753. {
  236754. [session startRunning];
  236755. return;
  236756. }
  236757. }
  236758. }
  236759. openingError = nsStringToJuce ([err description]);
  236760. DBG (openingError);
  236761. }
  236762. ~QTCameraDeviceInteral()
  236763. {
  236764. [session stopRunning];
  236765. [session removeOutput: imageOutput];
  236766. [session release];
  236767. [input release];
  236768. [device release];
  236769. [audioDevice release];
  236770. [audioInput release];
  236771. [fileOutput release];
  236772. [imageOutput release];
  236773. [callbackDelegate release];
  236774. }
  236775. void resetFile()
  236776. {
  236777. [fileOutput recordToOutputFileURL: nil];
  236778. [session removeOutput: fileOutput];
  236779. [fileOutput release];
  236780. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236781. [session removeInput: audioInput];
  236782. [audioInput release];
  236783. audioInput = 0;
  236784. [audioDevice release];
  236785. audioDevice = 0;
  236786. [fileOutput setDelegate: callbackDelegate];
  236787. }
  236788. void addDefaultAudioInput()
  236789. {
  236790. NSError* err = nil;
  236791. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236792. if ([audioDevice open: &err])
  236793. [audioDevice retain];
  236794. else
  236795. audioDevice = nil;
  236796. if (audioDevice != 0)
  236797. {
  236798. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236799. [session addInput: audioInput error: &err];
  236800. }
  236801. }
  236802. void addListener (CameraDevice::Listener* listenerToAdd)
  236803. {
  236804. const ScopedLock sl (listenerLock);
  236805. if (listeners.size() == 0)
  236806. [session addOutput: imageOutput error: nil];
  236807. listeners.addIfNotAlreadyThere (listenerToAdd);
  236808. }
  236809. void removeListener (CameraDevice::Listener* listenerToRemove)
  236810. {
  236811. const ScopedLock sl (listenerLock);
  236812. listeners.removeValue (listenerToRemove);
  236813. if (listeners.size() == 0)
  236814. [session removeOutput: imageOutput];
  236815. }
  236816. void callListeners (CIImage* frame, int w, int h)
  236817. {
  236818. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236819. Image image (cgImage);
  236820. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236821. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236822. CGContextFlush (cgImage->context);
  236823. const ScopedLock sl (listenerLock);
  236824. for (int i = listeners.size(); --i >= 0;)
  236825. {
  236826. CameraDevice::Listener* const l = listeners[i];
  236827. if (l != 0)
  236828. l->imageReceived (image);
  236829. }
  236830. }
  236831. QTCaptureDevice* device;
  236832. QTCaptureDeviceInput* input;
  236833. QTCaptureDevice* audioDevice;
  236834. QTCaptureDeviceInput* audioInput;
  236835. QTCaptureSession* session;
  236836. QTCaptureMovieFileOutput* fileOutput;
  236837. QTCaptureDecompressedVideoOutput* imageOutput;
  236838. QTCaptureCallbackDelegate* callbackDelegate;
  236839. String openingError;
  236840. Array<CameraDevice::Listener*> listeners;
  236841. CriticalSection listenerLock;
  236842. };
  236843. END_JUCE_NAMESPACE
  236844. @implementation QTCaptureCallbackDelegate
  236845. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236846. internalDev: (QTCameraDeviceInteral*) d
  236847. {
  236848. [super init];
  236849. owner = owner_;
  236850. internal = d;
  236851. firstPresentationTime = 0;
  236852. averageTimeOffset = 0;
  236853. return self;
  236854. }
  236855. - (void) dealloc
  236856. {
  236857. [super dealloc];
  236858. }
  236859. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236860. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236861. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236862. fromConnection: (QTCaptureConnection*) connection
  236863. {
  236864. if (internal->listeners.size() > 0)
  236865. {
  236866. const ScopedAutoReleasePool pool;
  236867. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236868. CVPixelBufferGetWidth (videoFrame),
  236869. CVPixelBufferGetHeight (videoFrame));
  236870. }
  236871. }
  236872. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236873. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236874. fromConnection: (QTCaptureConnection*) connection
  236875. {
  236876. const Time now (Time::getCurrentTime());
  236877. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236878. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236879. #else
  236880. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236881. #endif
  236882. int64 presentationTime = (hosttime != nil)
  236883. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236884. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236885. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236886. if (firstPresentationTime == 0)
  236887. {
  236888. firstPresentationTime = presentationTime;
  236889. averageTimeOffset = timeDiff;
  236890. }
  236891. else
  236892. {
  236893. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236894. }
  236895. }
  236896. @end
  236897. BEGIN_JUCE_NAMESPACE
  236898. class QTCaptureViewerComp : public NSViewComponent
  236899. {
  236900. public:
  236901. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236902. {
  236903. const ScopedAutoReleasePool pool;
  236904. captureView = [[QTCaptureView alloc] init];
  236905. [captureView setCaptureSession: internal->session];
  236906. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236907. setView (captureView);
  236908. }
  236909. ~QTCaptureViewerComp()
  236910. {
  236911. setView (0);
  236912. [captureView setCaptureSession: nil];
  236913. [captureView release];
  236914. }
  236915. QTCaptureView* captureView;
  236916. };
  236917. CameraDevice::CameraDevice (const String& name_, int index)
  236918. : name (name_)
  236919. {
  236920. isRecording = false;
  236921. internal = new QTCameraDeviceInteral (this, index);
  236922. }
  236923. CameraDevice::~CameraDevice()
  236924. {
  236925. stopRecording();
  236926. delete static_cast <QTCameraDeviceInteral*> (internal);
  236927. internal = 0;
  236928. }
  236929. Component* CameraDevice::createViewerComponent()
  236930. {
  236931. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236932. }
  236933. const String CameraDevice::getFileExtension()
  236934. {
  236935. return ".mov";
  236936. }
  236937. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236938. {
  236939. stopRecording();
  236940. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236941. d->callbackDelegate->firstPresentationTime = 0;
  236942. file.deleteFile();
  236943. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236944. // out wrong, so we'll put some audio in there too..,
  236945. d->addDefaultAudioInput();
  236946. [d->session addOutput: d->fileOutput error: nil];
  236947. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236948. for (;;)
  236949. {
  236950. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236951. if (connection == 0)
  236952. break;
  236953. QTCompressionOptions* options = 0;
  236954. NSString* mediaType = [connection mediaType];
  236955. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236956. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236957. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236958. : @"QTCompressionOptions240SizeH264Video"];
  236959. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236960. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236961. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236962. }
  236963. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236964. isRecording = true;
  236965. }
  236966. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  236967. {
  236968. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236969. if (d->callbackDelegate->firstPresentationTime != 0)
  236970. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  236971. return Time();
  236972. }
  236973. void CameraDevice::stopRecording()
  236974. {
  236975. if (isRecording)
  236976. {
  236977. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  236978. isRecording = false;
  236979. }
  236980. }
  236981. void CameraDevice::addListener (Listener* listenerToAdd)
  236982. {
  236983. if (listenerToAdd != 0)
  236984. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  236985. }
  236986. void CameraDevice::removeListener (Listener* listenerToRemove)
  236987. {
  236988. if (listenerToRemove != 0)
  236989. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  236990. }
  236991. const StringArray CameraDevice::getAvailableDevices()
  236992. {
  236993. const ScopedAutoReleasePool pool;
  236994. StringArray results;
  236995. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236996. for (int i = 0; i < (int) [devs count]; ++i)
  236997. {
  236998. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  236999. results.add (nsStringToJuce ([dev localizedDisplayName]));
  237000. }
  237001. return results;
  237002. }
  237003. CameraDevice* CameraDevice::openDevice (int index,
  237004. int minWidth, int minHeight,
  237005. int maxWidth, int maxHeight)
  237006. {
  237007. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  237008. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  237009. return d.release();
  237010. return 0;
  237011. }
  237012. #endif
  237013. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  237014. #endif
  237015. #endif
  237016. END_JUCE_NAMESPACE
  237017. #endif
  237018. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  237019. #endif
  237020. #endif